commit
stringlengths 40
40
| old_file
stringlengths 4
118
| new_file
stringlengths 4
118
| old_contents
stringlengths 10
2.94k
| new_contents
stringlengths 21
3.18k
| subject
stringlengths 16
444
| message
stringlengths 17
2.63k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 5
43k
| ndiff
stringlengths 51
3.32k
| instruction
stringlengths 16
444
| content
stringlengths 133
4.32k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
aff0eba2c0f7f5a0c9bebbfc9402f04c2c9d6d11 | preference/miExecPref.py | preference/miExecPref.py | import os
import json
SCRIPT_PATH = os.path.dirname(__file__)
def getPreference():
""" Load pref json data nad return as dict"""
prefFile = open(os.path.join(SCRIPT_PATH, "miExecPref.json"), 'r')
prefDict = json.load(prefFile)
prefFile.close()
return prefDict
def getWindowSetting():
""" Load window setting json data and return as dict"""
prefDict = getPreference()
pardir = os.path.join(SCRIPT_PATH, os.pardir)
windowFilePath = os.path.join(
pardir,
"style",
prefDict['style'],
"window.json")
windowFile = open(windowFilePath, 'r')
windowDict = json.load(windowFile)
windowFile.close()
return windowDict
| import os
import json
import maya.cmds as cmds
SCRIPT_PATH = os.path.dirname(__file__)
MAYA_SCRIPT_DIR = cmds.internalVar(userScriptDir=True)
def getPreference():
""" Load pref json data nad return as dict"""
for root, dirs, files in os.walk(MAYA_SCRIPT_DIR):
if 'miExecPref.json' in files:
# Load pref json file from user script dir if exists.
abspath = os.path.join(root, 'miExecPref.json')
prefFile = open(abspath, 'r')
else:
# Load pref json file from miExec package directory.
prefFile = open(os.path.join(SCRIPT_PATH, "miExecPref.json"), 'r')
prefDict = json.load(prefFile)
prefFile.close()
return prefDict
def getWindowSetting():
""" Load window setting json data and return as dict"""
prefDict = getPreference()
pardir = os.path.join(SCRIPT_PATH, os.pardir)
windowFilePath = os.path.join(
pardir,
"style",
prefDict['style'],
"window.json")
windowFile = open(windowFilePath, 'r')
windowDict = json.load(windowFile)
windowFile.close()
return windowDict
| Load user pref file if exists in the maya user script directory | Load user pref file if exists in the maya user script directory
| Python | mit | minoue/miExecutor | import os
import json
-
+ import maya.cmds as cmds
SCRIPT_PATH = os.path.dirname(__file__)
+ MAYA_SCRIPT_DIR = cmds.internalVar(userScriptDir=True)
def getPreference():
""" Load pref json data nad return as dict"""
+ for root, dirs, files in os.walk(MAYA_SCRIPT_DIR):
+ if 'miExecPref.json' in files:
+ # Load pref json file from user script dir if exists.
+ abspath = os.path.join(root, 'miExecPref.json')
+ prefFile = open(abspath, 'r')
+ else:
+ # Load pref json file from miExec package directory.
- prefFile = open(os.path.join(SCRIPT_PATH, "miExecPref.json"), 'r')
+ prefFile = open(os.path.join(SCRIPT_PATH, "miExecPref.json"), 'r')
+
prefDict = json.load(prefFile)
prefFile.close()
return prefDict
def getWindowSetting():
""" Load window setting json data and return as dict"""
prefDict = getPreference()
pardir = os.path.join(SCRIPT_PATH, os.pardir)
windowFilePath = os.path.join(
pardir,
"style",
prefDict['style'],
"window.json")
windowFile = open(windowFilePath, 'r')
windowDict = json.load(windowFile)
windowFile.close()
return windowDict
| Load user pref file if exists in the maya user script directory | ## Code Before:
import os
import json
SCRIPT_PATH = os.path.dirname(__file__)
def getPreference():
""" Load pref json data nad return as dict"""
prefFile = open(os.path.join(SCRIPT_PATH, "miExecPref.json"), 'r')
prefDict = json.load(prefFile)
prefFile.close()
return prefDict
def getWindowSetting():
""" Load window setting json data and return as dict"""
prefDict = getPreference()
pardir = os.path.join(SCRIPT_PATH, os.pardir)
windowFilePath = os.path.join(
pardir,
"style",
prefDict['style'],
"window.json")
windowFile = open(windowFilePath, 'r')
windowDict = json.load(windowFile)
windowFile.close()
return windowDict
## Instruction:
Load user pref file if exists in the maya user script directory
## Code After:
import os
import json
import maya.cmds as cmds
SCRIPT_PATH = os.path.dirname(__file__)
MAYA_SCRIPT_DIR = cmds.internalVar(userScriptDir=True)
def getPreference():
""" Load pref json data nad return as dict"""
for root, dirs, files in os.walk(MAYA_SCRIPT_DIR):
if 'miExecPref.json' in files:
# Load pref json file from user script dir if exists.
abspath = os.path.join(root, 'miExecPref.json')
prefFile = open(abspath, 'r')
else:
# Load pref json file from miExec package directory.
prefFile = open(os.path.join(SCRIPT_PATH, "miExecPref.json"), 'r')
prefDict = json.load(prefFile)
prefFile.close()
return prefDict
def getWindowSetting():
""" Load window setting json data and return as dict"""
prefDict = getPreference()
pardir = os.path.join(SCRIPT_PATH, os.pardir)
windowFilePath = os.path.join(
pardir,
"style",
prefDict['style'],
"window.json")
windowFile = open(windowFilePath, 'r')
windowDict = json.load(windowFile)
windowFile.close()
return windowDict
|
7b5850d1b89d34ff9a60c3862d18691961c86656 | poisson/tests/test_irf.py | poisson/tests/test_irf.py | from numpy.testing import assert_almost_equal, assert_array_less
import numpy as np
from poisson import BmiPoisson
def test_grid_initialize():
model = BmiPoisson()
model.initialize()
assert_almost_equal(model.get_current_time(), 0.)
assert_array_less(model.get_value('land_surface__elevation'), 1.)
assert_array_less(0., model.get_value('land_surface__elevation'))
def test_update():
model = BmiPoisson()
model.initialize()
for time in xrange(10):
model.update()
assert_almost_equal(model.get_current_time(), time + 1.)
def test_update_until():
model = BmiPoisson()
model.initialize()
model.update_until(10.1)
assert_almost_equal(model.get_current_time(), 10.1)
def test_finalize():
model = BmiPoisson()
model.initialize()
model.update()
model.finalize()
| from nose.tools import assert_equal
from numpy.testing import assert_almost_equal, assert_array_less
import numpy as np
from poisson import BmiPoisson
def test_initialize_defaults():
model = BmiPoisson()
model.initialize()
assert_almost_equal(model.get_current_time(), 0.)
assert_array_less(model.get_value('land_surface__elevation'), 1.)
assert_array_less(0., model.get_value('land_surface__elevation'))
def test_initialize_from_file_like():
from StringIO import StringIO
import yaml
config = StringIO(yaml.dump({'shape': (7, 5)}))
model = BmiPoisson()
model.initialize(config)
assert_equal(model.get_grid_shape('land_surface__elevation'), (7, 5))
def test_initialize_from_file():
import os
import yaml
import tempfile
with tempfile.NamedTemporaryFile('w', delete=False) as fp:
fp.write(yaml.dump({'shape': (7, 5)}))
name = fp.name
model = BmiPoisson()
model.initialize(name)
os.remove(name)
assert_equal(model.get_grid_shape('land_surface__elevation'), (7, 5))
def test_update():
model = BmiPoisson()
model.initialize()
for time in xrange(10):
model.update()
assert_almost_equal(model.get_current_time(), time + 1.)
def test_update_until():
model = BmiPoisson()
model.initialize()
model.update_until(10.1)
assert_almost_equal(model.get_current_time(), 10.1)
def test_finalize():
model = BmiPoisson()
model.initialize()
model.update()
model.finalize()
| Test initialize with filename and file-like. | Test initialize with filename and file-like.
| Python | mit | mperignon/bmi-delta,mperignon/bmi-STM,mperignon/bmi-STM,mperignon/bmi-delta | + from nose.tools import assert_equal
from numpy.testing import assert_almost_equal, assert_array_less
import numpy as np
from poisson import BmiPoisson
- def test_grid_initialize():
+ def test_initialize_defaults():
model = BmiPoisson()
model.initialize()
assert_almost_equal(model.get_current_time(), 0.)
assert_array_less(model.get_value('land_surface__elevation'), 1.)
assert_array_less(0., model.get_value('land_surface__elevation'))
+
+
+ def test_initialize_from_file_like():
+ from StringIO import StringIO
+ import yaml
+
+ config = StringIO(yaml.dump({'shape': (7, 5)}))
+ model = BmiPoisson()
+ model.initialize(config)
+
+ assert_equal(model.get_grid_shape('land_surface__elevation'), (7, 5))
+
+
+ def test_initialize_from_file():
+ import os
+ import yaml
+ import tempfile
+
+ with tempfile.NamedTemporaryFile('w', delete=False) as fp:
+ fp.write(yaml.dump({'shape': (7, 5)}))
+ name = fp.name
+
+ model = BmiPoisson()
+ model.initialize(name)
+
+ os.remove(name)
+
+ assert_equal(model.get_grid_shape('land_surface__elevation'), (7, 5))
def test_update():
model = BmiPoisson()
model.initialize()
for time in xrange(10):
model.update()
assert_almost_equal(model.get_current_time(), time + 1.)
def test_update_until():
model = BmiPoisson()
model.initialize()
model.update_until(10.1)
assert_almost_equal(model.get_current_time(), 10.1)
def test_finalize():
model = BmiPoisson()
model.initialize()
model.update()
model.finalize()
| Test initialize with filename and file-like. | ## Code Before:
from numpy.testing import assert_almost_equal, assert_array_less
import numpy as np
from poisson import BmiPoisson
def test_grid_initialize():
model = BmiPoisson()
model.initialize()
assert_almost_equal(model.get_current_time(), 0.)
assert_array_less(model.get_value('land_surface__elevation'), 1.)
assert_array_less(0., model.get_value('land_surface__elevation'))
def test_update():
model = BmiPoisson()
model.initialize()
for time in xrange(10):
model.update()
assert_almost_equal(model.get_current_time(), time + 1.)
def test_update_until():
model = BmiPoisson()
model.initialize()
model.update_until(10.1)
assert_almost_equal(model.get_current_time(), 10.1)
def test_finalize():
model = BmiPoisson()
model.initialize()
model.update()
model.finalize()
## Instruction:
Test initialize with filename and file-like.
## Code After:
from nose.tools import assert_equal
from numpy.testing import assert_almost_equal, assert_array_less
import numpy as np
from poisson import BmiPoisson
def test_initialize_defaults():
model = BmiPoisson()
model.initialize()
assert_almost_equal(model.get_current_time(), 0.)
assert_array_less(model.get_value('land_surface__elevation'), 1.)
assert_array_less(0., model.get_value('land_surface__elevation'))
def test_initialize_from_file_like():
from StringIO import StringIO
import yaml
config = StringIO(yaml.dump({'shape': (7, 5)}))
model = BmiPoisson()
model.initialize(config)
assert_equal(model.get_grid_shape('land_surface__elevation'), (7, 5))
def test_initialize_from_file():
import os
import yaml
import tempfile
with tempfile.NamedTemporaryFile('w', delete=False) as fp:
fp.write(yaml.dump({'shape': (7, 5)}))
name = fp.name
model = BmiPoisson()
model.initialize(name)
os.remove(name)
assert_equal(model.get_grid_shape('land_surface__elevation'), (7, 5))
def test_update():
model = BmiPoisson()
model.initialize()
for time in xrange(10):
model.update()
assert_almost_equal(model.get_current_time(), time + 1.)
def test_update_until():
model = BmiPoisson()
model.initialize()
model.update_until(10.1)
assert_almost_equal(model.get_current_time(), 10.1)
def test_finalize():
model = BmiPoisson()
model.initialize()
model.update()
model.finalize()
|
7c68e3b00e7c66c0223617447e16a7159118d284 | goldstone/addons/utils.py | goldstone/addons/utils.py | """Addon utilities."""
# Copyright 2015 Solinea, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def update_addon_node():
"""Update the persistent resource graph's Addon node.
This is much simpler than the update_xxxxx_nodes functions that update
nodes for cloud entities. There will be only one Addon node in the table,
and all add-ons will be owned by it. If we're running for the first time,
the Addon node needs to be created. If it's already there, we leave it
alone.
"""
from goldstone.core.models import Addon
Addon.objects.get_or_create(native_id="Add-on", native_name="Add-on")
| """Addon utilities."""
# Copyright 2015 Solinea, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def update_addon_node():
"""Update the persistent resource graph's Addon node.
This is much simpler than the update_xxxxx_nodes functions that update
nodes for cloud entities. There will be only one Addon node in the table,
and all add-ons will be owned by it. If we're running for the first time,
the Addon node needs to be created. If it's already there, we leave it
alone.
This also differs from update_xxxxx_nodes by returning the Addon node that
is found or created.
"""
from goldstone.core.models import Addon
result, _ = Addon.objects.get_or_create(native_id="Add-on",
native_name="Add-on")
return result
| Change update_addon_node() to return the Addon node, whether created or found. | Change update_addon_node() to return the Addon node, whether created or found.
| Python | apache-2.0 | slashk/goldstone-server,slashk/goldstone-server,Solinea/goldstone-server,slashk/goldstone-server,slashk/goldstone-server,Solinea/goldstone-server,Solinea/goldstone-server,Solinea/goldstone-server,Solinea/goldstone-server,slashk/goldstone-server | """Addon utilities."""
# Copyright 2015 Solinea, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def update_addon_node():
"""Update the persistent resource graph's Addon node.
This is much simpler than the update_xxxxx_nodes functions that update
nodes for cloud entities. There will be only one Addon node in the table,
and all add-ons will be owned by it. If we're running for the first time,
the Addon node needs to be created. If it's already there, we leave it
alone.
+ This also differs from update_xxxxx_nodes by returning the Addon node that
+ is found or created.
+
"""
from goldstone.core.models import Addon
- Addon.objects.get_or_create(native_id="Add-on", native_name="Add-on")
+ result, _ = Addon.objects.get_or_create(native_id="Add-on",
+ native_name="Add-on")
+ return result
+ | Change update_addon_node() to return the Addon node, whether created or found. | ## Code Before:
"""Addon utilities."""
# Copyright 2015 Solinea, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def update_addon_node():
"""Update the persistent resource graph's Addon node.
This is much simpler than the update_xxxxx_nodes functions that update
nodes for cloud entities. There will be only one Addon node in the table,
and all add-ons will be owned by it. If we're running for the first time,
the Addon node needs to be created. If it's already there, we leave it
alone.
"""
from goldstone.core.models import Addon
Addon.objects.get_or_create(native_id="Add-on", native_name="Add-on")
## Instruction:
Change update_addon_node() to return the Addon node, whether created or found.
## Code After:
"""Addon utilities."""
# Copyright 2015 Solinea, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def update_addon_node():
"""Update the persistent resource graph's Addon node.
This is much simpler than the update_xxxxx_nodes functions that update
nodes for cloud entities. There will be only one Addon node in the table,
and all add-ons will be owned by it. If we're running for the first time,
the Addon node needs to be created. If it's already there, we leave it
alone.
This also differs from update_xxxxx_nodes by returning the Addon node that
is found or created.
"""
from goldstone.core.models import Addon
result, _ = Addon.objects.get_or_create(native_id="Add-on",
native_name="Add-on")
return result
|
0fb7e8d901addc801fb9b99d744666f573f672d3 | billjobs/migrations/0003_auto_20160822_2341.py | billjobs/migrations/0003_auto_20160822_2341.py | from __future__ import unicode_literals
from django.db import migrations
def add_billing_address(apps, schema_editor):
''' Data migration add billing_address in Bill from user billing_address
field
'''
Bill = apps.get_model('billjobs', 'Bill')
for bill in Bill.objects.all():
bill.billing_address = bill.user.billing_address
bill.save()
class Migration(migrations.Migration):
dependencies = [
('billjobs', '0002_service_is_available_squashed_0005_bill_issuer_address_default'),
]
operations = [
migrations.RunPython(add_billing_address),
]
| from __future__ import unicode_literals
from django.db import migrations, models
def add_billing_address(apps, schema_editor):
''' Data migration add billing_address in Bill from user billing_address
field
'''
Bill = apps.get_model('billjobs', 'Bill')
for bill in Bill.objects.all():
bill.billing_address = bill.user.userprofile.billing_address
bill.save()
class Migration(migrations.Migration):
dependencies = [
('billjobs', '0002_service_is_available_squashed_0005_bill_issuer_address_default'),
]
operations = [
migrations.AddField(
model_name='bill',
name='billing_address',
field=models.CharField(max_length=1024),
),
migrations.RunPython(add_billing_address),
]
| Add billing_address and migrate data | Add billing_address and migrate data
| Python | mit | ioO/billjobs | from __future__ import unicode_literals
- from django.db import migrations
+ from django.db import migrations, models
def add_billing_address(apps, schema_editor):
''' Data migration add billing_address in Bill from user billing_address
field
'''
Bill = apps.get_model('billjobs', 'Bill')
for bill in Bill.objects.all():
- bill.billing_address = bill.user.billing_address
+ bill.billing_address = bill.user.userprofile.billing_address
bill.save()
class Migration(migrations.Migration):
dependencies = [
('billjobs', '0002_service_is_available_squashed_0005_bill_issuer_address_default'),
]
operations = [
+ migrations.AddField(
+ model_name='bill',
+ name='billing_address',
+ field=models.CharField(max_length=1024),
+ ),
migrations.RunPython(add_billing_address),
]
| Add billing_address and migrate data | ## Code Before:
from __future__ import unicode_literals
from django.db import migrations
def add_billing_address(apps, schema_editor):
''' Data migration add billing_address in Bill from user billing_address
field
'''
Bill = apps.get_model('billjobs', 'Bill')
for bill in Bill.objects.all():
bill.billing_address = bill.user.billing_address
bill.save()
class Migration(migrations.Migration):
dependencies = [
('billjobs', '0002_service_is_available_squashed_0005_bill_issuer_address_default'),
]
operations = [
migrations.RunPython(add_billing_address),
]
## Instruction:
Add billing_address and migrate data
## Code After:
from __future__ import unicode_literals
from django.db import migrations, models
def add_billing_address(apps, schema_editor):
''' Data migration add billing_address in Bill from user billing_address
field
'''
Bill = apps.get_model('billjobs', 'Bill')
for bill in Bill.objects.all():
bill.billing_address = bill.user.userprofile.billing_address
bill.save()
class Migration(migrations.Migration):
dependencies = [
('billjobs', '0002_service_is_available_squashed_0005_bill_issuer_address_default'),
]
operations = [
migrations.AddField(
model_name='bill',
name='billing_address',
field=models.CharField(max_length=1024),
),
migrations.RunPython(add_billing_address),
]
|
bbb4496a99a5c65218b12c56de01c12ab83a1056 | demo/recent_questions.py | demo/recent_questions.py | from __future__ import print_function
# Same directory hack
import sys
sys.path.append('.')
sys.path.append('..')
try:
get_input = raw_input
except NameError:
get_input = input
user_api_key = get_input("Please enter an API key if you have one (Return for none):")
if not user_api_key: user_api_key = None
import stackexchange, thread
so = stackexchange.Site(stackexchange.StackOverflow, app_key=user_api_key, impose_throttling=True)
so.be_inclusive()
sys.stdout.write('Loading...')
sys.stdout.flush()
questions = so.recent_questions(pagesize=10, filter='_b')
print('\r # vote ans view')
cur = 1
for question in questions:
print('%2d %3d %3d %3d \t%s' % (cur, question.score, len(question.answers), question.view_count, question.title))
cur += 1
num = int(get_input('Question no.: '))
qu = questions[num - 1]
print('--- %s' % qu.title)
print('%d votes, %d answers, %d views.' % (qu.score, len(qu.answers), qu.view_count))
print('Tagged: ' + ', '.join(qu.tags))
print()
print(qu.body[:250] + ('...' if len(qu.body) > 250 else ''))
| from __future__ import print_function
from six.moves import input
# Same directory hack
import sys
sys.path.append('.')
sys.path.append('..')
user_api_key = input("Please enter an API key if you have one (Return for none):")
if not user_api_key: user_api_key = None
import stackexchange, thread
so = stackexchange.Site(stackexchange.StackOverflow, app_key=user_api_key, impose_throttling=True)
so.be_inclusive()
sys.stdout.write('Loading...')
sys.stdout.flush()
questions = so.recent_questions(pagesize=10, filter='_b')
print('\r # vote ans view')
cur = 1
for question in questions:
print('%2d %3d %3d %3d \t%s' % (cur, question.score, len(question.answers), question.view_count, question.title))
cur += 1
num = int(get_input('Question no.: '))
qu = questions[num - 1]
print('--- %s' % qu.title)
print('%d votes, %d answers, %d views.' % (qu.score, len(qu.answers), qu.view_count))
print('Tagged: ' + ', '.join(qu.tags))
print()
print(qu.body[:250] + ('...' if len(qu.body) > 250 else ''))
| Use six function for input() in recent questions demo | Use six function for input() in recent questions demo
| Python | bsd-3-clause | Khilo84/Py-StackExchange,lucjon/Py-StackExchange,damanjitsingh/StackExchange-python- | from __future__ import print_function
+ from six.moves import input
# Same directory hack
import sys
sys.path.append('.')
sys.path.append('..')
- try:
- get_input = raw_input
- except NameError:
- get_input = input
-
- user_api_key = get_input("Please enter an API key if you have one (Return for none):")
+ user_api_key = input("Please enter an API key if you have one (Return for none):")
if not user_api_key: user_api_key = None
import stackexchange, thread
so = stackexchange.Site(stackexchange.StackOverflow, app_key=user_api_key, impose_throttling=True)
so.be_inclusive()
sys.stdout.write('Loading...')
sys.stdout.flush()
questions = so.recent_questions(pagesize=10, filter='_b')
print('\r # vote ans view')
cur = 1
for question in questions:
print('%2d %3d %3d %3d \t%s' % (cur, question.score, len(question.answers), question.view_count, question.title))
cur += 1
num = int(get_input('Question no.: '))
qu = questions[num - 1]
print('--- %s' % qu.title)
print('%d votes, %d answers, %d views.' % (qu.score, len(qu.answers), qu.view_count))
print('Tagged: ' + ', '.join(qu.tags))
print()
print(qu.body[:250] + ('...' if len(qu.body) > 250 else ''))
| Use six function for input() in recent questions demo | ## Code Before:
from __future__ import print_function
# Same directory hack
import sys
sys.path.append('.')
sys.path.append('..')
try:
get_input = raw_input
except NameError:
get_input = input
user_api_key = get_input("Please enter an API key if you have one (Return for none):")
if not user_api_key: user_api_key = None
import stackexchange, thread
so = stackexchange.Site(stackexchange.StackOverflow, app_key=user_api_key, impose_throttling=True)
so.be_inclusive()
sys.stdout.write('Loading...')
sys.stdout.flush()
questions = so.recent_questions(pagesize=10, filter='_b')
print('\r # vote ans view')
cur = 1
for question in questions:
print('%2d %3d %3d %3d \t%s' % (cur, question.score, len(question.answers), question.view_count, question.title))
cur += 1
num = int(get_input('Question no.: '))
qu = questions[num - 1]
print('--- %s' % qu.title)
print('%d votes, %d answers, %d views.' % (qu.score, len(qu.answers), qu.view_count))
print('Tagged: ' + ', '.join(qu.tags))
print()
print(qu.body[:250] + ('...' if len(qu.body) > 250 else ''))
## Instruction:
Use six function for input() in recent questions demo
## Code After:
from __future__ import print_function
from six.moves import input
# Same directory hack
import sys
sys.path.append('.')
sys.path.append('..')
user_api_key = input("Please enter an API key if you have one (Return for none):")
if not user_api_key: user_api_key = None
import stackexchange, thread
so = stackexchange.Site(stackexchange.StackOverflow, app_key=user_api_key, impose_throttling=True)
so.be_inclusive()
sys.stdout.write('Loading...')
sys.stdout.flush()
questions = so.recent_questions(pagesize=10, filter='_b')
print('\r # vote ans view')
cur = 1
for question in questions:
print('%2d %3d %3d %3d \t%s' % (cur, question.score, len(question.answers), question.view_count, question.title))
cur += 1
num = int(get_input('Question no.: '))
qu = questions[num - 1]
print('--- %s' % qu.title)
print('%d votes, %d answers, %d views.' % (qu.score, len(qu.answers), qu.view_count))
print('Tagged: ' + ', '.join(qu.tags))
print()
print(qu.body[:250] + ('...' if len(qu.body) > 250 else ''))
|
d358a759d86ce2a377e4fef84f20075bd0481d3b | ditto/flickr/views.py | ditto/flickr/views.py | from ..ditto.views import PaginatedListView
from .models import Account, Photo, User
class Home(PaginatedListView):
template_name = 'flickr/index.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['account_list'] = Account.objects.all()
return context
def get_queryset(self):
"Get Photos by all of the Accounts that have Users."
# Use select_related to fetch user details too. Could be nasty...
return Photo.public_photo_objects.all().select_related()
| from ..ditto.views import PaginatedListView
from .models import Account, Photo, User
class Home(PaginatedListView):
template_name = 'flickr/index.html'
paginate_by = 48
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['account_list'] = Account.objects.all()
return context
def get_queryset(self):
"Get Photos by all of the Accounts that have Users."
# Use select_related to fetch user details too. Could be nasty...
return Photo.public_photo_objects.all().select_related()
| Change number of photos per page | Change number of photos per page
| Python | mit | philgyford/django-ditto,philgyford/django-ditto,philgyford/django-ditto | from ..ditto.views import PaginatedListView
from .models import Account, Photo, User
class Home(PaginatedListView):
template_name = 'flickr/index.html'
+ paginate_by = 48
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['account_list'] = Account.objects.all()
return context
def get_queryset(self):
"Get Photos by all of the Accounts that have Users."
# Use select_related to fetch user details too. Could be nasty...
return Photo.public_photo_objects.all().select_related()
| Change number of photos per page | ## Code Before:
from ..ditto.views import PaginatedListView
from .models import Account, Photo, User
class Home(PaginatedListView):
template_name = 'flickr/index.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['account_list'] = Account.objects.all()
return context
def get_queryset(self):
"Get Photos by all of the Accounts that have Users."
# Use select_related to fetch user details too. Could be nasty...
return Photo.public_photo_objects.all().select_related()
## Instruction:
Change number of photos per page
## Code After:
from ..ditto.views import PaginatedListView
from .models import Account, Photo, User
class Home(PaginatedListView):
template_name = 'flickr/index.html'
paginate_by = 48
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['account_list'] = Account.objects.all()
return context
def get_queryset(self):
"Get Photos by all of the Accounts that have Users."
# Use select_related to fetch user details too. Could be nasty...
return Photo.public_photo_objects.all().select_related()
|
7560bce01be5560395dd2373e979dbee086f3c21 | py2app/converters/nibfile.py | py2app/converters/nibfile.py | import subprocess, os
from py2app.decorators import converts
@converts(suffix=".xib")
def convert_xib(source, destination, dry_run=0):
destination = destination[:-4] + ".nib"
if dry_run:
return
p = subprocess.Popen(['ibtool', '--compile', destination, source])
xit = p.wait()
if xit != 0:
raise RuntimeError("ibtool failed, code %d"%(xit,))
@converts(suffix=".nib")
def convert_nib(source, destination, dry_run=0):
destination = destination[:-4] + ".nib"
if dry_run:
return
p = subprocess.Popen(['ibtool', '--compile', destination, source])
xit = p.wait()
if xit != 0:
raise RuntimeError("ibtool failed, code %d"%(xit,))
| from __future__ import print_function
import subprocess, os
from py2app.decorators import converts
gTool = None
def _get_ibtool():
global gTool
if gTool is None:
if os.path.exists('/usr/bin/xcrun'):
gTool = subprocess.check_output(['/usr/bin/xcrun', '-find', 'ibtool'])[:-1]
else:
gTool = 'ibtool'
print (gTool)
return gTool
@converts(suffix=".xib")
def convert_xib(source, destination, dry_run=0):
destination = destination[:-4] + ".nib"
print("compile %s -> %s"%(source, destination))
if dry_run:
return
subprocess.check_call([_get_ibtool(), '--compile', destination, source])
@converts(suffix=".nib")
def convert_nib(source, destination, dry_run=0):
destination = destination[:-4] + ".nib"
print("compile %s -> %s"%(source, destination))
if dry_run:
return
subprocess.check_call([_get_ibtool, '--compile', destination, source])
| Simplify nib compiler and support recent Xcode versions by using xcrun | Simplify nib compiler and support recent Xcode versions by using xcrun
| Python | mit | metachris/py2app,metachris/py2app,metachris/py2app,metachris/py2app | + from __future__ import print_function
import subprocess, os
from py2app.decorators import converts
+
+ gTool = None
+ def _get_ibtool():
+ global gTool
+ if gTool is None:
+ if os.path.exists('/usr/bin/xcrun'):
+ gTool = subprocess.check_output(['/usr/bin/xcrun', '-find', 'ibtool'])[:-1]
+ else:
+ gTool = 'ibtool'
+
+ print (gTool)
+ return gTool
@converts(suffix=".xib")
def convert_xib(source, destination, dry_run=0):
destination = destination[:-4] + ".nib"
+ print("compile %s -> %s"%(source, destination))
if dry_run:
return
- p = subprocess.Popen(['ibtool', '--compile', destination, source])
+ subprocess.check_call([_get_ibtool(), '--compile', destination, source])
- xit = p.wait()
- if xit != 0:
- raise RuntimeError("ibtool failed, code %d"%(xit,))
-
@converts(suffix=".nib")
def convert_nib(source, destination, dry_run=0):
destination = destination[:-4] + ".nib"
+ print("compile %s -> %s"%(source, destination))
if dry_run:
return
- p = subprocess.Popen(['ibtool', '--compile', destination, source])
+ subprocess.check_call([_get_ibtool, '--compile', destination, source])
- xit = p.wait()
- if xit != 0:
- raise RuntimeError("ibtool failed, code %d"%(xit,))
- | Simplify nib compiler and support recent Xcode versions by using xcrun | ## Code Before:
import subprocess, os
from py2app.decorators import converts
@converts(suffix=".xib")
def convert_xib(source, destination, dry_run=0):
destination = destination[:-4] + ".nib"
if dry_run:
return
p = subprocess.Popen(['ibtool', '--compile', destination, source])
xit = p.wait()
if xit != 0:
raise RuntimeError("ibtool failed, code %d"%(xit,))
@converts(suffix=".nib")
def convert_nib(source, destination, dry_run=0):
destination = destination[:-4] + ".nib"
if dry_run:
return
p = subprocess.Popen(['ibtool', '--compile', destination, source])
xit = p.wait()
if xit != 0:
raise RuntimeError("ibtool failed, code %d"%(xit,))
## Instruction:
Simplify nib compiler and support recent Xcode versions by using xcrun
## Code After:
from __future__ import print_function
import subprocess, os
from py2app.decorators import converts
gTool = None
def _get_ibtool():
global gTool
if gTool is None:
if os.path.exists('/usr/bin/xcrun'):
gTool = subprocess.check_output(['/usr/bin/xcrun', '-find', 'ibtool'])[:-1]
else:
gTool = 'ibtool'
print (gTool)
return gTool
@converts(suffix=".xib")
def convert_xib(source, destination, dry_run=0):
destination = destination[:-4] + ".nib"
print("compile %s -> %s"%(source, destination))
if dry_run:
return
subprocess.check_call([_get_ibtool(), '--compile', destination, source])
@converts(suffix=".nib")
def convert_nib(source, destination, dry_run=0):
destination = destination[:-4] + ".nib"
print("compile %s -> %s"%(source, destination))
if dry_run:
return
subprocess.check_call([_get_ibtool, '--compile', destination, source])
|
b6d08abf7bc4aafaeec59944bdcdf8ae4a9352d5 | recipe_scrapers/consts.py | recipe_scrapers/consts.py | import re
TIME_REGEX = re.compile(
r'\A(\s*(?P<hours>\d+)\s{1}(hours|hrs|hr|h))?((?P<minutes>\s*\d+)\s{1}(minutes|mins|min|m))?\Z'
)
HTML_SYMBOLS = '\xa0' #
| import re
TIME_REGEX = re.compile(
r'\A(\s*(?P<hours>\d+)\s*(hours|hrs|hr|h))?(\s*(?P<minutes>\d+)\s*(minutes|mins|min|m))?\Z'
)
HTML_SYMBOLS = '\xa0' #
| Update time_regex captcher so to work with more sites | Update time_regex captcher so to work with more sites
| Python | mit | hhursev/recipe-scraper | import re
TIME_REGEX = re.compile(
- r'\A(\s*(?P<hours>\d+)\s{1}(hours|hrs|hr|h))?((?P<minutes>\s*\d+)\s{1}(minutes|mins|min|m))?\Z'
+ r'\A(\s*(?P<hours>\d+)\s*(hours|hrs|hr|h))?(\s*(?P<minutes>\d+)\s*(minutes|mins|min|m))?\Z'
)
HTML_SYMBOLS = '\xa0' #
| Update time_regex captcher so to work with more sites | ## Code Before:
import re
TIME_REGEX = re.compile(
r'\A(\s*(?P<hours>\d+)\s{1}(hours|hrs|hr|h))?((?P<minutes>\s*\d+)\s{1}(minutes|mins|min|m))?\Z'
)
HTML_SYMBOLS = '\xa0' #
## Instruction:
Update time_regex captcher so to work with more sites
## Code After:
import re
TIME_REGEX = re.compile(
r'\A(\s*(?P<hours>\d+)\s*(hours|hrs|hr|h))?(\s*(?P<minutes>\d+)\s*(minutes|mins|min|m))?\Z'
)
HTML_SYMBOLS = '\xa0' #
|
c0de2a081cfe9af7f6b9d39daae557d45f5d69ee | middleware/module_yaml.py | middleware/module_yaml.py | from __future__ import unicode_literals
import os
import yaml
def main(app, data):
filepath = os.path.join(app.data_dir, data.get('filename'))
with open(filepath, 'r') as f:
contents = yaml.load(f)
return contents
| from __future__ import unicode_literals
import os
import yaml
import requests
def local(app, data):
filepath = os.path.join(app.data_dir, data.get('filename'))
with open(filepath, 'r') as f:
contents = yaml.load(f)
return contents
def remote(app, data):
r = requests.get(data.get('url'))
contents = yaml.load(r.data)
return contents
def main(app, data):
if data.get('filename'):
return local(app, data)
if data.get('url'):
return remote(app, data)
| Allow remote and local files. | Allow remote and local files.
| Python | mit | myles/me-api,myles/me-api | from __future__ import unicode_literals
import os
import yaml
+ import requests
- def main(app, data):
+ def local(app, data):
filepath = os.path.join(app.data_dir, data.get('filename'))
with open(filepath, 'r') as f:
contents = yaml.load(f)
return contents
+
+ def remote(app, data):
+ r = requests.get(data.get('url'))
+
+ contents = yaml.load(r.data)
+
+ return contents
+
+
+ def main(app, data):
+ if data.get('filename'):
+ return local(app, data)
+
+ if data.get('url'):
+ return remote(app, data)
+ | Allow remote and local files. | ## Code Before:
from __future__ import unicode_literals
import os
import yaml
def main(app, data):
filepath = os.path.join(app.data_dir, data.get('filename'))
with open(filepath, 'r') as f:
contents = yaml.load(f)
return contents
## Instruction:
Allow remote and local files.
## Code After:
from __future__ import unicode_literals
import os
import yaml
import requests
def local(app, data):
filepath = os.path.join(app.data_dir, data.get('filename'))
with open(filepath, 'r') as f:
contents = yaml.load(f)
return contents
def remote(app, data):
r = requests.get(data.get('url'))
contents = yaml.load(r.data)
return contents
def main(app, data):
if data.get('filename'):
return local(app, data)
if data.get('url'):
return remote(app, data)
|
2c8351ff8691eb9ad3009d316d932528d6f5c57d | runtests.py | runtests.py | import sys
import os
import django
from django.conf import settings
from django.core.management import call_command
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
opts = {'INSTALLED_APPS': ['widget_tweaks']}
if django.VERSION[:2] < (1, 5):
opts['DATABASES'] = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':MEMORY:',
}
}
if django.VERSION[:2] >= (1, 10):
opts['TEMPLATES'] = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
},
]
settings.configure(**opts)
if django.VERSION[:2] >= (1, 7):
django.setup()
if __name__ == "__main__":
call_command('test', 'widget_tweaks')
| import sys
import os
import django
from django.conf import settings
from django.core.management import call_command
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
opts = {'INSTALLED_APPS': ['widget_tweaks']}
if django.VERSION[:2] < (1, 5):
opts['DATABASES'] = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':MEMORY:',
}
}
if django.VERSION[:2] >= (1, 10):
opts['TEMPLATES'] = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
},
]
settings.configure(**opts)
if django.VERSION[:2] >= (1, 7):
django.setup()
if __name__ == "__main__":
call_command('test', 'widget_tweaks', verbosity=2)
| Add more verbosity on test running | :lipstick: Add more verbosity on test running
| Python | mit | kmike/django-widget-tweaks,daniboy/django-widget-tweaks | import sys
import os
import django
from django.conf import settings
from django.core.management import call_command
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
opts = {'INSTALLED_APPS': ['widget_tweaks']}
if django.VERSION[:2] < (1, 5):
opts['DATABASES'] = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':MEMORY:',
}
}
if django.VERSION[:2] >= (1, 10):
opts['TEMPLATES'] = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
},
]
settings.configure(**opts)
if django.VERSION[:2] >= (1, 7):
django.setup()
if __name__ == "__main__":
- call_command('test', 'widget_tweaks')
+ call_command('test', 'widget_tweaks', verbosity=2)
| Add more verbosity on test running | ## Code Before:
import sys
import os
import django
from django.conf import settings
from django.core.management import call_command
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
opts = {'INSTALLED_APPS': ['widget_tweaks']}
if django.VERSION[:2] < (1, 5):
opts['DATABASES'] = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':MEMORY:',
}
}
if django.VERSION[:2] >= (1, 10):
opts['TEMPLATES'] = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
},
]
settings.configure(**opts)
if django.VERSION[:2] >= (1, 7):
django.setup()
if __name__ == "__main__":
call_command('test', 'widget_tweaks')
## Instruction:
Add more verbosity on test running
## Code After:
import sys
import os
import django
from django.conf import settings
from django.core.management import call_command
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
opts = {'INSTALLED_APPS': ['widget_tweaks']}
if django.VERSION[:2] < (1, 5):
opts['DATABASES'] = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':MEMORY:',
}
}
if django.VERSION[:2] >= (1, 10):
opts['TEMPLATES'] = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
},
]
settings.configure(**opts)
if django.VERSION[:2] >= (1, 7):
django.setup()
if __name__ == "__main__":
call_command('test', 'widget_tweaks', verbosity=2)
|
4359a9947c1d86d9e4003c1e8fc358e9a66c6b1d | DisplayAdapter/display_adapter/scripts/init_db.py | DisplayAdapter/display_adapter/scripts/init_db.py | __author__ = 'richard'
| import sys
import sqlite3
from display_adapter import db_name
help_message = """
This initialises an sqlite3 db for the purposes of the DisplayAdapter programs.
Arguments: init_db.py database_name
"""
runs_table = """
CREATE TABLE runs (
id INTEGER NOT NULL,
input_pattern VARCHAR,
time_slot DATETIME,
user_name VARCHAR(50),
PRIMARY KEY (id)
)
"""
screensavers_table = """
CREATE TABLE screensavers (
pattern VARCHAR
)
"""
def init_db(db_name=db_name):
"""
This function takes a database name and creates the database required
for the DisplayAdapter programs
"""
con = sqlite3.connect(db_name)
cur = con.cursor()
cur.execute(runs_table)
cur.execute(screensavers_table)
con.commit()
con.close()
if __name__ == "__main__":
if len(sys.argv) < 2:
if sys.argv[1].lower() == "help":
print(help_message)
else:
init_db(sys.argv[1])
else:
init_db() | Create internal db initialisation script | Create internal db initialisation script
Paired by Michael and Richard
| Python | mit | CO600GOL/Game_of_life,CO600GOL/Game_of_life,CO600GOL/Game_of_life | - __author__ = 'richard'
+ import sys
+ import sqlite3
+ from display_adapter import db_name
+ help_message = """
+ This initialises an sqlite3 db for the purposes of the DisplayAdapter programs.
+
+ Arguments: init_db.py database_name
+ """
+
+ runs_table = """
+ CREATE TABLE runs (
+ id INTEGER NOT NULL,
+ input_pattern VARCHAR,
+ time_slot DATETIME,
+ user_name VARCHAR(50),
+ PRIMARY KEY (id)
+ )
+ """
+
+ screensavers_table = """
+ CREATE TABLE screensavers (
+ pattern VARCHAR
+ )
+ """
+
+
+ def init_db(db_name=db_name):
+ """
+ This function takes a database name and creates the database required
+ for the DisplayAdapter programs
+ """
+ con = sqlite3.connect(db_name)
+ cur = con.cursor()
+
+ cur.execute(runs_table)
+ cur.execute(screensavers_table)
+
+ con.commit()
+ con.close()
+
+
+ if __name__ == "__main__":
+ if len(sys.argv) < 2:
+ if sys.argv[1].lower() == "help":
+ print(help_message)
+ else:
+ init_db(sys.argv[1])
+ else:
+ init_db() | Create internal db initialisation script | ## Code Before:
__author__ = 'richard'
## Instruction:
Create internal db initialisation script
## Code After:
import sys
import sqlite3
from display_adapter import db_name
help_message = """
This initialises an sqlite3 db for the purposes of the DisplayAdapter programs.
Arguments: init_db.py database_name
"""
runs_table = """
CREATE TABLE runs (
id INTEGER NOT NULL,
input_pattern VARCHAR,
time_slot DATETIME,
user_name VARCHAR(50),
PRIMARY KEY (id)
)
"""
screensavers_table = """
CREATE TABLE screensavers (
pattern VARCHAR
)
"""
def init_db(db_name=db_name):
"""
This function takes a database name and creates the database required
for the DisplayAdapter programs
"""
con = sqlite3.connect(db_name)
cur = con.cursor()
cur.execute(runs_table)
cur.execute(screensavers_table)
con.commit()
con.close()
if __name__ == "__main__":
if len(sys.argv) < 2:
if sys.argv[1].lower() == "help":
print(help_message)
else:
init_db(sys.argv[1])
else:
init_db() |
4e9dfbaff5a91af75e3b18e6b4e06379747c6083 | research_pyutils/__init__.py | research_pyutils/__init__.py | from .path_related import (mkdir_p, rm_if_exists, remove_empty_paths,
copy_contents_of_folder, count_files,
copy_the_previous_if_missing,
folders_last_modification)
try:
from .menpo_related import (resize_all_images, from_ln_to_bb_path,
process_lns_path, compute_overlap,
rasterize_all_lns, flip_images)
except ImportError:
m1 = ('The menpo related utils are not imported. If '
'you intended to use them please check your '
'menpo installation.')
print(m1)
from .filenames_changes import (rename_files, change_suffix,
strip_filenames)
from .auxiliary import (execution_stats, compare_python_types,
whoami, populate_visual_options)
| from .path_related import (mkdir_p, rm_if_exists, remove_empty_paths,
copy_contents_of_folder, count_files,
copy_the_previous_if_missing,
folders_last_modification)
try:
from .menpo_related import (resize_all_images, from_ln_to_bb_path,
process_lns_path, compute_overlap,
rasterize_all_lns, flip_images,
check_if_greyscale_values)
except ImportError:
m1 = ('The menpo related utils are not imported. If '
'you intended to use them please check your '
'menpo installation.')
print(m1)
from .filenames_changes import (rename_files, change_suffix,
strip_filenames)
from .auxiliary import (execution_stats, compare_python_types,
whoami, populate_visual_options)
| Add in the init the newly introduced function | Add in the init the newly introduced function
| Python | apache-2.0 | grigorisg9gr/pyutils,grigorisg9gr/pyutils | from .path_related import (mkdir_p, rm_if_exists, remove_empty_paths,
copy_contents_of_folder, count_files,
copy_the_previous_if_missing,
folders_last_modification)
try:
from .menpo_related import (resize_all_images, from_ln_to_bb_path,
process_lns_path, compute_overlap,
- rasterize_all_lns, flip_images)
+ rasterize_all_lns, flip_images,
+ check_if_greyscale_values)
except ImportError:
m1 = ('The menpo related utils are not imported. If '
'you intended to use them please check your '
'menpo installation.')
print(m1)
from .filenames_changes import (rename_files, change_suffix,
strip_filenames)
from .auxiliary import (execution_stats, compare_python_types,
whoami, populate_visual_options)
| Add in the init the newly introduced function | ## Code Before:
from .path_related import (mkdir_p, rm_if_exists, remove_empty_paths,
copy_contents_of_folder, count_files,
copy_the_previous_if_missing,
folders_last_modification)
try:
from .menpo_related import (resize_all_images, from_ln_to_bb_path,
process_lns_path, compute_overlap,
rasterize_all_lns, flip_images)
except ImportError:
m1 = ('The menpo related utils are not imported. If '
'you intended to use them please check your '
'menpo installation.')
print(m1)
from .filenames_changes import (rename_files, change_suffix,
strip_filenames)
from .auxiliary import (execution_stats, compare_python_types,
whoami, populate_visual_options)
## Instruction:
Add in the init the newly introduced function
## Code After:
from .path_related import (mkdir_p, rm_if_exists, remove_empty_paths,
copy_contents_of_folder, count_files,
copy_the_previous_if_missing,
folders_last_modification)
try:
from .menpo_related import (resize_all_images, from_ln_to_bb_path,
process_lns_path, compute_overlap,
rasterize_all_lns, flip_images,
check_if_greyscale_values)
except ImportError:
m1 = ('The menpo related utils are not imported. If '
'you intended to use them please check your '
'menpo installation.')
print(m1)
from .filenames_changes import (rename_files, change_suffix,
strip_filenames)
from .auxiliary import (execution_stats, compare_python_types,
whoami, populate_visual_options)
|
76c87d06efaac19350d870cd1c95229ed0a66c29 | editdistance/__init__.py | editdistance/__init__.py | from .bycython import eval
__all__ = ('eval',)
| from .bycython import eval
def distance(*args, **kwargs):
""""An alias to eval"""
return eval(*args, **kwargs)
__all__ = ('eval', 'distance')
| Add alias method named "distance" | Add alias method named "distance"
| Python | mit | aflc/editdistance,aflc/editdistance,aflc/editdistance | from .bycython import eval
- __all__ = ('eval',)
+
+ def distance(*args, **kwargs):
+ """"An alias to eval"""
+ return eval(*args, **kwargs)
+
+
+ __all__ = ('eval', 'distance')
+ | Add alias method named "distance" | ## Code Before:
from .bycython import eval
__all__ = ('eval',)
## Instruction:
Add alias method named "distance"
## Code After:
from .bycython import eval
def distance(*args, **kwargs):
""""An alias to eval"""
return eval(*args, **kwargs)
__all__ = ('eval', 'distance')
|
aff77b144c1a1895c9e8c0ca2d4e79451525901c | terminus/models/trunk.py | terminus/models/trunk.py |
from road import Road
class Trunk(Road):
def __init__(self, name=None):
super(Trunk, self).__init__(name)
self.add_lane(2)
self.add_lane(-2)
def accept(self, generator):
generator.start_trunk(self)
for lane in self.lanes():
lane.accept(generator)
generator.end_trunk(self)
|
from road import Road
class Trunk(Road):
def __init__(self, name=None):
super(Trunk, self).__init__(name)
self.add_lane(2)
self.add_lane(-2, reversed=True)
def accept(self, generator):
generator.start_trunk(self)
for lane in self.lanes():
lane.accept(generator)
generator.end_trunk(self)
| Make Trunks have opposite directions in the included lanes | Make Trunks have opposite directions in the included lanes
| Python | apache-2.0 | ekumenlabs/terminus,ekumenlabs/terminus |
from road import Road
class Trunk(Road):
def __init__(self, name=None):
super(Trunk, self).__init__(name)
self.add_lane(2)
- self.add_lane(-2)
+ self.add_lane(-2, reversed=True)
def accept(self, generator):
generator.start_trunk(self)
for lane in self.lanes():
lane.accept(generator)
generator.end_trunk(self)
| Make Trunks have opposite directions in the included lanes | ## Code Before:
from road import Road
class Trunk(Road):
def __init__(self, name=None):
super(Trunk, self).__init__(name)
self.add_lane(2)
self.add_lane(-2)
def accept(self, generator):
generator.start_trunk(self)
for lane in self.lanes():
lane.accept(generator)
generator.end_trunk(self)
## Instruction:
Make Trunks have opposite directions in the included lanes
## Code After:
from road import Road
class Trunk(Road):
def __init__(self, name=None):
super(Trunk, self).__init__(name)
self.add_lane(2)
self.add_lane(-2, reversed=True)
def accept(self, generator):
generator.start_trunk(self)
for lane in self.lanes():
lane.accept(generator)
generator.end_trunk(self)
|
e8940b632737f75897c0ea7c108563a63f1a5dde | transducer/test/test_functional.py | transducer/test/test_functional.py | import unittest
from transducer.functional import compose
class TestComposition(unittest.TestCase):
def test_single(self):
"""
compose(f)(x) -> f(x)
"""
f = lambda x: x * 2
c = compose(f)
# We can't test the equivalence of functions completely, so...
self.assertSequenceEqual([f(x) for x in range(1000)],
[c(x) for x in range(1000)])
def test_double(self):
"""
compose(f, g)(x) -> f(g(x))
"""
f = lambda x: x * 2
g = lambda x: x + 1
c = compose(f, g)
self.assertSequenceEqual([f(g(x)) for x in range(100)],
[c(x) for x in range(100)])
def test_triple(self):
"""
compose(f, g, h)(x) -> f(g(h(x)))
"""
f = lambda x: x * 2
g = lambda x: x + 1
h = lambda x: x - 7
c = compose(f, g, h)
self.assertSequenceEqual([f(g(h(x))) for x in range(100)],
[c(x) for x in range(100)])
if __name__ == '__main__':
unittest.main()
| import unittest
from transducer.functional import compose, true, identity, false
class TestComposition(unittest.TestCase):
def test_single(self):
"""
compose(f)(x) -> f(x)
"""
f = lambda x: x * 2
c = compose(f)
# We can't test the equivalence of functions completely, so...
self.assertSequenceEqual([f(x) for x in range(1000)],
[c(x) for x in range(1000)])
def test_double(self):
"""
compose(f, g)(x) -> f(g(x))
"""
f = lambda x: x * 2
g = lambda x: x + 1
c = compose(f, g)
self.assertSequenceEqual([f(g(x)) for x in range(100)],
[c(x) for x in range(100)])
def test_triple(self):
"""
compose(f, g, h)(x) -> f(g(h(x)))
"""
f = lambda x: x * 2
g = lambda x: x + 1
h = lambda x: x - 7
c = compose(f, g, h)
self.assertSequenceEqual([f(g(h(x))) for x in range(100)],
[c(x) for x in range(100)])
class TestFunctions(unittest.TestCase):
def test_true(self):
self.assertTrue(true())
def test_false(self):
self.assertFalse(false())
def test_identity(self):
self.assertEqual(identity(42), 42)
if __name__ == '__main__':
unittest.main()
| Improve test coverage of functional.py. | Improve test coverage of functional.py.
| Python | mit | sixty-north/python-transducers | import unittest
- from transducer.functional import compose
+ from transducer.functional import compose, true, identity, false
class TestComposition(unittest.TestCase):
def test_single(self):
"""
compose(f)(x) -> f(x)
"""
f = lambda x: x * 2
c = compose(f)
# We can't test the equivalence of functions completely, so...
self.assertSequenceEqual([f(x) for x in range(1000)],
[c(x) for x in range(1000)])
def test_double(self):
"""
compose(f, g)(x) -> f(g(x))
"""
f = lambda x: x * 2
g = lambda x: x + 1
c = compose(f, g)
self.assertSequenceEqual([f(g(x)) for x in range(100)],
[c(x) for x in range(100)])
-
def test_triple(self):
"""
compose(f, g, h)(x) -> f(g(h(x)))
"""
f = lambda x: x * 2
g = lambda x: x + 1
h = lambda x: x - 7
c = compose(f, g, h)
self.assertSequenceEqual([f(g(h(x))) for x in range(100)],
[c(x) for x in range(100)])
+ class TestFunctions(unittest.TestCase):
+
+ def test_true(self):
+ self.assertTrue(true())
+
+ def test_false(self):
+ self.assertFalse(false())
+
+ def test_identity(self):
+ self.assertEqual(identity(42), 42)
+
+
if __name__ == '__main__':
unittest.main()
| Improve test coverage of functional.py. | ## Code Before:
import unittest
from transducer.functional import compose
class TestComposition(unittest.TestCase):
def test_single(self):
"""
compose(f)(x) -> f(x)
"""
f = lambda x: x * 2
c = compose(f)
# We can't test the equivalence of functions completely, so...
self.assertSequenceEqual([f(x) for x in range(1000)],
[c(x) for x in range(1000)])
def test_double(self):
"""
compose(f, g)(x) -> f(g(x))
"""
f = lambda x: x * 2
g = lambda x: x + 1
c = compose(f, g)
self.assertSequenceEqual([f(g(x)) for x in range(100)],
[c(x) for x in range(100)])
def test_triple(self):
"""
compose(f, g, h)(x) -> f(g(h(x)))
"""
f = lambda x: x * 2
g = lambda x: x + 1
h = lambda x: x - 7
c = compose(f, g, h)
self.assertSequenceEqual([f(g(h(x))) for x in range(100)],
[c(x) for x in range(100)])
if __name__ == '__main__':
unittest.main()
## Instruction:
Improve test coverage of functional.py.
## Code After:
import unittest
from transducer.functional import compose, true, identity, false
class TestComposition(unittest.TestCase):
def test_single(self):
"""
compose(f)(x) -> f(x)
"""
f = lambda x: x * 2
c = compose(f)
# We can't test the equivalence of functions completely, so...
self.assertSequenceEqual([f(x) for x in range(1000)],
[c(x) for x in range(1000)])
def test_double(self):
"""
compose(f, g)(x) -> f(g(x))
"""
f = lambda x: x * 2
g = lambda x: x + 1
c = compose(f, g)
self.assertSequenceEqual([f(g(x)) for x in range(100)],
[c(x) for x in range(100)])
def test_triple(self):
"""
compose(f, g, h)(x) -> f(g(h(x)))
"""
f = lambda x: x * 2
g = lambda x: x + 1
h = lambda x: x - 7
c = compose(f, g, h)
self.assertSequenceEqual([f(g(h(x))) for x in range(100)],
[c(x) for x in range(100)])
class TestFunctions(unittest.TestCase):
def test_true(self):
self.assertTrue(true())
def test_false(self):
self.assertFalse(false())
def test_identity(self):
self.assertEqual(identity(42), 42)
if __name__ == '__main__':
unittest.main()
|
2408c5260106e050557b4898d5826932eb758142 | normandy/selfrepair/views.py | normandy/selfrepair/views.py | from django.shortcuts import render
from normandy.base.decorators import api_cache_control
@api_cache_control()
def repair(request, locale):
return render(request, "selfrepair/repair.html")
| from django.shortcuts import render
from django.views.decorators.cache import cache_control
ONE_WEEK_IN_SECONDS = 60 * 60 * 24 * 7
@cache_control(public=True, max_age=ONE_WEEK_IN_SECONDS)
def repair(request, locale):
return render(request, "selfrepair/repair.html")
| Increase cache on deprecated self-repair to one week | Increase cache on deprecated self-repair to one week
This view serves a message that the system is no longer active. We keep
it around because it is still gets about 40 million hits per day,
primarily from Firefox ESR 52, which never got the Normandy client.
Notably, when we dropped support for Windows XP from Firefox, we put all
XP users onto ESR 52, so we are not likely to be able to remove this
endpoint any time soon.
Fixes #1563
| Python | mpl-2.0 | mozilla/normandy,mozilla/normandy,mozilla/normandy,mozilla/normandy | from django.shortcuts import render
-
- from normandy.base.decorators import api_cache_control
+ from django.views.decorators.cache import cache_control
- @api_cache_control()
+ ONE_WEEK_IN_SECONDS = 60 * 60 * 24 * 7
+
+
+ @cache_control(public=True, max_age=ONE_WEEK_IN_SECONDS)
def repair(request, locale):
return render(request, "selfrepair/repair.html")
| Increase cache on deprecated self-repair to one week | ## Code Before:
from django.shortcuts import render
from normandy.base.decorators import api_cache_control
@api_cache_control()
def repair(request, locale):
return render(request, "selfrepair/repair.html")
## Instruction:
Increase cache on deprecated self-repair to one week
## Code After:
from django.shortcuts import render
from django.views.decorators.cache import cache_control
ONE_WEEK_IN_SECONDS = 60 * 60 * 24 * 7
@cache_control(public=True, max_age=ONE_WEEK_IN_SECONDS)
def repair(request, locale):
return render(request, "selfrepair/repair.html")
|
dd260182bd8157fd6ac2a266b3ae5cf168400266 | tests/custom_keywords.py | tests/custom_keywords.py | import os
from raven import Client
def generate_event(msg, dsn):
client = Client(dsn)
client.captureMessage(msg)
def clear_inbox(maildir):
print('Clearing inbox at {}'.format(maildir))
for fname in os.listdir(maildir):
os.remove(os.path.join(maildir, fname))
def inbox_should_contain_num_mails(maildir, count):
print('Testing if inbox at {} has {} items.'.format(maildir, count))
count = int(count)
nmails = len(os.listdir(maildir))
if nmails != count:
raise AssertionError(
'Inbox should contain {} messages, but has {}.'.format(
count, nmails)
)
def mail_should_contain_text(maildir, num, text):
print('Testing if mail {} in {} contains text {}.'.format(
num, maildir, text))
mails = os.listdir(maildir)
num = int(num)
if len(mails) < num:
raise AssertionError('Not enough mails in inbox (found {}).'.format(len(mails)))
fname = mails[num - 1]
with open(os.path.join(maildir, fname)) as f:
content = f.read()
if not text in content:
raise AssertionError('Mail does not contain text.')
| import os
from raven import Client
def generate_event(msg, dsn):
client = Client(dsn)
client.captureMessage(msg)
def clear_inbox(maildir):
print('Clearing inbox at {}'.format(maildir))
if not os.path.isdir(maildir):
return
for fname in os.listdir(maildir):
os.remove(os.path.join(maildir, fname))
def inbox_should_contain_num_mails(maildir, count):
print('Testing if inbox at {} has {} items.'.format(maildir, count))
count = int(count)
nmails = len(os.listdir(maildir))
if nmails != count:
raise AssertionError(
'Inbox should contain {} messages, but has {}.'.format(
count, nmails)
)
def mail_should_contain_text(maildir, num, text):
print('Testing if mail {} in {} contains text {}.'.format(
num, maildir, text))
mails = os.listdir(maildir)
num = int(num)
if len(mails) < num:
raise AssertionError('Not enough mails in inbox (found {}).'.format(len(mails)))
fname = mails[num - 1]
with open(os.path.join(maildir, fname)) as f:
content = f.read()
if not text in content:
raise AssertionError('Mail does not contain text.')
| Make Clear Inbox keyword more robust. | Make Clear Inbox keyword more robust.
| Python | bsd-3-clause | andialbrecht/sentry-comments,andialbrecht/sentry-comments | import os
from raven import Client
def generate_event(msg, dsn):
client = Client(dsn)
client.captureMessage(msg)
def clear_inbox(maildir):
print('Clearing inbox at {}'.format(maildir))
+ if not os.path.isdir(maildir):
+ return
for fname in os.listdir(maildir):
os.remove(os.path.join(maildir, fname))
def inbox_should_contain_num_mails(maildir, count):
print('Testing if inbox at {} has {} items.'.format(maildir, count))
count = int(count)
nmails = len(os.listdir(maildir))
if nmails != count:
raise AssertionError(
'Inbox should contain {} messages, but has {}.'.format(
count, nmails)
)
def mail_should_contain_text(maildir, num, text):
print('Testing if mail {} in {} contains text {}.'.format(
num, maildir, text))
mails = os.listdir(maildir)
num = int(num)
if len(mails) < num:
raise AssertionError('Not enough mails in inbox (found {}).'.format(len(mails)))
fname = mails[num - 1]
with open(os.path.join(maildir, fname)) as f:
content = f.read()
if not text in content:
raise AssertionError('Mail does not contain text.')
| Make Clear Inbox keyword more robust. | ## Code Before:
import os
from raven import Client
def generate_event(msg, dsn):
client = Client(dsn)
client.captureMessage(msg)
def clear_inbox(maildir):
print('Clearing inbox at {}'.format(maildir))
for fname in os.listdir(maildir):
os.remove(os.path.join(maildir, fname))
def inbox_should_contain_num_mails(maildir, count):
print('Testing if inbox at {} has {} items.'.format(maildir, count))
count = int(count)
nmails = len(os.listdir(maildir))
if nmails != count:
raise AssertionError(
'Inbox should contain {} messages, but has {}.'.format(
count, nmails)
)
def mail_should_contain_text(maildir, num, text):
print('Testing if mail {} in {} contains text {}.'.format(
num, maildir, text))
mails = os.listdir(maildir)
num = int(num)
if len(mails) < num:
raise AssertionError('Not enough mails in inbox (found {}).'.format(len(mails)))
fname = mails[num - 1]
with open(os.path.join(maildir, fname)) as f:
content = f.read()
if not text in content:
raise AssertionError('Mail does not contain text.')
## Instruction:
Make Clear Inbox keyword more robust.
## Code After:
import os
from raven import Client
def generate_event(msg, dsn):
client = Client(dsn)
client.captureMessage(msg)
def clear_inbox(maildir):
print('Clearing inbox at {}'.format(maildir))
if not os.path.isdir(maildir):
return
for fname in os.listdir(maildir):
os.remove(os.path.join(maildir, fname))
def inbox_should_contain_num_mails(maildir, count):
print('Testing if inbox at {} has {} items.'.format(maildir, count))
count = int(count)
nmails = len(os.listdir(maildir))
if nmails != count:
raise AssertionError(
'Inbox should contain {} messages, but has {}.'.format(
count, nmails)
)
def mail_should_contain_text(maildir, num, text):
print('Testing if mail {} in {} contains text {}.'.format(
num, maildir, text))
mails = os.listdir(maildir)
num = int(num)
if len(mails) < num:
raise AssertionError('Not enough mails in inbox (found {}).'.format(len(mails)))
fname = mails[num - 1]
with open(os.path.join(maildir, fname)) as f:
content = f.read()
if not text in content:
raise AssertionError('Mail does not contain text.')
|
114f40dd282d1837db42ffb6625760d1483d3192 | jfu/templatetags/jfutags.py | jfu/templatetags/jfutags.py | from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.template import Library, Context, loader
register = Library()
@register.simple_tag( takes_context = True )
def jfu(
context,
template_name = 'jfu/upload_form.html',
upload_handler_name = 'jfu_upload'
):
"""
Displays a form for uploading files using jQuery File Upload.
A user may supply both a custom template or a custom upload-handling URL
name by supplying values for template_name and upload_handler_name
respectively.
"""
context.update( {
'JQ_OPEN' : '{%',
'JQ_CLOSE' : '%}',
'upload_handler_url': reverse( upload_handler_name ),
} )
# Use the request context variable, injected
# by django.core.context_processors.request
# to generate the CSRF token.
context.update( csrf( context.get('request') ) )
t = loader.get_template( template_name )
return t.render( Context( context ) )
| from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.template import Library, Context, loader
register = Library()
@register.simple_tag( takes_context = True )
def jfu(
context,
template_name = 'jfu/upload_form.html',
upload_handler_name = 'jfu_upload',
*args, **kwargs
):
"""
Displays a form for uploading files using jQuery File Upload.
A user may supply both a custom template or a custom upload-handling URL
name by supplying values for template_name and upload_handler_name
respectively.
"""
context.update( {
'JQ_OPEN' : '{%',
'JQ_CLOSE' : '%}',
'upload_handler_url': reverse( upload_handler_name, kwargs=kwargs, args=args ),
} )
# Use the request context variable, injected
# by django.core.context_processors.request
# to generate the CSRF token.
context.update( csrf( context.get('request') ) )
t = loader.get_template( template_name )
return t.render( Context( context ) )
| Allow args and kwargs to upload_handler_name | Allow args and kwargs to upload_handler_name
Now can use args and kwargs for reverse url. Example in template:
{% jfu 'core/core_fileuploader.html' 'core_upload' object_id=1 content_type_str='app.model' %} | Python | bsd-3-clause | Alem/django-jfu,dzhuang/django-jfu,Alem/django-jfu,dzhuang/django-jfu,Alem/django-jfu,dzhuang/django-jfu,dzhuang/django-jfu,Alem/django-jfu | from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.template import Library, Context, loader
register = Library()
@register.simple_tag( takes_context = True )
def jfu(
context,
template_name = 'jfu/upload_form.html',
- upload_handler_name = 'jfu_upload'
+ upload_handler_name = 'jfu_upload',
+ *args, **kwargs
):
"""
Displays a form for uploading files using jQuery File Upload.
A user may supply both a custom template or a custom upload-handling URL
name by supplying values for template_name and upload_handler_name
respectively.
"""
context.update( {
'JQ_OPEN' : '{%',
'JQ_CLOSE' : '%}',
- 'upload_handler_url': reverse( upload_handler_name ),
+ 'upload_handler_url': reverse( upload_handler_name, kwargs=kwargs, args=args ),
} )
# Use the request context variable, injected
# by django.core.context_processors.request
# to generate the CSRF token.
context.update( csrf( context.get('request') ) )
t = loader.get_template( template_name )
return t.render( Context( context ) )
| Allow args and kwargs to upload_handler_name | ## Code Before:
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.template import Library, Context, loader
register = Library()
@register.simple_tag( takes_context = True )
def jfu(
context,
template_name = 'jfu/upload_form.html',
upload_handler_name = 'jfu_upload'
):
"""
Displays a form for uploading files using jQuery File Upload.
A user may supply both a custom template or a custom upload-handling URL
name by supplying values for template_name and upload_handler_name
respectively.
"""
context.update( {
'JQ_OPEN' : '{%',
'JQ_CLOSE' : '%}',
'upload_handler_url': reverse( upload_handler_name ),
} )
# Use the request context variable, injected
# by django.core.context_processors.request
# to generate the CSRF token.
context.update( csrf( context.get('request') ) )
t = loader.get_template( template_name )
return t.render( Context( context ) )
## Instruction:
Allow args and kwargs to upload_handler_name
## Code After:
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.template import Library, Context, loader
register = Library()
@register.simple_tag( takes_context = True )
def jfu(
context,
template_name = 'jfu/upload_form.html',
upload_handler_name = 'jfu_upload',
*args, **kwargs
):
"""
Displays a form for uploading files using jQuery File Upload.
A user may supply both a custom template or a custom upload-handling URL
name by supplying values for template_name and upload_handler_name
respectively.
"""
context.update( {
'JQ_OPEN' : '{%',
'JQ_CLOSE' : '%}',
'upload_handler_url': reverse( upload_handler_name, kwargs=kwargs, args=args ),
} )
# Use the request context variable, injected
# by django.core.context_processors.request
# to generate the CSRF token.
context.update( csrf( context.get('request') ) )
t = loader.get_template( template_name )
return t.render( Context( context ) )
|
9f3289f45c727835c8f52b0c2489b06da2f03c25 | pyglab/__init__.py | pyglab/__init__.py | __title__ = 'pyglab'
__version__ = '0.0dev'
__author__ = 'Michael Schlottke'
__license__ = 'MIT License'
__copyright__ = '(c) 2014 Michael Schlottke'
from .pyglab import Pyglab
from .apirequest import ApiRequest, RequestType
| __title__ = 'pyglab'
__version__ = '0.0dev'
__author__ = 'Michael Schlottke'
__license__ = 'MIT License'
__copyright__ = '(c) 2014 Michael Schlottke'
from .pyglab import Pyglab
from .exceptions import RequestError
from .apirequest import ApiRequest, RequestType
| Make RequestError available in package root. | Make RequestError available in package root.
| Python | mit | sloede/pyglab,sloede/pyglab | __title__ = 'pyglab'
__version__ = '0.0dev'
__author__ = 'Michael Schlottke'
__license__ = 'MIT License'
__copyright__ = '(c) 2014 Michael Schlottke'
from .pyglab import Pyglab
+ from .exceptions import RequestError
from .apirequest import ApiRequest, RequestType
| Make RequestError available in package root. | ## Code Before:
__title__ = 'pyglab'
__version__ = '0.0dev'
__author__ = 'Michael Schlottke'
__license__ = 'MIT License'
__copyright__ = '(c) 2014 Michael Schlottke'
from .pyglab import Pyglab
from .apirequest import ApiRequest, RequestType
## Instruction:
Make RequestError available in package root.
## Code After:
__title__ = 'pyglab'
__version__ = '0.0dev'
__author__ = 'Michael Schlottke'
__license__ = 'MIT License'
__copyright__ = '(c) 2014 Michael Schlottke'
from .pyglab import Pyglab
from .exceptions import RequestError
from .apirequest import ApiRequest, RequestType
|
cd2bc29837d31d8999d9f72f7ddaecddb56e26a5 | tests/unit/test_views.py | tests/unit/test_views.py | from flask import json
from nose.tools import eq_
from server import app
client = app.test_client()
def test_hello_world():
# When: I access root path
resp = client.get('/')
# Then: Expected response is returned
eq_(resp.status_code, 200)
eq_(resp.headers['Content-Type'], 'application/json')
data = json.loads(resp.data.decode())
eq_(data['message'], 'Hello Worlb!')
| from flask import json
from nose.tools import eq_
from server import app
client = app.test_client()
def test_hello_world():
# When: I access root path
resp = client.get('/')
# Then: Expected response is returned
eq_(resp.status_code, 200)
eq_(resp.headers['Content-Type'], 'application/json')
data = json.loads(resp.data.decode())
eq_(data['message'].startswith('Hello'), True)
| Use startswith instead of exact string match | Use startswith instead of exact string match
| Python | mit | agarone-mm/scholastic-demo,totem/totem-demo,risingspiral/appnexus-demo | from flask import json
from nose.tools import eq_
from server import app
client = app.test_client()
def test_hello_world():
# When: I access root path
resp = client.get('/')
# Then: Expected response is returned
eq_(resp.status_code, 200)
eq_(resp.headers['Content-Type'], 'application/json')
data = json.loads(resp.data.decode())
- eq_(data['message'], 'Hello Worlb!')
+ eq_(data['message'].startswith('Hello'), True)
| Use startswith instead of exact string match | ## Code Before:
from flask import json
from nose.tools import eq_
from server import app
client = app.test_client()
def test_hello_world():
# When: I access root path
resp = client.get('/')
# Then: Expected response is returned
eq_(resp.status_code, 200)
eq_(resp.headers['Content-Type'], 'application/json')
data = json.loads(resp.data.decode())
eq_(data['message'], 'Hello Worlb!')
## Instruction:
Use startswith instead of exact string match
## Code After:
from flask import json
from nose.tools import eq_
from server import app
client = app.test_client()
def test_hello_world():
# When: I access root path
resp = client.get('/')
# Then: Expected response is returned
eq_(resp.status_code, 200)
eq_(resp.headers['Content-Type'], 'application/json')
data = json.loads(resp.data.decode())
eq_(data['message'].startswith('Hello'), True)
|
b30d4301d58766471f435536cf804f7a63448ac5 | qotr/tests/test_server.py | qotr/tests/test_server.py | from tornado import testing
from qotr.server import make_application
from qotr.config import config
class TestChannelHandler(testing.AsyncHTTPTestCase):
'''
Test the channel creation handler.
'''
port = None
application = None
def get_app(self):
return make_application()
def test_index(self):
response = self.fetch('/')
self.assertEqual(200, response.code)
def test_channel(self):
response = self.fetch('/c/foo')
self.assertEqual(200, response.code)
def test_arbitrary(self):
response = self.fetch('/arbitrary-page')
self.assertEqual(404, response.code)
def test_https_redirect(self):
_old_cfg = config.redirect_to_https
config.redirect_to_https = True
response = self.fetch('/c/foo', follow_redirects=False)
config.redirect_to_https = _old_cfg
self.assertEqual(301, response.code)
| from tornado import testing
from qotr.server import make_application
from qotr.config import config
class TestChannelHandler(testing.AsyncHTTPTestCase):
'''
Test the channel creation handler.
'''
port = None
application = None
def get_app(self):
return make_application()
# def test_index(self):
# response = self.fetch('/')
# self.assertEqual(200, response.code)
# def test_channel(self):
# response = self.fetch('/c/foo')
# self.assertEqual(200, response.code)
# def test_arbitrary(self):
# response = self.fetch('/arbitrary-page')
# self.assertEqual(404, response.code)
def test_https_redirect(self):
_old_cfg = config.redirect_to_https
config.redirect_to_https = True
response = self.fetch('/c/foo', follow_redirects=False)
config.redirect_to_https = _old_cfg
self.assertEqual(301, response.code)
| Disable testing for index.html, needs ember build | Disable testing for index.html, needs ember build
Signed-off-by: Rohan Jain <[email protected]>
| Python | agpl-3.0 | rmoorman/qotr,rmoorman/qotr,sbuss/qotr,rmoorman/qotr,crodjer/qotr,sbuss/qotr,crodjer/qotr,sbuss/qotr,curtiszimmerman/qotr,curtiszimmerman/qotr,rmoorman/qotr,crodjer/qotr,curtiszimmerman/qotr,curtiszimmerman/qotr,sbuss/qotr,crodjer/qotr | from tornado import testing
from qotr.server import make_application
from qotr.config import config
class TestChannelHandler(testing.AsyncHTTPTestCase):
'''
Test the channel creation handler.
'''
port = None
application = None
def get_app(self):
return make_application()
+ # def test_index(self):
+ # response = self.fetch('/')
+ # self.assertEqual(200, response.code)
- def test_index(self):
+ # def test_channel(self):
- response = self.fetch('/')
+ # response = self.fetch('/c/foo')
- self.assertEqual(200, response.code)
+ # self.assertEqual(200, response.code)
- def test_channel(self):
- response = self.fetch('/c/foo')
- self.assertEqual(200, response.code)
-
- def test_arbitrary(self):
+ # def test_arbitrary(self):
- response = self.fetch('/arbitrary-page')
+ # response = self.fetch('/arbitrary-page')
- self.assertEqual(404, response.code)
+ # self.assertEqual(404, response.code)
def test_https_redirect(self):
_old_cfg = config.redirect_to_https
config.redirect_to_https = True
response = self.fetch('/c/foo', follow_redirects=False)
config.redirect_to_https = _old_cfg
self.assertEqual(301, response.code)
| Disable testing for index.html, needs ember build | ## Code Before:
from tornado import testing
from qotr.server import make_application
from qotr.config import config
class TestChannelHandler(testing.AsyncHTTPTestCase):
'''
Test the channel creation handler.
'''
port = None
application = None
def get_app(self):
return make_application()
def test_index(self):
response = self.fetch('/')
self.assertEqual(200, response.code)
def test_channel(self):
response = self.fetch('/c/foo')
self.assertEqual(200, response.code)
def test_arbitrary(self):
response = self.fetch('/arbitrary-page')
self.assertEqual(404, response.code)
def test_https_redirect(self):
_old_cfg = config.redirect_to_https
config.redirect_to_https = True
response = self.fetch('/c/foo', follow_redirects=False)
config.redirect_to_https = _old_cfg
self.assertEqual(301, response.code)
## Instruction:
Disable testing for index.html, needs ember build
## Code After:
from tornado import testing
from qotr.server import make_application
from qotr.config import config
class TestChannelHandler(testing.AsyncHTTPTestCase):
'''
Test the channel creation handler.
'''
port = None
application = None
def get_app(self):
return make_application()
# def test_index(self):
# response = self.fetch('/')
# self.assertEqual(200, response.code)
# def test_channel(self):
# response = self.fetch('/c/foo')
# self.assertEqual(200, response.code)
# def test_arbitrary(self):
# response = self.fetch('/arbitrary-page')
# self.assertEqual(404, response.code)
def test_https_redirect(self):
_old_cfg = config.redirect_to_https
config.redirect_to_https = True
response = self.fetch('/c/foo', follow_redirects=False)
config.redirect_to_https = _old_cfg
self.assertEqual(301, response.code)
|
cda81a4585d2b2be868e784566f3c804feb1e9bf | analyze.py | analyze.py | import sys
import re
def main(argv):
# Message to perform sentiment analysis on
message = argv[0] if len(argv) > 0 else ""
if message == "":
print("Usage: python analyze.py [message]")
sys.exit(1)
# Load the positive and negative words
words = {}
with open("words/positive.txt") as file:
for line in file:
words[line.rstrip()] = 1
with open("words/negative.txt") as file:
for line in file:
words[line.rstrip()] = -1
# Perform the sentiment analysis
score = 0
found = 0
for w in message.split():
# Only keep alphanumeric characters and some punctuation.
w = re.sub(r'[^\-\'+\w]', '', w).lower()
if w in words:
score += words[w]
found += 1
print(round(score / float(found) if found != 0 else 0, 2))
if __name__ == "__main__":
main(sys.argv[1:])
| import sys
import re
def main(argv):
# Load the positive and negative words
words = {}
with open("words/positive.txt") as file:
for line in file:
words[line.rstrip()] = 1
with open("words/negative.txt") as file:
for line in file:
words[line.rstrip()] = -1
# Perform the sentiment analysis
for message in sys.stdin:
score = 0
found = 0
for w in message.split():
# Only keep alphanumeric characters and some punctuation.
w = re.sub(r'[^\-\'+\w]', '', w).lower()
if w in words:
score += words[w]
found += 1
print(round(score / float(found) if found != 0 else 0, 2))
if __name__ == "__main__":
main(sys.argv[1:])
| Read from standard input and perform on each line | Read from standard input and perform on each line
The analyze script can now be run with, for example
- echo "Message" | python analyze.py
- cat | python analyze.py (enter messages and end with Ctrl-D)
- python analyze.py < filename
- MapReduce (at some point)
| Python | mit | timvandermeij/sentiment-analysis,timvandermeij/sentiment-analysis | import sys
import re
def main(argv):
- # Message to perform sentiment analysis on
- message = argv[0] if len(argv) > 0 else ""
-
- if message == "":
- print("Usage: python analyze.py [message]")
- sys.exit(1)
-
# Load the positive and negative words
words = {}
with open("words/positive.txt") as file:
for line in file:
words[line.rstrip()] = 1
with open("words/negative.txt") as file:
for line in file:
words[line.rstrip()] = -1
# Perform the sentiment analysis
+ for message in sys.stdin:
- score = 0
+ score = 0
- found = 0
+ found = 0
- for w in message.split():
+ for w in message.split():
- # Only keep alphanumeric characters and some punctuation.
+ # Only keep alphanumeric characters and some punctuation.
- w = re.sub(r'[^\-\'+\w]', '', w).lower()
+ w = re.sub(r'[^\-\'+\w]', '', w).lower()
- if w in words:
+ if w in words:
- score += words[w]
+ score += words[w]
- found += 1
+ found += 1
- print(round(score / float(found) if found != 0 else 0, 2))
+ print(round(score / float(found) if found != 0 else 0, 2))
if __name__ == "__main__":
main(sys.argv[1:])
| Read from standard input and perform on each line | ## Code Before:
import sys
import re
def main(argv):
# Message to perform sentiment analysis on
message = argv[0] if len(argv) > 0 else ""
if message == "":
print("Usage: python analyze.py [message]")
sys.exit(1)
# Load the positive and negative words
words = {}
with open("words/positive.txt") as file:
for line in file:
words[line.rstrip()] = 1
with open("words/negative.txt") as file:
for line in file:
words[line.rstrip()] = -1
# Perform the sentiment analysis
score = 0
found = 0
for w in message.split():
# Only keep alphanumeric characters and some punctuation.
w = re.sub(r'[^\-\'+\w]', '', w).lower()
if w in words:
score += words[w]
found += 1
print(round(score / float(found) if found != 0 else 0, 2))
if __name__ == "__main__":
main(sys.argv[1:])
## Instruction:
Read from standard input and perform on each line
## Code After:
import sys
import re
def main(argv):
# Load the positive and negative words
words = {}
with open("words/positive.txt") as file:
for line in file:
words[line.rstrip()] = 1
with open("words/negative.txt") as file:
for line in file:
words[line.rstrip()] = -1
# Perform the sentiment analysis
for message in sys.stdin:
score = 0
found = 0
for w in message.split():
# Only keep alphanumeric characters and some punctuation.
w = re.sub(r'[^\-\'+\w]', '', w).lower()
if w in words:
score += words[w]
found += 1
print(round(score / float(found) if found != 0 else 0, 2))
if __name__ == "__main__":
main(sys.argv[1:])
|
ac3c0e93adf35015d7f6cfc8c6cf2e6ec45cdeae | server/canonicalization/relationship_mapper.py | server/canonicalization/relationship_mapper.py | """Contains functions to canonicalize relationships."""
from __future__ import absolute_import
from __future__ import print_function
from nltk.corpus import wordnet
from .utils import wordnet_helper
from .utils import common
def canonicalize_relationship(text):
words = common.clean_text(text).split()
freq = []
for word in words:
for pos in [wordnet.VERB, wordnet.ADV]:
freq.extend(wordnet_helper.lemma_counter(word,
pos=pos).most_common())
if freq:
return max(freq, key=lambda x: x[1])[0]
else:
return None
| """Contains functions to canonicalize relationships."""
from __future__ import absolute_import
from __future__ import print_function
import repoze.lru
from nltk.corpus import wordnet
from .utils import wordnet_helper
from .utils import common
@repoze.lru.lru_cache(4096)
def canonicalize_relationship(text):
words = common.clean_text(text).split()
freq = []
for word in words:
for pos in [wordnet.VERB, wordnet.ADV]:
freq.extend(wordnet_helper.lemma_counter(word,
pos=pos).most_common())
if freq:
return max(freq, key=lambda x: x[1])[0]
else:
return None
| Add LRU for relationship mapper. | [master] Add LRU for relationship mapper.
| Python | mit | hotpxl/canonicalization-server,hotpxl/canonicalization-server | """Contains functions to canonicalize relationships."""
from __future__ import absolute_import
from __future__ import print_function
+ import repoze.lru
from nltk.corpus import wordnet
from .utils import wordnet_helper
from .utils import common
+ @repoze.lru.lru_cache(4096)
def canonicalize_relationship(text):
words = common.clean_text(text).split()
freq = []
for word in words:
for pos in [wordnet.VERB, wordnet.ADV]:
freq.extend(wordnet_helper.lemma_counter(word,
pos=pos).most_common())
if freq:
return max(freq, key=lambda x: x[1])[0]
else:
return None
| Add LRU for relationship mapper. | ## Code Before:
"""Contains functions to canonicalize relationships."""
from __future__ import absolute_import
from __future__ import print_function
from nltk.corpus import wordnet
from .utils import wordnet_helper
from .utils import common
def canonicalize_relationship(text):
words = common.clean_text(text).split()
freq = []
for word in words:
for pos in [wordnet.VERB, wordnet.ADV]:
freq.extend(wordnet_helper.lemma_counter(word,
pos=pos).most_common())
if freq:
return max(freq, key=lambda x: x[1])[0]
else:
return None
## Instruction:
Add LRU for relationship mapper.
## Code After:
"""Contains functions to canonicalize relationships."""
from __future__ import absolute_import
from __future__ import print_function
import repoze.lru
from nltk.corpus import wordnet
from .utils import wordnet_helper
from .utils import common
@repoze.lru.lru_cache(4096)
def canonicalize_relationship(text):
words = common.clean_text(text).split()
freq = []
for word in words:
for pos in [wordnet.VERB, wordnet.ADV]:
freq.extend(wordnet_helper.lemma_counter(word,
pos=pos).most_common())
if freq:
return max(freq, key=lambda x: x[1])[0]
else:
return None
|
452924faafcfb4dcb1eb960ea30ab000f1f93962 | migrations/versions/0245_archived_flag_jobs.py | migrations/versions/0245_archived_flag_jobs.py | from alembic import op
import sqlalchemy as sa
revision = '0245_archived_flag_jobs'
down_revision = '0244_another_letter_org'
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('jobs', sa.Column('archived', sa.Boolean(), nullable=False, server_default=sa.false()))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('jobs', 'archived')
# ### end Alembic commands ###
| from alembic import op
import sqlalchemy as sa
revision = '0245_archived_flag_jobs'
down_revision = '0244_another_letter_org'
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('jobs', sa.Column('archived', sa.Boolean(), nullable=True))
op.execute('update jobs set archived = false')
op.alter_column('jobs', 'archived', nullable=False, server_default=sa.false())
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('jobs', 'archived')
# ### end Alembic commands ###
| Update jobs archived flag before setting the default value | Update jobs archived flag before setting the default value
Running an update before setting the column default value reduces
the time the table is locked (since most rows don't have a NULL
value anymore), but the migration takes slightly longer to run
overall.
| Python | mit | alphagov/notifications-api,alphagov/notifications-api | from alembic import op
import sqlalchemy as sa
revision = '0245_archived_flag_jobs'
down_revision = '0244_another_letter_org'
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
+ op.add_column('jobs', sa.Column('archived', sa.Boolean(), nullable=True))
+ op.execute('update jobs set archived = false')
- op.add_column('jobs', sa.Column('archived', sa.Boolean(), nullable=False, server_default=sa.false()))
+ op.alter_column('jobs', 'archived', nullable=False, server_default=sa.false())
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('jobs', 'archived')
# ### end Alembic commands ###
| Update jobs archived flag before setting the default value | ## Code Before:
from alembic import op
import sqlalchemy as sa
revision = '0245_archived_flag_jobs'
down_revision = '0244_another_letter_org'
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('jobs', sa.Column('archived', sa.Boolean(), nullable=False, server_default=sa.false()))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('jobs', 'archived')
# ### end Alembic commands ###
## Instruction:
Update jobs archived flag before setting the default value
## Code After:
from alembic import op
import sqlalchemy as sa
revision = '0245_archived_flag_jobs'
down_revision = '0244_another_letter_org'
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('jobs', sa.Column('archived', sa.Boolean(), nullable=True))
op.execute('update jobs set archived = false')
op.alter_column('jobs', 'archived', nullable=False, server_default=sa.false())
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('jobs', 'archived')
# ### end Alembic commands ###
|
e3a530d741529a7bbfeb274c232e2c6b8a5faddc | kokki/cookbooks/postgresql9/recipes/default.py | kokki/cookbooks/postgresql9/recipes/default.py | import os
from kokki import Execute, Package
apt_list_path = '/etc/apt/sources.list.d/pitti-postgresql-lucid.list'
Execute("apt-update-postgresql9",
command = "apt-get update",
action = "nothing")
apt = None
if env.system.platform == "ubuntu":
Package("python-software-properties")
Execute("add-apt-repository ppa:pitti/postgresql",
not_if = lambda:os.path.exists(apt_list_path),
notifies = [("run", env.resources["Execute"]["apt-update-postgresql9"], True)])
| import os
from kokki import Execute, Package
if not (env.system.platform == "ubuntu" and env.system.lsb['release'] in ["11.10"]):
apt_list_path = '/etc/apt/sources.list.d/pitti-postgresql-lucid.list'
Execute("apt-update-postgresql9",
command = "apt-get update",
action = "nothing")
apt = None
if env.system.platform == "ubuntu":
Package("python-software-properties")
Execute("add-apt-repository ppa:pitti/postgresql",
not_if = lambda:os.path.exists(apt_list_path),
notifies = [("run", env.resources["Execute"]["apt-update-postgresql9"], True)])
| Use standard repo for postgresql9 in ubuntu 11.10 | Use standard repo for postgresql9 in ubuntu 11.10
| Python | bsd-3-clause | samuel/kokki | import os
from kokki import Execute, Package
+ if not (env.system.platform == "ubuntu" and env.system.lsb['release'] in ["11.10"]):
- apt_list_path = '/etc/apt/sources.list.d/pitti-postgresql-lucid.list'
+ apt_list_path = '/etc/apt/sources.list.d/pitti-postgresql-lucid.list'
- Execute("apt-update-postgresql9",
+ Execute("apt-update-postgresql9",
- command = "apt-get update",
+ command = "apt-get update",
- action = "nothing")
+ action = "nothing")
- apt = None
+ apt = None
- if env.system.platform == "ubuntu":
+ if env.system.platform == "ubuntu":
- Package("python-software-properties")
+ Package("python-software-properties")
- Execute("add-apt-repository ppa:pitti/postgresql",
+ Execute("add-apt-repository ppa:pitti/postgresql",
- not_if = lambda:os.path.exists(apt_list_path),
+ not_if = lambda:os.path.exists(apt_list_path),
- notifies = [("run", env.resources["Execute"]["apt-update-postgresql9"], True)])
+ notifies = [("run", env.resources["Execute"]["apt-update-postgresql9"], True)])
| Use standard repo for postgresql9 in ubuntu 11.10 | ## Code Before:
import os
from kokki import Execute, Package
apt_list_path = '/etc/apt/sources.list.d/pitti-postgresql-lucid.list'
Execute("apt-update-postgresql9",
command = "apt-get update",
action = "nothing")
apt = None
if env.system.platform == "ubuntu":
Package("python-software-properties")
Execute("add-apt-repository ppa:pitti/postgresql",
not_if = lambda:os.path.exists(apt_list_path),
notifies = [("run", env.resources["Execute"]["apt-update-postgresql9"], True)])
## Instruction:
Use standard repo for postgresql9 in ubuntu 11.10
## Code After:
import os
from kokki import Execute, Package
if not (env.system.platform == "ubuntu" and env.system.lsb['release'] in ["11.10"]):
apt_list_path = '/etc/apt/sources.list.d/pitti-postgresql-lucid.list'
Execute("apt-update-postgresql9",
command = "apt-get update",
action = "nothing")
apt = None
if env.system.platform == "ubuntu":
Package("python-software-properties")
Execute("add-apt-repository ppa:pitti/postgresql",
not_if = lambda:os.path.exists(apt_list_path),
notifies = [("run", env.resources["Execute"]["apt-update-postgresql9"], True)])
|
8e47696a805cce70989a79cc6e8324aaec870f6d | electionleaflets/apps/people/devs_dc_helpers.py | electionleaflets/apps/people/devs_dc_helpers.py | import requests
from django.conf import settings
class DevsDCAPIHelper:
def __init__(self):
self.AUTH_TOKEN = settings.DEVS_DC_AUTH_TOKEN
self.base_url = "https://developers.democracyclub.org.uk/api/v1"
def make_request(self, endpoint, **params):
default_params = {
"auth_token": self.AUTH_TOKEN
}
if params:
default_params.update(params)
url = "{}/{}/".format(self.base_url, endpoint)
return requests.get(url, default_params)
def postcode_request(self, postcode):
return self.make_request("postcode/{}".format(postcode))
| import requests
from django.conf import settings
class DevsDCAPIHelper:
def __init__(self):
self.AUTH_TOKEN = settings.DEVS_DC_AUTH_TOKEN
self.base_url = "https://developers.democracyclub.org.uk/api/v1"
self.ballot_cache = {}
def make_request(self, endpoint, **params):
default_params = {
"auth_token": self.AUTH_TOKEN
}
if params:
default_params.update(params)
url = "{}/{}/".format(self.base_url, endpoint)
return requests.get(url, default_params)
def postcode_request(self, postcode):
return self.make_request("postcode/{}".format(postcode))
def ballot_request(self, ballot_paper_id):
if ballot_paper_id not in self.ballot_cache:
r = self.make_request("elections/{}".format(ballot_paper_id))
if r.status_code == 200:
self.ballot_cache[ballot_paper_id] = r
else:
return r
return self.ballot_cache[ballot_paper_id]
| Add a cached ballot fetcher to the DevsDC helper | Add a cached ballot fetcher to the DevsDC helper
If we happen to run out of RAM in Lambda (we won't), Lambda will just
kill the function and invoke a new one next time.
| Python | mit | DemocracyClub/electionleaflets,DemocracyClub/electionleaflets,DemocracyClub/electionleaflets | import requests
from django.conf import settings
class DevsDCAPIHelper:
def __init__(self):
self.AUTH_TOKEN = settings.DEVS_DC_AUTH_TOKEN
self.base_url = "https://developers.democracyclub.org.uk/api/v1"
+ self.ballot_cache = {}
def make_request(self, endpoint, **params):
default_params = {
"auth_token": self.AUTH_TOKEN
}
if params:
default_params.update(params)
url = "{}/{}/".format(self.base_url, endpoint)
return requests.get(url, default_params)
def postcode_request(self, postcode):
return self.make_request("postcode/{}".format(postcode))
+ def ballot_request(self, ballot_paper_id):
+ if ballot_paper_id not in self.ballot_cache:
+ r = self.make_request("elections/{}".format(ballot_paper_id))
+ if r.status_code == 200:
+ self.ballot_cache[ballot_paper_id] = r
+ else:
+ return r
+
+ return self.ballot_cache[ballot_paper_id]
+ | Add a cached ballot fetcher to the DevsDC helper | ## Code Before:
import requests
from django.conf import settings
class DevsDCAPIHelper:
def __init__(self):
self.AUTH_TOKEN = settings.DEVS_DC_AUTH_TOKEN
self.base_url = "https://developers.democracyclub.org.uk/api/v1"
def make_request(self, endpoint, **params):
default_params = {
"auth_token": self.AUTH_TOKEN
}
if params:
default_params.update(params)
url = "{}/{}/".format(self.base_url, endpoint)
return requests.get(url, default_params)
def postcode_request(self, postcode):
return self.make_request("postcode/{}".format(postcode))
## Instruction:
Add a cached ballot fetcher to the DevsDC helper
## Code After:
import requests
from django.conf import settings
class DevsDCAPIHelper:
def __init__(self):
self.AUTH_TOKEN = settings.DEVS_DC_AUTH_TOKEN
self.base_url = "https://developers.democracyclub.org.uk/api/v1"
self.ballot_cache = {}
def make_request(self, endpoint, **params):
default_params = {
"auth_token": self.AUTH_TOKEN
}
if params:
default_params.update(params)
url = "{}/{}/".format(self.base_url, endpoint)
return requests.get(url, default_params)
def postcode_request(self, postcode):
return self.make_request("postcode/{}".format(postcode))
def ballot_request(self, ballot_paper_id):
if ballot_paper_id not in self.ballot_cache:
r = self.make_request("elections/{}".format(ballot_paper_id))
if r.status_code == 200:
self.ballot_cache[ballot_paper_id] = r
else:
return r
return self.ballot_cache[ballot_paper_id]
|
00c808efd2ab38bcf9d808dcb784c9360a19937f | api/radar_api/views/organisation_consultants.py | api/radar_api/views/organisation_consultants.py | from radar_api.serializers.organisation_consultants import OrganisationConsultantSerializer
from radar.models import OrganisationConsultant
from radar.views.core import RetrieveUpdateDestroyModelView, ListCreateModelView
class OrganisationConsultantListView(ListCreateModelView):
serializer_class = OrganisationConsultantSerializer
model_class = OrganisationConsultant
class OrganisationConsultantDetailView(RetrieveUpdateDestroyModelView):
serializer_class = OrganisationConsultantSerializer
model_class = OrganisationConsultant
def register_views(app):
app.add_url_rule('/organisation-consultants', view_func=OrganisationConsultantListView.as_view('organisation_consultant_list'))
app.add_url_rule('/organisation-consultants/<int:id>', view_func=OrganisationConsultantDetailView.as_view('organisation_consultant_detail'))
| from radar_api.serializers.organisation_consultants import OrganisationConsultantSerializer
from radar.models import OrganisationConsultant
from radar.views.core import RetrieveUpdateDestroyModelView, ListCreateModelView
from radar.permissions import AdminPermission
class OrganisationConsultantListView(ListCreateModelView):
serializer_class = OrganisationConsultantSerializer
model_class = OrganisationConsultant
permission_classes = [AdminPermission]
class OrganisationConsultantDetailView(RetrieveUpdateDestroyModelView):
serializer_class = OrganisationConsultantSerializer
model_class = OrganisationConsultant
permission_classes = [AdminPermission]
def register_views(app):
app.add_url_rule('/organisation-consultants', view_func=OrganisationConsultantListView.as_view('organisation_consultant_list'))
app.add_url_rule('/organisation-consultants/<int:id>', view_func=OrganisationConsultantDetailView.as_view('organisation_consultant_detail'))
| Add permissions to organisation consultants endpoint | Add permissions to organisation consultants endpoint
| Python | agpl-3.0 | renalreg/radar,renalreg/radar,renalreg/radar,renalreg/radar | from radar_api.serializers.organisation_consultants import OrganisationConsultantSerializer
from radar.models import OrganisationConsultant
from radar.views.core import RetrieveUpdateDestroyModelView, ListCreateModelView
+ from radar.permissions import AdminPermission
class OrganisationConsultantListView(ListCreateModelView):
serializer_class = OrganisationConsultantSerializer
model_class = OrganisationConsultant
+ permission_classes = [AdminPermission]
class OrganisationConsultantDetailView(RetrieveUpdateDestroyModelView):
serializer_class = OrganisationConsultantSerializer
model_class = OrganisationConsultant
+ permission_classes = [AdminPermission]
def register_views(app):
app.add_url_rule('/organisation-consultants', view_func=OrganisationConsultantListView.as_view('organisation_consultant_list'))
app.add_url_rule('/organisation-consultants/<int:id>', view_func=OrganisationConsultantDetailView.as_view('organisation_consultant_detail'))
| Add permissions to organisation consultants endpoint | ## Code Before:
from radar_api.serializers.organisation_consultants import OrganisationConsultantSerializer
from radar.models import OrganisationConsultant
from radar.views.core import RetrieveUpdateDestroyModelView, ListCreateModelView
class OrganisationConsultantListView(ListCreateModelView):
serializer_class = OrganisationConsultantSerializer
model_class = OrganisationConsultant
class OrganisationConsultantDetailView(RetrieveUpdateDestroyModelView):
serializer_class = OrganisationConsultantSerializer
model_class = OrganisationConsultant
def register_views(app):
app.add_url_rule('/organisation-consultants', view_func=OrganisationConsultantListView.as_view('organisation_consultant_list'))
app.add_url_rule('/organisation-consultants/<int:id>', view_func=OrganisationConsultantDetailView.as_view('organisation_consultant_detail'))
## Instruction:
Add permissions to organisation consultants endpoint
## Code After:
from radar_api.serializers.organisation_consultants import OrganisationConsultantSerializer
from radar.models import OrganisationConsultant
from radar.views.core import RetrieveUpdateDestroyModelView, ListCreateModelView
from radar.permissions import AdminPermission
class OrganisationConsultantListView(ListCreateModelView):
serializer_class = OrganisationConsultantSerializer
model_class = OrganisationConsultant
permission_classes = [AdminPermission]
class OrganisationConsultantDetailView(RetrieveUpdateDestroyModelView):
serializer_class = OrganisationConsultantSerializer
model_class = OrganisationConsultant
permission_classes = [AdminPermission]
def register_views(app):
app.add_url_rule('/organisation-consultants', view_func=OrganisationConsultantListView.as_view('organisation_consultant_list'))
app.add_url_rule('/organisation-consultants/<int:id>', view_func=OrganisationConsultantDetailView.as_view('organisation_consultant_detail'))
|
c977e1c235ccb040f28bc03c63d2667924d5edd3 | pythonforandroid/recipes/xeddsa/__init__.py | pythonforandroid/recipes/xeddsa/__init__.py | from pythonforandroid.recipe import CythonRecipe
from pythonforandroid.toolchain import current_directory, shprint
from os.path import join
import sh
class XedDSARecipe(CythonRecipe):
name = 'xeddsa'
version = '0.4.4'
url = 'https://pypi.python.org/packages/source/X/XEdDSA/XEdDSA-{version}.tar.gz'
depends = [
'setuptools',
'cffi',
'pynacl',
]
patches = ['remove_dependencies.patch']
call_hostpython_via_targetpython = False
def build_arch(self, arch):
with current_directory(join(self.get_build_dir(arch.arch))):
env = self.get_recipe_env(arch)
hostpython = sh.Command(self.ctx.hostpython)
shprint(
hostpython, 'ref10/build.py',
_env=env
)
shprint(sh.cp, '_crypto_sign.so', self.ctx.get_site_packages_dir())
self.install_python_package(arch)
recipe = XedDSARecipe()
| from pythonforandroid.recipe import CythonRecipe
from pythonforandroid.toolchain import current_directory, shprint
from os.path import join
import sh
class XedDSARecipe(CythonRecipe):
name = 'xeddsa'
version = '0.4.4'
url = 'https://pypi.python.org/packages/source/X/XEdDSA/XEdDSA-{version}.tar.gz'
depends = [
'setuptools',
'cffi',
'pynacl',
]
patches = ['remove_dependencies.patch']
call_hostpython_via_targetpython = False
def build_arch(self, arch):
with current_directory(join(self.get_build_dir(arch.arch))):
env = self.get_recipe_env(arch)
hostpython = sh.Command(self.ctx.hostpython)
shprint(
hostpython, 'ref10/build.py',
_env=env
)
# the library could be `_crypto_sign.cpython-37m-x86_64-linux-gnu.so`
# or simply `_crypto_sign.so` depending on the platform/distribution
sh.cp('-a', sh.glob('_crypto_sign*.so'), self.ctx.get_site_packages_dir())
self.install_python_package(arch)
recipe = XedDSARecipe()
| Fix xeddsa crypto_sign shared lib copy | Fix xeddsa crypto_sign shared lib copy
Could be `_crypto_sign.cpython-37m-x86_64-linux-gnu.so` or simply `_crypto_sign.so` depending on the platform/distribution | Python | mit | germn/python-for-android,rnixx/python-for-android,rnixx/python-for-android,germn/python-for-android,rnixx/python-for-android,kivy/python-for-android,PKRoma/python-for-android,germn/python-for-android,germn/python-for-android,kronenpj/python-for-android,kivy/python-for-android,kronenpj/python-for-android,kivy/python-for-android,PKRoma/python-for-android,kronenpj/python-for-android,germn/python-for-android,kronenpj/python-for-android,kivy/python-for-android,PKRoma/python-for-android,kivy/python-for-android,rnixx/python-for-android,kronenpj/python-for-android,germn/python-for-android,rnixx/python-for-android,PKRoma/python-for-android,rnixx/python-for-android,PKRoma/python-for-android | from pythonforandroid.recipe import CythonRecipe
from pythonforandroid.toolchain import current_directory, shprint
from os.path import join
import sh
class XedDSARecipe(CythonRecipe):
name = 'xeddsa'
version = '0.4.4'
url = 'https://pypi.python.org/packages/source/X/XEdDSA/XEdDSA-{version}.tar.gz'
depends = [
'setuptools',
'cffi',
'pynacl',
]
patches = ['remove_dependencies.patch']
call_hostpython_via_targetpython = False
def build_arch(self, arch):
with current_directory(join(self.get_build_dir(arch.arch))):
env = self.get_recipe_env(arch)
hostpython = sh.Command(self.ctx.hostpython)
shprint(
hostpython, 'ref10/build.py',
_env=env
)
+ # the library could be `_crypto_sign.cpython-37m-x86_64-linux-gnu.so`
+ # or simply `_crypto_sign.so` depending on the platform/distribution
- shprint(sh.cp, '_crypto_sign.so', self.ctx.get_site_packages_dir())
+ sh.cp('-a', sh.glob('_crypto_sign*.so'), self.ctx.get_site_packages_dir())
self.install_python_package(arch)
recipe = XedDSARecipe()
| Fix xeddsa crypto_sign shared lib copy | ## Code Before:
from pythonforandroid.recipe import CythonRecipe
from pythonforandroid.toolchain import current_directory, shprint
from os.path import join
import sh
class XedDSARecipe(CythonRecipe):
name = 'xeddsa'
version = '0.4.4'
url = 'https://pypi.python.org/packages/source/X/XEdDSA/XEdDSA-{version}.tar.gz'
depends = [
'setuptools',
'cffi',
'pynacl',
]
patches = ['remove_dependencies.patch']
call_hostpython_via_targetpython = False
def build_arch(self, arch):
with current_directory(join(self.get_build_dir(arch.arch))):
env = self.get_recipe_env(arch)
hostpython = sh.Command(self.ctx.hostpython)
shprint(
hostpython, 'ref10/build.py',
_env=env
)
shprint(sh.cp, '_crypto_sign.so', self.ctx.get_site_packages_dir())
self.install_python_package(arch)
recipe = XedDSARecipe()
## Instruction:
Fix xeddsa crypto_sign shared lib copy
## Code After:
from pythonforandroid.recipe import CythonRecipe
from pythonforandroid.toolchain import current_directory, shprint
from os.path import join
import sh
class XedDSARecipe(CythonRecipe):
name = 'xeddsa'
version = '0.4.4'
url = 'https://pypi.python.org/packages/source/X/XEdDSA/XEdDSA-{version}.tar.gz'
depends = [
'setuptools',
'cffi',
'pynacl',
]
patches = ['remove_dependencies.patch']
call_hostpython_via_targetpython = False
def build_arch(self, arch):
with current_directory(join(self.get_build_dir(arch.arch))):
env = self.get_recipe_env(arch)
hostpython = sh.Command(self.ctx.hostpython)
shprint(
hostpython, 'ref10/build.py',
_env=env
)
# the library could be `_crypto_sign.cpython-37m-x86_64-linux-gnu.so`
# or simply `_crypto_sign.so` depending on the platform/distribution
sh.cp('-a', sh.glob('_crypto_sign*.so'), self.ctx.get_site_packages_dir())
self.install_python_package(arch)
recipe = XedDSARecipe()
|
6deab74e41cabcb9a3fb4075f270a9cdd591a435 | pgallery/tests/test_utils.py | pgallery/tests/test_utils.py | from __future__ import unicode_literals
import unittest
from ..models import sanitize_exif_value
class SanitizeExifValueTestCase(unittest.TestCase):
def test_strip_null_bytes(self):
"""
Check that null bytes are stripped from the string.
"""
key = "not relevant"
value = "abc\x00d"
self.assertEqual(sanitize_exif_value(key, value), "abcd")
| from __future__ import unicode_literals
import unittest
from ..models import sanitize_exif_value
class SanitizeExifValueTestCase(unittest.TestCase):
def test_strip_null_bytes(self):
"""
Check that null bytes are stripped from the string.
"""
key = "not relevant"
value = "abc\x00d"
self.assertEqual(sanitize_exif_value(key, value), "abcd")
def test_coerce_to_text(self):
"""
Check that non-text types are coerced to text.
"""
key = "not relevant"
value = (20, 70)
self.assertEqual(sanitize_exif_value(key, value), "(20, 70)")
| Test type coercion in sanitize_exif_value | Test type coercion in sanitize_exif_value
| Python | mit | zsiciarz/django-pgallery,zsiciarz/django-pgallery | from __future__ import unicode_literals
import unittest
from ..models import sanitize_exif_value
class SanitizeExifValueTestCase(unittest.TestCase):
def test_strip_null_bytes(self):
"""
Check that null bytes are stripped from the string.
"""
key = "not relevant"
value = "abc\x00d"
self.assertEqual(sanitize_exif_value(key, value), "abcd")
+ def test_coerce_to_text(self):
+ """
+ Check that non-text types are coerced to text.
+ """
+ key = "not relevant"
+ value = (20, 70)
+ self.assertEqual(sanitize_exif_value(key, value), "(20, 70)")
+ | Test type coercion in sanitize_exif_value | ## Code Before:
from __future__ import unicode_literals
import unittest
from ..models import sanitize_exif_value
class SanitizeExifValueTestCase(unittest.TestCase):
def test_strip_null_bytes(self):
"""
Check that null bytes are stripped from the string.
"""
key = "not relevant"
value = "abc\x00d"
self.assertEqual(sanitize_exif_value(key, value), "abcd")
## Instruction:
Test type coercion in sanitize_exif_value
## Code After:
from __future__ import unicode_literals
import unittest
from ..models import sanitize_exif_value
class SanitizeExifValueTestCase(unittest.TestCase):
def test_strip_null_bytes(self):
"""
Check that null bytes are stripped from the string.
"""
key = "not relevant"
value = "abc\x00d"
self.assertEqual(sanitize_exif_value(key, value), "abcd")
def test_coerce_to_text(self):
"""
Check that non-text types are coerced to text.
"""
key = "not relevant"
value = (20, 70)
self.assertEqual(sanitize_exif_value(key, value), "(20, 70)")
|
42709afec9f2e2ed419365f61324ce0c8ff96423 | budget/forms.py | budget/forms.py | from django import forms
from django.template.defaultfilters import slugify
from budget.models import Budget, BudgetEstimate
class BudgetForm(forms.ModelForm):
class Meta:
model = Budget
fields = ('name', 'start_date')
def save(self):
if not self.instance.slug:
self.instance.slug = slugify(self.cleaned_data['name'])
super(BudgetForm, self).save()
class BudgetEstimateForm(forms.ModelForm):
class Meta:
model = BudgetEstimate
fields = ('category', 'amount')
def save(self, budget):
self.instance.budget = budget
super(BudgetEstimateForm, self).save()
| import datetime
from django import forms
from django.template.defaultfilters import slugify
from budget.models import Budget, BudgetEstimate
class BudgetForm(forms.ModelForm):
start_date = forms.DateTimeField(initial=datetime.datetime.now, required=False, widget=forms.SplitDateTimeWidget)
class Meta:
model = Budget
fields = ('name', 'start_date')
def save(self):
if not self.instance.slug:
self.instance.slug = slugify(self.cleaned_data['name'])
super(BudgetForm, self).save()
class BudgetEstimateForm(forms.ModelForm):
class Meta:
model = BudgetEstimate
fields = ('category', 'amount')
def save(self, budget):
self.instance.budget = budget
super(BudgetEstimateForm, self).save()
| Split the start_date for better data entry (and Javascript date pickers). | Split the start_date for better data entry (and Javascript date pickers).
| Python | bsd-3-clause | jokimies/django-pj-budget,jokimies/django-pj-budget,toastdriven/django-budget,toastdriven/django-budget,jokimies/django-pj-budget | + import datetime
from django import forms
from django.template.defaultfilters import slugify
from budget.models import Budget, BudgetEstimate
class BudgetForm(forms.ModelForm):
+ start_date = forms.DateTimeField(initial=datetime.datetime.now, required=False, widget=forms.SplitDateTimeWidget)
+
class Meta:
model = Budget
fields = ('name', 'start_date')
def save(self):
if not self.instance.slug:
self.instance.slug = slugify(self.cleaned_data['name'])
super(BudgetForm, self).save()
class BudgetEstimateForm(forms.ModelForm):
class Meta:
model = BudgetEstimate
fields = ('category', 'amount')
def save(self, budget):
self.instance.budget = budget
super(BudgetEstimateForm, self).save()
| Split the start_date for better data entry (and Javascript date pickers). | ## Code Before:
from django import forms
from django.template.defaultfilters import slugify
from budget.models import Budget, BudgetEstimate
class BudgetForm(forms.ModelForm):
class Meta:
model = Budget
fields = ('name', 'start_date')
def save(self):
if not self.instance.slug:
self.instance.slug = slugify(self.cleaned_data['name'])
super(BudgetForm, self).save()
class BudgetEstimateForm(forms.ModelForm):
class Meta:
model = BudgetEstimate
fields = ('category', 'amount')
def save(self, budget):
self.instance.budget = budget
super(BudgetEstimateForm, self).save()
## Instruction:
Split the start_date for better data entry (and Javascript date pickers).
## Code After:
import datetime
from django import forms
from django.template.defaultfilters import slugify
from budget.models import Budget, BudgetEstimate
class BudgetForm(forms.ModelForm):
start_date = forms.DateTimeField(initial=datetime.datetime.now, required=False, widget=forms.SplitDateTimeWidget)
class Meta:
model = Budget
fields = ('name', 'start_date')
def save(self):
if not self.instance.slug:
self.instance.slug = slugify(self.cleaned_data['name'])
super(BudgetForm, self).save()
class BudgetEstimateForm(forms.ModelForm):
class Meta:
model = BudgetEstimate
fields = ('category', 'amount')
def save(self, budget):
self.instance.budget = budget
super(BudgetEstimateForm, self).save()
|
db6b9761d51d45b2708ba6bca997196fc73fbe94 | sheldon/__init__.py | sheldon/__init__.py |
# Bot module contains bot's main class - Sheldon
from sheldon.bot import *
# Hooks module contains hooks for plugins
from sheldon.hooks import *
# Utils folder contains scripts for more
# comfortable work with sending and parsing
# messages. For example, script for downloading
# files by url.
from sheldon.utils import *
__author__ = 'Seva Zhidkov'
__version__ = '0.0.1#dev'
__email__ = '[email protected]'
|
# Bot module contains bot's main class - Sheldon
from sheldon.bot import *
# Hooks module contains hooks for plugins
from sheldon.hooks import *
# Adapter module contains classes and tools
# for plugins sending messages
from sheldon.adapter import *
# Utils folder contains scripts for more
# comfortable work with sending and parsing
# messages. For example, script for downloading
# files by url.
from sheldon.utils import *
__author__ = 'Seva Zhidkov'
__version__ = '0.0.1#dev'
__email__ = '[email protected]'
| Add adapter module to init file | Add adapter module to init file
| Python | mit | lises/sheldon |
# Bot module contains bot's main class - Sheldon
from sheldon.bot import *
# Hooks module contains hooks for plugins
from sheldon.hooks import *
+
+ # Adapter module contains classes and tools
+ # for plugins sending messages
+ from sheldon.adapter import *
# Utils folder contains scripts for more
# comfortable work with sending and parsing
# messages. For example, script for downloading
# files by url.
from sheldon.utils import *
__author__ = 'Seva Zhidkov'
__version__ = '0.0.1#dev'
__email__ = '[email protected]'
| Add adapter module to init file | ## Code Before:
# Bot module contains bot's main class - Sheldon
from sheldon.bot import *
# Hooks module contains hooks for plugins
from sheldon.hooks import *
# Utils folder contains scripts for more
# comfortable work with sending and parsing
# messages. For example, script for downloading
# files by url.
from sheldon.utils import *
__author__ = 'Seva Zhidkov'
__version__ = '0.0.1#dev'
__email__ = '[email protected]'
## Instruction:
Add adapter module to init file
## Code After:
# Bot module contains bot's main class - Sheldon
from sheldon.bot import *
# Hooks module contains hooks for plugins
from sheldon.hooks import *
# Adapter module contains classes and tools
# for plugins sending messages
from sheldon.adapter import *
# Utils folder contains scripts for more
# comfortable work with sending and parsing
# messages. For example, script for downloading
# files by url.
from sheldon.utils import *
__author__ = 'Seva Zhidkov'
__version__ = '0.0.1#dev'
__email__ = '[email protected]'
|
987fd7555eadfa15d10db7991f4a7e8a4a7dbbbf | custom/topo-2sw-2host.py | custom/topo-2sw-2host.py |
from mininet.topo import Topo, Node
class MyTopo( Topo ):
"Simple topology example."
def __init__( self, enable_all = True ):
"Create custom topo."
# Add default members to class.
super( MyTopo, self ).__init__()
# Set Node IDs for hosts and switches
leftHost = 1
leftSwitch = 2
rightSwitch = 3
rightHost = 4
# Add nodes
self.addNode( leftSwitch, Node( isSwitch=True ) )
self.addNode( rightSwitch, Node( isSwitch=True ) )
self.addNode( leftHost, Node( isSwitch=False ) )
self.addNode( rightHost, Node( isSwitch=False ) )
# Add edges
self.add_edge( leftHost, leftSwitch )
self.add_edge( leftSwitch, rightSwitch )
self.add_edge( rightSwitch, rightHost )
# Consider all switches and hosts 'on'
self.enable_all()
topos = { 'mytopo': ( lambda: MyTopo() ) }
|
from mininet.topo import Topo
from mininet.node import Node
class MyTopo( Topo ):
"Simple topology example."
def __init__( self, enable_all = True ):
"Create custom topo."
# Add default members to class.
super( MyTopo, self ).__init__()
# Set Node IDs for hosts and switches
leftHost = 1
leftSwitch = 2
rightSwitch = 3
rightHost = 4
# Add nodes
self.addNode( leftSwitch, Node( isSwitch=True ) )
self.addNode( rightSwitch, Node( isSwitch=True ) )
self.addNode( leftHost, Node( isSwitch=False ) )
self.addNode( rightHost, Node( isSwitch=False ) )
# Add edges
self.add_edge( leftHost, leftSwitch )
self.add_edge( leftSwitch, rightSwitch )
self.add_edge( rightSwitch, rightHost )
# Consider all switches and hosts 'on'
self.enable_all()
topos = { 'mytopo': ( lambda: MyTopo() ) }
| Fix custom topology example; outdated import | Fix custom topology example; outdated import
Reported-by: Julius Bachnick
| Python | bsd-3-clause | mininet/mininet,mininet/mininet,mininet/mininet |
- from mininet.topo import Topo, Node
+ from mininet.topo import Topo
+ from mininet.node import Node
class MyTopo( Topo ):
"Simple topology example."
def __init__( self, enable_all = True ):
"Create custom topo."
# Add default members to class.
super( MyTopo, self ).__init__()
# Set Node IDs for hosts and switches
leftHost = 1
leftSwitch = 2
rightSwitch = 3
rightHost = 4
# Add nodes
self.addNode( leftSwitch, Node( isSwitch=True ) )
self.addNode( rightSwitch, Node( isSwitch=True ) )
self.addNode( leftHost, Node( isSwitch=False ) )
self.addNode( rightHost, Node( isSwitch=False ) )
# Add edges
self.add_edge( leftHost, leftSwitch )
self.add_edge( leftSwitch, rightSwitch )
self.add_edge( rightSwitch, rightHost )
# Consider all switches and hosts 'on'
self.enable_all()
topos = { 'mytopo': ( lambda: MyTopo() ) }
| Fix custom topology example; outdated import | ## Code Before:
from mininet.topo import Topo, Node
class MyTopo( Topo ):
"Simple topology example."
def __init__( self, enable_all = True ):
"Create custom topo."
# Add default members to class.
super( MyTopo, self ).__init__()
# Set Node IDs for hosts and switches
leftHost = 1
leftSwitch = 2
rightSwitch = 3
rightHost = 4
# Add nodes
self.addNode( leftSwitch, Node( isSwitch=True ) )
self.addNode( rightSwitch, Node( isSwitch=True ) )
self.addNode( leftHost, Node( isSwitch=False ) )
self.addNode( rightHost, Node( isSwitch=False ) )
# Add edges
self.add_edge( leftHost, leftSwitch )
self.add_edge( leftSwitch, rightSwitch )
self.add_edge( rightSwitch, rightHost )
# Consider all switches and hosts 'on'
self.enable_all()
topos = { 'mytopo': ( lambda: MyTopo() ) }
## Instruction:
Fix custom topology example; outdated import
## Code After:
from mininet.topo import Topo
from mininet.node import Node
class MyTopo( Topo ):
"Simple topology example."
def __init__( self, enable_all = True ):
"Create custom topo."
# Add default members to class.
super( MyTopo, self ).__init__()
# Set Node IDs for hosts and switches
leftHost = 1
leftSwitch = 2
rightSwitch = 3
rightHost = 4
# Add nodes
self.addNode( leftSwitch, Node( isSwitch=True ) )
self.addNode( rightSwitch, Node( isSwitch=True ) )
self.addNode( leftHost, Node( isSwitch=False ) )
self.addNode( rightHost, Node( isSwitch=False ) )
# Add edges
self.add_edge( leftHost, leftSwitch )
self.add_edge( leftSwitch, rightSwitch )
self.add_edge( rightSwitch, rightHost )
# Consider all switches and hosts 'on'
self.enable_all()
topos = { 'mytopo': ( lambda: MyTopo() ) }
|
4b819129557d5f0546d9edf206710fd2ec962881 | utsokt/restapi/models.py | utsokt/restapi/models.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
class Story(models.Model):
url = models.URLField(_('URL'))
title = models.CharField(_('Title'), max_length=64)
excerpt = models.CharField(_('Excerpt'), max_length=64, null=True, blank=True)
created_at = models.TimeField(_('Created at'), auto_now_add=True)
is_unread = models.BooleanField(_('Is unread?'), default=True)
| from django.db import models
from django.utils.translation import ugettext_lazy as _
class Story(models.Model):
url = models.URLField(_('URL'))
title = models.CharField(_('Title'), max_length=64)
excerpt = models.CharField(_('Excerpt'), max_length=64, null=True, blank=True)
created_at = models.TimeField(_('Created at'), auto_now_add=True)
is_unread = models.BooleanField(_('Is unread?'), default=True)
class Meta:
ordering = ['-created_at']
| Order stories by descending creation time | Order stories by descending creation time
| Python | bsd-3-clause | madr/utsokt,madr/utsokt | from django.db import models
from django.utils.translation import ugettext_lazy as _
class Story(models.Model):
url = models.URLField(_('URL'))
title = models.CharField(_('Title'), max_length=64)
excerpt = models.CharField(_('Excerpt'), max_length=64, null=True, blank=True)
created_at = models.TimeField(_('Created at'), auto_now_add=True)
is_unread = models.BooleanField(_('Is unread?'), default=True)
+ class Meta:
+ ordering = ['-created_at']
+ | Order stories by descending creation time | ## Code Before:
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Story(models.Model):
url = models.URLField(_('URL'))
title = models.CharField(_('Title'), max_length=64)
excerpt = models.CharField(_('Excerpt'), max_length=64, null=True, blank=True)
created_at = models.TimeField(_('Created at'), auto_now_add=True)
is_unread = models.BooleanField(_('Is unread?'), default=True)
## Instruction:
Order stories by descending creation time
## Code After:
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Story(models.Model):
url = models.URLField(_('URL'))
title = models.CharField(_('Title'), max_length=64)
excerpt = models.CharField(_('Excerpt'), max_length=64, null=True, blank=True)
created_at = models.TimeField(_('Created at'), auto_now_add=True)
is_unread = models.BooleanField(_('Is unread?'), default=True)
class Meta:
ordering = ['-created_at']
|
dd50858ee22c27076919614d1994e3ce9c8e2399 | soundem/handlers.py | soundem/handlers.py | from flask import jsonify
from soundem import app
def json_error_handler(e):
return jsonify({
'status_code': e.code,
'error': 'Bad Request',
'detail': e.description
}), e.code
@app.errorhandler(400)
def bad_request_handler(e):
return json_error_handler(e)
@app.errorhandler(401)
def unauthorized_handler(e):
return json_error_handler(e)
@app.errorhandler(404)
def not_found_handler(e):
return json_error_handler(e)
@app.errorhandler(405)
def method_not_allowed_handler(e):
return json_error_handler(e)
| from flask import jsonify
from soundem import app
def json_error_handler(e):
return jsonify({
'status_code': e.code,
'error': e.name,
'detail': e.description
}), e.code
@app.errorhandler(400)
def bad_request_handler(e):
return json_error_handler(e)
@app.errorhandler(401)
def unauthorized_handler(e):
return json_error_handler(e)
@app.errorhandler(404)
def not_found_handler(e):
return json_error_handler(e)
@app.errorhandler(405)
def method_not_allowed_handler(e):
return json_error_handler(e)
| Fix json error handler name | Fix json error handler name | Python | mit | building4theweb/soundem-api | from flask import jsonify
from soundem import app
def json_error_handler(e):
return jsonify({
'status_code': e.code,
- 'error': 'Bad Request',
+ 'error': e.name,
'detail': e.description
}), e.code
@app.errorhandler(400)
def bad_request_handler(e):
return json_error_handler(e)
@app.errorhandler(401)
def unauthorized_handler(e):
return json_error_handler(e)
@app.errorhandler(404)
def not_found_handler(e):
return json_error_handler(e)
@app.errorhandler(405)
def method_not_allowed_handler(e):
return json_error_handler(e)
| Fix json error handler name | ## Code Before:
from flask import jsonify
from soundem import app
def json_error_handler(e):
return jsonify({
'status_code': e.code,
'error': 'Bad Request',
'detail': e.description
}), e.code
@app.errorhandler(400)
def bad_request_handler(e):
return json_error_handler(e)
@app.errorhandler(401)
def unauthorized_handler(e):
return json_error_handler(e)
@app.errorhandler(404)
def not_found_handler(e):
return json_error_handler(e)
@app.errorhandler(405)
def method_not_allowed_handler(e):
return json_error_handler(e)
## Instruction:
Fix json error handler name
## Code After:
from flask import jsonify
from soundem import app
def json_error_handler(e):
return jsonify({
'status_code': e.code,
'error': e.name,
'detail': e.description
}), e.code
@app.errorhandler(400)
def bad_request_handler(e):
return json_error_handler(e)
@app.errorhandler(401)
def unauthorized_handler(e):
return json_error_handler(e)
@app.errorhandler(404)
def not_found_handler(e):
return json_error_handler(e)
@app.errorhandler(405)
def method_not_allowed_handler(e):
return json_error_handler(e)
|
dfc7e8a46558d3cf0e7f63da347e2b34253e302c | soundmeter/utils.py | soundmeter/utils.py | from ctypes import *
from contextlib import contextmanager
import os
import stat
def get_file_path(f):
if f:
name = getattr(f, 'name')
if name:
path = os.path.abspath(name)
return path
def create_executable(path, content):
with open(path, 'w') as f:
f.write(content)
s = os.stat(path)
os.chmod(path, s.st_mode | stat.S_IEXEC)
# Work-around on error messages by alsa-lib
# http://stackoverflow.com/questions/7088672/
ERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int,
c_char_p, c_int, c_char_p)
def py_error_handler(filename, line, function, err, fmt):
pass
c_error_handler = ERROR_HANDLER_FUNC(py_error_handler)
@contextmanager
def noalsaerr():
asound = cdll.LoadLibrary('libasound.so')
asound.snd_lib_error_set_handler(c_error_handler)
yield
asound.snd_lib_error_set_handler(None)
| from ctypes import * # NOQA
from contextlib import contextmanager
import os
import stat
def get_file_path(f):
if f:
name = getattr(f, 'name')
if name:
path = os.path.abspath(name)
return path
def create_executable(path, content):
with open(path, 'w') as f:
f.write(content)
s = os.stat(path)
os.chmod(path, s.st_mode | stat.S_IEXEC)
# Work-around on error messages by alsa-lib
# http://stackoverflow.com/questions/7088672/
ERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int,
c_char_p, c_int, c_char_p)
def py_error_handler(filename, line, function, err, fmt):
pass
c_error_handler = ERROR_HANDLER_FUNC(py_error_handler)
@contextmanager
def noalsaerr():
asound = cdll.LoadLibrary('libasound.so')
asound.snd_lib_error_set_handler(c_error_handler)
yield
asound.snd_lib_error_set_handler(None)
| Enforce flake8 and NOQA cases | Enforce flake8 and NOQA cases
| Python | bsd-2-clause | shichao-an/soundmeter | - from ctypes import *
+ from ctypes import * # NOQA
from contextlib import contextmanager
import os
import stat
def get_file_path(f):
if f:
name = getattr(f, 'name')
if name:
path = os.path.abspath(name)
return path
def create_executable(path, content):
with open(path, 'w') as f:
f.write(content)
s = os.stat(path)
os.chmod(path, s.st_mode | stat.S_IEXEC)
- # Work-around on error messages by alsa-lib
+ # Work-around on error messages by alsa-lib
# http://stackoverflow.com/questions/7088672/
ERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int,
- c_char_p, c_int, c_char_p)
+ c_char_p, c_int, c_char_p)
+
def py_error_handler(filename, line, function, err, fmt):
pass
c_error_handler = ERROR_HANDLER_FUNC(py_error_handler)
+
@contextmanager
def noalsaerr():
asound = cdll.LoadLibrary('libasound.so')
asound.snd_lib_error_set_handler(c_error_handler)
yield
asound.snd_lib_error_set_handler(None)
| Enforce flake8 and NOQA cases | ## Code Before:
from ctypes import *
from contextlib import contextmanager
import os
import stat
def get_file_path(f):
if f:
name = getattr(f, 'name')
if name:
path = os.path.abspath(name)
return path
def create_executable(path, content):
with open(path, 'w') as f:
f.write(content)
s = os.stat(path)
os.chmod(path, s.st_mode | stat.S_IEXEC)
# Work-around on error messages by alsa-lib
# http://stackoverflow.com/questions/7088672/
ERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int,
c_char_p, c_int, c_char_p)
def py_error_handler(filename, line, function, err, fmt):
pass
c_error_handler = ERROR_HANDLER_FUNC(py_error_handler)
@contextmanager
def noalsaerr():
asound = cdll.LoadLibrary('libasound.so')
asound.snd_lib_error_set_handler(c_error_handler)
yield
asound.snd_lib_error_set_handler(None)
## Instruction:
Enforce flake8 and NOQA cases
## Code After:
from ctypes import * # NOQA
from contextlib import contextmanager
import os
import stat
def get_file_path(f):
if f:
name = getattr(f, 'name')
if name:
path = os.path.abspath(name)
return path
def create_executable(path, content):
with open(path, 'w') as f:
f.write(content)
s = os.stat(path)
os.chmod(path, s.st_mode | stat.S_IEXEC)
# Work-around on error messages by alsa-lib
# http://stackoverflow.com/questions/7088672/
ERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int,
c_char_p, c_int, c_char_p)
def py_error_handler(filename, line, function, err, fmt):
pass
c_error_handler = ERROR_HANDLER_FUNC(py_error_handler)
@contextmanager
def noalsaerr():
asound = cdll.LoadLibrary('libasound.so')
asound.snd_lib_error_set_handler(c_error_handler)
yield
asound.snd_lib_error_set_handler(None)
|
569dbdc820d9ead02a8941d69b1c8143fe4d4cfa | pytest_pipeline/plugin.py | pytest_pipeline/plugin.py |
## credits to Holger Krekel himself for these xfail marking functions
## http://stackoverflow.com/a/12579625/243058
def pytest_runtest_makereport(item, call):
if "xfail_pipeline" in item.keywords:
if call.excinfo is not None:
parent = item.parent
parent._previousfailed = item
def pytest_addoption(parser):
group = parser.getgroup("general")
group.addoption("--base-pipeline-dir", dest="base_pipeline_dir",
default=None, metavar="dir",
help="Base directory to put all pipeline test directories")
group.addoption("--xfail-pipeline", dest="xfail_pipeline", action="store_true",
default=False,
help="Whether to fail a class immediately if any of its tests fail")
group.addoption("--skip-run", dest="skip_run", action="store_true",
default=False,
help="Whether to skip the pipeline run and all tests after it")
|
## credits to Holger Krekel himself for these xfail marking functions
## http://stackoverflow.com/a/12579625/243058
def pytest_runtest_makereport(item, call):
if "xfail_pipeline" in item.keywords:
if call.excinfo is not None:
parent = item.parent
parent._previousfailed = item
def pytest_addoption(parser):
group = parser.getgroup("general")
group.addoption("--base-pipeline-dir", dest="base_pipeline_dir",
default=None, metavar="dir",
help="Base directory to put all pipeline test directories")
group.addoption("--xfail-pipeline", dest="xfail_pipeline", action="store_true",
default=False,
help="Whether to fail a class immediately if any of its tests fail")
| Remove unused 'skip_run' option flag | Remove unused 'skip_run' option flag
| Python | bsd-3-clause | bow/pytest-pipeline |
## credits to Holger Krekel himself for these xfail marking functions
## http://stackoverflow.com/a/12579625/243058
def pytest_runtest_makereport(item, call):
if "xfail_pipeline" in item.keywords:
if call.excinfo is not None:
parent = item.parent
parent._previousfailed = item
def pytest_addoption(parser):
group = parser.getgroup("general")
group.addoption("--base-pipeline-dir", dest="base_pipeline_dir",
default=None, metavar="dir",
help="Base directory to put all pipeline test directories")
group.addoption("--xfail-pipeline", dest="xfail_pipeline", action="store_true",
default=False,
help="Whether to fail a class immediately if any of its tests fail")
- group.addoption("--skip-run", dest="skip_run", action="store_true",
- default=False,
- help="Whether to skip the pipeline run and all tests after it")
| Remove unused 'skip_run' option flag | ## Code Before:
## credits to Holger Krekel himself for these xfail marking functions
## http://stackoverflow.com/a/12579625/243058
def pytest_runtest_makereport(item, call):
if "xfail_pipeline" in item.keywords:
if call.excinfo is not None:
parent = item.parent
parent._previousfailed = item
def pytest_addoption(parser):
group = parser.getgroup("general")
group.addoption("--base-pipeline-dir", dest="base_pipeline_dir",
default=None, metavar="dir",
help="Base directory to put all pipeline test directories")
group.addoption("--xfail-pipeline", dest="xfail_pipeline", action="store_true",
default=False,
help="Whether to fail a class immediately if any of its tests fail")
group.addoption("--skip-run", dest="skip_run", action="store_true",
default=False,
help="Whether to skip the pipeline run and all tests after it")
## Instruction:
Remove unused 'skip_run' option flag
## Code After:
## credits to Holger Krekel himself for these xfail marking functions
## http://stackoverflow.com/a/12579625/243058
def pytest_runtest_makereport(item, call):
if "xfail_pipeline" in item.keywords:
if call.excinfo is not None:
parent = item.parent
parent._previousfailed = item
def pytest_addoption(parser):
group = parser.getgroup("general")
group.addoption("--base-pipeline-dir", dest="base_pipeline_dir",
default=None, metavar="dir",
help="Base directory to put all pipeline test directories")
group.addoption("--xfail-pipeline", dest="xfail_pipeline", action="store_true",
default=False,
help="Whether to fail a class immediately if any of its tests fail")
|
4f2a3f26b8b0ec1f62e036f0bd9d15d71a628e0c | mamba/formatters.py | mamba/formatters.py |
from clint.textui import indent, puts, colored
from mamba import spec
class DocumentationFormatter(object):
def __init__(self):
self.has_failed_tests = False
self.total_specs = 0
self.total_seconds = .0
def format(self, item):
puts(colored.white(item.name))
self._format_children(item)
def _format_children(self, item):
for spec_ in item.specs:
if isinstance(spec_, spec.Suite):
self.format_suite(spec_)
else:
self.format_spec(spec_)
def format_suite(self, suite):
with indent(1 + suite.depth):
puts(colored.white(suite.name))
self._format_children(suite)
def format_spec(self, spec_):
with indent(1 + spec_.depth):
symbol = colored.green('✓')
if spec_.failed:
symbol = colored.red('✗')
self.has_failed_tests = True
puts(symbol + ' ' + spec_.name.replace('_', ' '))
if spec_.failed:
with indent(spec_.depth + 2):
puts(colored.red(str(spec_.exception_caught())))
self.total_seconds += spec_.elapsed_time.total_seconds()
self.total_specs += 1
def format_summary(self):
puts()
color = colored.red if self.has_failed_tests else colored.green
puts(color("%d specs ran in %.4f seconds" % (self.total_specs, self.total_seconds)))
|
from clint.textui import indent, puts, colored
from mamba import spec
class DocumentationFormatter(object):
def __init__(self):
self.has_failed_tests = False
self.total_specs = 0
self.total_seconds = .0
def format(self, item):
puts()
puts(colored.white(item.name))
self._format_children(item)
def _format_children(self, item):
for spec_ in item.specs:
if isinstance(spec_, spec.Suite):
self.format_suite(spec_)
else:
self.format_spec(spec_)
def format_suite(self, suite):
with indent(1 + suite.depth):
puts(colored.white(suite.name))
self._format_children(suite)
def format_spec(self, spec_):
with indent(1 + spec_.depth):
symbol = colored.green('✓')
if spec_.failed:
symbol = colored.red('✗')
self.has_failed_tests = True
puts(symbol + ' ' + spec_.name.replace('_', ' '))
if spec_.failed:
with indent(spec_.depth + 2):
puts(colored.red(str(spec_.exception_caught())))
self.total_seconds += spec_.elapsed_time.total_seconds()
self.total_specs += 1
def format_summary(self):
puts()
color = colored.red if self.has_failed_tests else colored.green
puts(color("%d specs ran in %.4f seconds" % (self.total_specs, self.total_seconds)))
| Put a blank line among main suites | Put a blank line among main suites
| Python | mit | alejandrodob/mamba,eferro/mamba,jaimegildesagredo/mamba,dex4er/mamba,angelsanz/mamba,nestorsalceda/mamba,markng/mamba |
from clint.textui import indent, puts, colored
from mamba import spec
class DocumentationFormatter(object):
def __init__(self):
self.has_failed_tests = False
self.total_specs = 0
self.total_seconds = .0
def format(self, item):
+ puts()
puts(colored.white(item.name))
self._format_children(item)
def _format_children(self, item):
for spec_ in item.specs:
if isinstance(spec_, spec.Suite):
self.format_suite(spec_)
else:
self.format_spec(spec_)
def format_suite(self, suite):
with indent(1 + suite.depth):
puts(colored.white(suite.name))
self._format_children(suite)
def format_spec(self, spec_):
with indent(1 + spec_.depth):
symbol = colored.green('✓')
if spec_.failed:
symbol = colored.red('✗')
self.has_failed_tests = True
puts(symbol + ' ' + spec_.name.replace('_', ' '))
if spec_.failed:
with indent(spec_.depth + 2):
puts(colored.red(str(spec_.exception_caught())))
self.total_seconds += spec_.elapsed_time.total_seconds()
self.total_specs += 1
def format_summary(self):
puts()
color = colored.red if self.has_failed_tests else colored.green
puts(color("%d specs ran in %.4f seconds" % (self.total_specs, self.total_seconds)))
| Put a blank line among main suites | ## Code Before:
from clint.textui import indent, puts, colored
from mamba import spec
class DocumentationFormatter(object):
def __init__(self):
self.has_failed_tests = False
self.total_specs = 0
self.total_seconds = .0
def format(self, item):
puts(colored.white(item.name))
self._format_children(item)
def _format_children(self, item):
for spec_ in item.specs:
if isinstance(spec_, spec.Suite):
self.format_suite(spec_)
else:
self.format_spec(spec_)
def format_suite(self, suite):
with indent(1 + suite.depth):
puts(colored.white(suite.name))
self._format_children(suite)
def format_spec(self, spec_):
with indent(1 + spec_.depth):
symbol = colored.green('✓')
if spec_.failed:
symbol = colored.red('✗')
self.has_failed_tests = True
puts(symbol + ' ' + spec_.name.replace('_', ' '))
if spec_.failed:
with indent(spec_.depth + 2):
puts(colored.red(str(spec_.exception_caught())))
self.total_seconds += spec_.elapsed_time.total_seconds()
self.total_specs += 1
def format_summary(self):
puts()
color = colored.red if self.has_failed_tests else colored.green
puts(color("%d specs ran in %.4f seconds" % (self.total_specs, self.total_seconds)))
## Instruction:
Put a blank line among main suites
## Code After:
from clint.textui import indent, puts, colored
from mamba import spec
class DocumentationFormatter(object):
def __init__(self):
self.has_failed_tests = False
self.total_specs = 0
self.total_seconds = .0
def format(self, item):
puts()
puts(colored.white(item.name))
self._format_children(item)
def _format_children(self, item):
for spec_ in item.specs:
if isinstance(spec_, spec.Suite):
self.format_suite(spec_)
else:
self.format_spec(spec_)
def format_suite(self, suite):
with indent(1 + suite.depth):
puts(colored.white(suite.name))
self._format_children(suite)
def format_spec(self, spec_):
with indent(1 + spec_.depth):
symbol = colored.green('✓')
if spec_.failed:
symbol = colored.red('✗')
self.has_failed_tests = True
puts(symbol + ' ' + spec_.name.replace('_', ' '))
if spec_.failed:
with indent(spec_.depth + 2):
puts(colored.red(str(spec_.exception_caught())))
self.total_seconds += spec_.elapsed_time.total_seconds()
self.total_specs += 1
def format_summary(self):
puts()
color = colored.red if self.has_failed_tests else colored.green
puts(color("%d specs ran in %.4f seconds" % (self.total_specs, self.total_seconds)))
|
f9f9111ddafb7dfd0554d541befd3cc660169689 | apps/redirects/urls.py | apps/redirects/urls.py | from django.conf.urls.defaults import *
from util import redirect
urlpatterns = patterns('',
redirect(r'^b2g', 'firefoxos'),
redirect(r'^b2g/faq', 'firefoxos'),
redirect(r'^b2g/about', 'firefoxos'),
)
| from django.conf.urls.defaults import *
from util import redirect
urlpatterns = patterns('',
redirect(r'^b2g', 'firefoxos.firefoxos'),
redirect(r'^b2g/faq', 'firefoxos.firefoxos'),
redirect(r'^b2g/about', 'firefoxos.firefoxos'),
)
| Fix view name for b2g redirects | Fix view name for b2g redirects
bug 792482
| Python | mpl-2.0 | dudepare/bedrock,rishiloyola/bedrock,mahinthjoe/bedrock,ckprice/bedrock,davehunt/bedrock,davidwboswell/documentation_autoresponse,jpetto/bedrock,dudepare/bedrock,glogiotatidis/bedrock,kyoshino/bedrock,mahinthjoe/bedrock,MichaelKohler/bedrock,ckprice/bedrock,analytics-pros/mozilla-bedrock,analytics-pros/mozilla-bedrock,MichaelKohler/bedrock,sylvestre/bedrock,CSCI-462-01-2017/bedrock,chirilo/bedrock,chirilo/bedrock,yglazko/bedrock,sgarrity/bedrock,SujaySKumar/bedrock,elin-moco/bedrock,kyoshino/bedrock,mmmavis/bedrock,jpetto/bedrock,andreadelrio/bedrock,davidwboswell/documentation_autoresponse,jpetto/bedrock,jacshfr/mozilla-bedrock,davehunt/bedrock,gauthierm/bedrock,Sancus/bedrock,ericawright/bedrock,gauthierm/bedrock,TheoChevalier/bedrock,mozilla/bedrock,gauthierm/bedrock,TheJJ100100/bedrock,ckprice/bedrock,TheoChevalier/bedrock,yglazko/bedrock,mmmavis/bedrock,flodolo/bedrock,bensternthal/bedrock,mmmavis/lightbeam-bedrock-website,glogiotatidis/bedrock,alexgibson/bedrock,glogiotatidis/bedrock,pascalchevrel/bedrock,MichaelKohler/bedrock,pmclanahan/bedrock,mmmavis/lightbeam-bedrock-website,jgmize/bedrock,sylvestre/bedrock,Sancus/bedrock,malena/bedrock,mozilla/mwc,kyoshino/bedrock,Jobava/bedrock,petabyte/bedrock,schalkneethling/bedrock,sgarrity/bedrock,gerv/bedrock,pascalchevrel/bedrock,CSCI-462-01-2017/bedrock,yglazko/bedrock,mozilla/mwc,jacshfr/mozilla-bedrock,jgmize/bedrock,mozilla/bedrock,Jobava/bedrock,mmmavis/bedrock,mkmelin/bedrock,glogiotatidis/bedrock,davidwboswell/documentation_autoresponse,petabyte/bedrock,marcoscaceres/bedrock,petabyte/bedrock,mermi/bedrock,jacshfr/mozilla-bedrock,davehunt/bedrock,CSCI-462-01-2017/bedrock,chirilo/bedrock,andreadelrio/bedrock,SujaySKumar/bedrock,ericawright/bedrock,sgarrity/bedrock,analytics-pros/mozilla-bedrock,TheJJ100100/bedrock,malena/bedrock,alexgibson/bedrock,craigcook/bedrock,malena/bedrock,mmmavis/bedrock,davehunt/bedrock,rishiloyola/bedrock,l-hedgehog/bedrock,mahinthjoe/bedrock,jacshfr/mozilla-bedrock,kyoshino/bedrock,flodolo/bedrock,pmclanahan/bedrock,gauthierm/bedrock,ericawright/bedrock,sgarrity/bedrock,andreadelrio/bedrock,bensternthal/bedrock,bensternthal/bedrock,mermi/bedrock,pmclanahan/bedrock,flodolo/bedrock,yglazko/bedrock,marcoscaceres/bedrock,mkmelin/bedrock,hoosteeno/bedrock,davidwboswell/documentation_autoresponse,amjadm61/bedrock,amjadm61/bedrock,TheoChevalier/bedrock,alexgibson/bedrock,Jobava/bedrock,jgmize/bedrock,amjadm61/bedrock,dudepare/bedrock,mozilla/bedrock,elin-moco/bedrock,schalkneethling/bedrock,petabyte/bedrock,mermi/bedrock,mmmavis/lightbeam-bedrock-website,craigcook/bedrock,pmclanahan/bedrock,rishiloyola/bedrock,analytics-pros/mozilla-bedrock,gerv/bedrock,alexgibson/bedrock,SujaySKumar/bedrock,dudepare/bedrock,andreadelrio/bedrock,amjadm61/bedrock,marcoscaceres/bedrock,elin-moco/bedrock,chirilo/bedrock,jacshfr/mozilla-bedrock,l-hedgehog/bedrock,gerv/bedrock,schalkneethling/bedrock,flodolo/bedrock,pascalchevrel/bedrock,bensternthal/bedrock,mozilla/bedrock,hoosteeno/bedrock,sylvestre/bedrock,Sancus/bedrock,jgmize/bedrock,hoosteeno/bedrock,sylvestre/bedrock,mahinthjoe/bedrock,TheJJ100100/bedrock,mozilla/mwc,ericawright/bedrock,Jobava/bedrock,rishiloyola/bedrock,craigcook/bedrock,amjadm61/bedrock,gerv/bedrock,mozilla/mwc,malena/bedrock,craigcook/bedrock,TheoChevalier/bedrock,schalkneethling/bedrock,TheJJ100100/bedrock,marcoscaceres/bedrock,mermi/bedrock,SujaySKumar/bedrock,ckprice/bedrock,pascalchevrel/bedrock,Sancus/bedrock,elin-moco/bedrock,l-hedgehog/bedrock,jpetto/bedrock,CSCI-462-01-2017/bedrock,l-hedgehog/bedrock,mkmelin/bedrock,hoosteeno/bedrock,mkmelin/bedrock,MichaelKohler/bedrock | from django.conf.urls.defaults import *
from util import redirect
urlpatterns = patterns('',
- redirect(r'^b2g', 'firefoxos'),
+ redirect(r'^b2g', 'firefoxos.firefoxos'),
- redirect(r'^b2g/faq', 'firefoxos'),
+ redirect(r'^b2g/faq', 'firefoxos.firefoxos'),
- redirect(r'^b2g/about', 'firefoxos'),
+ redirect(r'^b2g/about', 'firefoxos.firefoxos'),
-
+
)
| Fix view name for b2g redirects | ## Code Before:
from django.conf.urls.defaults import *
from util import redirect
urlpatterns = patterns('',
redirect(r'^b2g', 'firefoxos'),
redirect(r'^b2g/faq', 'firefoxos'),
redirect(r'^b2g/about', 'firefoxos'),
)
## Instruction:
Fix view name for b2g redirects
## Code After:
from django.conf.urls.defaults import *
from util import redirect
urlpatterns = patterns('',
redirect(r'^b2g', 'firefoxos.firefoxos'),
redirect(r'^b2g/faq', 'firefoxos.firefoxos'),
redirect(r'^b2g/about', 'firefoxos.firefoxos'),
)
|
960eb0ce813988d8f90e76fbfd0485656cef541f | mff_rams_plugin/__init__.py | mff_rams_plugin/__init__.py | from uber.common import *
from ._version import __version__
from .config import *
from .models import *
from .model_checks import *
from .automated_emails import *
static_overrides(join(config['module_root'], 'static'))
template_overrides(join(config['module_root'], 'templates'))
mount_site_sections(config['module_root'])
c.MENU.append_menu_item(MenuItem(name='People', access=[c.PEOPLE, c.REG_AT_CON], submenu=[
MenuItem(name='Comped Badges', href='../mff_reports/comped_badges', access=c.PEOPLE),
])
)
| from uber.common import *
from ._version import __version__
from .config import *
from .models import *
from .model_checks import *
from .automated_emails import *
static_overrides(join(config['module_root'], 'static'))
template_overrides(join(config['module_root'], 'templates'))
mount_site_sections(config['module_root'])
c.MENU.append_menu_item(MenuItem(name='Midwest FurFest', access=c.PEOPLE, submenu=[
MenuItem(name='Comped Badges', href='../mff_reports/comped_badges'),
])
)
| Rename new admin dropdown menu | Rename new admin dropdown menu
| Python | agpl-3.0 | MidwestFurryFandom/mff-rams-plugin,MidwestFurryFandom/mff-rams-plugin | from uber.common import *
from ._version import __version__
from .config import *
from .models import *
from .model_checks import *
from .automated_emails import *
static_overrides(join(config['module_root'], 'static'))
template_overrides(join(config['module_root'], 'templates'))
mount_site_sections(config['module_root'])
- c.MENU.append_menu_item(MenuItem(name='People', access=[c.PEOPLE, c.REG_AT_CON], submenu=[
+ c.MENU.append_menu_item(MenuItem(name='Midwest FurFest', access=c.PEOPLE, submenu=[
- MenuItem(name='Comped Badges', href='../mff_reports/comped_badges', access=c.PEOPLE),
+ MenuItem(name='Comped Badges', href='../mff_reports/comped_badges'),
])
)
| Rename new admin dropdown menu | ## Code Before:
from uber.common import *
from ._version import __version__
from .config import *
from .models import *
from .model_checks import *
from .automated_emails import *
static_overrides(join(config['module_root'], 'static'))
template_overrides(join(config['module_root'], 'templates'))
mount_site_sections(config['module_root'])
c.MENU.append_menu_item(MenuItem(name='People', access=[c.PEOPLE, c.REG_AT_CON], submenu=[
MenuItem(name='Comped Badges', href='../mff_reports/comped_badges', access=c.PEOPLE),
])
)
## Instruction:
Rename new admin dropdown menu
## Code After:
from uber.common import *
from ._version import __version__
from .config import *
from .models import *
from .model_checks import *
from .automated_emails import *
static_overrides(join(config['module_root'], 'static'))
template_overrides(join(config['module_root'], 'templates'))
mount_site_sections(config['module_root'])
c.MENU.append_menu_item(MenuItem(name='Midwest FurFest', access=c.PEOPLE, submenu=[
MenuItem(name='Comped Badges', href='../mff_reports/comped_badges'),
])
)
|
6196c1fe13df88c1d9f1fe706120c175ab890a1d | gen_tone.py | gen_tone.py | import math
import numpy
from demodulate.cfg import *
def gen_tone(pattern, WPM):
cycles_per_sample = MORSE_FREQ/SAMPLE_FREQ
radians_per_sample = cycles_per_sample * 2 * math.pi
elements_per_second = WPM * 50.0 / 60.0
samples_per_element = int(SAMPLE_FREQ/elements_per_second)
length = samples_per_element * len(pattern)
# Empty returns array containing random stuff, so we NEED to overwrite it
data = numpy.empty(length, dtype=numpy.float32)
for i in xrange(length):
keyed = pattern[int(i/samples_per_element)]
#keyed = 1
data[i] = 0 if not keyed else (radians_per_sample * i)
data = numpy.sin(data)
return data
| import math
import numpy
from demodulate.cfg import *
def gen_tone(pattern, WPM):
cycles_per_sample = MORSE_FREQ/SAMPLE_FREQ
radians_per_sample = cycles_per_sample * 2 * math.pi
elements_per_second = WPM * 50.0 / 60.0
samples_per_element = int(SAMPLE_FREQ/elements_per_second)
length = samples_per_element * len(pattern)
# Empty returns array containing random stuff, so we NEED to overwrite it
data = numpy.empty(length, dtype=numpy.float32)
for i in xrange(length):
keyed = pattern[int(i/samples_per_element)]
#keyed = 1
data[i] = 0 if not keyed else (radians_per_sample * i)
data = numpy.sin(data)
data *= 2**16-1
data = numpy.array(data, dtype=numpy.int16)
return data
| Use 16 bit samples instead of float | Use 16 bit samples instead of float
| Python | mit | nickodell/morse-code | import math
import numpy
from demodulate.cfg import *
def gen_tone(pattern, WPM):
cycles_per_sample = MORSE_FREQ/SAMPLE_FREQ
radians_per_sample = cycles_per_sample * 2 * math.pi
elements_per_second = WPM * 50.0 / 60.0
samples_per_element = int(SAMPLE_FREQ/elements_per_second)
length = samples_per_element * len(pattern)
# Empty returns array containing random stuff, so we NEED to overwrite it
data = numpy.empty(length, dtype=numpy.float32)
for i in xrange(length):
keyed = pattern[int(i/samples_per_element)]
#keyed = 1
data[i] = 0 if not keyed else (radians_per_sample * i)
data = numpy.sin(data)
-
+ data *= 2**16-1
+ data = numpy.array(data, dtype=numpy.int16)
return data
| Use 16 bit samples instead of float | ## Code Before:
import math
import numpy
from demodulate.cfg import *
def gen_tone(pattern, WPM):
cycles_per_sample = MORSE_FREQ/SAMPLE_FREQ
radians_per_sample = cycles_per_sample * 2 * math.pi
elements_per_second = WPM * 50.0 / 60.0
samples_per_element = int(SAMPLE_FREQ/elements_per_second)
length = samples_per_element * len(pattern)
# Empty returns array containing random stuff, so we NEED to overwrite it
data = numpy.empty(length, dtype=numpy.float32)
for i in xrange(length):
keyed = pattern[int(i/samples_per_element)]
#keyed = 1
data[i] = 0 if not keyed else (radians_per_sample * i)
data = numpy.sin(data)
return data
## Instruction:
Use 16 bit samples instead of float
## Code After:
import math
import numpy
from demodulate.cfg import *
def gen_tone(pattern, WPM):
cycles_per_sample = MORSE_FREQ/SAMPLE_FREQ
radians_per_sample = cycles_per_sample * 2 * math.pi
elements_per_second = WPM * 50.0 / 60.0
samples_per_element = int(SAMPLE_FREQ/elements_per_second)
length = samples_per_element * len(pattern)
# Empty returns array containing random stuff, so we NEED to overwrite it
data = numpy.empty(length, dtype=numpy.float32)
for i in xrange(length):
keyed = pattern[int(i/samples_per_element)]
#keyed = 1
data[i] = 0 if not keyed else (radians_per_sample * i)
data = numpy.sin(data)
data *= 2**16-1
data = numpy.array(data, dtype=numpy.int16)
return data
|
da28458dffc3529f16cb222fce1676ddb0d87e05 | oembed/resources.py | oembed/resources.py | from django.utils.simplejson import simplejson
from oembed.exceptions import OEmbedException
class OEmbedResource(object):
"""
OEmbed resource, as well as a factory for creating resource instances
from response json
"""
_data = {}
content_object = None
def __getattr__(self, name):
return self._data.get(name)
def get_data(self):
return self._data
def load_data(self, data):
self._data = data
@property
def json(self):
return simplejson.dumps(self._data)
@classmethod
def create(cls, data):
if not 'type' in data or not 'version' in data:
raise OEmbedException('Missing required fields on OEmbed response.')
data['width'] = data.get('width') and int(data['width']) or None
data['height'] = data.get('height') and int(data['height']) or None
filtered_data = dict([(k, v) for k, v in data.items() if v])
resource = cls()
resource.load_data(filtered_data)
return resource
@classmethod
def create_json(cls, raw):
data = simplejson.loads(raw)
return cls.create(data)
| from django.utils import simplejson
from oembed.exceptions import OEmbedException
class OEmbedResource(object):
"""
OEmbed resource, as well as a factory for creating resource instances
from response json
"""
_data = {}
content_object = None
def __getattr__(self, name):
return self._data.get(name)
def get_data(self):
return self._data
def load_data(self, data):
self._data = data
@property
def json(self):
return simplejson.dumps(self._data)
@classmethod
def create(cls, data):
if not 'type' in data or not 'version' in data:
raise OEmbedException('Missing required fields on OEmbed response.')
data['width'] = data.get('width') and int(data['width']) or None
data['height'] = data.get('height') and int(data['height']) or None
filtered_data = dict([(k, v) for k, v in data.items() if v])
resource = cls()
resource.load_data(filtered_data)
return resource
@classmethod
def create_json(cls, raw):
data = simplejson.loads(raw)
return cls.create(data)
| Use the simplejson bundled with django | Use the simplejson bundled with django
| Python | mit | 0101/djangoembed,worldcompany/djangoembed,akvo/djangoembed,akvo/djangoembed,worldcompany/djangoembed,d4nielcosta/djangoembed,0101/djangoembed,d4nielcosta/djangoembed | - from django.utils.simplejson import simplejson
+ from django.utils import simplejson
from oembed.exceptions import OEmbedException
class OEmbedResource(object):
"""
OEmbed resource, as well as a factory for creating resource instances
from response json
"""
_data = {}
content_object = None
def __getattr__(self, name):
return self._data.get(name)
def get_data(self):
return self._data
def load_data(self, data):
self._data = data
@property
def json(self):
return simplejson.dumps(self._data)
@classmethod
def create(cls, data):
if not 'type' in data or not 'version' in data:
raise OEmbedException('Missing required fields on OEmbed response.')
data['width'] = data.get('width') and int(data['width']) or None
data['height'] = data.get('height') and int(data['height']) or None
filtered_data = dict([(k, v) for k, v in data.items() if v])
resource = cls()
resource.load_data(filtered_data)
return resource
@classmethod
def create_json(cls, raw):
data = simplejson.loads(raw)
return cls.create(data)
| Use the simplejson bundled with django | ## Code Before:
from django.utils.simplejson import simplejson
from oembed.exceptions import OEmbedException
class OEmbedResource(object):
"""
OEmbed resource, as well as a factory for creating resource instances
from response json
"""
_data = {}
content_object = None
def __getattr__(self, name):
return self._data.get(name)
def get_data(self):
return self._data
def load_data(self, data):
self._data = data
@property
def json(self):
return simplejson.dumps(self._data)
@classmethod
def create(cls, data):
if not 'type' in data or not 'version' in data:
raise OEmbedException('Missing required fields on OEmbed response.')
data['width'] = data.get('width') and int(data['width']) or None
data['height'] = data.get('height') and int(data['height']) or None
filtered_data = dict([(k, v) for k, v in data.items() if v])
resource = cls()
resource.load_data(filtered_data)
return resource
@classmethod
def create_json(cls, raw):
data = simplejson.loads(raw)
return cls.create(data)
## Instruction:
Use the simplejson bundled with django
## Code After:
from django.utils import simplejson
from oembed.exceptions import OEmbedException
class OEmbedResource(object):
"""
OEmbed resource, as well as a factory for creating resource instances
from response json
"""
_data = {}
content_object = None
def __getattr__(self, name):
return self._data.get(name)
def get_data(self):
return self._data
def load_data(self, data):
self._data = data
@property
def json(self):
return simplejson.dumps(self._data)
@classmethod
def create(cls, data):
if not 'type' in data or not 'version' in data:
raise OEmbedException('Missing required fields on OEmbed response.')
data['width'] = data.get('width') and int(data['width']) or None
data['height'] = data.get('height') and int(data['height']) or None
filtered_data = dict([(k, v) for k, v in data.items() if v])
resource = cls()
resource.load_data(filtered_data)
return resource
@classmethod
def create_json(cls, raw):
data = simplejson.loads(raw)
return cls.create(data)
|
1cb201c57c592ebd014910fe225fa594cd87c745 | opendebates/middleware.py | opendebates/middleware.py | from opendebates.utils import get_site_mode
class SiteModeMiddleware(object):
"""
Gets or creates a SiteMode for the request, based on the hostname.
"""
def process_view(self, request, view_func, view_args, view_kwargs):
request.site_mode = get_site_mode(request)
| from opendebates.utils import get_site_mode
class SiteModeMiddleware(object):
"""
Gets or creates a SiteMode for the request, based on the hostname.
"""
def process_request(self, request):
request.site_mode = get_site_mode(request)
| Make sure that the site mode is populated on the request | Make sure that the site mode is populated on the request
even if the request winds up getting dispatched to a flatpage.
| Python | apache-2.0 | caktus/django-opendebates,caktus/django-opendebates,caktus/django-opendebates,caktus/django-opendebates | from opendebates.utils import get_site_mode
class SiteModeMiddleware(object):
"""
Gets or creates a SiteMode for the request, based on the hostname.
"""
- def process_view(self, request, view_func, view_args, view_kwargs):
+ def process_request(self, request):
request.site_mode = get_site_mode(request)
| Make sure that the site mode is populated on the request | ## Code Before:
from opendebates.utils import get_site_mode
class SiteModeMiddleware(object):
"""
Gets or creates a SiteMode for the request, based on the hostname.
"""
def process_view(self, request, view_func, view_args, view_kwargs):
request.site_mode = get_site_mode(request)
## Instruction:
Make sure that the site mode is populated on the request
## Code After:
from opendebates.utils import get_site_mode
class SiteModeMiddleware(object):
"""
Gets or creates a SiteMode for the request, based on the hostname.
"""
def process_request(self, request):
request.site_mode = get_site_mode(request)
|
9651c0278d93bf5c4620e198baac975f0c84e9a0 | src/unittest/stattestmain.py | src/unittest/stattestmain.py | def main():
from _m5.stattest import stattest_init, stattest_run
import m5.stats
stattest_init()
# Initialize the global statistics
m5.stats.initSimStats()
m5.stats.initText("cout")
# We're done registering statistics. Enable the stats package now.
m5.stats.enable()
# Reset to put the stats in a consistent state.
m5.stats.reset()
stattest_run()
m5.stats.dump()
| def main():
from _m5.stattest import stattest_init, stattest_run
import m5.stats
stattest_init()
# Initialize the global statistics
m5.stats.initSimStats()
m5.stats.addStatVisitor("cout")
# We're done registering statistics. Enable the stats package now.
m5.stats.enable()
# Reset to put the stats in a consistent state.
m5.stats.reset()
stattest_run()
m5.stats.dump()
| Fix the stats unit test. | tests: Fix the stats unit test.
This has been broken since February. The interface for opening
initializing where the stats output should go was changed, but the
test wasn't updated.
Change-Id: I54bd8be15bf870352d5fcfad95ded28d87c7cc5a
Reviewed-on: https://gem5-review.googlesource.com/6001
Reviewed-by: Andreas Sandberg <[email protected]>
Maintainer: Andreas Sandberg <[email protected]>
| Python | bsd-3-clause | TUD-OS/gem5-dtu,gem5/gem5,TUD-OS/gem5-dtu,gem5/gem5,gem5/gem5,TUD-OS/gem5-dtu,TUD-OS/gem5-dtu,gem5/gem5,TUD-OS/gem5-dtu,gem5/gem5,TUD-OS/gem5-dtu,gem5/gem5,gem5/gem5,TUD-OS/gem5-dtu | def main():
from _m5.stattest import stattest_init, stattest_run
import m5.stats
stattest_init()
# Initialize the global statistics
m5.stats.initSimStats()
- m5.stats.initText("cout")
+ m5.stats.addStatVisitor("cout")
# We're done registering statistics. Enable the stats package now.
m5.stats.enable()
# Reset to put the stats in a consistent state.
m5.stats.reset()
stattest_run()
m5.stats.dump()
| Fix the stats unit test. | ## Code Before:
def main():
from _m5.stattest import stattest_init, stattest_run
import m5.stats
stattest_init()
# Initialize the global statistics
m5.stats.initSimStats()
m5.stats.initText("cout")
# We're done registering statistics. Enable the stats package now.
m5.stats.enable()
# Reset to put the stats in a consistent state.
m5.stats.reset()
stattest_run()
m5.stats.dump()
## Instruction:
Fix the stats unit test.
## Code After:
def main():
from _m5.stattest import stattest_init, stattest_run
import m5.stats
stattest_init()
# Initialize the global statistics
m5.stats.initSimStats()
m5.stats.addStatVisitor("cout")
# We're done registering statistics. Enable the stats package now.
m5.stats.enable()
# Reset to put the stats in a consistent state.
m5.stats.reset()
stattest_run()
m5.stats.dump()
|
61accbe3fa6ebdeed3bbf48573d5ac5412d0f1db | app/status/views.py | app/status/views.py | import os
from flask import jsonify, current_app, request
from sqlalchemy.exc import SQLAlchemyError
from . import status
from . import utils
from dmutils.status import get_flags
@status.route('/_status')
def status_no_db():
if 'ignore-dependencies' in request.args:
return jsonify(
status="ok",
), 200
version = current_app.config['VERSION']
try:
return jsonify(
status="ok",
version=version,
db_version=utils.get_db_version(),
flags=get_flags(current_app)
)
except SQLAlchemyError:
current_app.logger.exception('Error connecting to database')
return jsonify(
status="error",
version=version,
message="Error connecting to database",
flags=get_flags(current_app)
), 500
| from flask import jsonify, current_app, request
from sqlalchemy.exc import SQLAlchemyError
from . import status
from . import utils
from ..models import Framework
from dmutils.status import get_flags
@status.route('/_status')
def status_no_db():
if 'ignore-dependencies' in request.args:
return jsonify(
status="ok",
), 200
version = current_app.config['VERSION']
try:
return jsonify(
status="ok",
frameworks={f.slug: f.status for f in Framework.query.all()},
version=version,
db_version=utils.get_db_version(),
flags=get_flags(current_app)
)
except SQLAlchemyError:
current_app.logger.exception('Error connecting to database')
return jsonify(
status="error",
version=version,
message="Error connecting to database",
flags=get_flags(current_app)
), 500
| Add framework status to API /_status | Add framework status to API /_status
To figure out current framework statuses for the given environment
you either need access to the API token or you'd have to look through
a number of frontend pages to infer the status from.
Framework status is a part of almost every request to the API, so
it should always be available for a working API instance and it makes
sense to add it to the /_status page.
Adding it to the /_status page creates an easier way to get the list
of all framework statuses.
| Python | mit | alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api | - import os
from flask import jsonify, current_app, request
from sqlalchemy.exc import SQLAlchemyError
from . import status
from . import utils
+ from ..models import Framework
from dmutils.status import get_flags
@status.route('/_status')
def status_no_db():
if 'ignore-dependencies' in request.args:
return jsonify(
status="ok",
), 200
version = current_app.config['VERSION']
try:
return jsonify(
status="ok",
+ frameworks={f.slug: f.status for f in Framework.query.all()},
version=version,
db_version=utils.get_db_version(),
flags=get_flags(current_app)
)
except SQLAlchemyError:
current_app.logger.exception('Error connecting to database')
return jsonify(
status="error",
version=version,
message="Error connecting to database",
flags=get_flags(current_app)
), 500
| Add framework status to API /_status | ## Code Before:
import os
from flask import jsonify, current_app, request
from sqlalchemy.exc import SQLAlchemyError
from . import status
from . import utils
from dmutils.status import get_flags
@status.route('/_status')
def status_no_db():
if 'ignore-dependencies' in request.args:
return jsonify(
status="ok",
), 200
version = current_app.config['VERSION']
try:
return jsonify(
status="ok",
version=version,
db_version=utils.get_db_version(),
flags=get_flags(current_app)
)
except SQLAlchemyError:
current_app.logger.exception('Error connecting to database')
return jsonify(
status="error",
version=version,
message="Error connecting to database",
flags=get_flags(current_app)
), 500
## Instruction:
Add framework status to API /_status
## Code After:
from flask import jsonify, current_app, request
from sqlalchemy.exc import SQLAlchemyError
from . import status
from . import utils
from ..models import Framework
from dmutils.status import get_flags
@status.route('/_status')
def status_no_db():
if 'ignore-dependencies' in request.args:
return jsonify(
status="ok",
), 200
version = current_app.config['VERSION']
try:
return jsonify(
status="ok",
frameworks={f.slug: f.status for f in Framework.query.all()},
version=version,
db_version=utils.get_db_version(),
flags=get_flags(current_app)
)
except SQLAlchemyError:
current_app.logger.exception('Error connecting to database')
return jsonify(
status="error",
version=version,
message="Error connecting to database",
flags=get_flags(current_app)
), 500
|
8d1a4869286735a55773ce0c074349bb0cafd3aa | ca_on_ottawa/people.py | ca_on_ottawa/people.py | from utils import CSVScraper
class OttawaPersonScraper(CSVScraper):
csv_url = 'http://data.ottawa.ca/en/dataset/fd26ae83-fe1a-40d8-8951-72df40021c82/resource/33a437d3-a06d-4c56-a7fe-4fd622364ce6/download/elected-officials-282014-201829-v.2.csv'
| from utils import CSVScraper
class OttawaPersonScraper(CSVScraper):
csv_url = 'http://data.ottawa.ca/en/dataset/fd26ae83-fe1a-40d8-8951-72df40021c82/resource/33a437d3-a06d-4c56-a7fe-4fd622364ce6/download/elected-officials-282014-201829-v.2.csv'
corrections = {
'district name': {
"Orl\u0082ans": 'Orléans',
},
} | Use corrections, as none of utf-8, iso-8859-1 or windows-1252 work | ca_on_ottawa: Use corrections, as none of utf-8, iso-8859-1 or windows-1252 work
| Python | mit | opencivicdata/scrapers-ca,opencivicdata/scrapers-ca | from utils import CSVScraper
class OttawaPersonScraper(CSVScraper):
csv_url = 'http://data.ottawa.ca/en/dataset/fd26ae83-fe1a-40d8-8951-72df40021c82/resource/33a437d3-a06d-4c56-a7fe-4fd622364ce6/download/elected-officials-282014-201829-v.2.csv'
-
+ corrections = {
+ 'district name': {
+ "Orl\u0082ans": 'Orléans',
+ },
+ } | Use corrections, as none of utf-8, iso-8859-1 or windows-1252 work | ## Code Before:
from utils import CSVScraper
class OttawaPersonScraper(CSVScraper):
csv_url = 'http://data.ottawa.ca/en/dataset/fd26ae83-fe1a-40d8-8951-72df40021c82/resource/33a437d3-a06d-4c56-a7fe-4fd622364ce6/download/elected-officials-282014-201829-v.2.csv'
## Instruction:
Use corrections, as none of utf-8, iso-8859-1 or windows-1252 work
## Code After:
from utils import CSVScraper
class OttawaPersonScraper(CSVScraper):
csv_url = 'http://data.ottawa.ca/en/dataset/fd26ae83-fe1a-40d8-8951-72df40021c82/resource/33a437d3-a06d-4c56-a7fe-4fd622364ce6/download/elected-officials-282014-201829-v.2.csv'
corrections = {
'district name': {
"Orl\u0082ans": 'Orléans',
},
} |
e326cef4ae66d4d2dd500e933ff4f7c6fc619b28 | fix-perm.py | fix-perm.py |
from __future__ import print_function
import os
import stat
import sys
if __name__ == '__main__':
for line in sys.stdin:
path = line.rstrip('\n')
if path == '':
continue
if not os.path.isfile(path):
continue
st = os.stat(path)
mode = st.st_mode
os.chmod(path, mode | stat.S_IRUSR | stat.S_IWUSR)
|
from __future__ import print_function
import os
import stat
import sys
if __name__ == '__main__':
for line in sys.stdin:
path = line.rstrip('\n')
if path == '':
continue
if not os.path.isfile(path):
continue
st = os.stat(path)
mode = int('644', 8)
if st.st_mode & stat.S_IXUSR != 0:
mode = int('755', 8)
with open(path) as f:
x = f.read(2)
if x == '#!':
mode = int('755', 8)
os.chmod(path, mode)
| Change permissions to either 644 or 755. | Change permissions to either 644 or 755.
| Python | isc | eliteraspberries/minipkg,eliteraspberries/minipkg |
from __future__ import print_function
import os
import stat
import sys
if __name__ == '__main__':
for line in sys.stdin:
path = line.rstrip('\n')
if path == '':
continue
if not os.path.isfile(path):
continue
st = os.stat(path)
- mode = st.st_mode
- os.chmod(path, mode | stat.S_IRUSR | stat.S_IWUSR)
+ mode = int('644', 8)
+ if st.st_mode & stat.S_IXUSR != 0:
+ mode = int('755', 8)
+ with open(path) as f:
+ x = f.read(2)
+ if x == '#!':
+ mode = int('755', 8)
+ os.chmod(path, mode)
| Change permissions to either 644 or 755. | ## Code Before:
from __future__ import print_function
import os
import stat
import sys
if __name__ == '__main__':
for line in sys.stdin:
path = line.rstrip('\n')
if path == '':
continue
if not os.path.isfile(path):
continue
st = os.stat(path)
mode = st.st_mode
os.chmod(path, mode | stat.S_IRUSR | stat.S_IWUSR)
## Instruction:
Change permissions to either 644 or 755.
## Code After:
from __future__ import print_function
import os
import stat
import sys
if __name__ == '__main__':
for line in sys.stdin:
path = line.rstrip('\n')
if path == '':
continue
if not os.path.isfile(path):
continue
st = os.stat(path)
mode = int('644', 8)
if st.st_mode & stat.S_IXUSR != 0:
mode = int('755', 8)
with open(path) as f:
x = f.read(2)
if x == '#!':
mode = int('755', 8)
os.chmod(path, mode)
|
0078bb14b85df519744371df89e243822a86ed4c | generate.py | generate.py | import random
import sys
population = bytes([i for i in range(256)])
if sys.argv[1] == 'reflector':
popset = set(population)
buffer = [None for i in range(256)]
for i in range(128):
x, y = random.sample(popset, 2)
popset.remove(x)
popset.remove(y)
buffer[x] = y
buffer[y] = x
print(bytes(buffer))
elif sys.argv[1] == 'rotor':
print(bytes(random.sample(population, 256)))
| import random
import sys
population = bytes([i for i in range(256)])
if sys.argv[1] == 'reflector':
print('WIRING')
popset = set(population)
buffer = [None for i in range(256)]
for i in range(128):
x, y = random.sample(popset, 2)
popset.remove(x)
popset.remove(y)
buffer[x] = y
buffer[y] = x
print(bytes(buffer))
elif sys.argv[1] == 'rotor':
print('WIRING')
print(bytes(random.sample(population, 256)))
print('NOTCHES')
print(random.sample(population, 3))
| Add a little more detail to the generator | Add a little more detail to the generator
| Python | mit | spgill/bitnigma | import random
import sys
population = bytes([i for i in range(256)])
if sys.argv[1] == 'reflector':
+ print('WIRING')
popset = set(population)
buffer = [None for i in range(256)]
for i in range(128):
x, y = random.sample(popset, 2)
popset.remove(x)
popset.remove(y)
buffer[x] = y
buffer[y] = x
print(bytes(buffer))
elif sys.argv[1] == 'rotor':
+ print('WIRING')
print(bytes(random.sample(population, 256)))
+ print('NOTCHES')
+ print(random.sample(population, 3))
| Add a little more detail to the generator | ## Code Before:
import random
import sys
population = bytes([i for i in range(256)])
if sys.argv[1] == 'reflector':
popset = set(population)
buffer = [None for i in range(256)]
for i in range(128):
x, y = random.sample(popset, 2)
popset.remove(x)
popset.remove(y)
buffer[x] = y
buffer[y] = x
print(bytes(buffer))
elif sys.argv[1] == 'rotor':
print(bytes(random.sample(population, 256)))
## Instruction:
Add a little more detail to the generator
## Code After:
import random
import sys
population = bytes([i for i in range(256)])
if sys.argv[1] == 'reflector':
print('WIRING')
popset = set(population)
buffer = [None for i in range(256)]
for i in range(128):
x, y = random.sample(popset, 2)
popset.remove(x)
popset.remove(y)
buffer[x] = y
buffer[y] = x
print(bytes(buffer))
elif sys.argv[1] == 'rotor':
print('WIRING')
print(bytes(random.sample(population, 256)))
print('NOTCHES')
print(random.sample(population, 3))
|
211f1fdfe1d969df7c9762ba8e914d3ea829e9b4 | manual/conf.py | manual/conf.py | import sphinx_rtd_theme # noQA F401
import os
import sys
sys.path.append(os.path.abspath("./_ext"))
project = 'QPDF'
copyright = '2005-2021, Jay Berkenbilt'
author = 'Jay Berkenbilt'
# make_dist and the CI build lexically find the release version from this file.
release = '10.5.0'
version = release
extensions = [
'sphinx_rtd_theme',
'qpdf',
]
html_theme = 'sphinx_rtd_theme'
html_theme_options = {
"body_max_width": None,
}
html_logo = '../logo/qpdf.svg'
html_static_path = ['_static']
html_css_files = [
'css/wraptable.css',
]
highlight_language = 'none'
| import sphinx_rtd_theme # noQA F401
import os
import sys
sys.path.append(os.path.abspath("./_ext"))
project = 'QPDF'
copyright = '2005-2021, Jay Berkenbilt'
author = 'Jay Berkenbilt'
# make_dist and the CI build lexically find the release version from this file.
release = '10.5.0'
version = release
extensions = [
'sphinx_rtd_theme',
'qpdf',
]
html_theme = 'sphinx_rtd_theme'
html_theme_options = {
"body_max_width": None,
}
html_logo = '../logo/qpdf.svg'
html_static_path = ['_static']
html_css_files = [
'css/wraptable.css',
]
latex_elements = {
'preamble': r'''
\sphinxDUC{2264}{$\leq$}
\sphinxDUC{2265}{$\geq$}
''',
}
highlight_language = 'none'
| Allow real <= and >= in LateX | Allow real <= and >= in LateX
| Python | apache-2.0 | jberkenbilt/qpdf,jberkenbilt/qpdf,jberkenbilt/qpdf,qpdf/qpdf,jberkenbilt/qpdf,qpdf/qpdf,jberkenbilt/qpdf,qpdf/qpdf,qpdf/qpdf,qpdf/qpdf | import sphinx_rtd_theme # noQA F401
import os
import sys
sys.path.append(os.path.abspath("./_ext"))
project = 'QPDF'
copyright = '2005-2021, Jay Berkenbilt'
author = 'Jay Berkenbilt'
# make_dist and the CI build lexically find the release version from this file.
release = '10.5.0'
version = release
extensions = [
'sphinx_rtd_theme',
'qpdf',
]
html_theme = 'sphinx_rtd_theme'
html_theme_options = {
"body_max_width": None,
}
html_logo = '../logo/qpdf.svg'
html_static_path = ['_static']
html_css_files = [
'css/wraptable.css',
]
+ latex_elements = {
+ 'preamble': r'''
+ \sphinxDUC{2264}{$\leq$}
+ \sphinxDUC{2265}{$\geq$}
+ ''',
+ }
highlight_language = 'none'
| Allow real <= and >= in LateX | ## Code Before:
import sphinx_rtd_theme # noQA F401
import os
import sys
sys.path.append(os.path.abspath("./_ext"))
project = 'QPDF'
copyright = '2005-2021, Jay Berkenbilt'
author = 'Jay Berkenbilt'
# make_dist and the CI build lexically find the release version from this file.
release = '10.5.0'
version = release
extensions = [
'sphinx_rtd_theme',
'qpdf',
]
html_theme = 'sphinx_rtd_theme'
html_theme_options = {
"body_max_width": None,
}
html_logo = '../logo/qpdf.svg'
html_static_path = ['_static']
html_css_files = [
'css/wraptable.css',
]
highlight_language = 'none'
## Instruction:
Allow real <= and >= in LateX
## Code After:
import sphinx_rtd_theme # noQA F401
import os
import sys
sys.path.append(os.path.abspath("./_ext"))
project = 'QPDF'
copyright = '2005-2021, Jay Berkenbilt'
author = 'Jay Berkenbilt'
# make_dist and the CI build lexically find the release version from this file.
release = '10.5.0'
version = release
extensions = [
'sphinx_rtd_theme',
'qpdf',
]
html_theme = 'sphinx_rtd_theme'
html_theme_options = {
"body_max_width": None,
}
html_logo = '../logo/qpdf.svg'
html_static_path = ['_static']
html_css_files = [
'css/wraptable.css',
]
latex_elements = {
'preamble': r'''
\sphinxDUC{2264}{$\leq$}
\sphinxDUC{2265}{$\geq$}
''',
}
highlight_language = 'none'
|
ad55d04d6688f75f0e441603668e0337a0333d76 | tests/test_validate.py | tests/test_validate.py | import pytest
from marshmallow import validate, ValidationError
def test_invalid_email():
invalid1 = "user@example"
with pytest.raises(ValidationError):
validate.email(invalid1)
invalid2 = "example.com"
with pytest.raises(ValidationError):
validate.email(invalid2)
invalid3 = "user"
with pytest.raises(ValidationError):
validate.email(invalid3)
with pytest.raises(ValidationError):
validate.email('@nouser.com')
def test_validate_email_none():
assert validate.email(None) is None
def test_validate_url_none():
assert validate.url(None) is None
| import pytest
from marshmallow import validate, ValidationError
def test_invalid_email():
invalid1 = "user@example"
with pytest.raises(ValidationError):
validate.email(invalid1)
invalid2 = "example.com"
with pytest.raises(ValidationError):
validate.email(invalid2)
invalid3 = "user"
with pytest.raises(ValidationError):
validate.email(invalid3)
with pytest.raises(ValidationError):
validate.email('@nouser.com')
def test_validate_email_none():
assert validate.email(None) is None
def test_validate_url_none():
assert validate.url(None) is None
def test_min_length():
with pytest.raises(ValidationError):
validate.length('foo', 4, 5)
assert validate.length('foo', 3, 5) == 'foo'
with pytest.raises(ValidationError):
validate.length([1, 2, 3], 4, 5)
assert validate.length([1, 2, 3], 3, 5) == [1, 2, 3]
with pytest.raises(ValidationError):
validate.length('foo', 5)
def test_max_length():
with pytest.raises(ValidationError):
validate.length('foo', 1, 2)
assert validate.length('foo', 1, 3) == 'foo'
with pytest.raises(ValidationError):
validate.length([1, 2, 3], 1, 2)
assert validate.length([1, 2, 3], 1, 3) == [1, 2, 3]
with pytest.raises(ValidationError):
validate.length('foo', None, 2)
def test_validate_length_none():
assert validate.length(None) is None
| Add length validator unit tests | Add length validator unit tests | Python | mit | maximkulkin/marshmallow,0xDCA/marshmallow,Tim-Erwin/marshmallow,xLegoz/marshmallow,marshmallow-code/marshmallow,VladimirPal/marshmallow,0xDCA/marshmallow,daniloakamine/marshmallow,dwieeb/marshmallow,mwstobo/marshmallow,quxiaolong1504/marshmallow,etataurov/marshmallow,Bachmann1234/marshmallow,bartaelterman/marshmallow | import pytest
from marshmallow import validate, ValidationError
def test_invalid_email():
invalid1 = "user@example"
with pytest.raises(ValidationError):
validate.email(invalid1)
invalid2 = "example.com"
with pytest.raises(ValidationError):
validate.email(invalid2)
invalid3 = "user"
with pytest.raises(ValidationError):
validate.email(invalid3)
with pytest.raises(ValidationError):
validate.email('@nouser.com')
def test_validate_email_none():
assert validate.email(None) is None
def test_validate_url_none():
assert validate.url(None) is None
+ def test_min_length():
+ with pytest.raises(ValidationError):
+ validate.length('foo', 4, 5)
+ assert validate.length('foo', 3, 5) == 'foo'
+ with pytest.raises(ValidationError):
+ validate.length([1, 2, 3], 4, 5)
+ assert validate.length([1, 2, 3], 3, 5) == [1, 2, 3]
+ with pytest.raises(ValidationError):
+ validate.length('foo', 5)
+
+ def test_max_length():
+ with pytest.raises(ValidationError):
+ validate.length('foo', 1, 2)
+ assert validate.length('foo', 1, 3) == 'foo'
+ with pytest.raises(ValidationError):
+ validate.length([1, 2, 3], 1, 2)
+ assert validate.length([1, 2, 3], 1, 3) == [1, 2, 3]
+ with pytest.raises(ValidationError):
+ validate.length('foo', None, 2)
+
+ def test_validate_length_none():
+ assert validate.length(None) is None
+ | Add length validator unit tests | ## Code Before:
import pytest
from marshmallow import validate, ValidationError
def test_invalid_email():
invalid1 = "user@example"
with pytest.raises(ValidationError):
validate.email(invalid1)
invalid2 = "example.com"
with pytest.raises(ValidationError):
validate.email(invalid2)
invalid3 = "user"
with pytest.raises(ValidationError):
validate.email(invalid3)
with pytest.raises(ValidationError):
validate.email('@nouser.com')
def test_validate_email_none():
assert validate.email(None) is None
def test_validate_url_none():
assert validate.url(None) is None
## Instruction:
Add length validator unit tests
## Code After:
import pytest
from marshmallow import validate, ValidationError
def test_invalid_email():
invalid1 = "user@example"
with pytest.raises(ValidationError):
validate.email(invalid1)
invalid2 = "example.com"
with pytest.raises(ValidationError):
validate.email(invalid2)
invalid3 = "user"
with pytest.raises(ValidationError):
validate.email(invalid3)
with pytest.raises(ValidationError):
validate.email('@nouser.com')
def test_validate_email_none():
assert validate.email(None) is None
def test_validate_url_none():
assert validate.url(None) is None
def test_min_length():
with pytest.raises(ValidationError):
validate.length('foo', 4, 5)
assert validate.length('foo', 3, 5) == 'foo'
with pytest.raises(ValidationError):
validate.length([1, 2, 3], 4, 5)
assert validate.length([1, 2, 3], 3, 5) == [1, 2, 3]
with pytest.raises(ValidationError):
validate.length('foo', 5)
def test_max_length():
with pytest.raises(ValidationError):
validate.length('foo', 1, 2)
assert validate.length('foo', 1, 3) == 'foo'
with pytest.raises(ValidationError):
validate.length([1, 2, 3], 1, 2)
assert validate.length([1, 2, 3], 1, 3) == [1, 2, 3]
with pytest.raises(ValidationError):
validate.length('foo', None, 2)
def test_validate_length_none():
assert validate.length(None) is None
|
98eaf33328814342cdf6a2e8379c87cd00c911ce | campaign/views.py | campaign/views.py | from django.core.urlresolvers import reverse
from django.shortcuts import redirect, render_to_response
from django.template import RequestContext
from campaign.forms import CampaignFormSet, ProspectusForm
from campaign.models import PROSPECTUS_FIELD_HELP
def create_edit_prospectus(request):
if request.method == 'POST':
prospectus_form = ProspectusForm(request.POST)
campaign_formset = CampaignFormSet(request.POST)
if prospectus_form.is_valid():
prospectus_form.save(commit=False)
if request.user.is_authenticated():
prospectus_form.instance.owner = request.user
if campaign_formset.is_valid():
prospectus_form.instance.save()
for campaign in campaign_formset.save(commit=False):
campaign.prospectus = prospectus_form.instance
campaign.save()
return redirect(reverse('index'))
else:
prospectus_form = ProspectusForm()
campaign_formset = CampaignFormSet()
return render_to_response('campaign/new_prospectus.html',
{'prospectus_form': prospectus_form,
'campaign_forms': campaign_formset,
'prospectus_help': PROSPECTUS_FIELD_HELP},
RequestContext(request))
| from django.core.urlresolvers import reverse
from django.shortcuts import redirect, render_to_response
from django.template import RequestContext
from campaign.forms import CampaignFormSet, ProspectusForm
from campaign.models import PROSPECTUS_FIELD_HELP, Campaign
def create_edit_prospectus(request):
if request.method == 'POST':
prospectus_form = ProspectusForm(request.POST)
campaign_formset = CampaignFormSet(request.POST,
queryset=Campaign.objects.none())
if prospectus_form.is_valid():
prospectus_form.save(commit=False)
if request.user.is_authenticated():
prospectus_form.instance.owner = request.user
if campaign_formset.is_valid():
prospectus_form.instance.save()
for campaign in campaign_formset.save(commit=False):
campaign.prospectus = prospectus_form.instance
campaign.save()
return redirect(reverse('index'))
else:
prospectus_form = ProspectusForm()
campaign_formset = CampaignFormSet(queryset=Campaign.objects.none())
return render_to_response('campaign/new_prospectus.html',
{'prospectus_form': prospectus_form,
'campaign_forms': campaign_formset,
'prospectus_help': PROSPECTUS_FIELD_HELP},
RequestContext(request))
| Update default queryset for formsets | Update default queryset for formsets | Python | mit | tdphillips/campaigns,tdphillips/campaigns | from django.core.urlresolvers import reverse
from django.shortcuts import redirect, render_to_response
from django.template import RequestContext
from campaign.forms import CampaignFormSet, ProspectusForm
- from campaign.models import PROSPECTUS_FIELD_HELP
+ from campaign.models import PROSPECTUS_FIELD_HELP, Campaign
def create_edit_prospectus(request):
if request.method == 'POST':
prospectus_form = ProspectusForm(request.POST)
- campaign_formset = CampaignFormSet(request.POST)
+ campaign_formset = CampaignFormSet(request.POST,
+ queryset=Campaign.objects.none())
if prospectus_form.is_valid():
prospectus_form.save(commit=False)
if request.user.is_authenticated():
prospectus_form.instance.owner = request.user
if campaign_formset.is_valid():
prospectus_form.instance.save()
for campaign in campaign_formset.save(commit=False):
campaign.prospectus = prospectus_form.instance
campaign.save()
return redirect(reverse('index'))
else:
prospectus_form = ProspectusForm()
- campaign_formset = CampaignFormSet()
+ campaign_formset = CampaignFormSet(queryset=Campaign.objects.none())
return render_to_response('campaign/new_prospectus.html',
{'prospectus_form': prospectus_form,
'campaign_forms': campaign_formset,
'prospectus_help': PROSPECTUS_FIELD_HELP},
RequestContext(request))
| Update default queryset for formsets | ## Code Before:
from django.core.urlresolvers import reverse
from django.shortcuts import redirect, render_to_response
from django.template import RequestContext
from campaign.forms import CampaignFormSet, ProspectusForm
from campaign.models import PROSPECTUS_FIELD_HELP
def create_edit_prospectus(request):
if request.method == 'POST':
prospectus_form = ProspectusForm(request.POST)
campaign_formset = CampaignFormSet(request.POST)
if prospectus_form.is_valid():
prospectus_form.save(commit=False)
if request.user.is_authenticated():
prospectus_form.instance.owner = request.user
if campaign_formset.is_valid():
prospectus_form.instance.save()
for campaign in campaign_formset.save(commit=False):
campaign.prospectus = prospectus_form.instance
campaign.save()
return redirect(reverse('index'))
else:
prospectus_form = ProspectusForm()
campaign_formset = CampaignFormSet()
return render_to_response('campaign/new_prospectus.html',
{'prospectus_form': prospectus_form,
'campaign_forms': campaign_formset,
'prospectus_help': PROSPECTUS_FIELD_HELP},
RequestContext(request))
## Instruction:
Update default queryset for formsets
## Code After:
from django.core.urlresolvers import reverse
from django.shortcuts import redirect, render_to_response
from django.template import RequestContext
from campaign.forms import CampaignFormSet, ProspectusForm
from campaign.models import PROSPECTUS_FIELD_HELP, Campaign
def create_edit_prospectus(request):
if request.method == 'POST':
prospectus_form = ProspectusForm(request.POST)
campaign_formset = CampaignFormSet(request.POST,
queryset=Campaign.objects.none())
if prospectus_form.is_valid():
prospectus_form.save(commit=False)
if request.user.is_authenticated():
prospectus_form.instance.owner = request.user
if campaign_formset.is_valid():
prospectus_form.instance.save()
for campaign in campaign_formset.save(commit=False):
campaign.prospectus = prospectus_form.instance
campaign.save()
return redirect(reverse('index'))
else:
prospectus_form = ProspectusForm()
campaign_formset = CampaignFormSet(queryset=Campaign.objects.none())
return render_to_response('campaign/new_prospectus.html',
{'prospectus_form': prospectus_form,
'campaign_forms': campaign_formset,
'prospectus_help': PROSPECTUS_FIELD_HELP},
RequestContext(request))
|
547130e5f3717fd5bfd083be89afd361fdcdefc1 | van/contactology/tests/test_contactology.py | van/contactology/tests/test_contactology.py | import unittest
from simplejson import dumps
from twisted.trial.unittest import TestCase
from twisted.internet import defer
from mock import patch, Mock
from van.contactology import Contactology
class TestProxy(TestCase):
@defer.inlineCallbacks
def test_list_return(self):
patcher = patch('van.contactology.getPage')
getPage = patcher.start()
try:
proxy = Contactology('API Key')
getPage.return_value = dumps([])
out = yield proxy.Campaign_Find()
yield self.assertEquals(out, [])
finally:
patcher.stop()
| import unittest
from simplejson import dumps
from twisted.trial.unittest import TestCase
from twisted.internet import defer
from mock import patch, Mock
from van.contactology import Contactology, APIError
class TestProxy(TestCase):
@defer.inlineCallbacks
def test_list_return(self):
patcher = patch('van.contactology.getPage')
getPage = patcher.start()
try:
proxy = Contactology('API Key')
getPage.return_value = dumps([])
out = yield proxy.Campaign_Find()
yield self.assertEquals(out, [])
finally:
patcher.stop()
@defer.inlineCallbacks
def test_api_error(self):
patcher = patch('van.contactology.getPage')
getPage = patcher.start()
try:
proxy = Contactology('API Key')
getPage.return_value = dumps({'code': 221, 'message': 'Key not found', 'result': 'error'})
yield self.failUnlessFailure(proxy.List_Get_Active_Lists(), APIError)
finally:
patcher.stop()
| Test for exception raising on API error. | Test for exception raising on API error.
| Python | bsd-3-clause | jinty/van.contactology | import unittest
from simplejson import dumps
from twisted.trial.unittest import TestCase
from twisted.internet import defer
from mock import patch, Mock
- from van.contactology import Contactology
+ from van.contactology import Contactology, APIError
class TestProxy(TestCase):
@defer.inlineCallbacks
def test_list_return(self):
patcher = patch('van.contactology.getPage')
getPage = patcher.start()
try:
proxy = Contactology('API Key')
getPage.return_value = dumps([])
out = yield proxy.Campaign_Find()
yield self.assertEquals(out, [])
finally:
patcher.stop()
+
+ @defer.inlineCallbacks
+ def test_api_error(self):
+ patcher = patch('van.contactology.getPage')
+ getPage = patcher.start()
+ try:
+ proxy = Contactology('API Key')
+ getPage.return_value = dumps({'code': 221, 'message': 'Key not found', 'result': 'error'})
+ yield self.failUnlessFailure(proxy.List_Get_Active_Lists(), APIError)
+ finally:
+ patcher.stop()
| Test for exception raising on API error. | ## Code Before:
import unittest
from simplejson import dumps
from twisted.trial.unittest import TestCase
from twisted.internet import defer
from mock import patch, Mock
from van.contactology import Contactology
class TestProxy(TestCase):
@defer.inlineCallbacks
def test_list_return(self):
patcher = patch('van.contactology.getPage')
getPage = patcher.start()
try:
proxy = Contactology('API Key')
getPage.return_value = dumps([])
out = yield proxy.Campaign_Find()
yield self.assertEquals(out, [])
finally:
patcher.stop()
## Instruction:
Test for exception raising on API error.
## Code After:
import unittest
from simplejson import dumps
from twisted.trial.unittest import TestCase
from twisted.internet import defer
from mock import patch, Mock
from van.contactology import Contactology, APIError
class TestProxy(TestCase):
@defer.inlineCallbacks
def test_list_return(self):
patcher = patch('van.contactology.getPage')
getPage = patcher.start()
try:
proxy = Contactology('API Key')
getPage.return_value = dumps([])
out = yield proxy.Campaign_Find()
yield self.assertEquals(out, [])
finally:
patcher.stop()
@defer.inlineCallbacks
def test_api_error(self):
patcher = patch('van.contactology.getPage')
getPage = patcher.start()
try:
proxy = Contactology('API Key')
getPage.return_value = dumps({'code': 221, 'message': 'Key not found', 'result': 'error'})
yield self.failUnlessFailure(proxy.List_Get_Active_Lists(), APIError)
finally:
patcher.stop()
|
87de1fce846d7f50017fba885725a0907d43275e | swf/querysets/__init__.py | swf/querysets/__init__.py |
from swf.querysets.activity import ActivityTypeQuerySet
from swf.querysets.domain import DomainQuerySet
from swf.querysets.workflow import (WorkflowTypeQuerySet,
WorkflowExecutionQuerySet)
|
from swf.querysets.activity import ActivityTypeQuerySet
from swf.querysets.domain import DomainQuerySet
from swf.querysets.history import HistoryQuerySet
from swf.querysets.workflow import (WorkflowTypeQuerySet,
WorkflowExecutionQuerySet)
| Add history qs to swf querysets modules | Add history qs to swf querysets modules
| Python | mit | botify-labs/python-simple-workflow,botify-labs/python-simple-workflow |
from swf.querysets.activity import ActivityTypeQuerySet
from swf.querysets.domain import DomainQuerySet
+ from swf.querysets.history import HistoryQuerySet
from swf.querysets.workflow import (WorkflowTypeQuerySet,
WorkflowExecutionQuerySet)
| Add history qs to swf querysets modules | ## Code Before:
from swf.querysets.activity import ActivityTypeQuerySet
from swf.querysets.domain import DomainQuerySet
from swf.querysets.workflow import (WorkflowTypeQuerySet,
WorkflowExecutionQuerySet)
## Instruction:
Add history qs to swf querysets modules
## Code After:
from swf.querysets.activity import ActivityTypeQuerySet
from swf.querysets.domain import DomainQuerySet
from swf.querysets.history import HistoryQuerySet
from swf.querysets.workflow import (WorkflowTypeQuerySet,
WorkflowExecutionQuerySet)
|
3a0b844f33274f7d9c389dd89b21a953cb9c1510 | promgen/sender/webhook.py | promgen/sender/webhook.py | '''
Simple webhook bridge
Accepts alert json from Alert Manager and then POSTs individual alerts to
configured webhook destinations
'''
import logging
import requests
from promgen.sender import SenderBase
logger = logging.getLogger(__name__)
class SenderWebhook(SenderBase):
def _send(self, url, alert, data):
body = {
'prometheus': alert['generatorURL'],
'status': alert['status'],
'alertmanager': data['externalURL']
}
body.update(alert['labels'])
body.update(alert['annotations'])
requests.post(url, body).raise_for_status()
return True
| '''
Simple webhook bridge
Accepts alert json from Alert Manager and then POSTs individual alerts to
configured webhook destinations
'''
import logging
import requests
from promgen.sender import SenderBase
logger = logging.getLogger(__name__)
class SenderWebhook(SenderBase):
def _send(self, url, alert, data):
body = {
'prometheus': alert['generatorURL'],
'status': alert['status'],
'alertmanager': data['externalURL']
}
body.update(alert.get('labels', {}))
body.update(alert.get('annotations', {}))
requests.post(url, body).raise_for_status()
return True
| Fix case where annotations may not exist | Fix case where annotations may not exist
| Python | mit | kfdm/promgen,kfdm/promgen,kfdm/promgen,kfdm/promgen | '''
Simple webhook bridge
Accepts alert json from Alert Manager and then POSTs individual alerts to
configured webhook destinations
'''
import logging
+
import requests
+
from promgen.sender import SenderBase
logger = logging.getLogger(__name__)
class SenderWebhook(SenderBase):
def _send(self, url, alert, data):
body = {
'prometheus': alert['generatorURL'],
'status': alert['status'],
'alertmanager': data['externalURL']
}
- body.update(alert['labels'])
+ body.update(alert.get('labels', {}))
- body.update(alert['annotations'])
+ body.update(alert.get('annotations', {}))
requests.post(url, body).raise_for_status()
return True
| Fix case where annotations may not exist | ## Code Before:
'''
Simple webhook bridge
Accepts alert json from Alert Manager and then POSTs individual alerts to
configured webhook destinations
'''
import logging
import requests
from promgen.sender import SenderBase
logger = logging.getLogger(__name__)
class SenderWebhook(SenderBase):
def _send(self, url, alert, data):
body = {
'prometheus': alert['generatorURL'],
'status': alert['status'],
'alertmanager': data['externalURL']
}
body.update(alert['labels'])
body.update(alert['annotations'])
requests.post(url, body).raise_for_status()
return True
## Instruction:
Fix case where annotations may not exist
## Code After:
'''
Simple webhook bridge
Accepts alert json from Alert Manager and then POSTs individual alerts to
configured webhook destinations
'''
import logging
import requests
from promgen.sender import SenderBase
logger = logging.getLogger(__name__)
class SenderWebhook(SenderBase):
def _send(self, url, alert, data):
body = {
'prometheus': alert['generatorURL'],
'status': alert['status'],
'alertmanager': data['externalURL']
}
body.update(alert.get('labels', {}))
body.update(alert.get('annotations', {}))
requests.post(url, body).raise_for_status()
return True
|
e9e632008db1eb2bbdbd989584b82255a10f8944 | CodeFights/arrayReplace.py | CodeFights/arrayReplace.py |
def arrayReplace(inputArray, elemToReplace, substitutionElem):
pass
def main():
pass
if __name__ == '__main__':
main()
|
def arrayReplace(inputArray, elemToReplace, substitutionElem):
return [x if x != elemToReplace else substitutionElem for x in inputArray]
def main():
tests = [
[[1, 2, 1], 1, 3, [3, 2, 3]],
[[1, 2, 3, 4, 5], 3, 0, [1, 2, 0, 4, 5]],
[[1, 1, 1], 1, 10, [10, 10, 10]]
]
for t in tests:
res = arrayReplace(t[0], t[1], t[2])
if t[3] == res:
print("PASSED: arrayReplace({}, {}, {}) returned {}"
.format(t[0], t[1], t[2], res))
else:
print("FAILED: arrayReplace({}, {}, {}) returned {}, should have returned {}"
.format(t[0], t[1], t[2], res, t[3]))
if __name__ == '__main__':
main()
| Solve Code Fights array replace problem | Solve Code Fights array replace problem
| Python | mit | HKuz/Test_Code |
def arrayReplace(inputArray, elemToReplace, substitutionElem):
- pass
+ return [x if x != elemToReplace else substitutionElem for x in inputArray]
def main():
- pass
+ tests = [
+ [[1, 2, 1], 1, 3, [3, 2, 3]],
+ [[1, 2, 3, 4, 5], 3, 0, [1, 2, 0, 4, 5]],
+ [[1, 1, 1], 1, 10, [10, 10, 10]]
+ ]
+
+ for t in tests:
+ res = arrayReplace(t[0], t[1], t[2])
+ if t[3] == res:
+ print("PASSED: arrayReplace({}, {}, {}) returned {}"
+ .format(t[0], t[1], t[2], res))
+ else:
+ print("FAILED: arrayReplace({}, {}, {}) returned {}, should have returned {}"
+ .format(t[0], t[1], t[2], res, t[3]))
if __name__ == '__main__':
main()
| Solve Code Fights array replace problem | ## Code Before:
def arrayReplace(inputArray, elemToReplace, substitutionElem):
pass
def main():
pass
if __name__ == '__main__':
main()
## Instruction:
Solve Code Fights array replace problem
## Code After:
def arrayReplace(inputArray, elemToReplace, substitutionElem):
return [x if x != elemToReplace else substitutionElem for x in inputArray]
def main():
tests = [
[[1, 2, 1], 1, 3, [3, 2, 3]],
[[1, 2, 3, 4, 5], 3, 0, [1, 2, 0, 4, 5]],
[[1, 1, 1], 1, 10, [10, 10, 10]]
]
for t in tests:
res = arrayReplace(t[0], t[1], t[2])
if t[3] == res:
print("PASSED: arrayReplace({}, {}, {}) returned {}"
.format(t[0], t[1], t[2], res))
else:
print("FAILED: arrayReplace({}, {}, {}) returned {}, should have returned {}"
.format(t[0], t[1], t[2], res, t[3]))
if __name__ == '__main__':
main()
|
016d955319b6971fec42ac6ada1052f88d867cee | freepacktbook/__init__.py | freepacktbook/__init__.py | import os
from bs4 import BeautifulSoup
import requests
class FreePacktBook(object):
base_url = 'https://www.packtpub.com'
url = base_url + '/packt/offers/free-learning/'
def __init__(self, email=None, password=None):
self.session = requests.Session()
self.email = email
self.password = password
def claim_free_ebook(self):
response = self.session.post(self.url, {
'email': self.email,
'password': self.password,
'form_id': 'packt_user_login_form'})
parser = BeautifulSoup(response.text, 'html.parser')
claim_url = self.base_url + parser.find('div', {
'class': 'free-ebook'}).a['href']
response = self.session.get(claim_url)
assert response.status_code == 200
def claim_free_ebook():
client = FreePacktBook(
os.environ.get('PACKTPUB_EMAIL'), os.environ.get('PACKTPUB_PASSWORD'))
client.claim_free_ebook()
| import os
from bs4 import BeautifulSoup
import requests
class FreePacktBook(object):
base_url = 'https://www.packtpub.com'
url = base_url + '/packt/offers/free-learning/'
def __init__(self, email=None, password=None):
self.session = requests.Session()
self.email = email
self.password = password
def claim_free_ebook(self):
response = self.session.post(self.url, {
'email': self.email,
'password': self.password,
'form_id': 'packt_user_login_form'})
parser = BeautifulSoup(response.text, 'html.parser')
claim_url = self.base_url + parser.find('div', {
'class': 'free-ebook'}).a['href']
response = self.session.get(claim_url)
assert response.status_code == 200
def get_book_details(self):
response = self.session.get(self.url)
parser = BeautifulSoup(response.text, 'html.parser')
summary = parser.find('div', {'class': 'dotd-main-book-summary'})
title = summary.find('div', {'class': 'dotd-title'}).getText().strip()
description = summary.find('div', {'class': None}).getText().strip()
main_book_image = parser.find('div', {'class': 'dotd-main-book-image'})
image_url = 'https:%s' % main_book_image.img['src']
url = self.base_url + main_book_image.a['href']
return {'title': title, 'description': description,
'url': url, 'image_url': image_url}
def claim_free_ebook():
client = FreePacktBook(
os.environ.get('PACKTPUB_EMAIL'), os.environ.get('PACKTPUB_PASSWORD'))
client.claim_free_ebook()
| Add ability to get book details | Add ability to get book details
| Python | mit | bogdal/freepacktbook | import os
from bs4 import BeautifulSoup
import requests
class FreePacktBook(object):
base_url = 'https://www.packtpub.com'
url = base_url + '/packt/offers/free-learning/'
def __init__(self, email=None, password=None):
self.session = requests.Session()
self.email = email
self.password = password
def claim_free_ebook(self):
response = self.session.post(self.url, {
'email': self.email,
'password': self.password,
'form_id': 'packt_user_login_form'})
parser = BeautifulSoup(response.text, 'html.parser')
claim_url = self.base_url + parser.find('div', {
'class': 'free-ebook'}).a['href']
response = self.session.get(claim_url)
assert response.status_code == 200
+ def get_book_details(self):
+ response = self.session.get(self.url)
+ parser = BeautifulSoup(response.text, 'html.parser')
+ summary = parser.find('div', {'class': 'dotd-main-book-summary'})
+ title = summary.find('div', {'class': 'dotd-title'}).getText().strip()
+ description = summary.find('div', {'class': None}).getText().strip()
+ main_book_image = parser.find('div', {'class': 'dotd-main-book-image'})
+ image_url = 'https:%s' % main_book_image.img['src']
+ url = self.base_url + main_book_image.a['href']
+ return {'title': title, 'description': description,
+ 'url': url, 'image_url': image_url}
+
def claim_free_ebook():
client = FreePacktBook(
os.environ.get('PACKTPUB_EMAIL'), os.environ.get('PACKTPUB_PASSWORD'))
client.claim_free_ebook()
| Add ability to get book details | ## Code Before:
import os
from bs4 import BeautifulSoup
import requests
class FreePacktBook(object):
base_url = 'https://www.packtpub.com'
url = base_url + '/packt/offers/free-learning/'
def __init__(self, email=None, password=None):
self.session = requests.Session()
self.email = email
self.password = password
def claim_free_ebook(self):
response = self.session.post(self.url, {
'email': self.email,
'password': self.password,
'form_id': 'packt_user_login_form'})
parser = BeautifulSoup(response.text, 'html.parser')
claim_url = self.base_url + parser.find('div', {
'class': 'free-ebook'}).a['href']
response = self.session.get(claim_url)
assert response.status_code == 200
def claim_free_ebook():
client = FreePacktBook(
os.environ.get('PACKTPUB_EMAIL'), os.environ.get('PACKTPUB_PASSWORD'))
client.claim_free_ebook()
## Instruction:
Add ability to get book details
## Code After:
import os
from bs4 import BeautifulSoup
import requests
class FreePacktBook(object):
base_url = 'https://www.packtpub.com'
url = base_url + '/packt/offers/free-learning/'
def __init__(self, email=None, password=None):
self.session = requests.Session()
self.email = email
self.password = password
def claim_free_ebook(self):
response = self.session.post(self.url, {
'email': self.email,
'password': self.password,
'form_id': 'packt_user_login_form'})
parser = BeautifulSoup(response.text, 'html.parser')
claim_url = self.base_url + parser.find('div', {
'class': 'free-ebook'}).a['href']
response = self.session.get(claim_url)
assert response.status_code == 200
def get_book_details(self):
response = self.session.get(self.url)
parser = BeautifulSoup(response.text, 'html.parser')
summary = parser.find('div', {'class': 'dotd-main-book-summary'})
title = summary.find('div', {'class': 'dotd-title'}).getText().strip()
description = summary.find('div', {'class': None}).getText().strip()
main_book_image = parser.find('div', {'class': 'dotd-main-book-image'})
image_url = 'https:%s' % main_book_image.img['src']
url = self.base_url + main_book_image.a['href']
return {'title': title, 'description': description,
'url': url, 'image_url': image_url}
def claim_free_ebook():
client = FreePacktBook(
os.environ.get('PACKTPUB_EMAIL'), os.environ.get('PACKTPUB_PASSWORD'))
client.claim_free_ebook()
|
76b39021fb0171da6036ceaf7894e3ff18d259ae | src/syft/grid/client/request_api/worker_api.py | src/syft/grid/client/request_api/worker_api.py | from typing import Any
from typing import Dict
# third party
from pandas import DataFrame
# syft relative
from ...messages.infra_messages import CreateWorkerMessage
from ...messages.infra_messages import DeleteWorkerMessage
from ...messages.infra_messages import GetWorkerMessage
from ...messages.infra_messages import GetWorkersMessage
from ...messages.infra_messages import UpdateWorkerMessage
from .request_api import GridRequestAPI
class WorkerRequestAPI(GridRequestAPI):
response_key = "worker"
def __init__(self, send):
super().__init__(
create_msg=CreateWorkerMessage,
get_msg=GetWorkerMessage,
get_all_msg=GetWorkersMessage,
update_msg=UpdateWorkerMessage,
delete_msg=DeleteWorkerMessage,
send=send,
response_key=WorkerRequestAPI.response_key,
)
def __getitem__(self, key):
return self.get(worker_id=key)
def __delitem__(self, key):
self.delete(worker_id=key)
| from typing import Callable
# syft relative
from ...messages.infra_messages import CreateWorkerMessage
from ...messages.infra_messages import DeleteWorkerMessage
from ...messages.infra_messages import GetWorkerMessage
from ...messages.infra_messages import GetWorkersMessage
from ...messages.infra_messages import UpdateWorkerMessage
from .request_api import GridRequestAPI
class WorkerRequestAPI(GridRequestAPI):
response_key = "worker"
def __init__(self, send: Callable):
super().__init__(
create_msg=CreateWorkerMessage,
get_msg=GetWorkerMessage,
get_all_msg=GetWorkersMessage,
update_msg=UpdateWorkerMessage,
delete_msg=DeleteWorkerMessage,
send=send,
response_key=WorkerRequestAPI.response_key,
)
def __getitem__(self, key: int) -> object:
return self.get(worker_id=key)
def __delitem__(self, key: int) -> None:
self.delete(worker_id=key)
| Update Worker API - ADD type hints - Remove unused imports | Update Worker API
- ADD type hints
- Remove unused imports
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft | - from typing import Any
+ from typing import Callable
- from typing import Dict
-
- # third party
- from pandas import DataFrame
# syft relative
from ...messages.infra_messages import CreateWorkerMessage
from ...messages.infra_messages import DeleteWorkerMessage
from ...messages.infra_messages import GetWorkerMessage
from ...messages.infra_messages import GetWorkersMessage
from ...messages.infra_messages import UpdateWorkerMessage
from .request_api import GridRequestAPI
class WorkerRequestAPI(GridRequestAPI):
response_key = "worker"
- def __init__(self, send):
+ def __init__(self, send: Callable):
super().__init__(
create_msg=CreateWorkerMessage,
get_msg=GetWorkerMessage,
get_all_msg=GetWorkersMessage,
update_msg=UpdateWorkerMessage,
delete_msg=DeleteWorkerMessage,
send=send,
response_key=WorkerRequestAPI.response_key,
)
- def __getitem__(self, key):
+ def __getitem__(self, key: int) -> object:
return self.get(worker_id=key)
- def __delitem__(self, key):
+ def __delitem__(self, key: int) -> None:
self.delete(worker_id=key)
| Update Worker API - ADD type hints - Remove unused imports | ## Code Before:
from typing import Any
from typing import Dict
# third party
from pandas import DataFrame
# syft relative
from ...messages.infra_messages import CreateWorkerMessage
from ...messages.infra_messages import DeleteWorkerMessage
from ...messages.infra_messages import GetWorkerMessage
from ...messages.infra_messages import GetWorkersMessage
from ...messages.infra_messages import UpdateWorkerMessage
from .request_api import GridRequestAPI
class WorkerRequestAPI(GridRequestAPI):
response_key = "worker"
def __init__(self, send):
super().__init__(
create_msg=CreateWorkerMessage,
get_msg=GetWorkerMessage,
get_all_msg=GetWorkersMessage,
update_msg=UpdateWorkerMessage,
delete_msg=DeleteWorkerMessage,
send=send,
response_key=WorkerRequestAPI.response_key,
)
def __getitem__(self, key):
return self.get(worker_id=key)
def __delitem__(self, key):
self.delete(worker_id=key)
## Instruction:
Update Worker API - ADD type hints - Remove unused imports
## Code After:
from typing import Callable
# syft relative
from ...messages.infra_messages import CreateWorkerMessage
from ...messages.infra_messages import DeleteWorkerMessage
from ...messages.infra_messages import GetWorkerMessage
from ...messages.infra_messages import GetWorkersMessage
from ...messages.infra_messages import UpdateWorkerMessage
from .request_api import GridRequestAPI
class WorkerRequestAPI(GridRequestAPI):
response_key = "worker"
def __init__(self, send: Callable):
super().__init__(
create_msg=CreateWorkerMessage,
get_msg=GetWorkerMessage,
get_all_msg=GetWorkersMessage,
update_msg=UpdateWorkerMessage,
delete_msg=DeleteWorkerMessage,
send=send,
response_key=WorkerRequestAPI.response_key,
)
def __getitem__(self, key: int) -> object:
return self.get(worker_id=key)
def __delitem__(self, key: int) -> None:
self.delete(worker_id=key)
|
6153952ca9794ccb1dd5d76696aa2d4881a665c1 | tests/core/migrations/0004_bookwithchapters.py | tests/core/migrations/0004_bookwithchapters.py | from __future__ import unicode_literals
import django.contrib.postgres.fields
from django.db import migrations, models
class PostgresOnlyCreateModel(migrations.CreateModel):
def database_forwards(self, app_label, schema_editor, from_state, to_state):
if schema_editor.connection.vendor.startswith("postgres"):
super(PostgresOnlyCreateModel, self).database_forwards(app_label, schema_editor, from_state, to_state)
def database_backwards(self, app_label, schema_editor, from_state, to_state):
if schema_editor.connection.vendor.startswith("postgres"):
super(PostgresOnlyCreateModel, self).database_backwards(app_label, schema_editor, from_state, to_state)
class Migration(migrations.Migration):
dependencies = [
('core', '0003_withfloatfield'),
]
operations = [
PostgresOnlyCreateModel(
name='BookWithChapters',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, verbose_name='Book name')),
('chapters',
django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=100), default=list,
size=None)),
],
),
]
| from __future__ import unicode_literals
from django import VERSION
from django.db import migrations, models
if VERSION >= (1, 8):
from django.contrib.postgres.fields import ArrayField
chapters_field = ArrayField(base_field=models.CharField(max_length=100), default=list, size=None)
else:
chapters_field = models.Field() # Dummy field
class PostgresOnlyCreateModel(migrations.CreateModel):
def database_forwards(self, app_label, schema_editor, from_state, to_state):
if VERSION >= (1, 8) and schema_editor.connection.vendor.startswith("postgres"):
super(PostgresOnlyCreateModel, self).database_forwards(app_label, schema_editor, from_state, to_state)
def database_backwards(self, app_label, schema_editor, from_state, to_state):
if VERSION >= (1, 8) and schema_editor.connection.vendor.startswith("postgres"):
super(PostgresOnlyCreateModel, self).database_backwards(app_label, schema_editor, from_state, to_state)
class Migration(migrations.Migration):
dependencies = [
('core', '0003_withfloatfield'),
]
operations = [
PostgresOnlyCreateModel(
name='BookWithChapters',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, verbose_name='Book name')),
('chapters', chapters_field)
],
),
]
| Add version check for importing django.contrib.postgres.fields.ArrayField | Add version check for importing django.contrib.postgres.fields.ArrayField
| Python | bsd-2-clause | daniell/django-import-export,jnns/django-import-export,django-import-export/django-import-export,bmihelac/django-import-export,copperleaftech/django-import-export,brillgen/django-import-export,PetrDlouhy/django-import-export,daniell/django-import-export,daniell/django-import-export,PetrDlouhy/django-import-export,PetrDlouhy/django-import-export,jnns/django-import-export,brillgen/django-import-export,daniell/django-import-export,copperleaftech/django-import-export,jnns/django-import-export,brillgen/django-import-export,brillgen/django-import-export,copperleaftech/django-import-export,bmihelac/django-import-export,PetrDlouhy/django-import-export,django-import-export/django-import-export,django-import-export/django-import-export,bmihelac/django-import-export,bmihelac/django-import-export,jnns/django-import-export,django-import-export/django-import-export,copperleaftech/django-import-export | from __future__ import unicode_literals
- import django.contrib.postgres.fields
+ from django import VERSION
from django.db import migrations, models
+ if VERSION >= (1, 8):
+ from django.contrib.postgres.fields import ArrayField
+ chapters_field = ArrayField(base_field=models.CharField(max_length=100), default=list, size=None)
+ else:
+ chapters_field = models.Field() # Dummy field
class PostgresOnlyCreateModel(migrations.CreateModel):
def database_forwards(self, app_label, schema_editor, from_state, to_state):
- if schema_editor.connection.vendor.startswith("postgres"):
+ if VERSION >= (1, 8) and schema_editor.connection.vendor.startswith("postgres"):
super(PostgresOnlyCreateModel, self).database_forwards(app_label, schema_editor, from_state, to_state)
def database_backwards(self, app_label, schema_editor, from_state, to_state):
- if schema_editor.connection.vendor.startswith("postgres"):
+ if VERSION >= (1, 8) and schema_editor.connection.vendor.startswith("postgres"):
super(PostgresOnlyCreateModel, self).database_backwards(app_label, schema_editor, from_state, to_state)
class Migration(migrations.Migration):
dependencies = [
('core', '0003_withfloatfield'),
]
operations = [
PostgresOnlyCreateModel(
name='BookWithChapters',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, verbose_name='Book name')),
- ('chapters',
+ ('chapters', chapters_field)
- django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=100), default=list,
- size=None)),
],
),
]
| Add version check for importing django.contrib.postgres.fields.ArrayField | ## Code Before:
from __future__ import unicode_literals
import django.contrib.postgres.fields
from django.db import migrations, models
class PostgresOnlyCreateModel(migrations.CreateModel):
def database_forwards(self, app_label, schema_editor, from_state, to_state):
if schema_editor.connection.vendor.startswith("postgres"):
super(PostgresOnlyCreateModel, self).database_forwards(app_label, schema_editor, from_state, to_state)
def database_backwards(self, app_label, schema_editor, from_state, to_state):
if schema_editor.connection.vendor.startswith("postgres"):
super(PostgresOnlyCreateModel, self).database_backwards(app_label, schema_editor, from_state, to_state)
class Migration(migrations.Migration):
dependencies = [
('core', '0003_withfloatfield'),
]
operations = [
PostgresOnlyCreateModel(
name='BookWithChapters',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, verbose_name='Book name')),
('chapters',
django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=100), default=list,
size=None)),
],
),
]
## Instruction:
Add version check for importing django.contrib.postgres.fields.ArrayField
## Code After:
from __future__ import unicode_literals
from django import VERSION
from django.db import migrations, models
if VERSION >= (1, 8):
from django.contrib.postgres.fields import ArrayField
chapters_field = ArrayField(base_field=models.CharField(max_length=100), default=list, size=None)
else:
chapters_field = models.Field() # Dummy field
class PostgresOnlyCreateModel(migrations.CreateModel):
def database_forwards(self, app_label, schema_editor, from_state, to_state):
if VERSION >= (1, 8) and schema_editor.connection.vendor.startswith("postgres"):
super(PostgresOnlyCreateModel, self).database_forwards(app_label, schema_editor, from_state, to_state)
def database_backwards(self, app_label, schema_editor, from_state, to_state):
if VERSION >= (1, 8) and schema_editor.connection.vendor.startswith("postgres"):
super(PostgresOnlyCreateModel, self).database_backwards(app_label, schema_editor, from_state, to_state)
class Migration(migrations.Migration):
dependencies = [
('core', '0003_withfloatfield'),
]
operations = [
PostgresOnlyCreateModel(
name='BookWithChapters',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, verbose_name='Book name')),
('chapters', chapters_field)
],
),
]
|
d317b27a5dac13900beb8f2674b0725313970a80 | nodeconductor/core/handlers.py | nodeconductor/core/handlers.py | from __future__ import unicode_literals
import logging
from nodeconductor.core.log import EventLoggerAdapter
logger = logging.getLogger(__name__)
event_logger = EventLoggerAdapter(logger)
def log_ssh_key_save(sender, instance, created=False, **kwargs):
if created:
event_logger.info(
'SSH key %s has been created.', instance.name,
extra={'ssh_key': instance, 'event_type': 'ssh_key_created'})
def log_ssh_key_delete(sender, instance, **kwargs):
event_logger.info(
'SSH key %s has been deleted.', instance.name,
extra={'ssh_key': instance, 'event_type': 'ssh_key_deleted'})
| from __future__ import unicode_literals
import logging
from nodeconductor.core.log import EventLoggerAdapter
logger = logging.getLogger(__name__)
event_logger = EventLoggerAdapter(logger)
def log_ssh_key_save(sender, instance, created=False, **kwargs):
if created:
event_logger.info(
'SSH key %s has been created.', instance.name,
extra={'ssh_key': instance, 'event_type': 'ssh_key_creation_succeeded'})
def log_ssh_key_delete(sender, instance, **kwargs):
event_logger.info(
'SSH key %s has been deleted.', instance.name,
extra={'ssh_key': instance, 'event_type': 'ssh_key_deletion_succeeded'})
| Rename event types for consistency | Rename event types for consistency
- NC-332
| Python | mit | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor | from __future__ import unicode_literals
import logging
from nodeconductor.core.log import EventLoggerAdapter
logger = logging.getLogger(__name__)
event_logger = EventLoggerAdapter(logger)
def log_ssh_key_save(sender, instance, created=False, **kwargs):
if created:
event_logger.info(
'SSH key %s has been created.', instance.name,
- extra={'ssh_key': instance, 'event_type': 'ssh_key_created'})
+ extra={'ssh_key': instance, 'event_type': 'ssh_key_creation_succeeded'})
def log_ssh_key_delete(sender, instance, **kwargs):
event_logger.info(
'SSH key %s has been deleted.', instance.name,
- extra={'ssh_key': instance, 'event_type': 'ssh_key_deleted'})
+ extra={'ssh_key': instance, 'event_type': 'ssh_key_deletion_succeeded'})
| Rename event types for consistency | ## Code Before:
from __future__ import unicode_literals
import logging
from nodeconductor.core.log import EventLoggerAdapter
logger = logging.getLogger(__name__)
event_logger = EventLoggerAdapter(logger)
def log_ssh_key_save(sender, instance, created=False, **kwargs):
if created:
event_logger.info(
'SSH key %s has been created.', instance.name,
extra={'ssh_key': instance, 'event_type': 'ssh_key_created'})
def log_ssh_key_delete(sender, instance, **kwargs):
event_logger.info(
'SSH key %s has been deleted.', instance.name,
extra={'ssh_key': instance, 'event_type': 'ssh_key_deleted'})
## Instruction:
Rename event types for consistency
## Code After:
from __future__ import unicode_literals
import logging
from nodeconductor.core.log import EventLoggerAdapter
logger = logging.getLogger(__name__)
event_logger = EventLoggerAdapter(logger)
def log_ssh_key_save(sender, instance, created=False, **kwargs):
if created:
event_logger.info(
'SSH key %s has been created.', instance.name,
extra={'ssh_key': instance, 'event_type': 'ssh_key_creation_succeeded'})
def log_ssh_key_delete(sender, instance, **kwargs):
event_logger.info(
'SSH key %s has been deleted.', instance.name,
extra={'ssh_key': instance, 'event_type': 'ssh_key_deletion_succeeded'})
|
fba983fa54691fcde0de93d6519b3906dff3cb32 | sara_flexbe_states/src/sara_flexbe_states/get_distance2D.py | sara_flexbe_states/src/sara_flexbe_states/get_distance2D.py |
from flexbe_core import EventState, Logger
import rospy
import re
import ros
import math
class getDistance(EventState):
"""
Calcule la distance entre deux points donnes.
### InputKey
># point1
># point2
### OutputKey
#> distance
<= done
"""
def __init__(self):
"""Constructor"""
super(GetNumberFromText, self).__init__(outcomes = ['done'], input_keys = ['point1','point2'], output_keys = ['distance'])
def execute(self, userdata):
"""Wait for action result and return outcome accordingly"""
userdata.distance= calculate_distance(userdata.point1,userdata.point2)
return 'done'
def calculate_distance(p1,p2):
return math.sqrt(math.pow(p2.x-p1.x,2)+math.pow(p2.y-p1.y,2))
|
from flexbe_core import EventState, Logger
import rospy
import re
import ros
import math
class getDistance(EventState):
"""
Calcule la distance entre deux points donnes.
### InputKey
># point1
># point2
### OutputKey
#> distance
<= done
"""
def __init__(self):
"""Constructor"""
super(getDistance, self).__init__(outcomes = ['done'], input_keys = ['point1','point2'], output_keys = ['distance'])
def execute(self, userdata):
"""Wait for action result and return outcome accordingly"""
userdata.distance= calculate_distance(userdata.point1,userdata.point2)
return 'done'
def calculate_distance(p1,p2):
return math.sqrt(math.pow(p2.x-p1.x,2)+math.pow(p2.y-p1.y,2))
| Correct call to super constructor | Correct call to super constructor
| Python | bsd-3-clause | WalkingMachine/sara_behaviors,WalkingMachine/sara_behaviors |
from flexbe_core import EventState, Logger
import rospy
import re
import ros
import math
class getDistance(EventState):
"""
Calcule la distance entre deux points donnes.
### InputKey
># point1
># point2
### OutputKey
#> distance
<= done
"""
def __init__(self):
"""Constructor"""
- super(GetNumberFromText, self).__init__(outcomes = ['done'], input_keys = ['point1','point2'], output_keys = ['distance'])
+ super(getDistance, self).__init__(outcomes = ['done'], input_keys = ['point1','point2'], output_keys = ['distance'])
def execute(self, userdata):
"""Wait for action result and return outcome accordingly"""
userdata.distance= calculate_distance(userdata.point1,userdata.point2)
return 'done'
def calculate_distance(p1,p2):
return math.sqrt(math.pow(p2.x-p1.x,2)+math.pow(p2.y-p1.y,2))
| Correct call to super constructor | ## Code Before:
from flexbe_core import EventState, Logger
import rospy
import re
import ros
import math
class getDistance(EventState):
"""
Calcule la distance entre deux points donnes.
### InputKey
># point1
># point2
### OutputKey
#> distance
<= done
"""
def __init__(self):
"""Constructor"""
super(GetNumberFromText, self).__init__(outcomes = ['done'], input_keys = ['point1','point2'], output_keys = ['distance'])
def execute(self, userdata):
"""Wait for action result and return outcome accordingly"""
userdata.distance= calculate_distance(userdata.point1,userdata.point2)
return 'done'
def calculate_distance(p1,p2):
return math.sqrt(math.pow(p2.x-p1.x,2)+math.pow(p2.y-p1.y,2))
## Instruction:
Correct call to super constructor
## Code After:
from flexbe_core import EventState, Logger
import rospy
import re
import ros
import math
class getDistance(EventState):
"""
Calcule la distance entre deux points donnes.
### InputKey
># point1
># point2
### OutputKey
#> distance
<= done
"""
def __init__(self):
"""Constructor"""
super(getDistance, self).__init__(outcomes = ['done'], input_keys = ['point1','point2'], output_keys = ['distance'])
def execute(self, userdata):
"""Wait for action result and return outcome accordingly"""
userdata.distance= calculate_distance(userdata.point1,userdata.point2)
return 'done'
def calculate_distance(p1,p2):
return math.sqrt(math.pow(p2.x-p1.x,2)+math.pow(p2.y-p1.y,2))
|
06914af3d8df899947a53c2fe3b3ce1de208d04d | robot-framework-needle.py | robot-framework-needle.py | from needle.cases import NeedleTestCase
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
class TestLogo(NeedleTestCase):
def test_logo(self):
self.driver.get('http://www.bbc.co.uk/news/')
try:
WebDriverWait(self.driver, 20).until(
ec.presence_of_element_located((By.ID, "blq-mast"))
)
finally:
pass
self.assertScreenshot('#blq-mast', 'bbc-masthead') | from needle.cases import NeedleTestCase
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
class TestLogo(NeedleTestCase):
def test_logo(self):
self.driver.get('http://www.bbc.co.uk/news/')
try:
WebDriverWait(self.driver, 20).until(
ec.presence_of_element_located((By.ID, "idcta-link"))
)
finally:
pass
self.assertScreenshot('#idcta-link', 'bbc-masthead') | Fix locators used in needle example on BBC site | Fix locators used in needle example on BBC site
| Python | apache-2.0 | laurentbristiel/robotframework-needle | from needle.cases import NeedleTestCase
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
class TestLogo(NeedleTestCase):
def test_logo(self):
self.driver.get('http://www.bbc.co.uk/news/')
try:
WebDriverWait(self.driver, 20).until(
- ec.presence_of_element_located((By.ID, "blq-mast"))
+ ec.presence_of_element_located((By.ID, "idcta-link"))
)
finally:
pass
- self.assertScreenshot('#blq-mast', 'bbc-masthead')
+ self.assertScreenshot('#idcta-link', 'bbc-masthead') | Fix locators used in needle example on BBC site | ## Code Before:
from needle.cases import NeedleTestCase
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
class TestLogo(NeedleTestCase):
def test_logo(self):
self.driver.get('http://www.bbc.co.uk/news/')
try:
WebDriverWait(self.driver, 20).until(
ec.presence_of_element_located((By.ID, "blq-mast"))
)
finally:
pass
self.assertScreenshot('#blq-mast', 'bbc-masthead')
## Instruction:
Fix locators used in needle example on BBC site
## Code After:
from needle.cases import NeedleTestCase
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
class TestLogo(NeedleTestCase):
def test_logo(self):
self.driver.get('http://www.bbc.co.uk/news/')
try:
WebDriverWait(self.driver, 20).until(
ec.presence_of_element_located((By.ID, "idcta-link"))
)
finally:
pass
self.assertScreenshot('#idcta-link', 'bbc-masthead') |
ede4689ce3f9e03db5f250617e793083333af3a5 | notification/backends/email.py | notification/backends/email.py |
from django.conf import settings
from django.core.urlresolvers import reverse
from django.template.loader import render_to_string
from django.utils.translation import ugettext
from django.contrib.sites.models import Site
from notification import backends
from notification.message import message_to_text
# favour django-mailer but fall back to django.core.mail
try:
from mailer import send_mail
except ImportError:
from django.core.mail import send_mail
class EmailBackend(backends.BaseBackend):
def can_send(self, user, notice_type):
if should_send(user, notice_type, "1") and user.email:
return True
return False
def deliver(self, recipients, notice_type, message):
notices_url = u"http://%s%s" % (
unicode(Site.objects.get_current()),
reverse("notification_notices"),
)
subject = render_to_string("notification/notification_subject.txt", {
"display": ugettext(notice_type.display),
})
message_body = render_to_string("notification/notification_body.txt", {
"message": message_to_text(message),
"notices_url": notices_url,
"contact_email": settings.CONTACT_EMAIL,
})
send_mail(subject, message_body,
settings.DEFAULT_FROM_EMAIL, recipients)
|
from django.conf import settings
from django.db.models.loading import get_app
from django.core.urlresolvers import reverse
from django.template.loader import render_to_string
from django.utils.translation import ugettext
from django.contrib.sites.models import Site
from django.core.exceptions import ImproperlyConfigured
from notification import backends
from notification.message import message_to_text
# favour django-mailer but fall back to django.core.mail
try:
mailer = get_app("mailer")
from mailer import send_mail
except ImproperlyConfigured:
from django.core.mail import send_mail
class EmailBackend(backends.BaseBackend):
def can_send(self, user, notice_type):
if should_send(user, notice_type, "1") and user.email:
return True
return False
def deliver(self, recipients, notice_type, message):
notices_url = u"http://%s%s" % (
unicode(Site.objects.get_current()),
reverse("notification_notices"),
)
subject = render_to_string("notification/notification_subject.txt", {
"display": ugettext(notice_type.display),
})
message_body = render_to_string("notification/notification_body.txt", {
"message": message_to_text(message),
"notices_url": notices_url,
"contact_email": settings.CONTACT_EMAIL,
})
send_mail(subject, message_body,
settings.DEFAULT_FROM_EMAIL, recipients)
| Use get_app over to include django-mailer support over a standard import and ImportError exception handling. | pluggable-backends: Use get_app over to include django-mailer support over a standard import and ImportError exception handling.
git-svn-id: 12265af7f62f437cb19748843ef653b20b846039@130 590c3fc9-4838-0410-bb95-17a0c9b37ca9
| Python | mit | brosner/django-notification,arctelix/django-notification-automated |
from django.conf import settings
+ from django.db.models.loading import get_app
from django.core.urlresolvers import reverse
from django.template.loader import render_to_string
from django.utils.translation import ugettext
from django.contrib.sites.models import Site
+ from django.core.exceptions import ImproperlyConfigured
from notification import backends
from notification.message import message_to_text
# favour django-mailer but fall back to django.core.mail
try:
+ mailer = get_app("mailer")
from mailer import send_mail
- except ImportError:
+ except ImproperlyConfigured:
from django.core.mail import send_mail
class EmailBackend(backends.BaseBackend):
def can_send(self, user, notice_type):
if should_send(user, notice_type, "1") and user.email:
return True
return False
def deliver(self, recipients, notice_type, message):
notices_url = u"http://%s%s" % (
unicode(Site.objects.get_current()),
reverse("notification_notices"),
)
subject = render_to_string("notification/notification_subject.txt", {
"display": ugettext(notice_type.display),
})
message_body = render_to_string("notification/notification_body.txt", {
"message": message_to_text(message),
"notices_url": notices_url,
"contact_email": settings.CONTACT_EMAIL,
})
send_mail(subject, message_body,
settings.DEFAULT_FROM_EMAIL, recipients)
| Use get_app over to include django-mailer support over a standard import and ImportError exception handling. | ## Code Before:
from django.conf import settings
from django.core.urlresolvers import reverse
from django.template.loader import render_to_string
from django.utils.translation import ugettext
from django.contrib.sites.models import Site
from notification import backends
from notification.message import message_to_text
# favour django-mailer but fall back to django.core.mail
try:
from mailer import send_mail
except ImportError:
from django.core.mail import send_mail
class EmailBackend(backends.BaseBackend):
def can_send(self, user, notice_type):
if should_send(user, notice_type, "1") and user.email:
return True
return False
def deliver(self, recipients, notice_type, message):
notices_url = u"http://%s%s" % (
unicode(Site.objects.get_current()),
reverse("notification_notices"),
)
subject = render_to_string("notification/notification_subject.txt", {
"display": ugettext(notice_type.display),
})
message_body = render_to_string("notification/notification_body.txt", {
"message": message_to_text(message),
"notices_url": notices_url,
"contact_email": settings.CONTACT_EMAIL,
})
send_mail(subject, message_body,
settings.DEFAULT_FROM_EMAIL, recipients)
## Instruction:
Use get_app over to include django-mailer support over a standard import and ImportError exception handling.
## Code After:
from django.conf import settings
from django.db.models.loading import get_app
from django.core.urlresolvers import reverse
from django.template.loader import render_to_string
from django.utils.translation import ugettext
from django.contrib.sites.models import Site
from django.core.exceptions import ImproperlyConfigured
from notification import backends
from notification.message import message_to_text
# favour django-mailer but fall back to django.core.mail
try:
mailer = get_app("mailer")
from mailer import send_mail
except ImproperlyConfigured:
from django.core.mail import send_mail
class EmailBackend(backends.BaseBackend):
def can_send(self, user, notice_type):
if should_send(user, notice_type, "1") and user.email:
return True
return False
def deliver(self, recipients, notice_type, message):
notices_url = u"http://%s%s" % (
unicode(Site.objects.get_current()),
reverse("notification_notices"),
)
subject = render_to_string("notification/notification_subject.txt", {
"display": ugettext(notice_type.display),
})
message_body = render_to_string("notification/notification_body.txt", {
"message": message_to_text(message),
"notices_url": notices_url,
"contact_email": settings.CONTACT_EMAIL,
})
send_mail(subject, message_body,
settings.DEFAULT_FROM_EMAIL, recipients)
|
24c1309a9f221ec8be6a3b15dc843769f4157cf1 | allauth/socialaccount/providers/twitch/views.py | allauth/socialaccount/providers/twitch/views.py | import requests
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
from .provider import TwitchProvider
class TwitchOAuth2Adapter(OAuth2Adapter):
provider_id = TwitchProvider.id
access_token_url = 'https://api.twitch.tv/kraken/oauth2/token'
authorize_url = 'https://api.twitch.tv/kraken/oauth2/authorize'
profile_url = 'https://api.twitch.tv/kraken/user'
def complete_login(self, request, app, token, **kwargs):
resp = requests.get(
self.profile_url,
params={'oauth_token': token.token,
'client_id': app.client_id})
extra_data = resp.json()
return self.get_provider().sociallogin_from_response(request,
extra_data)
oauth2_login = OAuth2LoginView.adapter_view(TwitchOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(TwitchOAuth2Adapter)
| import requests
from allauth.socialaccount.providers.oauth2.client import OAuth2Error
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
from .provider import TwitchProvider
class TwitchOAuth2Adapter(OAuth2Adapter):
provider_id = TwitchProvider.id
access_token_url = 'https://api.twitch.tv/kraken/oauth2/token'
authorize_url = 'https://api.twitch.tv/kraken/oauth2/authorize'
profile_url = 'https://api.twitch.tv/kraken/user'
def complete_login(self, request, app, token, **kwargs):
params = {"oauth_token": token.token, "client_id": app.client_id}
response = requests.get(self.profile_url, params=params)
data = response.json()
if response.status_code >= 400:
error = data.get("error", "")
message = data.get("message", "")
raise OAuth2Error("Twitch API Error: %s (%s)" % (error, message))
if "_id" not in data:
raise OAuth2Error("Invalid data from Twitch API: %r" % (data))
return self.get_provider().sociallogin_from_response(request, data)
oauth2_login = OAuth2LoginView.adapter_view(TwitchOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(TwitchOAuth2Adapter)
| Add error checking in API response | twitch: Add error checking in API response
| Python | mit | rsalmaso/django-allauth,lukeburden/django-allauth,pennersr/django-allauth,AltSchool/django-allauth,pztrick/django-allauth,AltSchool/django-allauth,rsalmaso/django-allauth,bittner/django-allauth,pztrick/django-allauth,pennersr/django-allauth,lukeburden/django-allauth,lukeburden/django-allauth,pztrick/django-allauth,bittner/django-allauth,AltSchool/django-allauth,rsalmaso/django-allauth,bittner/django-allauth,pennersr/django-allauth | import requests
+ from allauth.socialaccount.providers.oauth2.client import OAuth2Error
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
from .provider import TwitchProvider
class TwitchOAuth2Adapter(OAuth2Adapter):
provider_id = TwitchProvider.id
access_token_url = 'https://api.twitch.tv/kraken/oauth2/token'
authorize_url = 'https://api.twitch.tv/kraken/oauth2/authorize'
profile_url = 'https://api.twitch.tv/kraken/user'
def complete_login(self, request, app, token, **kwargs):
+ params = {"oauth_token": token.token, "client_id": app.client_id}
+ response = requests.get(self.profile_url, params=params)
+
- resp = requests.get(
- self.profile_url,
- params={'oauth_token': token.token,
- 'client_id': app.client_id})
- extra_data = resp.json()
+ data = response.json()
+ if response.status_code >= 400:
+ error = data.get("error", "")
+ message = data.get("message", "")
+ raise OAuth2Error("Twitch API Error: %s (%s)" % (error, message))
+
+ if "_id" not in data:
+ raise OAuth2Error("Invalid data from Twitch API: %r" % (data))
+
- return self.get_provider().sociallogin_from_response(request,
+ return self.get_provider().sociallogin_from_response(request, data)
- extra_data)
oauth2_login = OAuth2LoginView.adapter_view(TwitchOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(TwitchOAuth2Adapter)
| Add error checking in API response | ## Code Before:
import requests
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
from .provider import TwitchProvider
class TwitchOAuth2Adapter(OAuth2Adapter):
provider_id = TwitchProvider.id
access_token_url = 'https://api.twitch.tv/kraken/oauth2/token'
authorize_url = 'https://api.twitch.tv/kraken/oauth2/authorize'
profile_url = 'https://api.twitch.tv/kraken/user'
def complete_login(self, request, app, token, **kwargs):
resp = requests.get(
self.profile_url,
params={'oauth_token': token.token,
'client_id': app.client_id})
extra_data = resp.json()
return self.get_provider().sociallogin_from_response(request,
extra_data)
oauth2_login = OAuth2LoginView.adapter_view(TwitchOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(TwitchOAuth2Adapter)
## Instruction:
Add error checking in API response
## Code After:
import requests
from allauth.socialaccount.providers.oauth2.client import OAuth2Error
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
from .provider import TwitchProvider
class TwitchOAuth2Adapter(OAuth2Adapter):
provider_id = TwitchProvider.id
access_token_url = 'https://api.twitch.tv/kraken/oauth2/token'
authorize_url = 'https://api.twitch.tv/kraken/oauth2/authorize'
profile_url = 'https://api.twitch.tv/kraken/user'
def complete_login(self, request, app, token, **kwargs):
params = {"oauth_token": token.token, "client_id": app.client_id}
response = requests.get(self.profile_url, params=params)
data = response.json()
if response.status_code >= 400:
error = data.get("error", "")
message = data.get("message", "")
raise OAuth2Error("Twitch API Error: %s (%s)" % (error, message))
if "_id" not in data:
raise OAuth2Error("Invalid data from Twitch API: %r" % (data))
return self.get_provider().sociallogin_from_response(request, data)
oauth2_login = OAuth2LoginView.adapter_view(TwitchOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(TwitchOAuth2Adapter)
|
8386d7372f9ff8bfad651efe43504746aff19b73 | app/models/rooms/rooms.py | app/models/rooms/rooms.py | from models.people.people import Staff, Fellow
from models.rooms.rooms import Office, LivingSpace
import random
class Dojo(object):
def __init__(self):
self.offices = []
self.livingrooms = []
self.staff = []
self.fellows = []
self.all_rooms = []
self.all_people = []
def get_room(self, rooms):
"""A function to generate a list of random rooms with space.
:param rooms:
:return: room_name
"""
# a room is only available if it's capacity is not exceeded
available_rooms = [room for room in rooms if len(room.occupants) < room.room_capacity]
# return False if all rooms are full
if len(available_rooms) < 1:
return False
# choose a room fro the list of available rooms.
chosen_room = random.choice(available_rooms)
return chosen_room.room_name
def create_room(self, room_name, room_type):
if room_type is 'office':
if room_name not in [room.room_name for room in self.offices]:
room = Office(room_name=room_name, room_type=room_type)
self.offices.append(room)
self.all_rooms.append(room)
return 'An office called' + ' ' + room_name + ' ' + 'has been successfully created'
return 'An office with that name already exists'
if room_type is 'livingspace':
if room_name not in [room.room_name for room in self.livingrooms]:
room = LivingSpace(room_name=room_name, room_type=room_type)
# add object to list( has both room_name and room_type)
self.livingrooms.append(room)
self.all_rooms.append(room)
return 'A room called ' + room_name + ' has been successfully created!'
return 'A living room with that name already exists'
| import os
import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
class Room(object):
"""Models the kind of rooms available at Andela,
It forms the base class Room from which OfficeSpace and LivingRoom inherit"""
def __init__(self, room_name, room_type, room_capacity):
"""Initializes the base class Room
:param room_name: A string representing the name of the room
:param room_type: A string representing the type of room, whether office or residential
:param room_capacity: An integer representing the amount of space per room.
"""
self.room_name = room_name
self.room_type = room_type
self.room_capacity = room_capacity
self.occupants = []
| Implement the Room base class | Implement the Room base class
| Python | mit | Alweezy/alvin-mutisya-dojo-project | - from models.people.people import Staff, Fellow
- from models.rooms.rooms import Office, LivingSpace
- import random
+ import os
+ import sys
+ from os import path
+ sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
- class Dojo(object):
+ class Room(object):
+ """Models the kind of rooms available at Andela,
+ It forms the base class Room from which OfficeSpace and LivingRoom inherit"""
+ def __init__(self, room_name, room_type, room_capacity):
+ """Initializes the base class Room
+ :param room_name: A string representing the name of the room
+ :param room_type: A string representing the type of room, whether office or residential
+ :param room_capacity: An integer representing the amount of space per room.
- def __init__(self):
- self.offices = []
- self.livingrooms = []
- self.staff = []
- self.fellows = []
- self.all_rooms = []
- self.all_people = []
-
- def get_room(self, rooms):
- """A function to generate a list of random rooms with space.
- :param rooms:
- :return: room_name
"""
+ self.room_name = room_name
+ self.room_type = room_type
+ self.room_capacity = room_capacity
+ self.occupants = []
- # a room is only available if it's capacity is not exceeded
- available_rooms = [room for room in rooms if len(room.occupants) < room.room_capacity]
- # return False if all rooms are full
- if len(available_rooms) < 1:
- return False
- # choose a room fro the list of available rooms.
- chosen_room = random.choice(available_rooms)
- return chosen_room.room_name
-
- def create_room(self, room_name, room_type):
- if room_type is 'office':
- if room_name not in [room.room_name for room in self.offices]:
- room = Office(room_name=room_name, room_type=room_type)
- self.offices.append(room)
- self.all_rooms.append(room)
- return 'An office called' + ' ' + room_name + ' ' + 'has been successfully created'
- return 'An office with that name already exists'
- if room_type is 'livingspace':
- if room_name not in [room.room_name for room in self.livingrooms]:
- room = LivingSpace(room_name=room_name, room_type=room_type)
- # add object to list( has both room_name and room_type)
- self.livingrooms.append(room)
- self.all_rooms.append(room)
- return 'A room called ' + room_name + ' has been successfully created!'
- return 'A living room with that name already exists'
| Implement the Room base class | ## Code Before:
from models.people.people import Staff, Fellow
from models.rooms.rooms import Office, LivingSpace
import random
class Dojo(object):
def __init__(self):
self.offices = []
self.livingrooms = []
self.staff = []
self.fellows = []
self.all_rooms = []
self.all_people = []
def get_room(self, rooms):
"""A function to generate a list of random rooms with space.
:param rooms:
:return: room_name
"""
# a room is only available if it's capacity is not exceeded
available_rooms = [room for room in rooms if len(room.occupants) < room.room_capacity]
# return False if all rooms are full
if len(available_rooms) < 1:
return False
# choose a room fro the list of available rooms.
chosen_room = random.choice(available_rooms)
return chosen_room.room_name
def create_room(self, room_name, room_type):
if room_type is 'office':
if room_name not in [room.room_name for room in self.offices]:
room = Office(room_name=room_name, room_type=room_type)
self.offices.append(room)
self.all_rooms.append(room)
return 'An office called' + ' ' + room_name + ' ' + 'has been successfully created'
return 'An office with that name already exists'
if room_type is 'livingspace':
if room_name not in [room.room_name for room in self.livingrooms]:
room = LivingSpace(room_name=room_name, room_type=room_type)
# add object to list( has both room_name and room_type)
self.livingrooms.append(room)
self.all_rooms.append(room)
return 'A room called ' + room_name + ' has been successfully created!'
return 'A living room with that name already exists'
## Instruction:
Implement the Room base class
## Code After:
import os
import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
class Room(object):
"""Models the kind of rooms available at Andela,
It forms the base class Room from which OfficeSpace and LivingRoom inherit"""
def __init__(self, room_name, room_type, room_capacity):
"""Initializes the base class Room
:param room_name: A string representing the name of the room
:param room_type: A string representing the type of room, whether office or residential
:param room_capacity: An integer representing the amount of space per room.
"""
self.room_name = room_name
self.room_type = room_type
self.room_capacity = room_capacity
self.occupants = []
|
df2d24757d8e12035437d152d17dc9016f1cd9df | app/__init__.py | app/__init__.py |
from flask import Flask
app = Flask(__name__) # pylint: disable=invalid-name
app.config.from_object('config')
# commented as for file structure, should recover later.
# from app import models
@app.route('/')
@app.route('/hellworld')
def helloworld():
""" Hello World for app. """
return 'Hello world from {}!'.format(__name__)
|
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__) # pylint: disable=invalid-name
app.config.from_object('config')
# commented as for file structure, should recover later.
# from app import models
db = SQLAlchemy(app)
@app.route('/')
@app.route('/hellworld')
def helloworld():
""" Hello World for app. """
return 'Hello world from {}!'.format(__name__)
| Create model in config file. | Create model in config file.
| Python | mit | CAPU-ENG/CAPUHome-API,huxuan/CAPUHome-API |
from flask import Flask
+ from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__) # pylint: disable=invalid-name
app.config.from_object('config')
# commented as for file structure, should recover later.
# from app import models
+
+ db = SQLAlchemy(app)
@app.route('/')
@app.route('/hellworld')
def helloworld():
""" Hello World for app. """
return 'Hello world from {}!'.format(__name__)
| Create model in config file. | ## Code Before:
from flask import Flask
app = Flask(__name__) # pylint: disable=invalid-name
app.config.from_object('config')
# commented as for file structure, should recover later.
# from app import models
@app.route('/')
@app.route('/hellworld')
def helloworld():
""" Hello World for app. """
return 'Hello world from {}!'.format(__name__)
## Instruction:
Create model in config file.
## Code After:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__) # pylint: disable=invalid-name
app.config.from_object('config')
# commented as for file structure, should recover later.
# from app import models
db = SQLAlchemy(app)
@app.route('/')
@app.route('/hellworld')
def helloworld():
""" Hello World for app. """
return 'Hello world from {}!'.format(__name__)
|
8c2996b94cdc3210b24ebeaeb957c625629f68a5 | hunting/level/encoder.py | hunting/level/encoder.py | import json
import hunting.sim.entities as entities
class GameObjectEncoder(json.JSONEncoder):
def default(self, o):
d = o.__dict__
d.pop('owner', None)
if isinstance(o, entities.GameObject):
d.pop('log', None)
d.pop('ai', None)
return d
elif isinstance(o, entities.Fighter):
d.pop('death_function')
return d
elif isinstance(o, entities.ChangeableProperty):
return {k: o.__dict__[k] for k in ['property_type', 'base']}
else:
return d
def encode_level(level):
save_factions = [f for f in level.get_factions() if level.get_faction_info(f)['save'] is True]
factions_to_objects = {f: level.get_objects_inside_faction(f) for f in save_factions}
return json.dumps(factions_to_objects, cls=GameObjectEncoder, indent=2)
| import json
import hunting.sim.entities as entities
class GameObjectEncoder(json.JSONEncoder):
def default(self, o):
d = o.__dict__
d.pop('owner', None)
if isinstance(o, entities.GameObject):
d.pop('log', None)
d.pop('ai', None)
return d
elif isinstance(o, entities.Fighter):
d.pop('death_function')
return d
elif isinstance(o, entities.ChangeableProperty):
return {k: o.__dict__[k] for k in ['property_type', 'base']}
else:
return d
def encode_level(level):
save_factions = {f: level.get_faction_info(f) for f in level.get_factions()
if level.get_faction_info(f)['save'] is True}
for f in save_factions:
save_factions[f]['objects'] = level.get_objects_inside_faction(f)
output = {'log': level.log.events,
'factions': save_factions}
return json.dumps(output, cls=GameObjectEncoder, indent=2)
| Add log to encoding output (still fails due to objects) | Add log to encoding output (still fails due to objects)
| Python | mit | MoyTW/RL_Arena_Experiment | import json
import hunting.sim.entities as entities
class GameObjectEncoder(json.JSONEncoder):
def default(self, o):
d = o.__dict__
d.pop('owner', None)
if isinstance(o, entities.GameObject):
d.pop('log', None)
d.pop('ai', None)
return d
elif isinstance(o, entities.Fighter):
d.pop('death_function')
return d
elif isinstance(o, entities.ChangeableProperty):
return {k: o.__dict__[k] for k in ['property_type', 'base']}
else:
return d
def encode_level(level):
+ save_factions = {f: level.get_faction_info(f) for f in level.get_factions()
+ if level.get_faction_info(f)['save'] is True}
- save_factions = [f for f in level.get_factions() if level.get_faction_info(f)['save'] is True]
- factions_to_objects = {f: level.get_objects_inside_faction(f) for f in save_factions}
- return json.dumps(factions_to_objects, cls=GameObjectEncoder, indent=2)
+ for f in save_factions:
+ save_factions[f]['objects'] = level.get_objects_inside_faction(f)
+
+ output = {'log': level.log.events,
+ 'factions': save_factions}
+
+ return json.dumps(output, cls=GameObjectEncoder, indent=2)
+ | Add log to encoding output (still fails due to objects) | ## Code Before:
import json
import hunting.sim.entities as entities
class GameObjectEncoder(json.JSONEncoder):
def default(self, o):
d = o.__dict__
d.pop('owner', None)
if isinstance(o, entities.GameObject):
d.pop('log', None)
d.pop('ai', None)
return d
elif isinstance(o, entities.Fighter):
d.pop('death_function')
return d
elif isinstance(o, entities.ChangeableProperty):
return {k: o.__dict__[k] for k in ['property_type', 'base']}
else:
return d
def encode_level(level):
save_factions = [f for f in level.get_factions() if level.get_faction_info(f)['save'] is True]
factions_to_objects = {f: level.get_objects_inside_faction(f) for f in save_factions}
return json.dumps(factions_to_objects, cls=GameObjectEncoder, indent=2)
## Instruction:
Add log to encoding output (still fails due to objects)
## Code After:
import json
import hunting.sim.entities as entities
class GameObjectEncoder(json.JSONEncoder):
def default(self, o):
d = o.__dict__
d.pop('owner', None)
if isinstance(o, entities.GameObject):
d.pop('log', None)
d.pop('ai', None)
return d
elif isinstance(o, entities.Fighter):
d.pop('death_function')
return d
elif isinstance(o, entities.ChangeableProperty):
return {k: o.__dict__[k] for k in ['property_type', 'base']}
else:
return d
def encode_level(level):
save_factions = {f: level.get_faction_info(f) for f in level.get_factions()
if level.get_faction_info(f)['save'] is True}
for f in save_factions:
save_factions[f]['objects'] = level.get_objects_inside_faction(f)
output = {'log': level.log.events,
'factions': save_factions}
return json.dumps(output, cls=GameObjectEncoder, indent=2)
|
b723cbceb896f7ca8690eaa13c38ffb20fecd0be | avocado/search_indexes.py | avocado/search_indexes.py | import warnings
from haystack import indexes
from avocado.conf import settings
from avocado.models import DataConcept, DataField
# Warn if either of the settings are set to false
if not getattr(settings, 'CONCEPT_SEARCH_ENABLED', True) or \
not getattr(settings, 'FIELD_SEARCH_ENABLED', True):
warnings.warn('CONCEPT_SEARCH_ENABLED and FIELD_SEARCH_ENABLED have been '
'deprecated due to changes in Haystack 2.x API. To exclude '
'an index from being discovered, add the path to the class '
'to EXCLUDED_INDEXES in the appropriate '
'HAYSTACK_CONNECTIONS entry in settings.')
class DataIndex(indexes.SearchIndex):
text = indexes.CharField(document=True, use_template=True)
text_auto = indexes.EdgeNgramField(use_template=True)
def index_queryset(self, using=None):
return self.get_model().objects.published()
def load_all_queryset(self):
return self.index_queryset()
class DataConceptIndex(DataIndex, indexes.Indexable):
def get_model(self):
return DataConcept
class DataFieldIndex(DataIndex, indexes.Indexable):
def get_model(self):
return DataField
| from haystack import indexes
from avocado.models import DataConcept, DataField
class DataIndex(indexes.SearchIndex):
text = indexes.CharField(document=True, use_template=True)
text_auto = indexes.EdgeNgramField(use_template=True)
def index_queryset(self, using=None):
return self.get_model().objects.filter(published=True, archived=False)
def read_queryset(self, using=None):
return self.index_queryset()
def load_all_queryset(self):
return self.index_queryset()
class DataConceptIndex(DataIndex, indexes.Indexable):
def get_model(self):
return DataConcept
class DataFieldIndex(DataIndex, indexes.Indexable):
def get_model(self):
return DataField
| Change DataIndex to restrict on published and archived flags only | Change DataIndex to restrict on published and archived flags only
In addition, the warnings of the deprecated settings have been removed.
Fix #290
Signed-off-by: Byron Ruth <[email protected]>
| Python | bsd-2-clause | murphyke/avocado,murphyke/avocado,murphyke/avocado,murphyke/avocado | - import warnings
from haystack import indexes
- from avocado.conf import settings
from avocado.models import DataConcept, DataField
-
- # Warn if either of the settings are set to false
- if not getattr(settings, 'CONCEPT_SEARCH_ENABLED', True) or \
- not getattr(settings, 'FIELD_SEARCH_ENABLED', True):
- warnings.warn('CONCEPT_SEARCH_ENABLED and FIELD_SEARCH_ENABLED have been '
- 'deprecated due to changes in Haystack 2.x API. To exclude '
- 'an index from being discovered, add the path to the class '
- 'to EXCLUDED_INDEXES in the appropriate '
- 'HAYSTACK_CONNECTIONS entry in settings.')
class DataIndex(indexes.SearchIndex):
text = indexes.CharField(document=True, use_template=True)
text_auto = indexes.EdgeNgramField(use_template=True)
def index_queryset(self, using=None):
- return self.get_model().objects.published()
+ return self.get_model().objects.filter(published=True, archived=False)
+
+ def read_queryset(self, using=None):
+ return self.index_queryset()
def load_all_queryset(self):
return self.index_queryset()
class DataConceptIndex(DataIndex, indexes.Indexable):
def get_model(self):
return DataConcept
class DataFieldIndex(DataIndex, indexes.Indexable):
def get_model(self):
return DataField
| Change DataIndex to restrict on published and archived flags only | ## Code Before:
import warnings
from haystack import indexes
from avocado.conf import settings
from avocado.models import DataConcept, DataField
# Warn if either of the settings are set to false
if not getattr(settings, 'CONCEPT_SEARCH_ENABLED', True) or \
not getattr(settings, 'FIELD_SEARCH_ENABLED', True):
warnings.warn('CONCEPT_SEARCH_ENABLED and FIELD_SEARCH_ENABLED have been '
'deprecated due to changes in Haystack 2.x API. To exclude '
'an index from being discovered, add the path to the class '
'to EXCLUDED_INDEXES in the appropriate '
'HAYSTACK_CONNECTIONS entry in settings.')
class DataIndex(indexes.SearchIndex):
text = indexes.CharField(document=True, use_template=True)
text_auto = indexes.EdgeNgramField(use_template=True)
def index_queryset(self, using=None):
return self.get_model().objects.published()
def load_all_queryset(self):
return self.index_queryset()
class DataConceptIndex(DataIndex, indexes.Indexable):
def get_model(self):
return DataConcept
class DataFieldIndex(DataIndex, indexes.Indexable):
def get_model(self):
return DataField
## Instruction:
Change DataIndex to restrict on published and archived flags only
## Code After:
from haystack import indexes
from avocado.models import DataConcept, DataField
class DataIndex(indexes.SearchIndex):
text = indexes.CharField(document=True, use_template=True)
text_auto = indexes.EdgeNgramField(use_template=True)
def index_queryset(self, using=None):
return self.get_model().objects.filter(published=True, archived=False)
def read_queryset(self, using=None):
return self.index_queryset()
def load_all_queryset(self):
return self.index_queryset()
class DataConceptIndex(DataIndex, indexes.Indexable):
def get_model(self):
return DataConcept
class DataFieldIndex(DataIndex, indexes.Indexable):
def get_model(self):
return DataField
|
86a2e55954ff4b8f5e005296e2ae336b6be627a0 | py/rackattack/clientfactory.py | py/rackattack/clientfactory.py | import os
from rackattack.tcp import client
_VAR_NAME = "RACKATTACK_PROVIDER"
def factory():
if _VAR_NAME not in os.environ:
raise Exception(
"The environment variable '%s' must be defined properly" % _VAR_NAME)
request, subscribe, http = os.environ[_VAR_NAME].split("@@")
return client.Client(
providerRequestLocation=request,
providerSubscribeLocation=subscribe,
providerHTTPLocation=http)
| import os
from rackattack.tcp import client
_VAR_NAME = "RACKATTACK_PROVIDER"
def factory(connectionString=None):
if connectionString is None:
if _VAR_NAME not in os.environ:
raise Exception(
"The environment variable '%s' must be defined properly" % _VAR_NAME)
connectionString = os.environ[_VAR_NAME]
request, subscribe, http = connectionString.split("@@")
return client.Client(
providerRequestLocation=request,
providerSubscribeLocation=subscribe,
providerHTTPLocation=http)
| Allow passing the rackattack connection string as an argument to the client factory | Allow passing the rackattack connection string as an argument to the client factory
| Python | apache-2.0 | eliran-stratoscale/rackattack-api,Stratoscale/rackattack-api | import os
from rackattack.tcp import client
_VAR_NAME = "RACKATTACK_PROVIDER"
- def factory():
+ def factory(connectionString=None):
+ if connectionString is None:
- if _VAR_NAME not in os.environ:
+ if _VAR_NAME not in os.environ:
- raise Exception(
+ raise Exception(
- "The environment variable '%s' must be defined properly" % _VAR_NAME)
+ "The environment variable '%s' must be defined properly" % _VAR_NAME)
- request, subscribe, http = os.environ[_VAR_NAME].split("@@")
+ connectionString = os.environ[_VAR_NAME]
+ request, subscribe, http = connectionString.split("@@")
return client.Client(
providerRequestLocation=request,
providerSubscribeLocation=subscribe,
providerHTTPLocation=http)
| Allow passing the rackattack connection string as an argument to the client factory | ## Code Before:
import os
from rackattack.tcp import client
_VAR_NAME = "RACKATTACK_PROVIDER"
def factory():
if _VAR_NAME not in os.environ:
raise Exception(
"The environment variable '%s' must be defined properly" % _VAR_NAME)
request, subscribe, http = os.environ[_VAR_NAME].split("@@")
return client.Client(
providerRequestLocation=request,
providerSubscribeLocation=subscribe,
providerHTTPLocation=http)
## Instruction:
Allow passing the rackattack connection string as an argument to the client factory
## Code After:
import os
from rackattack.tcp import client
_VAR_NAME = "RACKATTACK_PROVIDER"
def factory(connectionString=None):
if connectionString is None:
if _VAR_NAME not in os.environ:
raise Exception(
"The environment variable '%s' must be defined properly" % _VAR_NAME)
connectionString = os.environ[_VAR_NAME]
request, subscribe, http = connectionString.split("@@")
return client.Client(
providerRequestLocation=request,
providerSubscribeLocation=subscribe,
providerHTTPLocation=http)
|
43f67067c470386b6b24080642cc845ec1655f58 | utils/networking.py | utils/networking.py | import fcntl
import socket
import struct
from contextlib import contextmanager
@contextmanager
def use_interface(ifname):
"""
:type ifname: str
"""
ip = _ip_address_for_interface(ifname.encode('ascii'))
original_socket = socket.socket
def rebound_socket(*args, **kwargs):
sock = original_socket(*args, **kwargs)
sock.bind((ip, 0))
return sock
socket.socket = rebound_socket
yield
socket.socket = original_socket
def _ip_address_for_interface(ifname):
"""
:type ifname: bytes
:rtype: str
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
sock.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
| import fcntl
import socket
import struct
from contextlib import contextmanager
@contextmanager
def use_interface(ifname):
"""
:type ifname: str
"""
ip = _ip_address_for_interface(ifname)
original_socket = socket.socket
def rebound_socket(*args, **kwargs):
sock = original_socket(*args, **kwargs)
sock.bind((ip, 0))
return sock
socket.socket = rebound_socket
yield
socket.socket = original_socket
def _ip_address_for_interface(ifname):
"""
:type ifname: str
:rtype: str
"""
ifname = ifname.encode('ascii')
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
sock.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
| Make _ip_address_for_interface easier to use | Make _ip_address_for_interface easier to use
| Python | apache-2.0 | OPWEN/opwen-webapp,ascoderu/opwen-webapp,ascoderu/opwen-webapp,OPWEN/opwen-webapp,OPWEN/opwen-webapp,ascoderu/opwen-cloudserver,ascoderu/opwen-cloudserver,ascoderu/opwen-webapp | import fcntl
import socket
import struct
from contextlib import contextmanager
@contextmanager
def use_interface(ifname):
"""
:type ifname: str
"""
- ip = _ip_address_for_interface(ifname.encode('ascii'))
+ ip = _ip_address_for_interface(ifname)
original_socket = socket.socket
def rebound_socket(*args, **kwargs):
sock = original_socket(*args, **kwargs)
sock.bind((ip, 0))
return sock
socket.socket = rebound_socket
yield
socket.socket = original_socket
def _ip_address_for_interface(ifname):
"""
- :type ifname: bytes
+ :type ifname: str
:rtype: str
"""
+ ifname = ifname.encode('ascii')
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
sock.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
| Make _ip_address_for_interface easier to use | ## Code Before:
import fcntl
import socket
import struct
from contextlib import contextmanager
@contextmanager
def use_interface(ifname):
"""
:type ifname: str
"""
ip = _ip_address_for_interface(ifname.encode('ascii'))
original_socket = socket.socket
def rebound_socket(*args, **kwargs):
sock = original_socket(*args, **kwargs)
sock.bind((ip, 0))
return sock
socket.socket = rebound_socket
yield
socket.socket = original_socket
def _ip_address_for_interface(ifname):
"""
:type ifname: bytes
:rtype: str
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
sock.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
## Instruction:
Make _ip_address_for_interface easier to use
## Code After:
import fcntl
import socket
import struct
from contextlib import contextmanager
@contextmanager
def use_interface(ifname):
"""
:type ifname: str
"""
ip = _ip_address_for_interface(ifname)
original_socket = socket.socket
def rebound_socket(*args, **kwargs):
sock = original_socket(*args, **kwargs)
sock.bind((ip, 0))
return sock
socket.socket = rebound_socket
yield
socket.socket = original_socket
def _ip_address_for_interface(ifname):
"""
:type ifname: str
:rtype: str
"""
ifname = ifname.encode('ascii')
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
sock.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
|
c80a68b81e936435434931f0b5bf748bcbea54dc | statistics/webui.py | statistics/webui.py | from flask import render_template, g, redirect, request
from db import connect_db, get_all_sum
from statistics import app
@app.before_request
def before_request():
g.db = connect_db()
g.fields = ["CPU", "TOTAL", "SQL", "SOLR", "REDIS", "MEMCACHED"]
@app.route("/")
def main_page():
sort_by = request.args.get('sort_by', None)
data = get_all_sum(g.db)
if sort_by:
data = sorted(data, key=lambda row: row[sort_by])
return render_template("main_page.html", data=data)
@app.route("/add/")
def add_page():
key = request.args.get('KEY')
for field in g.fields:
new_val = int(request.args.get(field, '0'))
old_val = int(g.db.hget(key, field) or '0')
new_val += old_val
g.db.hset(key, field, new_val)
g.db.hincrby(key, "REQUESTS", "1")
return redirect("/")
| from flask import render_template, g, redirect, request
from db import connect_db, get_all_sum
from statistics import app
@app.before_request
def before_request():
g.db = connect_db()
g.fields = ["CPU", "TOTAL", "SQL", "SOLR", "REDIS", "MEMCACHED"]
@app.route("/")
def main_page():
sort_by = request.args.get('sort_by', None)
data = get_all_sum(g.db)
if sort_by:
data = sorted(data, key=lambda row: row[sort_by])
return render_template("main_page.html", data=data)
@app.route("/average/")
def average():
data = get_all_sum(g.db)
for row in data:
req_count = row['REQUESTS']
for k in row:
if k != 'NAME' and k != 'REQUESTS':
row[k] = float(row[k])/req_count
return render_template("main_page.html", data=data)
@app.route("/add/")
def add_page():
key = request.args.get('KEY')
for field in g.fields:
new_val = int(request.args.get(field, '0'))
old_val = int(g.db.hget(key, field) or '0')
new_val += old_val
g.db.hset(key, field, new_val)
g.db.hincrby(key, "REQUESTS", "1")
return redirect("/")
| Add proto of average page. Without sorting. | Add proto of average page. Without sorting.
| Python | mit | uvNikita/appstats,uvNikita/appstats,uvNikita/appstats | from flask import render_template, g, redirect, request
from db import connect_db, get_all_sum
from statistics import app
@app.before_request
def before_request():
g.db = connect_db()
g.fields = ["CPU", "TOTAL", "SQL", "SOLR", "REDIS", "MEMCACHED"]
@app.route("/")
def main_page():
sort_by = request.args.get('sort_by', None)
data = get_all_sum(g.db)
if sort_by:
data = sorted(data, key=lambda row: row[sort_by])
return render_template("main_page.html", data=data)
+ @app.route("/average/")
+ def average():
+ data = get_all_sum(g.db)
+ for row in data:
+ req_count = row['REQUESTS']
+ for k in row:
+ if k != 'NAME' and k != 'REQUESTS':
+ row[k] = float(row[k])/req_count
+ return render_template("main_page.html", data=data)
+
@app.route("/add/")
def add_page():
key = request.args.get('KEY')
for field in g.fields:
new_val = int(request.args.get(field, '0'))
old_val = int(g.db.hget(key, field) or '0')
new_val += old_val
g.db.hset(key, field, new_val)
g.db.hincrby(key, "REQUESTS", "1")
return redirect("/")
| Add proto of average page. Without sorting. | ## Code Before:
from flask import render_template, g, redirect, request
from db import connect_db, get_all_sum
from statistics import app
@app.before_request
def before_request():
g.db = connect_db()
g.fields = ["CPU", "TOTAL", "SQL", "SOLR", "REDIS", "MEMCACHED"]
@app.route("/")
def main_page():
sort_by = request.args.get('sort_by', None)
data = get_all_sum(g.db)
if sort_by:
data = sorted(data, key=lambda row: row[sort_by])
return render_template("main_page.html", data=data)
@app.route("/add/")
def add_page():
key = request.args.get('KEY')
for field in g.fields:
new_val = int(request.args.get(field, '0'))
old_val = int(g.db.hget(key, field) or '0')
new_val += old_val
g.db.hset(key, field, new_val)
g.db.hincrby(key, "REQUESTS", "1")
return redirect("/")
## Instruction:
Add proto of average page. Without sorting.
## Code After:
from flask import render_template, g, redirect, request
from db import connect_db, get_all_sum
from statistics import app
@app.before_request
def before_request():
g.db = connect_db()
g.fields = ["CPU", "TOTAL", "SQL", "SOLR", "REDIS", "MEMCACHED"]
@app.route("/")
def main_page():
sort_by = request.args.get('sort_by', None)
data = get_all_sum(g.db)
if sort_by:
data = sorted(data, key=lambda row: row[sort_by])
return render_template("main_page.html", data=data)
@app.route("/average/")
def average():
data = get_all_sum(g.db)
for row in data:
req_count = row['REQUESTS']
for k in row:
if k != 'NAME' and k != 'REQUESTS':
row[k] = float(row[k])/req_count
return render_template("main_page.html", data=data)
@app.route("/add/")
def add_page():
key = request.args.get('KEY')
for field in g.fields:
new_val = int(request.args.get(field, '0'))
old_val = int(g.db.hget(key, field) or '0')
new_val += old_val
g.db.hset(key, field, new_val)
g.db.hincrby(key, "REQUESTS", "1")
return redirect("/")
|
236a3e81164e8f7c37c50eaf59bfadd32e76735a | defines.py | defines.py | INFINITY = 1e+31
DIRECTIONS = ((-1,-1),(-1,0),(-1,1),
(0,-1), (0,1),
(1,-1), (1,0), (1,1))
EMPTY = 0
BLACK = 1
WHITE = 2
def opposite_colour(col):
if col == BLACK:
return WHITE
if col == WHITE:
return BLACK
| INFINITY = 1e+31
DIRECTIONS = ((-1,-1),(-1,0),(-1,1),
(0,-1), (0,1),
(1,-1), (1,0), (1,1))
EMPTY = 0
BLACK = 1
WHITE = 2
def opposite_colour(col):
if col == BLACK:
return WHITE
if col == WHITE:
return BLACK
from pdb import set_trace as st
| Make a shortcut for debugging with pdb | Make a shortcut for debugging with pdb
| Python | mit | cropleyb/pentai,cropleyb/pentai,cropleyb/pentai | INFINITY = 1e+31
DIRECTIONS = ((-1,-1),(-1,0),(-1,1),
(0,-1), (0,1),
(1,-1), (1,0), (1,1))
EMPTY = 0
BLACK = 1
WHITE = 2
def opposite_colour(col):
if col == BLACK:
return WHITE
if col == WHITE:
return BLACK
+ from pdb import set_trace as st
+ | Make a shortcut for debugging with pdb | ## Code Before:
INFINITY = 1e+31
DIRECTIONS = ((-1,-1),(-1,0),(-1,1),
(0,-1), (0,1),
(1,-1), (1,0), (1,1))
EMPTY = 0
BLACK = 1
WHITE = 2
def opposite_colour(col):
if col == BLACK:
return WHITE
if col == WHITE:
return BLACK
## Instruction:
Make a shortcut for debugging with pdb
## Code After:
INFINITY = 1e+31
DIRECTIONS = ((-1,-1),(-1,0),(-1,1),
(0,-1), (0,1),
(1,-1), (1,0), (1,1))
EMPTY = 0
BLACK = 1
WHITE = 2
def opposite_colour(col):
if col == BLACK:
return WHITE
if col == WHITE:
return BLACK
from pdb import set_trace as st
|
67b243915ef95ff1b9337bc67053d18df372e79d | unitypack/enums.py | unitypack/enums.py | from enum import IntEnum
class RuntimePlatform(IntEnum):
OSXEditor = 0
OSXPlayer = 1
WindowsPlayer = 2
OSXWebPlayer = 3
OSXDashboardPlayer = 4
WindowsWebPlayer = 5
WindowsEditor = 7
IPhonePlayer = 8
PS3 = 9
XBOX360 = 10
Android = 11
NaCl = 12
LinuxPlayer = 13
FlashPlayer = 15
WebGLPlayer = 17
MetroPlayerX86 = 18
WSAPlayerX86 = 18
MetroPlayerX64 = 19
WSAPlayerX64 = 19
MetroPlayerARM = 20
WSAPlayerARM = 20
WP8Player = 21
BB10Player = 22
BlackBerryPlayer = 22
TizenPlayer = 23
PSP2 = 24
PS4 = 25
PSM = 26
XboxOne = 27
| from enum import IntEnum
class RuntimePlatform(IntEnum):
OSXEditor = 0
OSXPlayer = 1
WindowsPlayer = 2
OSXWebPlayer = 3
OSXDashboardPlayer = 4
WindowsWebPlayer = 5
WindowsEditor = 7
IPhonePlayer = 8
PS3 = 9
XBOX360 = 10
Android = 11
NaCl = 12
LinuxPlayer = 13
FlashPlayer = 15
WebGLPlayer = 17
MetroPlayerX86 = 18
WSAPlayerX86 = 18
MetroPlayerX64 = 19
WSAPlayerX64 = 19
MetroPlayerARM = 20
WSAPlayerARM = 20
WP8Player = 21
BB10Player = 22
BlackBerryPlayer = 22
TizenPlayer = 23
PSP2 = 24
PS4 = 25
PSM = 26
PSMPlayer = 26
XboxOne = 27
SamsungTVPlayer = 28
| Add PSMPlayer and SamsungTVPlayer platforms | Add PSMPlayer and SamsungTVPlayer platforms
| Python | mit | andburn/python-unitypack | from enum import IntEnum
class RuntimePlatform(IntEnum):
OSXEditor = 0
OSXPlayer = 1
WindowsPlayer = 2
OSXWebPlayer = 3
OSXDashboardPlayer = 4
WindowsWebPlayer = 5
WindowsEditor = 7
IPhonePlayer = 8
PS3 = 9
XBOX360 = 10
Android = 11
NaCl = 12
LinuxPlayer = 13
FlashPlayer = 15
WebGLPlayer = 17
MetroPlayerX86 = 18
WSAPlayerX86 = 18
MetroPlayerX64 = 19
WSAPlayerX64 = 19
MetroPlayerARM = 20
WSAPlayerARM = 20
WP8Player = 21
BB10Player = 22
BlackBerryPlayer = 22
TizenPlayer = 23
PSP2 = 24
PS4 = 25
PSM = 26
+ PSMPlayer = 26
XboxOne = 27
+ SamsungTVPlayer = 28
| Add PSMPlayer and SamsungTVPlayer platforms | ## Code Before:
from enum import IntEnum
class RuntimePlatform(IntEnum):
OSXEditor = 0
OSXPlayer = 1
WindowsPlayer = 2
OSXWebPlayer = 3
OSXDashboardPlayer = 4
WindowsWebPlayer = 5
WindowsEditor = 7
IPhonePlayer = 8
PS3 = 9
XBOX360 = 10
Android = 11
NaCl = 12
LinuxPlayer = 13
FlashPlayer = 15
WebGLPlayer = 17
MetroPlayerX86 = 18
WSAPlayerX86 = 18
MetroPlayerX64 = 19
WSAPlayerX64 = 19
MetroPlayerARM = 20
WSAPlayerARM = 20
WP8Player = 21
BB10Player = 22
BlackBerryPlayer = 22
TizenPlayer = 23
PSP2 = 24
PS4 = 25
PSM = 26
XboxOne = 27
## Instruction:
Add PSMPlayer and SamsungTVPlayer platforms
## Code After:
from enum import IntEnum
class RuntimePlatform(IntEnum):
OSXEditor = 0
OSXPlayer = 1
WindowsPlayer = 2
OSXWebPlayer = 3
OSXDashboardPlayer = 4
WindowsWebPlayer = 5
WindowsEditor = 7
IPhonePlayer = 8
PS3 = 9
XBOX360 = 10
Android = 11
NaCl = 12
LinuxPlayer = 13
FlashPlayer = 15
WebGLPlayer = 17
MetroPlayerX86 = 18
WSAPlayerX86 = 18
MetroPlayerX64 = 19
WSAPlayerX64 = 19
MetroPlayerARM = 20
WSAPlayerARM = 20
WP8Player = 21
BB10Player = 22
BlackBerryPlayer = 22
TizenPlayer = 23
PSP2 = 24
PS4 = 25
PSM = 26
PSMPlayer = 26
XboxOne = 27
SamsungTVPlayer = 28
|
c4de9152f34d2831d43dfa3769a7a6452bba5814 | blockbuster/bb_security.py | blockbuster/bb_security.py | __author__ = 'matt'
from blockbuster import bb_dbconnector_factory
def credentials_are_valid(username, password):
db = bb_dbconnector_factory.DBConnectorInterfaceFactory().create()
print(username)
result = db.api_username_exists(username)
print (result)
return result
| __author__ = 'matt'
from blockbuster import bb_dbconnector_factory
def credentials_are_valid(username, password):
db = bb_dbconnector_factory.DBConnectorInterfaceFactory().create()
print(username)
result = db.api_credentials_are_valid(username, password)
print (result)
return result
| Update method to check both username and password | Update method to check both username and password
| Python | mit | mattstibbs/blockbuster-server,mattstibbs/blockbuster-server | __author__ = 'matt'
from blockbuster import bb_dbconnector_factory
def credentials_are_valid(username, password):
db = bb_dbconnector_factory.DBConnectorInterfaceFactory().create()
print(username)
- result = db.api_username_exists(username)
+ result = db.api_credentials_are_valid(username, password)
print (result)
return result
| Update method to check both username and password | ## Code Before:
__author__ = 'matt'
from blockbuster import bb_dbconnector_factory
def credentials_are_valid(username, password):
db = bb_dbconnector_factory.DBConnectorInterfaceFactory().create()
print(username)
result = db.api_username_exists(username)
print (result)
return result
## Instruction:
Update method to check both username and password
## Code After:
__author__ = 'matt'
from blockbuster import bb_dbconnector_factory
def credentials_are_valid(username, password):
db = bb_dbconnector_factory.DBConnectorInterfaceFactory().create()
print(username)
result = db.api_credentials_are_valid(username, password)
print (result)
return result
|
753f5bdc3f023cf31c0f189dd835978aad2b5d49 | djs_playground/urls.py | djs_playground/urls.py | from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin
from djs_playground.views import index
urlpatterns = [
url(r'^$', index, name='index'),
url(r'^admin/', admin.site.urls),
url(r'^summernote/', include('django_summernote.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| from django.conf import settings
from django.urls import re_path, include
from django.conf.urls.static import static
from django.contrib import admin
from djs_playground.views import index
urlpatterns = [
re_path(r'^$', index, name='index'),
re_path(r'^admin/', admin.site.urls),
re_path(r'^summernote/', include('django_summernote.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| Change url in favor of the re_path | Change url in favor of the re_path
| Python | mit | summernote/django-summernote,summernote/django-summernote,summernote/django-summernote | from django.conf import settings
- from django.conf.urls import url, include
+ from django.urls import re_path, include
from django.conf.urls.static import static
from django.contrib import admin
from djs_playground.views import index
urlpatterns = [
- url(r'^$', index, name='index'),
+ re_path(r'^$', index, name='index'),
- url(r'^admin/', admin.site.urls),
+ re_path(r'^admin/', admin.site.urls),
- url(r'^summernote/', include('django_summernote.urls')),
+ re_path(r'^summernote/', include('django_summernote.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| Change url in favor of the re_path | ## Code Before:
from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin
from djs_playground.views import index
urlpatterns = [
url(r'^$', index, name='index'),
url(r'^admin/', admin.site.urls),
url(r'^summernote/', include('django_summernote.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
## Instruction:
Change url in favor of the re_path
## Code After:
from django.conf import settings
from django.urls import re_path, include
from django.conf.urls.static import static
from django.contrib import admin
from djs_playground.views import index
urlpatterns = [
re_path(r'^$', index, name='index'),
re_path(r'^admin/', admin.site.urls),
re_path(r'^summernote/', include('django_summernote.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
5a641736faf6bb3ce335480848464a1f22fab040 | fabfile.py | fabfile.py |
from contextlib import nested
from fabric.api import *
def prepare_project():
u"""
Enters the directory and sources environment configuration.
I know ``nested`` is deprecated, but what a nice shortcut it is here ;)
"""
return nested(
cd(PROJECT_PATH),
prefix("source ../.virtualenvs/variablestars3/bin/activate")
)
PROJECT_PATH = "$HOME/variablestars.net"
env.roledefs = {
'web': ["[email protected]"],
}
env.color = True
env.forward_agent = True
@task
@roles("web")
def git_pull():
with cd(PROJECT_PATH):
run("git pull origin master")
@task
@roles("web")
def update_requirements():
with prepare_project():
run("pip install -r requirements.txt")
run("source ~/.nvm/nvm.sh && npm install")
@task
@roles("web")
def migrate():
with prepare_project():
run("python manage.py syncdb")
run("python manage.py migrate")
@task
@roles("web")
def collect_static():
with prepare_project():
run("python manage.py collectstatic --noinput")
@task
@roles("web")
def restart():
run("appctl restart variablestars2")
@task
@roles("web")
def deploy():
git_pull()
update_requirements()
migrate()
collect_static()
restart()
|
from contextlib import nested
from fabric.api import *
def prepare_project():
u"""
Enters the directory and sources environment configuration.
I know ``nested`` is deprecated, but what a nice shortcut it is here ;)
"""
return nested(
cd(PROJECT_PATH),
prefix("source ../.virtualenvs/variablestars3/bin/activate")
)
PROJECT_PATH = "$HOME/variablestars.net"
env.roledefs = {
'web': ["[email protected]"],
}
env.color = True
env.forward_agent = True
env.use_ssh_config = True
@task
@roles("web")
def git_pull():
with cd(PROJECT_PATH):
run("git pull origin master")
@task
@roles("web")
def update_requirements():
with prepare_project():
run("pip install -r requirements.txt")
run("source ~/.nvm/nvm.sh && npm install")
@task
@roles("web")
def migrate():
with prepare_project():
run("python manage.py syncdb")
run("python manage.py migrate")
@task
@roles("web")
def collect_static():
with prepare_project():
run("python manage.py collectstatic --noinput")
@task
@roles("web")
def restart():
run("appctl restart variablestars2")
@task
@roles("web")
def deploy():
git_pull()
update_requirements()
migrate()
collect_static()
restart()
| Make Fabric honor .ssh/config settings | Make Fabric honor .ssh/config settings
| Python | mit | zsiciarz/variablestars.net,zsiciarz/variablestars.net,zsiciarz/variablestars.net |
from contextlib import nested
from fabric.api import *
def prepare_project():
u"""
Enters the directory and sources environment configuration.
I know ``nested`` is deprecated, but what a nice shortcut it is here ;)
"""
return nested(
cd(PROJECT_PATH),
prefix("source ../.virtualenvs/variablestars3/bin/activate")
)
PROJECT_PATH = "$HOME/variablestars.net"
env.roledefs = {
'web': ["[email protected]"],
}
env.color = True
env.forward_agent = True
+ env.use_ssh_config = True
@task
@roles("web")
def git_pull():
with cd(PROJECT_PATH):
run("git pull origin master")
@task
@roles("web")
def update_requirements():
with prepare_project():
run("pip install -r requirements.txt")
run("source ~/.nvm/nvm.sh && npm install")
@task
@roles("web")
def migrate():
with prepare_project():
run("python manage.py syncdb")
run("python manage.py migrate")
@task
@roles("web")
def collect_static():
with prepare_project():
run("python manage.py collectstatic --noinput")
@task
@roles("web")
def restart():
run("appctl restart variablestars2")
@task
@roles("web")
def deploy():
git_pull()
update_requirements()
migrate()
collect_static()
restart()
| Make Fabric honor .ssh/config settings | ## Code Before:
from contextlib import nested
from fabric.api import *
def prepare_project():
u"""
Enters the directory and sources environment configuration.
I know ``nested`` is deprecated, but what a nice shortcut it is here ;)
"""
return nested(
cd(PROJECT_PATH),
prefix("source ../.virtualenvs/variablestars3/bin/activate")
)
PROJECT_PATH = "$HOME/variablestars.net"
env.roledefs = {
'web': ["[email protected]"],
}
env.color = True
env.forward_agent = True
@task
@roles("web")
def git_pull():
with cd(PROJECT_PATH):
run("git pull origin master")
@task
@roles("web")
def update_requirements():
with prepare_project():
run("pip install -r requirements.txt")
run("source ~/.nvm/nvm.sh && npm install")
@task
@roles("web")
def migrate():
with prepare_project():
run("python manage.py syncdb")
run("python manage.py migrate")
@task
@roles("web")
def collect_static():
with prepare_project():
run("python manage.py collectstatic --noinput")
@task
@roles("web")
def restart():
run("appctl restart variablestars2")
@task
@roles("web")
def deploy():
git_pull()
update_requirements()
migrate()
collect_static()
restart()
## Instruction:
Make Fabric honor .ssh/config settings
## Code After:
from contextlib import nested
from fabric.api import *
def prepare_project():
u"""
Enters the directory and sources environment configuration.
I know ``nested`` is deprecated, but what a nice shortcut it is here ;)
"""
return nested(
cd(PROJECT_PATH),
prefix("source ../.virtualenvs/variablestars3/bin/activate")
)
PROJECT_PATH = "$HOME/variablestars.net"
env.roledefs = {
'web': ["[email protected]"],
}
env.color = True
env.forward_agent = True
env.use_ssh_config = True
@task
@roles("web")
def git_pull():
with cd(PROJECT_PATH):
run("git pull origin master")
@task
@roles("web")
def update_requirements():
with prepare_project():
run("pip install -r requirements.txt")
run("source ~/.nvm/nvm.sh && npm install")
@task
@roles("web")
def migrate():
with prepare_project():
run("python manage.py syncdb")
run("python manage.py migrate")
@task
@roles("web")
def collect_static():
with prepare_project():
run("python manage.py collectstatic --noinput")
@task
@roles("web")
def restart():
run("appctl restart variablestars2")
@task
@roles("web")
def deploy():
git_pull()
update_requirements()
migrate()
collect_static()
restart()
|
dc1cf6fabcf871e3661125f7ac5d1cf9567798d6 | cms/management/commands/load_dev_fixtures.py | cms/management/commands/load_dev_fixtures.py | import requests
from django.core.management import call_command
from django.core.management.base import NoArgsCommand
from django.conf import settings
from django.utils.six.moves import input
class Command(NoArgsCommand):
"""
Download and load dev fixtures from www.python.org
"""
help = "Download and load dev fixtures from python.org"
def handle_noargs(self, **options):
# Confirm the user wants to do this
confirm = input("""You have requested to load the python.org development fixtures.
This will IRREVERSIBLY DESTROY all data currently in your local database.
Are you sure you want to do this?
Type 'y' or 'yes' to continue, 'n' or 'no' to cancel: """)
if confirm in ('y', 'yes'):
if confirm:
print()
print("Beginning download, note this can take a couple of minutes...")
r = requests.get(settings.DEV_FIXTURE_URL, stream=True)
if r.status_code != 200:
print("Unable to download file: Received status code {}".format(r.status_code))
with open('/tmp/dev-fixtures.json.gz', 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
f.write(chunk)
f.flush()
print("Download complete, loading fixtures")
call_command('loaddata', '/tmp/dev-fixtures.json')
print("END: Fixtures loaded")
| import requests
from django.core.management import call_command
from django.core.management.base import NoArgsCommand
from django.conf import settings
from django.utils.six.moves import input
class Command(NoArgsCommand):
"""
Download and load dev fixtures from www.python.org
"""
help = "Download and load dev fixtures from python.org"
def handle_noargs(self, **options):
# Confirm the user wants to do this
confirm = input("""You have requested to load the python.org development fixtures.
This will IRREVERSIBLY DESTROY all data currently in your local database.
Are you sure you want to do this?
Type 'y' or 'yes' to continue, 'n' or 'no' to cancel: """)
if confirm in ('y', 'yes'):
self.stdout.write("\nBeginning download, note this can take a couple of minutes...")
r = requests.get(settings.DEV_FIXTURE_URL, stream=True)
if r.status_code != 200:
self.stdout.write("Unable to download file: Received status code {}".format(r.status_code))
with open('/tmp/dev-fixtures.json.gz', 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
f.write(chunk)
f.flush()
self.stdout.write("Download complete, loading fixtures")
call_command('loaddata', '/tmp/dev-fixtures.json')
self.stdout.write("END: Fixtures loaded")
| Use self.stdout.write() instead of print(). | Use self.stdout.write() instead of print().
This is the recommended way in the Django documentation:
https://docs.djangoproject.com/en/1.7/howto/custom-management-commands/
| Python | apache-2.0 | manhhomienbienthuy/pythondotorg,python/pythondotorg,SujaySKumar/pythondotorg,lebronhkh/pythondotorg,SujaySKumar/pythondotorg,lepture/pythondotorg,python/pythondotorg,proevo/pythondotorg,Mariatta/pythondotorg,malemburg/pythondotorg,willingc/pythondotorg,fe11x/pythondotorg,berkerpeksag/pythondotorg,demvher/pythondotorg,python/pythondotorg,SujaySKumar/pythondotorg,berkerpeksag/pythondotorg,lepture/pythondotorg,manhhomienbienthuy/pythondotorg,ahua/pythondotorg,Mariatta/pythondotorg,lepture/pythondotorg,malemburg/pythondotorg,demvher/pythondotorg,fe11x/pythondotorg,SujaySKumar/pythondotorg,willingc/pythondotorg,Mariatta/pythondotorg,demvher/pythondotorg,proevo/pythondotorg,proevo/pythondotorg,SujaySKumar/pythondotorg,demvher/pythondotorg,ahua/pythondotorg,fe11x/pythondotorg,proevo/pythondotorg,manhhomienbienthuy/pythondotorg,fe11x/pythondotorg,willingc/pythondotorg,lebronhkh/pythondotorg,lepture/pythondotorg,berkerpeksag/pythondotorg,ahua/pythondotorg,manhhomienbienthuy/pythondotorg,Mariatta/pythondotorg,malemburg/pythondotorg,berkerpeksag/pythondotorg,lebronhkh/pythondotorg,ahua/pythondotorg,malemburg/pythondotorg,lepture/pythondotorg,fe11x/pythondotorg,willingc/pythondotorg,python/pythondotorg,ahua/pythondotorg,lebronhkh/pythondotorg,lebronhkh/pythondotorg,demvher/pythondotorg,berkerpeksag/pythondotorg | import requests
from django.core.management import call_command
from django.core.management.base import NoArgsCommand
from django.conf import settings
from django.utils.six.moves import input
class Command(NoArgsCommand):
"""
Download and load dev fixtures from www.python.org
"""
help = "Download and load dev fixtures from python.org"
def handle_noargs(self, **options):
# Confirm the user wants to do this
confirm = input("""You have requested to load the python.org development fixtures.
This will IRREVERSIBLY DESTROY all data currently in your local database.
Are you sure you want to do this?
Type 'y' or 'yes' to continue, 'n' or 'no' to cancel: """)
if confirm in ('y', 'yes'):
- if confirm:
- print()
- print("Beginning download, note this can take a couple of minutes...")
+ self.stdout.write("\nBeginning download, note this can take a couple of minutes...")
r = requests.get(settings.DEV_FIXTURE_URL, stream=True)
if r.status_code != 200:
- print("Unable to download file: Received status code {}".format(r.status_code))
+ self.stdout.write("Unable to download file: Received status code {}".format(r.status_code))
with open('/tmp/dev-fixtures.json.gz', 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
f.write(chunk)
f.flush()
- print("Download complete, loading fixtures")
+ self.stdout.write("Download complete, loading fixtures")
call_command('loaddata', '/tmp/dev-fixtures.json')
- print("END: Fixtures loaded")
+ self.stdout.write("END: Fixtures loaded")
| Use self.stdout.write() instead of print(). | ## Code Before:
import requests
from django.core.management import call_command
from django.core.management.base import NoArgsCommand
from django.conf import settings
from django.utils.six.moves import input
class Command(NoArgsCommand):
"""
Download and load dev fixtures from www.python.org
"""
help = "Download and load dev fixtures from python.org"
def handle_noargs(self, **options):
# Confirm the user wants to do this
confirm = input("""You have requested to load the python.org development fixtures.
This will IRREVERSIBLY DESTROY all data currently in your local database.
Are you sure you want to do this?
Type 'y' or 'yes' to continue, 'n' or 'no' to cancel: """)
if confirm in ('y', 'yes'):
if confirm:
print()
print("Beginning download, note this can take a couple of minutes...")
r = requests.get(settings.DEV_FIXTURE_URL, stream=True)
if r.status_code != 200:
print("Unable to download file: Received status code {}".format(r.status_code))
with open('/tmp/dev-fixtures.json.gz', 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
f.write(chunk)
f.flush()
print("Download complete, loading fixtures")
call_command('loaddata', '/tmp/dev-fixtures.json')
print("END: Fixtures loaded")
## Instruction:
Use self.stdout.write() instead of print().
## Code After:
import requests
from django.core.management import call_command
from django.core.management.base import NoArgsCommand
from django.conf import settings
from django.utils.six.moves import input
class Command(NoArgsCommand):
"""
Download and load dev fixtures from www.python.org
"""
help = "Download and load dev fixtures from python.org"
def handle_noargs(self, **options):
# Confirm the user wants to do this
confirm = input("""You have requested to load the python.org development fixtures.
This will IRREVERSIBLY DESTROY all data currently in your local database.
Are you sure you want to do this?
Type 'y' or 'yes' to continue, 'n' or 'no' to cancel: """)
if confirm in ('y', 'yes'):
self.stdout.write("\nBeginning download, note this can take a couple of minutes...")
r = requests.get(settings.DEV_FIXTURE_URL, stream=True)
if r.status_code != 200:
self.stdout.write("Unable to download file: Received status code {}".format(r.status_code))
with open('/tmp/dev-fixtures.json.gz', 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
f.write(chunk)
f.flush()
self.stdout.write("Download complete, loading fixtures")
call_command('loaddata', '/tmp/dev-fixtures.json')
self.stdout.write("END: Fixtures loaded")
|
125dfa47e5656c3f9b1e8846be03010ed02c6f91 | tests/rules_tests/isValid_tests/InvalidSyntaxTest.py | tests/rules_tests/isValid_tests/InvalidSyntaxTest.py |
from unittest import main, TestCase
from grammpy import Rule
class InvalidSyntaxTest(TestCase):
pass
if __name__ == '__main__':
main() |
from unittest import main, TestCase
from grammpy import Rule
from grammpy.exceptions import RuleSyntaxException
from .grammar import *
class InvalidSyntaxTest(TestCase):
def test_rulesMissingEncloseList(self):
class tmp(Rule):
rules = ([0], [1])
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_rulesMissingTuple(self):
class tmp(Rule):
rules = [[0], [1]]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_rulesMissingInnerLeftList(self):
class tmp(Rule):
rules = [(0, [1])]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_rulesMissingInnerRightList(self):
class tmp(Rule):
rules = [([0], 1)]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_multipleRulesMissingInnerLeftList(self):
class tmp(Rule):
rules = [(NFirst, TSecond), (0, [1])]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_multipleRulesMissingInnerRightList(self):
class tmp(Rule):
rules = [(NFifth, TFirst), ([0], 1)]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_emptyRule(self):
class tmp(Rule):
rules = [([], [])]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_emptyOneOfRules(self):
class tmp(Rule):
rules = [(NFifth, TFirst), ([], [])]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_onlyOuterArray(self):
class tmp(Rule):
rules = [NFifth, TFirst]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_outerIsTuple(self):
class tmp(Rule):
rules = (([NFirst], [TSecond]), ([0], [1]))
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
if __name__ == '__main__':
main()
| Add base set of rule's invalid syntax tests | Add base set of rule's invalid syntax tests
| Python | mit | PatrikValkovic/grammpy |
from unittest import main, TestCase
from grammpy import Rule
+ from grammpy.exceptions import RuleSyntaxException
+ from .grammar import *
class InvalidSyntaxTest(TestCase):
- pass
+ def test_rulesMissingEncloseList(self):
+ class tmp(Rule):
+ rules = ([0], [1])
+ with self.assertRaises(RuleSyntaxException):
+ tmp.validate(grammar)
+
+ def test_rulesMissingTuple(self):
+ class tmp(Rule):
+ rules = [[0], [1]]
+ with self.assertRaises(RuleSyntaxException):
+ tmp.validate(grammar)
+
+ def test_rulesMissingInnerLeftList(self):
+ class tmp(Rule):
+ rules = [(0, [1])]
+ with self.assertRaises(RuleSyntaxException):
+ tmp.validate(grammar)
+
+ def test_rulesMissingInnerRightList(self):
+ class tmp(Rule):
+ rules = [([0], 1)]
+ with self.assertRaises(RuleSyntaxException):
+ tmp.validate(grammar)
+
+ def test_multipleRulesMissingInnerLeftList(self):
+ class tmp(Rule):
+ rules = [(NFirst, TSecond), (0, [1])]
+ with self.assertRaises(RuleSyntaxException):
+ tmp.validate(grammar)
+
+ def test_multipleRulesMissingInnerRightList(self):
+ class tmp(Rule):
+ rules = [(NFifth, TFirst), ([0], 1)]
+ with self.assertRaises(RuleSyntaxException):
+ tmp.validate(grammar)
+
+ def test_emptyRule(self):
+ class tmp(Rule):
+ rules = [([], [])]
+ with self.assertRaises(RuleSyntaxException):
+ tmp.validate(grammar)
+
+ def test_emptyOneOfRules(self):
+ class tmp(Rule):
+ rules = [(NFifth, TFirst), ([], [])]
+ with self.assertRaises(RuleSyntaxException):
+ tmp.validate(grammar)
+
+ def test_onlyOuterArray(self):
+ class tmp(Rule):
+ rules = [NFifth, TFirst]
+ with self.assertRaises(RuleSyntaxException):
+ tmp.validate(grammar)
+
+ def test_outerIsTuple(self):
+ class tmp(Rule):
+ rules = (([NFirst], [TSecond]), ([0], [1]))
+ with self.assertRaises(RuleSyntaxException):
+ tmp.validate(grammar)
if __name__ == '__main__':
main()
+ | Add base set of rule's invalid syntax tests | ## Code Before:
from unittest import main, TestCase
from grammpy import Rule
class InvalidSyntaxTest(TestCase):
pass
if __name__ == '__main__':
main()
## Instruction:
Add base set of rule's invalid syntax tests
## Code After:
from unittest import main, TestCase
from grammpy import Rule
from grammpy.exceptions import RuleSyntaxException
from .grammar import *
class InvalidSyntaxTest(TestCase):
def test_rulesMissingEncloseList(self):
class tmp(Rule):
rules = ([0], [1])
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_rulesMissingTuple(self):
class tmp(Rule):
rules = [[0], [1]]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_rulesMissingInnerLeftList(self):
class tmp(Rule):
rules = [(0, [1])]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_rulesMissingInnerRightList(self):
class tmp(Rule):
rules = [([0], 1)]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_multipleRulesMissingInnerLeftList(self):
class tmp(Rule):
rules = [(NFirst, TSecond), (0, [1])]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_multipleRulesMissingInnerRightList(self):
class tmp(Rule):
rules = [(NFifth, TFirst), ([0], 1)]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_emptyRule(self):
class tmp(Rule):
rules = [([], [])]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_emptyOneOfRules(self):
class tmp(Rule):
rules = [(NFifth, TFirst), ([], [])]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_onlyOuterArray(self):
class tmp(Rule):
rules = [NFifth, TFirst]
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
def test_outerIsTuple(self):
class tmp(Rule):
rules = (([NFirst], [TSecond]), ([0], [1]))
with self.assertRaises(RuleSyntaxException):
tmp.validate(grammar)
if __name__ == '__main__':
main()
|
12cb8ca101faa09e4cc07f9e257b3d3130892297 | tests/sentry/web/frontend/tests.py | tests/sentry/web/frontend/tests.py |
from __future__ import absolute_import
import pytest
from django.core.urlresolvers import reverse
from exam import fixture
from sentry.testutils import TestCase
@pytest.mark.xfail
class ReplayTest(TestCase):
@fixture
def path(self):
return reverse('sentry-replay', kwargs={
'organization_slug': self.organization.slug,
'project_id': self.project.slug,
'group_id': self.group.id,
'event_id': self.event.id,
})
def test_does_render(self):
self.login_as(self.user)
resp = self.client.get(self.path)
self.assertEquals(resp.status_code, 200)
self.assertTemplateUsed(resp, 'sentry/events/replay_request.html')
|
from __future__ import absolute_import
from django.core.urlresolvers import reverse
from exam import fixture
from sentry.testutils import TestCase
class ReplayTest(TestCase):
@fixture
def path(self):
return reverse('sentry-replay', kwargs={
'organization_slug': self.organization.slug,
'project_id': self.project.slug,
'group_id': self.group.id,
'event_id': self.event.id,
})
def test_does_render(self):
self.login_as(self.user)
resp = self.client.get(self.path)
self.assertEquals(resp.status_code, 200)
self.assertTemplateUsed(resp, 'sentry/events/replay_request.html')
| Remove xfail from replay test | Remove xfail from replay test
| Python | bsd-3-clause | mitsuhiko/sentry,fotinakis/sentry,beeftornado/sentry,mvaled/sentry,mvaled/sentry,BuildingLink/sentry,alexm92/sentry,mvaled/sentry,mvaled/sentry,BuildingLink/sentry,nicholasserra/sentry,JackDanger/sentry,fotinakis/sentry,gencer/sentry,fotinakis/sentry,beeftornado/sentry,ifduyue/sentry,JamesMura/sentry,imankulov/sentry,looker/sentry,imankulov/sentry,zenefits/sentry,mvaled/sentry,JamesMura/sentry,gencer/sentry,daevaorn/sentry,JackDanger/sentry,zenefits/sentry,JamesMura/sentry,nicholasserra/sentry,ifduyue/sentry,mvaled/sentry,zenefits/sentry,gencer/sentry,looker/sentry,daevaorn/sentry,beeftornado/sentry,imankulov/sentry,JamesMura/sentry,looker/sentry,BuildingLink/sentry,daevaorn/sentry,ifduyue/sentry,looker/sentry,BuildingLink/sentry,fotinakis/sentry,JackDanger/sentry,zenefits/sentry,jean/sentry,nicholasserra/sentry,alexm92/sentry,zenefits/sentry,JamesMura/sentry,looker/sentry,jean/sentry,mitsuhiko/sentry,alexm92/sentry,ifduyue/sentry,gencer/sentry,daevaorn/sentry,jean/sentry,gencer/sentry,BuildingLink/sentry,jean/sentry,jean/sentry,ifduyue/sentry |
from __future__ import absolute_import
-
- import pytest
from django.core.urlresolvers import reverse
from exam import fixture
from sentry.testutils import TestCase
- @pytest.mark.xfail
class ReplayTest(TestCase):
@fixture
def path(self):
return reverse('sentry-replay', kwargs={
'organization_slug': self.organization.slug,
'project_id': self.project.slug,
'group_id': self.group.id,
'event_id': self.event.id,
})
def test_does_render(self):
self.login_as(self.user)
resp = self.client.get(self.path)
self.assertEquals(resp.status_code, 200)
self.assertTemplateUsed(resp, 'sentry/events/replay_request.html')
| Remove xfail from replay test | ## Code Before:
from __future__ import absolute_import
import pytest
from django.core.urlresolvers import reverse
from exam import fixture
from sentry.testutils import TestCase
@pytest.mark.xfail
class ReplayTest(TestCase):
@fixture
def path(self):
return reverse('sentry-replay', kwargs={
'organization_slug': self.organization.slug,
'project_id': self.project.slug,
'group_id': self.group.id,
'event_id': self.event.id,
})
def test_does_render(self):
self.login_as(self.user)
resp = self.client.get(self.path)
self.assertEquals(resp.status_code, 200)
self.assertTemplateUsed(resp, 'sentry/events/replay_request.html')
## Instruction:
Remove xfail from replay test
## Code After:
from __future__ import absolute_import
from django.core.urlresolvers import reverse
from exam import fixture
from sentry.testutils import TestCase
class ReplayTest(TestCase):
@fixture
def path(self):
return reverse('sentry-replay', kwargs={
'organization_slug': self.organization.slug,
'project_id': self.project.slug,
'group_id': self.group.id,
'event_id': self.event.id,
})
def test_does_render(self):
self.login_as(self.user)
resp = self.client.get(self.path)
self.assertEquals(resp.status_code, 200)
self.assertTemplateUsed(resp, 'sentry/events/replay_request.html')
|
23675e41656cac48f390d97f065b36de39e27d58 | duckbot.py | duckbot.py | import discord
import duckbot_settings
import random
from discord.ext import commands
_DESCRIPTION = '''quack'''
bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
@bot.event
async def on_ready():
print('logged in: %s (%s)' % (bot.user.name, bot.user.id))
oauth_url = discord.utils.oauth_url(duckbot_settings.CLIENT_ID, permissions=discord.Permissions.text())
print('invite me: %s' % oauth_url)
print('Channels:')
channels = bot.get_all_channels()
for channel in channels:
print('%s (%s)' % (channel.name, channel.id))
if channel.name == 'botspam':
await bot.send_message(channel, 'quack!! (ready to roll)')
@bot.command()
async def roll():
await bot.say('pretending to roll')
bot.run(duckbot_settings.TOKEN)
| import discord
import duckbot_settings
import random
from discord.ext import commands
_DESCRIPTION = '''quack'''
bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
rand = random.SystemRandom()
@bot.event
async def on_ready():
print('logged in: %s (%s)' % (bot.user.name, bot.user.id))
oauth_url = discord.utils.oauth_url(duckbot_settings.CLIENT_ID, permissions=discord.Permissions.text())
print('invite me: %s' % oauth_url)
print('Channels:')
channels = bot.get_all_channels()
for channel in channels:
print('%s (%s)' % (channel.name, channel.id))
if channel.name == 'botspam':
await bot.send_message(channel, 'quack!! (ready to roll)')
@bot.command()
async def roll():
lower_bound = 1
upper_boundb = 6
await bot.say('🎲 (%d-%d): %d' % (lower_bound, upper_bound, rand.randint(lower_bound, upper_bound)))
bot.run(duckbot_settings.TOKEN)
| Add a real roll command | Add a real roll command
| Python | mit | andrewlin16/duckbot,andrewlin16/duckbot | import discord
import duckbot_settings
import random
from discord.ext import commands
_DESCRIPTION = '''quack'''
bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
+ rand = random.SystemRandom()
@bot.event
async def on_ready():
print('logged in: %s (%s)' % (bot.user.name, bot.user.id))
oauth_url = discord.utils.oauth_url(duckbot_settings.CLIENT_ID, permissions=discord.Permissions.text())
print('invite me: %s' % oauth_url)
print('Channels:')
channels = bot.get_all_channels()
for channel in channels:
print('%s (%s)' % (channel.name, channel.id))
if channel.name == 'botspam':
await bot.send_message(channel, 'quack!! (ready to roll)')
@bot.command()
async def roll():
- await bot.say('pretending to roll')
+ lower_bound = 1
+ upper_boundb = 6
+ await bot.say('🎲 (%d-%d): %d' % (lower_bound, upper_bound, rand.randint(lower_bound, upper_bound)))
bot.run(duckbot_settings.TOKEN)
| Add a real roll command | ## Code Before:
import discord
import duckbot_settings
import random
from discord.ext import commands
_DESCRIPTION = '''quack'''
bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
@bot.event
async def on_ready():
print('logged in: %s (%s)' % (bot.user.name, bot.user.id))
oauth_url = discord.utils.oauth_url(duckbot_settings.CLIENT_ID, permissions=discord.Permissions.text())
print('invite me: %s' % oauth_url)
print('Channels:')
channels = bot.get_all_channels()
for channel in channels:
print('%s (%s)' % (channel.name, channel.id))
if channel.name == 'botspam':
await bot.send_message(channel, 'quack!! (ready to roll)')
@bot.command()
async def roll():
await bot.say('pretending to roll')
bot.run(duckbot_settings.TOKEN)
## Instruction:
Add a real roll command
## Code After:
import discord
import duckbot_settings
import random
from discord.ext import commands
_DESCRIPTION = '''quack'''
bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
rand = random.SystemRandom()
@bot.event
async def on_ready():
print('logged in: %s (%s)' % (bot.user.name, bot.user.id))
oauth_url = discord.utils.oauth_url(duckbot_settings.CLIENT_ID, permissions=discord.Permissions.text())
print('invite me: %s' % oauth_url)
print('Channels:')
channels = bot.get_all_channels()
for channel in channels:
print('%s (%s)' % (channel.name, channel.id))
if channel.name == 'botspam':
await bot.send_message(channel, 'quack!! (ready to roll)')
@bot.command()
async def roll():
lower_bound = 1
upper_boundb = 6
await bot.say('🎲 (%d-%d): %d' % (lower_bound, upper_bound, rand.randint(lower_bound, upper_bound)))
bot.run(duckbot_settings.TOKEN)
|
30ed3800fdeec4aec399e6e0ec0760e46eb891ec | djangoautoconf/model_utils/model_reversion.py | djangoautoconf/model_utils/model_reversion.py | from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import pre_save
from django.dispatch import receiver
from reversion.models import Version
from reversion.revisions import default_revision_manager
global_save_signal_receiver = []
class PreSaveHandler(object):
def __init__(self, model_inst):
super(PreSaveHandler, self).__init__()
self.model_inst = model_inst
def object_save_handler(self, sender, instance, **kwargs):
# logging.error("======================================")
if not (instance.pk is None):
content_type = ContentType.objects.get_for_model(self.model_inst)
versioned_pk_queryset = Version.objects.filter(content_type=content_type).filter(object_id_int=instance.pk)
if not versioned_pk_queryset.exists():
item = self.model_inst.objects.get(pk=instance.pk)
try:
default_revision_manager.save_revision((item,))
except:
pass
def add_reversion_before_save(model_inst):
s = PreSaveHandler(model_inst)
global_save_signal_receiver.append(s)
receiver(pre_save, sender=model_inst)(s.object_save_handler)
| from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import pre_save
from django.dispatch import receiver
from reversion.models import Version
def create_initial_version(obj):
try:
from reversion.revisions import default_revision_manager
default_revision_manager.save_revision((obj,))
except:
from reversion.revisions import add_to_revision
add_to_revision(obj)
global_save_signal_receiver = []
class PreSaveHandler(object):
def __init__(self, model_inst):
super(PreSaveHandler, self).__init__()
self.model_inst = model_inst
def object_save_handler(self, sender, instance, **kwargs):
# logging.error("======================================")
if not (instance.pk is None):
content_type = ContentType.objects.get_for_model(self.model_inst)
versioned_pk_queryset = Version.objects.filter(content_type=content_type).filter(object_id_int=instance.pk)
if not versioned_pk_queryset.exists():
item = self.model_inst.objects.get(pk=instance.pk)
try:
create_initial_version(item)
except:
pass
def add_reversion_before_save(model_inst):
s = PreSaveHandler(model_inst)
global_save_signal_receiver.append(s)
receiver(pre_save, sender=model_inst)(s.object_save_handler)
| Fix broken initial version creation. | Fix broken initial version creation.
| Python | bsd-3-clause | weijia/djangoautoconf,weijia/djangoautoconf | from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import pre_save
from django.dispatch import receiver
from reversion.models import Version
+
+
+ def create_initial_version(obj):
+ try:
- from reversion.revisions import default_revision_manager
+ from reversion.revisions import default_revision_manager
+ default_revision_manager.save_revision((obj,))
+ except:
+ from reversion.revisions import add_to_revision
+ add_to_revision(obj)
global_save_signal_receiver = []
class PreSaveHandler(object):
def __init__(self, model_inst):
super(PreSaveHandler, self).__init__()
self.model_inst = model_inst
def object_save_handler(self, sender, instance, **kwargs):
# logging.error("======================================")
if not (instance.pk is None):
content_type = ContentType.objects.get_for_model(self.model_inst)
versioned_pk_queryset = Version.objects.filter(content_type=content_type).filter(object_id_int=instance.pk)
if not versioned_pk_queryset.exists():
item = self.model_inst.objects.get(pk=instance.pk)
try:
- default_revision_manager.save_revision((item,))
+ create_initial_version(item)
except:
pass
def add_reversion_before_save(model_inst):
s = PreSaveHandler(model_inst)
global_save_signal_receiver.append(s)
receiver(pre_save, sender=model_inst)(s.object_save_handler)
| Fix broken initial version creation. | ## Code Before:
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import pre_save
from django.dispatch import receiver
from reversion.models import Version
from reversion.revisions import default_revision_manager
global_save_signal_receiver = []
class PreSaveHandler(object):
def __init__(self, model_inst):
super(PreSaveHandler, self).__init__()
self.model_inst = model_inst
def object_save_handler(self, sender, instance, **kwargs):
# logging.error("======================================")
if not (instance.pk is None):
content_type = ContentType.objects.get_for_model(self.model_inst)
versioned_pk_queryset = Version.objects.filter(content_type=content_type).filter(object_id_int=instance.pk)
if not versioned_pk_queryset.exists():
item = self.model_inst.objects.get(pk=instance.pk)
try:
default_revision_manager.save_revision((item,))
except:
pass
def add_reversion_before_save(model_inst):
s = PreSaveHandler(model_inst)
global_save_signal_receiver.append(s)
receiver(pre_save, sender=model_inst)(s.object_save_handler)
## Instruction:
Fix broken initial version creation.
## Code After:
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import pre_save
from django.dispatch import receiver
from reversion.models import Version
def create_initial_version(obj):
try:
from reversion.revisions import default_revision_manager
default_revision_manager.save_revision((obj,))
except:
from reversion.revisions import add_to_revision
add_to_revision(obj)
global_save_signal_receiver = []
class PreSaveHandler(object):
def __init__(self, model_inst):
super(PreSaveHandler, self).__init__()
self.model_inst = model_inst
def object_save_handler(self, sender, instance, **kwargs):
# logging.error("======================================")
if not (instance.pk is None):
content_type = ContentType.objects.get_for_model(self.model_inst)
versioned_pk_queryset = Version.objects.filter(content_type=content_type).filter(object_id_int=instance.pk)
if not versioned_pk_queryset.exists():
item = self.model_inst.objects.get(pk=instance.pk)
try:
create_initial_version(item)
except:
pass
def add_reversion_before_save(model_inst):
s = PreSaveHandler(model_inst)
global_save_signal_receiver.append(s)
receiver(pre_save, sender=model_inst)(s.object_save_handler)
|
5237cb7f1339eb13b4c01f1c3611448a8f865726 | terms/templatetags/terms.py | terms/templatetags/terms.py |
from django.template import Library
from ..html import TermsHTMLReconstructor
register = Library()
@register.filter
def replace_terms(html):
parser = TermsHTMLReconstructor()
parser.feed(html)
return parser.out
|
from django.template import Library
from django.template.defaultfilters import stringfilter
from ..html import TermsHTMLReconstructor
register = Library()
@register.filter
@stringfilter
def replace_terms(html):
parser = TermsHTMLReconstructor()
parser.feed(html)
return parser.out
| Make sure the filter arg is a string. | Make sure the filter arg is a string.
| Python | bsd-3-clause | BertrandBordage/django-terms,philippeowagner/django-terms,BertrandBordage/django-terms,philippeowagner/django-terms |
from django.template import Library
+ from django.template.defaultfilters import stringfilter
from ..html import TermsHTMLReconstructor
register = Library()
@register.filter
+ @stringfilter
def replace_terms(html):
parser = TermsHTMLReconstructor()
parser.feed(html)
return parser.out
| Make sure the filter arg is a string. | ## Code Before:
from django.template import Library
from ..html import TermsHTMLReconstructor
register = Library()
@register.filter
def replace_terms(html):
parser = TermsHTMLReconstructor()
parser.feed(html)
return parser.out
## Instruction:
Make sure the filter arg is a string.
## Code After:
from django.template import Library
from django.template.defaultfilters import stringfilter
from ..html import TermsHTMLReconstructor
register = Library()
@register.filter
@stringfilter
def replace_terms(html):
parser = TermsHTMLReconstructor()
parser.feed(html)
return parser.out
|
1b218de76e8b09c70abcd88a2c6dd2c043bfc7f0 | drcli/__main__.py | drcli/__main__.py | import os.path
import sys
import imp
import argparse
from api import App, add_subparsers
def load_plugins(dir):
for f in os.listdir(dir):
module_name, ext = os.path.splitext(f)
if ext == '.py':
imp.load_source('arbitrary', os.path.join(dir, f))
def main(args=sys.argv[1:]):
load_plugins(os.path.join(os.path.dirname(__file__), 'plugins/evaluators'))
load_plugins(os.path.join(os.path.dirname(__file__), 'plugins/apps'))
parser = argparse.ArgumentParser()
add_subparsers(parser, sorted(App.CLASSES.items()), 'app_cls', title='apps')
args = parser.parse_args()
args.app_cls(parser, args)()
if __name__ == '__main__':
main(sys.argv[1:])
| import os.path
import sys
import imp
import argparse
from api import App, add_subparsers
def load_plugins(dir):
for f in os.listdir(dir):
module_name, ext = os.path.splitext(f)
if ext == '.py':
imp.load_source('arbitrary', os.path.join(dir, f))
def main(args=None):
if args is None:
args = sys.argv[1:]
cmd = os.path.basename(sys.argv[0])
if cmd.startswith('dr-'):
args.insert(0, cmd[3:])
prog = 'dr'
else:
prog = None
load_plugins(os.path.join(os.path.dirname(__file__), 'plugins/evaluators'))
load_plugins(os.path.join(os.path.dirname(__file__), 'plugins/apps'))
parser = argparse.ArgumentParser(prog=prog)
add_subparsers(parser, sorted(App.CLASSES.items()), 'app_cls', title='apps')
args = parser.parse_args(args)
args.app_cls(parser, args)()
if __name__ == '__main__':
main()
| Allow sub-commands to use same main function | Allow sub-commands to use same main function
| Python | mit | schwa-lab/dr-apps-python | import os.path
import sys
import imp
import argparse
from api import App, add_subparsers
def load_plugins(dir):
for f in os.listdir(dir):
module_name, ext = os.path.splitext(f)
if ext == '.py':
imp.load_source('arbitrary', os.path.join(dir, f))
- def main(args=sys.argv[1:]):
+ def main(args=None):
+ if args is None:
+ args = sys.argv[1:]
+ cmd = os.path.basename(sys.argv[0])
+ if cmd.startswith('dr-'):
+ args.insert(0, cmd[3:])
+ prog = 'dr'
+ else:
+ prog = None
load_plugins(os.path.join(os.path.dirname(__file__), 'plugins/evaluators'))
load_plugins(os.path.join(os.path.dirname(__file__), 'plugins/apps'))
- parser = argparse.ArgumentParser()
+ parser = argparse.ArgumentParser(prog=prog)
add_subparsers(parser, sorted(App.CLASSES.items()), 'app_cls', title='apps')
- args = parser.parse_args()
+ args = parser.parse_args(args)
args.app_cls(parser, args)()
if __name__ == '__main__':
- main(sys.argv[1:])
+ main()
| Allow sub-commands to use same main function | ## Code Before:
import os.path
import sys
import imp
import argparse
from api import App, add_subparsers
def load_plugins(dir):
for f in os.listdir(dir):
module_name, ext = os.path.splitext(f)
if ext == '.py':
imp.load_source('arbitrary', os.path.join(dir, f))
def main(args=sys.argv[1:]):
load_plugins(os.path.join(os.path.dirname(__file__), 'plugins/evaluators'))
load_plugins(os.path.join(os.path.dirname(__file__), 'plugins/apps'))
parser = argparse.ArgumentParser()
add_subparsers(parser, sorted(App.CLASSES.items()), 'app_cls', title='apps')
args = parser.parse_args()
args.app_cls(parser, args)()
if __name__ == '__main__':
main(sys.argv[1:])
## Instruction:
Allow sub-commands to use same main function
## Code After:
import os.path
import sys
import imp
import argparse
from api import App, add_subparsers
def load_plugins(dir):
for f in os.listdir(dir):
module_name, ext = os.path.splitext(f)
if ext == '.py':
imp.load_source('arbitrary', os.path.join(dir, f))
def main(args=None):
if args is None:
args = sys.argv[1:]
cmd = os.path.basename(sys.argv[0])
if cmd.startswith('dr-'):
args.insert(0, cmd[3:])
prog = 'dr'
else:
prog = None
load_plugins(os.path.join(os.path.dirname(__file__), 'plugins/evaluators'))
load_plugins(os.path.join(os.path.dirname(__file__), 'plugins/apps'))
parser = argparse.ArgumentParser(prog=prog)
add_subparsers(parser, sorted(App.CLASSES.items()), 'app_cls', title='apps')
args = parser.parse_args(args)
args.app_cls(parser, args)()
if __name__ == '__main__':
main()
|
85d684369e72aa2968f9ffbd0632f84558e1b44e | tests/test_vector2_dot.py | tests/test_vector2_dot.py | from ppb_vector import Vector2
from math import isclose, sqrt
import pytest # type: ignore
from hypothesis import assume, given, note
from utils import floats, vectors
@given(x=vectors(), y=vectors())
def test_dot_commutes(x: Vector2, y: Vector2):
assert x * y == y * x
MAGNITUDE=1e10
@given(x=vectors(max_magnitude=MAGNITUDE), z=vectors(max_magnitude=MAGNITUDE),
y=vectors(max_magnitude=sqrt(MAGNITUDE)),
scalar=floats(max_magnitude=sqrt(MAGNITUDE)))
def test_dot_linear(x: Vector2, y: Vector2, z: Vector2, scalar: float):
"""Test that x · (λ y + z) = λ x·y + x·z"""
inner, outer = x * (scalar * y + z), scalar * x * y + x * z
note(f"inner: {inner}")
note(f"outer: {outer}")
assert isclose(inner, outer, abs_tol=1e-5, rel_tol=1e-5)
| from ppb_vector import Vector2
from math import isclose, sqrt
import pytest # type: ignore
from hypothesis import assume, given, note
from utils import floats, vectors
@given(x=vectors(), y=vectors())
def test_dot_commutes(x: Vector2, y: Vector2):
assert x * y == y * x
@given(x=vectors())
def test_dot_length(x: Vector2):
assert isclose(x * x, x.length * x.length)
MAGNITUDE=1e10
@given(x=vectors(max_magnitude=MAGNITUDE), z=vectors(max_magnitude=MAGNITUDE),
y=vectors(max_magnitude=sqrt(MAGNITUDE)),
scalar=floats(max_magnitude=sqrt(MAGNITUDE)))
def test_dot_linear(x: Vector2, y: Vector2, z: Vector2, scalar: float):
"""Test that x · (λ y + z) = λ x·y + x·z"""
inner, outer = x * (scalar * y + z), scalar * x * y + x * z
note(f"inner: {inner}")
note(f"outer: {outer}")
assert isclose(inner, outer, abs_tol=1e-5, rel_tol=1e-5)
| Test that x² == |x|² | tests/dot: Test that x² == |x|²
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector | from ppb_vector import Vector2
from math import isclose, sqrt
import pytest # type: ignore
from hypothesis import assume, given, note
from utils import floats, vectors
@given(x=vectors(), y=vectors())
def test_dot_commutes(x: Vector2, y: Vector2):
assert x * y == y * x
+
+ @given(x=vectors())
+ def test_dot_length(x: Vector2):
+ assert isclose(x * x, x.length * x.length)
MAGNITUDE=1e10
@given(x=vectors(max_magnitude=MAGNITUDE), z=vectors(max_magnitude=MAGNITUDE),
y=vectors(max_magnitude=sqrt(MAGNITUDE)),
scalar=floats(max_magnitude=sqrt(MAGNITUDE)))
def test_dot_linear(x: Vector2, y: Vector2, z: Vector2, scalar: float):
"""Test that x · (λ y + z) = λ x·y + x·z"""
inner, outer = x * (scalar * y + z), scalar * x * y + x * z
note(f"inner: {inner}")
note(f"outer: {outer}")
assert isclose(inner, outer, abs_tol=1e-5, rel_tol=1e-5)
| Test that x² == |x|² | ## Code Before:
from ppb_vector import Vector2
from math import isclose, sqrt
import pytest # type: ignore
from hypothesis import assume, given, note
from utils import floats, vectors
@given(x=vectors(), y=vectors())
def test_dot_commutes(x: Vector2, y: Vector2):
assert x * y == y * x
MAGNITUDE=1e10
@given(x=vectors(max_magnitude=MAGNITUDE), z=vectors(max_magnitude=MAGNITUDE),
y=vectors(max_magnitude=sqrt(MAGNITUDE)),
scalar=floats(max_magnitude=sqrt(MAGNITUDE)))
def test_dot_linear(x: Vector2, y: Vector2, z: Vector2, scalar: float):
"""Test that x · (λ y + z) = λ x·y + x·z"""
inner, outer = x * (scalar * y + z), scalar * x * y + x * z
note(f"inner: {inner}")
note(f"outer: {outer}")
assert isclose(inner, outer, abs_tol=1e-5, rel_tol=1e-5)
## Instruction:
Test that x² == |x|²
## Code After:
from ppb_vector import Vector2
from math import isclose, sqrt
import pytest # type: ignore
from hypothesis import assume, given, note
from utils import floats, vectors
@given(x=vectors(), y=vectors())
def test_dot_commutes(x: Vector2, y: Vector2):
assert x * y == y * x
@given(x=vectors())
def test_dot_length(x: Vector2):
assert isclose(x * x, x.length * x.length)
MAGNITUDE=1e10
@given(x=vectors(max_magnitude=MAGNITUDE), z=vectors(max_magnitude=MAGNITUDE),
y=vectors(max_magnitude=sqrt(MAGNITUDE)),
scalar=floats(max_magnitude=sqrt(MAGNITUDE)))
def test_dot_linear(x: Vector2, y: Vector2, z: Vector2, scalar: float):
"""Test that x · (λ y + z) = λ x·y + x·z"""
inner, outer = x * (scalar * y + z), scalar * x * y + x * z
note(f"inner: {inner}")
note(f"outer: {outer}")
assert isclose(inner, outer, abs_tol=1e-5, rel_tol=1e-5)
|
6d08c13fbf42eb4251d3477a904ab6d8513620df | dataset.py | dataset.py | from scrapy.item import Item, Field
class DatasetItem(Item):
name = Field()
frequency = Field()
| from scrapy.item import Item, Field
class DatasetItem(Item):
url = Field()
name = Field()
frequency = Field()
| Add url field to Dataset web item | Add url field to Dataset web item
| Python | mit | MaxLikelihood/CODE | from scrapy.item import Item, Field
class DatasetItem(Item):
+ url = Field()
name = Field()
frequency = Field()
-
+ | Add url field to Dataset web item | ## Code Before:
from scrapy.item import Item, Field
class DatasetItem(Item):
name = Field()
frequency = Field()
## Instruction:
Add url field to Dataset web item
## Code After:
from scrapy.item import Item, Field
class DatasetItem(Item):
url = Field()
name = Field()
frequency = Field()
|
b5006a2820051e00c9fe4f5efe43e90129c12b4d | troposphere/cloudtrail.py | troposphere/cloudtrail.py | from . import AWSObject, AWSProperty, Tags
from .validators import boolean
class DataResource(AWSProperty):
props = {
"Type": (str, True),
"Values": ([str], False),
}
class EventSelector(AWSProperty):
props = {
"DataResources": ([DataResource], False),
"IncludeManagementEvents": (boolean, False),
"ReadWriteType": (str, False),
}
class Trail(AWSObject):
resource_type = "AWS::CloudTrail::Trail"
props = {
"CloudWatchLogsLogGroupArn": (str, False),
"CloudWatchLogsRoleArn": (str, False),
"EnableLogFileValidation": (boolean, False),
"EventSelectors": ([EventSelector], False),
"IncludeGlobalServiceEvents": (boolean, False),
"IsLogging": (boolean, True),
"IsMultiRegionTrail": (boolean, False),
"KMSKeyId": (str, False),
"S3BucketName": (str, True),
"S3KeyPrefix": (str, False),
"SnsTopicName": (str, False),
"Tags": (Tags, False),
"TrailName": (str, False),
}
| from . import AWSObject, AWSProperty, Tags
from .validators import boolean
class DataResource(AWSProperty):
props = {
"Type": (str, True),
"Values": ([str], False),
}
class EventSelector(AWSProperty):
props = {
"DataResources": ([DataResource], False),
"ExcludeManagementEventSources": ([str], False),
"IncludeManagementEvents": (boolean, False),
"ReadWriteType": (str, False),
}
class InsightSelector(AWSProperty):
props = {
"InsightType": (str, False),
}
class Trail(AWSObject):
resource_type = "AWS::CloudTrail::Trail"
props = {
"CloudWatchLogsLogGroupArn": (str, False),
"CloudWatchLogsRoleArn": (str, False),
"EnableLogFileValidation": (boolean, False),
"EventSelectors": ([EventSelector], False),
"IncludeGlobalServiceEvents": (boolean, False),
"InsightSelectors": ([InsightSelector], False),
"IsLogging": (boolean, True),
"IsMultiRegionTrail": (boolean, False),
"IsOrganizationTrail": (boolean, False),
"KMSKeyId": (str, False),
"S3BucketName": (str, True),
"S3KeyPrefix": (str, False),
"SnsTopicName": (str, False),
"Tags": (Tags, False),
"TrailName": (str, False),
}
| Update Cloudtrail per 2021-09-10 changes | Update Cloudtrail per 2021-09-10 changes
| Python | bsd-2-clause | cloudtools/troposphere,cloudtools/troposphere | from . import AWSObject, AWSProperty, Tags
from .validators import boolean
class DataResource(AWSProperty):
props = {
"Type": (str, True),
"Values": ([str], False),
}
class EventSelector(AWSProperty):
props = {
"DataResources": ([DataResource], False),
+ "ExcludeManagementEventSources": ([str], False),
"IncludeManagementEvents": (boolean, False),
"ReadWriteType": (str, False),
+ }
+
+
+ class InsightSelector(AWSProperty):
+ props = {
+ "InsightType": (str, False),
}
class Trail(AWSObject):
resource_type = "AWS::CloudTrail::Trail"
props = {
"CloudWatchLogsLogGroupArn": (str, False),
"CloudWatchLogsRoleArn": (str, False),
"EnableLogFileValidation": (boolean, False),
"EventSelectors": ([EventSelector], False),
"IncludeGlobalServiceEvents": (boolean, False),
+ "InsightSelectors": ([InsightSelector], False),
"IsLogging": (boolean, True),
"IsMultiRegionTrail": (boolean, False),
+ "IsOrganizationTrail": (boolean, False),
"KMSKeyId": (str, False),
"S3BucketName": (str, True),
"S3KeyPrefix": (str, False),
"SnsTopicName": (str, False),
"Tags": (Tags, False),
"TrailName": (str, False),
}
| Update Cloudtrail per 2021-09-10 changes | ## Code Before:
from . import AWSObject, AWSProperty, Tags
from .validators import boolean
class DataResource(AWSProperty):
props = {
"Type": (str, True),
"Values": ([str], False),
}
class EventSelector(AWSProperty):
props = {
"DataResources": ([DataResource], False),
"IncludeManagementEvents": (boolean, False),
"ReadWriteType": (str, False),
}
class Trail(AWSObject):
resource_type = "AWS::CloudTrail::Trail"
props = {
"CloudWatchLogsLogGroupArn": (str, False),
"CloudWatchLogsRoleArn": (str, False),
"EnableLogFileValidation": (boolean, False),
"EventSelectors": ([EventSelector], False),
"IncludeGlobalServiceEvents": (boolean, False),
"IsLogging": (boolean, True),
"IsMultiRegionTrail": (boolean, False),
"KMSKeyId": (str, False),
"S3BucketName": (str, True),
"S3KeyPrefix": (str, False),
"SnsTopicName": (str, False),
"Tags": (Tags, False),
"TrailName": (str, False),
}
## Instruction:
Update Cloudtrail per 2021-09-10 changes
## Code After:
from . import AWSObject, AWSProperty, Tags
from .validators import boolean
class DataResource(AWSProperty):
props = {
"Type": (str, True),
"Values": ([str], False),
}
class EventSelector(AWSProperty):
props = {
"DataResources": ([DataResource], False),
"ExcludeManagementEventSources": ([str], False),
"IncludeManagementEvents": (boolean, False),
"ReadWriteType": (str, False),
}
class InsightSelector(AWSProperty):
props = {
"InsightType": (str, False),
}
class Trail(AWSObject):
resource_type = "AWS::CloudTrail::Trail"
props = {
"CloudWatchLogsLogGroupArn": (str, False),
"CloudWatchLogsRoleArn": (str, False),
"EnableLogFileValidation": (boolean, False),
"EventSelectors": ([EventSelector], False),
"IncludeGlobalServiceEvents": (boolean, False),
"InsightSelectors": ([InsightSelector], False),
"IsLogging": (boolean, True),
"IsMultiRegionTrail": (boolean, False),
"IsOrganizationTrail": (boolean, False),
"KMSKeyId": (str, False),
"S3BucketName": (str, True),
"S3KeyPrefix": (str, False),
"SnsTopicName": (str, False),
"Tags": (Tags, False),
"TrailName": (str, False),
}
|
053d6a2ca13b1f36a02fa3223092a10af35f6579 | erpnext/patches/v10_0/item_barcode_childtable_migrate.py | erpnext/patches/v10_0/item_barcode_childtable_migrate.py |
from __future__ import unicode_literals
import frappe
def execute():
items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') })
frappe.reload_doc("stock", "doctype", "item")
frappe.reload_doc("stock", "doctype", "item_barcode")
for item in items_barcode:
barcode = item.barcode.strip()
if barcode and '<' not in barcode:
try:
frappe.get_doc({
'idx': 0,
'doctype': 'Item Barcode',
'barcode': barcode,
'parenttype': 'Item',
'parent': item.name,
'parentfield': 'barcodes'
}).insert()
except frappe.DuplicateEntryError:
continue
|
from __future__ import unicode_literals
import frappe
def execute():
frappe.reload_doc("stock", "doctype", "item_barcode")
items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') })
frappe.reload_doc("stock", "doctype", "item")
for item in items_barcode:
barcode = item.barcode.strip()
if barcode and '<' not in barcode:
try:
frappe.get_doc({
'idx': 0,
'doctype': 'Item Barcode',
'barcode': barcode,
'parenttype': 'Item',
'parent': item.name,
'parentfield': 'barcodes'
}).insert()
except frappe.DuplicateEntryError:
continue
| Move reload doc before get query | Move reload doc before get query
| Python | agpl-3.0 | gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext |
from __future__ import unicode_literals
import frappe
def execute():
+ frappe.reload_doc("stock", "doctype", "item_barcode")
+
items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') })
+ frappe.reload_doc("stock", "doctype", "item")
+
- frappe.reload_doc("stock", "doctype", "item")
- frappe.reload_doc("stock", "doctype", "item_barcode")
for item in items_barcode:
barcode = item.barcode.strip()
if barcode and '<' not in barcode:
try:
frappe.get_doc({
'idx': 0,
'doctype': 'Item Barcode',
'barcode': barcode,
'parenttype': 'Item',
'parent': item.name,
'parentfield': 'barcodes'
}).insert()
except frappe.DuplicateEntryError:
continue
| Move reload doc before get query | ## Code Before:
from __future__ import unicode_literals
import frappe
def execute():
items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') })
frappe.reload_doc("stock", "doctype", "item")
frappe.reload_doc("stock", "doctype", "item_barcode")
for item in items_barcode:
barcode = item.barcode.strip()
if barcode and '<' not in barcode:
try:
frappe.get_doc({
'idx': 0,
'doctype': 'Item Barcode',
'barcode': barcode,
'parenttype': 'Item',
'parent': item.name,
'parentfield': 'barcodes'
}).insert()
except frappe.DuplicateEntryError:
continue
## Instruction:
Move reload doc before get query
## Code After:
from __future__ import unicode_literals
import frappe
def execute():
frappe.reload_doc("stock", "doctype", "item_barcode")
items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') })
frappe.reload_doc("stock", "doctype", "item")
for item in items_barcode:
barcode = item.barcode.strip()
if barcode and '<' not in barcode:
try:
frappe.get_doc({
'idx': 0,
'doctype': 'Item Barcode',
'barcode': barcode,
'parenttype': 'Item',
'parent': item.name,
'parentfield': 'barcodes'
}).insert()
except frappe.DuplicateEntryError:
continue
|
a2efdbc7c790df31f511d9a347774a961132d565 | txircd/modules/cmode_l.py | txircd/modules/cmode_l.py | from twisted.words.protocols import irc
from txircd.modbase import Mode
class LimitMode(Mode):
def checkSet(self, user, target, param):
intParam = int(param)
if str(intParam) != param:
return [False, param]
return [(intParam >= 0), param]
def checkPermission(self, user, cmd, data):
if cmd != "JOIN":
return data
targetChannels = data["targetchan"]
keys = data["keys"]
removeChannels = []
for channel in targetChannels:
if "l" in channel.mode and len(channel.users) >= int(channel.mode["l"]):
user.sendMessage(irc.ERR_CHANNELISFULL, channel.name, ":Cannot join channel (Channel is full)")
removeChannels.append(channel)
for channel in removeChannels:
index = targetChannels.index(channel)
targetChannels.pop(index)
keys.pop(index)
data["targetchan"] = targetChannels
data["keys"] = keys
return data
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn(self):
return {
"modes": {
"cpl": LimitMode()
},
"common": True
}
def cleanup(self):
self.ircd.removeMode("cpl") | from twisted.words.protocols import irc
from txircd.modbase import Mode
class LimitMode(Mode):
def checkSet(self, user, target, param):
try:
intParam = int(param)
except ValueError:
return [False, param]
if str(intParam) != param:
return [False, param]
return [(intParam > 0), param]
def checkPermission(self, user, cmd, data):
if cmd != "JOIN":
return data
targetChannels = data["targetchan"]
keys = data["keys"]
removeChannels = []
for channel in targetChannels:
if "l" in channel.mode and len(channel.users) >= int(channel.mode["l"]):
user.sendMessage(irc.ERR_CHANNELISFULL, channel.name, ":Cannot join channel (Channel is full)")
removeChannels.append(channel)
for channel in removeChannels:
index = targetChannels.index(channel)
targetChannels.pop(index)
keys.pop(index)
data["targetchan"] = targetChannels
data["keys"] = keys
return data
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn(self):
return {
"modes": {
"cpl": LimitMode()
},
"common": True
}
def cleanup(self):
self.ircd.removeMode("cpl") | Fix checking of limit parameter | Fix checking of limit parameter
| Python | bsd-3-clause | DesertBus/txircd,Heufneutje/txircd,ElementalAlchemist/txircd | from twisted.words.protocols import irc
from txircd.modbase import Mode
class LimitMode(Mode):
def checkSet(self, user, target, param):
+ try:
- intParam = int(param)
+ intParam = int(param)
+ except ValueError:
+ return [False, param]
if str(intParam) != param:
return [False, param]
- return [(intParam >= 0), param]
+ return [(intParam > 0), param]
def checkPermission(self, user, cmd, data):
if cmd != "JOIN":
return data
targetChannels = data["targetchan"]
keys = data["keys"]
removeChannels = []
for channel in targetChannels:
if "l" in channel.mode and len(channel.users) >= int(channel.mode["l"]):
user.sendMessage(irc.ERR_CHANNELISFULL, channel.name, ":Cannot join channel (Channel is full)")
removeChannels.append(channel)
for channel in removeChannels:
index = targetChannels.index(channel)
targetChannels.pop(index)
keys.pop(index)
data["targetchan"] = targetChannels
data["keys"] = keys
return data
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn(self):
return {
"modes": {
"cpl": LimitMode()
},
"common": True
}
def cleanup(self):
self.ircd.removeMode("cpl") | Fix checking of limit parameter | ## Code Before:
from twisted.words.protocols import irc
from txircd.modbase import Mode
class LimitMode(Mode):
def checkSet(self, user, target, param):
intParam = int(param)
if str(intParam) != param:
return [False, param]
return [(intParam >= 0), param]
def checkPermission(self, user, cmd, data):
if cmd != "JOIN":
return data
targetChannels = data["targetchan"]
keys = data["keys"]
removeChannels = []
for channel in targetChannels:
if "l" in channel.mode and len(channel.users) >= int(channel.mode["l"]):
user.sendMessage(irc.ERR_CHANNELISFULL, channel.name, ":Cannot join channel (Channel is full)")
removeChannels.append(channel)
for channel in removeChannels:
index = targetChannels.index(channel)
targetChannels.pop(index)
keys.pop(index)
data["targetchan"] = targetChannels
data["keys"] = keys
return data
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn(self):
return {
"modes": {
"cpl": LimitMode()
},
"common": True
}
def cleanup(self):
self.ircd.removeMode("cpl")
## Instruction:
Fix checking of limit parameter
## Code After:
from twisted.words.protocols import irc
from txircd.modbase import Mode
class LimitMode(Mode):
def checkSet(self, user, target, param):
try:
intParam = int(param)
except ValueError:
return [False, param]
if str(intParam) != param:
return [False, param]
return [(intParam > 0), param]
def checkPermission(self, user, cmd, data):
if cmd != "JOIN":
return data
targetChannels = data["targetchan"]
keys = data["keys"]
removeChannels = []
for channel in targetChannels:
if "l" in channel.mode and len(channel.users) >= int(channel.mode["l"]):
user.sendMessage(irc.ERR_CHANNELISFULL, channel.name, ":Cannot join channel (Channel is full)")
removeChannels.append(channel)
for channel in removeChannels:
index = targetChannels.index(channel)
targetChannels.pop(index)
keys.pop(index)
data["targetchan"] = targetChannels
data["keys"] = keys
return data
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn(self):
return {
"modes": {
"cpl": LimitMode()
},
"common": True
}
def cleanup(self):
self.ircd.removeMode("cpl") |
4de5050deda6c73fd9812a5e53938fea11e0b2cc | tests/unit/minion_test.py | tests/unit/minion_test.py | '''
:codeauthor: :email:`Mike Place <[email protected]>`
'''
# Import Salt Testing libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import NO_MOCK, NO_MOCK_REASON, patch
from salt import minion
from salt.exceptions import SaltSystemExit
ensure_in_syspath('../')
__opts__ = {}
@skipIf(NO_MOCK, NO_MOCK_REASON)
class MinionTestCase(TestCase):
def test_invalid_master_address(self):
with patch.dict(__opts__, {'ipv6': False, 'master': float('127.0'), 'master_port': '4555', 'retry_dns': False}):
self.assertRaises(SaltSystemExit, minion.resolve_dns, __opts__)
if __name__ == '__main__':
from integration import run_tests
run_tests(MinionTestCase, needs_daemon=False)
| '''
:codeauthor: :email:`Mike Place <[email protected]>`
'''
# Import python libs
import os
# Import Salt Testing libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import NO_MOCK, NO_MOCK_REASON, patch
# Import salt libs
from salt import minion
from salt.exceptions import SaltSystemExit
import salt.syspaths
ensure_in_syspath('../')
__opts__ = {}
@skipIf(NO_MOCK, NO_MOCK_REASON)
class MinionTestCase(TestCase):
def test_invalid_master_address(self):
with patch.dict(__opts__, {'ipv6': False, 'master': float('127.0'), 'master_port': '4555', 'retry_dns': False}):
self.assertRaises(SaltSystemExit, minion.resolve_dns, __opts__)
def test_sock_path_len(self):
'''
This tests whether or not a larger hash causes the sock path to exceed
the system's max sock path length. See the below link for more
information.
https://github.com/saltstack/salt/issues/12172#issuecomment-43903643
'''
opts = {
'id': 'salt-testing',
'hash_type': 'sha512',
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion')
}
with patch.dict(__opts__, opts):
testminion = minion.MinionBase(__opts__)
try:
testminion._prepare_minion_event_system()
result = True
except SaltSystemExit:
result = False
self.assertTrue(result)
if __name__ == '__main__':
from integration import run_tests
run_tests(MinionTestCase, needs_daemon=False)
| Add test for sock path length | Add test for sock path length
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | '''
:codeauthor: :email:`Mike Place <[email protected]>`
'''
+
+ # Import python libs
+ import os
# Import Salt Testing libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import NO_MOCK, NO_MOCK_REASON, patch
+ # Import salt libs
from salt import minion
from salt.exceptions import SaltSystemExit
-
+ import salt.syspaths
ensure_in_syspath('../')
__opts__ = {}
@skipIf(NO_MOCK, NO_MOCK_REASON)
class MinionTestCase(TestCase):
def test_invalid_master_address(self):
with patch.dict(__opts__, {'ipv6': False, 'master': float('127.0'), 'master_port': '4555', 'retry_dns': False}):
self.assertRaises(SaltSystemExit, minion.resolve_dns, __opts__)
+ def test_sock_path_len(self):
+ '''
+ This tests whether or not a larger hash causes the sock path to exceed
+ the system's max sock path length. See the below link for more
+ information.
+
+ https://github.com/saltstack/salt/issues/12172#issuecomment-43903643
+ '''
+ opts = {
+ 'id': 'salt-testing',
+ 'hash_type': 'sha512',
+ 'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion')
+ }
+ with patch.dict(__opts__, opts):
+ testminion = minion.MinionBase(__opts__)
+ try:
+ testminion._prepare_minion_event_system()
+ result = True
+ except SaltSystemExit:
+ result = False
+ self.assertTrue(result)
+
if __name__ == '__main__':
from integration import run_tests
run_tests(MinionTestCase, needs_daemon=False)
| Add test for sock path length | ## Code Before:
'''
:codeauthor: :email:`Mike Place <[email protected]>`
'''
# Import Salt Testing libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import NO_MOCK, NO_MOCK_REASON, patch
from salt import minion
from salt.exceptions import SaltSystemExit
ensure_in_syspath('../')
__opts__ = {}
@skipIf(NO_MOCK, NO_MOCK_REASON)
class MinionTestCase(TestCase):
def test_invalid_master_address(self):
with patch.dict(__opts__, {'ipv6': False, 'master': float('127.0'), 'master_port': '4555', 'retry_dns': False}):
self.assertRaises(SaltSystemExit, minion.resolve_dns, __opts__)
if __name__ == '__main__':
from integration import run_tests
run_tests(MinionTestCase, needs_daemon=False)
## Instruction:
Add test for sock path length
## Code After:
'''
:codeauthor: :email:`Mike Place <[email protected]>`
'''
# Import python libs
import os
# Import Salt Testing libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import NO_MOCK, NO_MOCK_REASON, patch
# Import salt libs
from salt import minion
from salt.exceptions import SaltSystemExit
import salt.syspaths
ensure_in_syspath('../')
__opts__ = {}
@skipIf(NO_MOCK, NO_MOCK_REASON)
class MinionTestCase(TestCase):
def test_invalid_master_address(self):
with patch.dict(__opts__, {'ipv6': False, 'master': float('127.0'), 'master_port': '4555', 'retry_dns': False}):
self.assertRaises(SaltSystemExit, minion.resolve_dns, __opts__)
def test_sock_path_len(self):
'''
This tests whether or not a larger hash causes the sock path to exceed
the system's max sock path length. See the below link for more
information.
https://github.com/saltstack/salt/issues/12172#issuecomment-43903643
'''
opts = {
'id': 'salt-testing',
'hash_type': 'sha512',
'sock_dir': os.path.join(salt.syspaths.SOCK_DIR, 'minion')
}
with patch.dict(__opts__, opts):
testminion = minion.MinionBase(__opts__)
try:
testminion._prepare_minion_event_system()
result = True
except SaltSystemExit:
result = False
self.assertTrue(result)
if __name__ == '__main__':
from integration import run_tests
run_tests(MinionTestCase, needs_daemon=False)
|
e379aa75690d5bacc1d0bdec325ed4c16cf1a183 | lims/permissions/views.py | lims/permissions/views.py | from django.contrib.auth.models import Permission
from rest_framework import viewsets
from .serializers import PermissionSerializer
class PermissionViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Permission.objects.all()
serializer_class = PermissionSerializer
| from django.contrib.auth.models import Permission
from rest_framework import viewsets
from .serializers import PermissionSerializer
class PermissionViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Permission.objects.all()
serializer_class = PermissionSerializer
search_fields = ('name',)
| Add search functionality to permissions endpoint | Add search functionality to permissions endpoint
| Python | mit | GETLIMS/LIMS-Backend,GETLIMS/LIMS-Backend | from django.contrib.auth.models import Permission
from rest_framework import viewsets
from .serializers import PermissionSerializer
class PermissionViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Permission.objects.all()
serializer_class = PermissionSerializer
+ search_fields = ('name',)
| Add search functionality to permissions endpoint | ## Code Before:
from django.contrib.auth.models import Permission
from rest_framework import viewsets
from .serializers import PermissionSerializer
class PermissionViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Permission.objects.all()
serializer_class = PermissionSerializer
## Instruction:
Add search functionality to permissions endpoint
## Code After:
from django.contrib.auth.models import Permission
from rest_framework import viewsets
from .serializers import PermissionSerializer
class PermissionViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Permission.objects.all()
serializer_class = PermissionSerializer
search_fields = ('name',)
|
00922099d6abb03a0dbcca19781eb586d367eab0 | skimage/measure/__init__.py | skimage/measure/__init__.py | from .find_contours import find_contours
from ._regionprops import regionprops
from .find_contours import find_contours
from ._structural_similarity import ssim
| from .find_contours import find_contours
from ._regionprops import regionprops
from ._structural_similarity import ssim
| Remove double import of find contours. | BUG: Remove double import of find contours.
| Python | bsd-3-clause | robintw/scikit-image,WarrenWeckesser/scikits-image,ofgulban/scikit-image,ajaybhat/scikit-image,rjeli/scikit-image,SamHames/scikit-image,chintak/scikit-image,ofgulban/scikit-image,SamHames/scikit-image,dpshelio/scikit-image,chintak/scikit-image,rjeli/scikit-image,oew1v07/scikit-image,almarklein/scikit-image,pratapvardhan/scikit-image,bsipocz/scikit-image,ClinicalGraphics/scikit-image,vighneshbirodkar/scikit-image,michaelaye/scikit-image,michaelaye/scikit-image,jwiggins/scikit-image,pratapvardhan/scikit-image,keflavich/scikit-image,chriscrosscutler/scikit-image,Britefury/scikit-image,dpshelio/scikit-image,bennlich/scikit-image,bsipocz/scikit-image,blink1073/scikit-image,GaZ3ll3/scikit-image,paalge/scikit-image,almarklein/scikit-image,Hiyorimi/scikit-image,bennlich/scikit-image,Hiyorimi/scikit-image,emon10005/scikit-image,emmanuelle/scikits.image,vighneshbirodkar/scikit-image,ofgulban/scikit-image,almarklein/scikit-image,warmspringwinds/scikit-image,Midafi/scikit-image,youprofit/scikit-image,chintak/scikit-image,newville/scikit-image,Britefury/scikit-image,almarklein/scikit-image,juliusbierk/scikit-image,jwiggins/scikit-image,chriscrosscutler/scikit-image,michaelpacer/scikit-image,emmanuelle/scikits.image,juliusbierk/scikit-image,SamHames/scikit-image,robintw/scikit-image,chintak/scikit-image,WarrenWeckesser/scikits-image,Midafi/scikit-image,emmanuelle/scikits.image,vighneshbirodkar/scikit-image,newville/scikit-image,blink1073/scikit-image,michaelpacer/scikit-image,emmanuelle/scikits.image,oew1v07/scikit-image,emon10005/scikit-image,youprofit/scikit-image,ajaybhat/scikit-image,paalge/scikit-image,rjeli/scikit-image,warmspringwinds/scikit-image,paalge/scikit-image,keflavich/scikit-image,ClinicalGraphics/scikit-image,GaZ3ll3/scikit-image,SamHames/scikit-image | from .find_contours import find_contours
from ._regionprops import regionprops
- from .find_contours import find_contours
from ._structural_similarity import ssim
| Remove double import of find contours. | ## Code Before:
from .find_contours import find_contours
from ._regionprops import regionprops
from .find_contours import find_contours
from ._structural_similarity import ssim
## Instruction:
Remove double import of find contours.
## Code After:
from .find_contours import find_contours
from ._regionprops import regionprops
from ._structural_similarity import ssim
|
985cefd81472069240b074423a831fe6031d6887 | website_sale_available/controllers/website_sale_available.py | website_sale_available/controllers/website_sale_available.py | from openerp import http
from openerp.http import request
from openerp.addons.website_sale.controllers.main import website_sale
class controller(website_sale):
@http.route(['/shop/confirm_order'], type='http', auth="public", website=True)
def confirm_order(self, **post):
res = super(controller, self).confirm_order(**post)
order = request.website.sale_get_order(context=request.context)
if not all([
line.product_uom_qty <= line.product_id.virtual_available
for line in order.order_line
]):
return request.redirect("/shop/cart")
return res
| from openerp import http
from openerp.http import request
from openerp.addons.website_sale.controllers.main import website_sale
class controller(website_sale):
@http.route(['/shop/confirm_order'], type='http', auth="public", website=True)
def confirm_order(self, **post):
res = super(controller, self).confirm_order(**post)
order = request.website.sale_get_order(context=request.context)
if not all([
line.product_uom_qty <= line.product_id.virtual_available
for line in order.order_line if not line.is_delivery
]):
return request.redirect("/shop/cart")
return res
| FIX sale_available integration with delivery | FIX sale_available integration with delivery
| Python | mit | it-projects-llc/website-addons,it-projects-llc/website-addons,it-projects-llc/website-addons | from openerp import http
from openerp.http import request
from openerp.addons.website_sale.controllers.main import website_sale
class controller(website_sale):
@http.route(['/shop/confirm_order'], type='http', auth="public", website=True)
def confirm_order(self, **post):
res = super(controller, self).confirm_order(**post)
order = request.website.sale_get_order(context=request.context)
if not all([
line.product_uom_qty <= line.product_id.virtual_available
- for line in order.order_line
+ for line in order.order_line if not line.is_delivery
]):
return request.redirect("/shop/cart")
return res
| FIX sale_available integration with delivery | ## Code Before:
from openerp import http
from openerp.http import request
from openerp.addons.website_sale.controllers.main import website_sale
class controller(website_sale):
@http.route(['/shop/confirm_order'], type='http', auth="public", website=True)
def confirm_order(self, **post):
res = super(controller, self).confirm_order(**post)
order = request.website.sale_get_order(context=request.context)
if not all([
line.product_uom_qty <= line.product_id.virtual_available
for line in order.order_line
]):
return request.redirect("/shop/cart")
return res
## Instruction:
FIX sale_available integration with delivery
## Code After:
from openerp import http
from openerp.http import request
from openerp.addons.website_sale.controllers.main import website_sale
class controller(website_sale):
@http.route(['/shop/confirm_order'], type='http', auth="public", website=True)
def confirm_order(self, **post):
res = super(controller, self).confirm_order(**post)
order = request.website.sale_get_order(context=request.context)
if not all([
line.product_uom_qty <= line.product_id.virtual_available
for line in order.order_line if not line.is_delivery
]):
return request.redirect("/shop/cart")
return res
|
3f26d3c53f4bff36ec05da7a51a026b7d3ba5517 | tests/modules/test_atbash.py | tests/modules/test_atbash.py | """Tests for the Caeser module"""
import pycipher
from lantern.modules import atbash
def _test_atbash(plaintext, *fitness_functions, top_n=1):
ciphertext = pycipher.Atbash().encipher(plaintext, keep_punct=True)
decryption = atbash.decrypt(ciphertext)
assert decryption == plaintext.upper()
def test_decrypt():
"""Test decryption"""
assert atbash.decrypt("uozt{Yzybolm}") == "flag{Babylon}"
def test_encrypt():
"""Test encrypt"""
assert ''.join(atbash.encrypt("flag{Babylon}")) == "uozt{Yzybolm}"
| """Tests for the Caeser module"""
from lantern.modules import atbash
def test_decrypt():
"""Test decryption"""
assert atbash.decrypt("uozt{Yzybolm}") == "flag{Babylon}"
def test_encrypt():
"""Test encryption"""
assert ''.join(atbash.encrypt("flag{Babylon}")) == "uozt{Yzybolm}"
| Remove unnecessary testing code from atbash | Remove unnecessary testing code from atbash
| Python | mit | CameronLonsdale/lantern | """Tests for the Caeser module"""
- import pycipher
-
from lantern.modules import atbash
-
-
- def _test_atbash(plaintext, *fitness_functions, top_n=1):
- ciphertext = pycipher.Atbash().encipher(plaintext, keep_punct=True)
- decryption = atbash.decrypt(ciphertext)
-
- assert decryption == plaintext.upper()
def test_decrypt():
"""Test decryption"""
assert atbash.decrypt("uozt{Yzybolm}") == "flag{Babylon}"
def test_encrypt():
- """Test encrypt"""
+ """Test encryption"""
assert ''.join(atbash.encrypt("flag{Babylon}")) == "uozt{Yzybolm}"
| Remove unnecessary testing code from atbash | ## Code Before:
"""Tests for the Caeser module"""
import pycipher
from lantern.modules import atbash
def _test_atbash(plaintext, *fitness_functions, top_n=1):
ciphertext = pycipher.Atbash().encipher(plaintext, keep_punct=True)
decryption = atbash.decrypt(ciphertext)
assert decryption == plaintext.upper()
def test_decrypt():
"""Test decryption"""
assert atbash.decrypt("uozt{Yzybolm}") == "flag{Babylon}"
def test_encrypt():
"""Test encrypt"""
assert ''.join(atbash.encrypt("flag{Babylon}")) == "uozt{Yzybolm}"
## Instruction:
Remove unnecessary testing code from atbash
## Code After:
"""Tests for the Caeser module"""
from lantern.modules import atbash
def test_decrypt():
"""Test decryption"""
assert atbash.decrypt("uozt{Yzybolm}") == "flag{Babylon}"
def test_encrypt():
"""Test encryption"""
assert ''.join(atbash.encrypt("flag{Babylon}")) == "uozt{Yzybolm}"
|
2c7065f82a242e6f05eaefda4ec902ddf9d90037 | tests/test_stanc_warnings.py | tests/test_stanc_warnings.py | """Test that stanc warnings are visible."""
import contextlib
import io
import stan
def test_stanc_no_warning() -> None:
"""No warnings."""
program_code = "parameters {real y;} model {y ~ normal(0,1);}"
buffer = io.StringIO()
with contextlib.redirect_stderr(buffer):
stan.build(program_code=program_code)
assert "warning" not in buffer.getvalue().lower()
def test_stanc_warning() -> None:
"""Test that stanc warning is shown to user."""
# stanc prints warning:
# assignment operator <- is deprecated in the Stan language; use = instead.
program_code = """
parameters {
real y;
}
model {
real x;
x <- 5;
}
"""
buffer = io.StringIO()
with contextlib.redirect_stderr(buffer):
stan.build(program_code=program_code)
assert "assignment operator <- is deprecated in the Stan language" in buffer.getvalue()
| """Test that stanc warnings are visible."""
import contextlib
import io
import stan
def test_stanc_no_warning() -> None:
"""No warnings."""
program_code = "parameters {real y;} model {y ~ normal(0,1);}"
buffer = io.StringIO()
with contextlib.redirect_stderr(buffer):
stan.build(program_code=program_code)
assert "warning" not in buffer.getvalue().lower()
def test_stanc_unused_warning() -> None:
"""Test that stanc warning is shown to user."""
program_code = """
parameters {
real y;
}
model {
real x;
x = 5;
}
"""
buffer = io.StringIO()
with contextlib.redirect_stderr(buffer):
stan.build(program_code=program_code)
assert "The parameter y was declared but was not used in the density" in buffer.getvalue()
def test_stanc_assignment_warning() -> None:
"""Test that stanc warning is shown to user."""
# stanc prints warning:
# assignment operator <- is deprecated in the Stan language; use = instead.
program_code = """
parameters {
real y;
}
model {
real x;
x <- 5;
y ~ normal(0,1);
}
"""
buffer = io.StringIO()
with contextlib.redirect_stderr(buffer):
stan.build(program_code=program_code)
assert "operator <- is deprecated in the Stan language and will be removed" in buffer.getvalue(), buffer.getvalue()
| Update test for Stan 2.29 | test: Update test for Stan 2.29
| Python | isc | stan-dev/pystan,stan-dev/pystan | """Test that stanc warnings are visible."""
import contextlib
import io
import stan
def test_stanc_no_warning() -> None:
"""No warnings."""
program_code = "parameters {real y;} model {y ~ normal(0,1);}"
buffer = io.StringIO()
with contextlib.redirect_stderr(buffer):
stan.build(program_code=program_code)
assert "warning" not in buffer.getvalue().lower()
- def test_stanc_warning() -> None:
+ def test_stanc_unused_warning() -> None:
+ """Test that stanc warning is shown to user."""
+ program_code = """
+ parameters {
+ real y;
+ }
+ model {
+ real x;
+ x = 5;
+ }
+ """
+ buffer = io.StringIO()
+ with contextlib.redirect_stderr(buffer):
+ stan.build(program_code=program_code)
+ assert "The parameter y was declared but was not used in the density" in buffer.getvalue()
+
+
+ def test_stanc_assignment_warning() -> None:
"""Test that stanc warning is shown to user."""
# stanc prints warning:
# assignment operator <- is deprecated in the Stan language; use = instead.
program_code = """
parameters {
real y;
}
model {
real x;
x <- 5;
+ y ~ normal(0,1);
}
"""
buffer = io.StringIO()
with contextlib.redirect_stderr(buffer):
stan.build(program_code=program_code)
- assert "assignment operator <- is deprecated in the Stan language" in buffer.getvalue()
+ assert "operator <- is deprecated in the Stan language and will be removed" in buffer.getvalue(), buffer.getvalue()
| Update test for Stan 2.29 | ## Code Before:
"""Test that stanc warnings are visible."""
import contextlib
import io
import stan
def test_stanc_no_warning() -> None:
"""No warnings."""
program_code = "parameters {real y;} model {y ~ normal(0,1);}"
buffer = io.StringIO()
with contextlib.redirect_stderr(buffer):
stan.build(program_code=program_code)
assert "warning" not in buffer.getvalue().lower()
def test_stanc_warning() -> None:
"""Test that stanc warning is shown to user."""
# stanc prints warning:
# assignment operator <- is deprecated in the Stan language; use = instead.
program_code = """
parameters {
real y;
}
model {
real x;
x <- 5;
}
"""
buffer = io.StringIO()
with contextlib.redirect_stderr(buffer):
stan.build(program_code=program_code)
assert "assignment operator <- is deprecated in the Stan language" in buffer.getvalue()
## Instruction:
Update test for Stan 2.29
## Code After:
"""Test that stanc warnings are visible."""
import contextlib
import io
import stan
def test_stanc_no_warning() -> None:
"""No warnings."""
program_code = "parameters {real y;} model {y ~ normal(0,1);}"
buffer = io.StringIO()
with contextlib.redirect_stderr(buffer):
stan.build(program_code=program_code)
assert "warning" not in buffer.getvalue().lower()
def test_stanc_unused_warning() -> None:
"""Test that stanc warning is shown to user."""
program_code = """
parameters {
real y;
}
model {
real x;
x = 5;
}
"""
buffer = io.StringIO()
with contextlib.redirect_stderr(buffer):
stan.build(program_code=program_code)
assert "The parameter y was declared but was not used in the density" in buffer.getvalue()
def test_stanc_assignment_warning() -> None:
"""Test that stanc warning is shown to user."""
# stanc prints warning:
# assignment operator <- is deprecated in the Stan language; use = instead.
program_code = """
parameters {
real y;
}
model {
real x;
x <- 5;
y ~ normal(0,1);
}
"""
buffer = io.StringIO()
with contextlib.redirect_stderr(buffer):
stan.build(program_code=program_code)
assert "operator <- is deprecated in the Stan language and will be removed" in buffer.getvalue(), buffer.getvalue()
|
f668956fd37fa2fa0a0c82a8241671bf3cc306cb | tests/unit/moto_test_data.py | tests/unit/moto_test_data.py | import boto3
def pre_load_s3_data(bucket_name, prefix, region='us-east-1'):
s3 = boto3.client('s3', region_name=region)
res = s3.create_bucket(Bucket=bucket_name)
default_kwargs = {"Body": b"Fake data for testing.", "Bucket": bucket_name}
s3.put_object(Key=f"{prefix}/readme.txt", **default_kwargs)
s3.put_object(Key=f"{prefix}/notes.md", **default_kwargs)
# load items, 3 directories
for i, _ in enumerate(range(500)):
res = s3.put_object(Key=f"{prefix}/images/myimage{i}.tif",
**default_kwargs)
for i, _ in enumerate(range(400)):
s3.put_object(
Key=f"{prefix}/scripts/myscripts{i}.py",
**default_kwargs
)
for i, _ in enumerate(range(110)):
s3.put_object(
Key=f"{prefix}/scripts/subdir/otherscripts{i}.sh",
**default_kwargs
)
| import boto3
def pre_load_s3_data(bucket_name, prefix, region='us-east-1'):
s3 = boto3.client('s3', region_name=region)
res = s3.create_bucket(Bucket=bucket_name)
default_kwargs = {"Body": b"Fake data for testing.", "Bucket": bucket_name}
s3.put_object(Key="{}/readme.txt".format(prefix), **default_kwargs)
s3.put_object(Key="{}/notes.md".format(prefix), **default_kwargs)
# load items, 3 directories
for i, _ in enumerate(range(500)):
res = s3.put_object(Key="{}/images/myimage{i}.tif".format(prefix),
**default_kwargs)
for i, _ in enumerate(range(400)):
s3.put_object(Key="{}/scripts/myscripts{i}.py".format(prefix),
**default_kwargs)
for i, _ in enumerate(range(110)):
s3.put_object(
Key="{}/scripts/subdir/otherscripts{i}.sh".format(prefix),
**default_kwargs)
| Fix string using py3 only feature. | Fix string using py3 only feature.
| Python | mit | DigitalGlobe/gbdxtools,DigitalGlobe/gbdxtools | import boto3
def pre_load_s3_data(bucket_name, prefix, region='us-east-1'):
s3 = boto3.client('s3', region_name=region)
res = s3.create_bucket(Bucket=bucket_name)
default_kwargs = {"Body": b"Fake data for testing.", "Bucket": bucket_name}
- s3.put_object(Key=f"{prefix}/readme.txt", **default_kwargs)
+ s3.put_object(Key="{}/readme.txt".format(prefix), **default_kwargs)
- s3.put_object(Key=f"{prefix}/notes.md", **default_kwargs)
+ s3.put_object(Key="{}/notes.md".format(prefix), **default_kwargs)
# load items, 3 directories
for i, _ in enumerate(range(500)):
- res = s3.put_object(Key=f"{prefix}/images/myimage{i}.tif",
+ res = s3.put_object(Key="{}/images/myimage{i}.tif".format(prefix),
**default_kwargs)
for i, _ in enumerate(range(400)):
+ s3.put_object(Key="{}/scripts/myscripts{i}.py".format(prefix),
- s3.put_object(
- Key=f"{prefix}/scripts/myscripts{i}.py",
- **default_kwargs
+ **default_kwargs)
- )
for i, _ in enumerate(range(110)):
- s3.put_object(
+ s3.put_object(
- Key=f"{prefix}/scripts/subdir/otherscripts{i}.sh",
+ Key="{}/scripts/subdir/otherscripts{i}.sh".format(prefix),
- **default_kwargs
+ **default_kwargs)
- )
| Fix string using py3 only feature. | ## Code Before:
import boto3
def pre_load_s3_data(bucket_name, prefix, region='us-east-1'):
s3 = boto3.client('s3', region_name=region)
res = s3.create_bucket(Bucket=bucket_name)
default_kwargs = {"Body": b"Fake data for testing.", "Bucket": bucket_name}
s3.put_object(Key=f"{prefix}/readme.txt", **default_kwargs)
s3.put_object(Key=f"{prefix}/notes.md", **default_kwargs)
# load items, 3 directories
for i, _ in enumerate(range(500)):
res = s3.put_object(Key=f"{prefix}/images/myimage{i}.tif",
**default_kwargs)
for i, _ in enumerate(range(400)):
s3.put_object(
Key=f"{prefix}/scripts/myscripts{i}.py",
**default_kwargs
)
for i, _ in enumerate(range(110)):
s3.put_object(
Key=f"{prefix}/scripts/subdir/otherscripts{i}.sh",
**default_kwargs
)
## Instruction:
Fix string using py3 only feature.
## Code After:
import boto3
def pre_load_s3_data(bucket_name, prefix, region='us-east-1'):
s3 = boto3.client('s3', region_name=region)
res = s3.create_bucket(Bucket=bucket_name)
default_kwargs = {"Body": b"Fake data for testing.", "Bucket": bucket_name}
s3.put_object(Key="{}/readme.txt".format(prefix), **default_kwargs)
s3.put_object(Key="{}/notes.md".format(prefix), **default_kwargs)
# load items, 3 directories
for i, _ in enumerate(range(500)):
res = s3.put_object(Key="{}/images/myimage{i}.tif".format(prefix),
**default_kwargs)
for i, _ in enumerate(range(400)):
s3.put_object(Key="{}/scripts/myscripts{i}.py".format(prefix),
**default_kwargs)
for i, _ in enumerate(range(110)):
s3.put_object(
Key="{}/scripts/subdir/otherscripts{i}.sh".format(prefix),
**default_kwargs)
|
03b685055037283279394d940602520c5ff7a817 | email_log/models.py | email_log/models.py | from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
@python_2_unicode_compatible
class Email(models.Model):
"""Model to store outgoing email information"""
from_email = models.TextField(_("from e-mail"))
recipients = models.TextField(_("recipients"))
subject = models.TextField(_("subject"))
body = models.TextField(_("body"))
ok = models.BooleanField(_("ok"), default=False, db_index=True)
date_sent = models.DateTimeField(_("date sent"), auto_now_add=True, db_index=True)
def __str__(self):
return "{s.recipients}: {s.subject}".format(s=self)
class Meta:
verbose_name = _("e-mail")
verbose_name_plural = _("e-mails")
ordering = ('-date_sent',)
| from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
@python_2_unicode_compatible
class Email(models.Model):
"""Model to store outgoing email information"""
from_email = models.TextField(_("from e-mail"))
recipients = models.TextField(_("recipients"))
subject = models.TextField(_("subject"))
body = models.TextField(_("body"))
ok = models.BooleanField(_("ok"), default=False, db_index=True)
date_sent = models.DateTimeField(_("date sent"), auto_now_add=True,
db_index=True)
def __str__(self):
return "{s.recipients}: {s.subject}".format(s=self)
class Meta:
verbose_name = _("e-mail")
verbose_name_plural = _("e-mails")
ordering = ('-date_sent',)
| Fix indentation problem and line length (PEP8) | Fix indentation problem and line length (PEP8)
| Python | mit | treyhunner/django-email-log,treyhunner/django-email-log | from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
@python_2_unicode_compatible
class Email(models.Model):
"""Model to store outgoing email information"""
from_email = models.TextField(_("from e-mail"))
recipients = models.TextField(_("recipients"))
subject = models.TextField(_("subject"))
body = models.TextField(_("body"))
ok = models.BooleanField(_("ok"), default=False, db_index=True)
- date_sent = models.DateTimeField(_("date sent"), auto_now_add=True, db_index=True)
+ date_sent = models.DateTimeField(_("date sent"), auto_now_add=True,
+ db_index=True)
def __str__(self):
return "{s.recipients}: {s.subject}".format(s=self)
class Meta:
- verbose_name = _("e-mail")
+ verbose_name = _("e-mail")
- verbose_name_plural = _("e-mails")
+ verbose_name_plural = _("e-mails")
ordering = ('-date_sent',)
- | Fix indentation problem and line length (PEP8) | ## Code Before:
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
@python_2_unicode_compatible
class Email(models.Model):
"""Model to store outgoing email information"""
from_email = models.TextField(_("from e-mail"))
recipients = models.TextField(_("recipients"))
subject = models.TextField(_("subject"))
body = models.TextField(_("body"))
ok = models.BooleanField(_("ok"), default=False, db_index=True)
date_sent = models.DateTimeField(_("date sent"), auto_now_add=True, db_index=True)
def __str__(self):
return "{s.recipients}: {s.subject}".format(s=self)
class Meta:
verbose_name = _("e-mail")
verbose_name_plural = _("e-mails")
ordering = ('-date_sent',)
## Instruction:
Fix indentation problem and line length (PEP8)
## Code After:
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
@python_2_unicode_compatible
class Email(models.Model):
"""Model to store outgoing email information"""
from_email = models.TextField(_("from e-mail"))
recipients = models.TextField(_("recipients"))
subject = models.TextField(_("subject"))
body = models.TextField(_("body"))
ok = models.BooleanField(_("ok"), default=False, db_index=True)
date_sent = models.DateTimeField(_("date sent"), auto_now_add=True,
db_index=True)
def __str__(self):
return "{s.recipients}: {s.subject}".format(s=self)
class Meta:
verbose_name = _("e-mail")
verbose_name_plural = _("e-mails")
ordering = ('-date_sent',)
|
b25164e69d255beae1a76a9e1f7168a436a81f38 | tests/test_utils.py | tests/test_utils.py | import helper
from rock import utils
class UtilsTestCase(helper.unittest.TestCase):
def test_shell(self):
utils.Shell.run = lambda self: self
s = utils.Shell()
self.assertTrue(isinstance(s.__enter__(), utils.Shell))
s.write('ok')
s.__exit__(None, None, None)
self.assertEqual(s.stdin.getvalue(), 'ok\n')
def execl(*args):
self.assertEqual(len(args), 4)
self.assertEqual(args[0], '/bin/bash')
self.assertEqual(args[1], '-l')
self.assertEqual(args[2], '-c')
self.assertEqual(args[3], 'ok\n')
utils.os.execl = execl
s.__exit__('type', 'value', 'tracebook')
| import helper
from rock import utils
from rock.exceptions import ConfigError
class UtilsTestCase(helper.unittest.TestCase):
def test_shell(self):
utils.Shell.run = lambda self: self
s = utils.Shell()
self.assertTrue(isinstance(s.__enter__(), utils.Shell))
s.write('ok')
s.__exit__(None, None, None)
self.assertEqual(s.stdin.getvalue(), 'ok\n')
def execl(*args):
self.assertEqual(len(args), 4)
self.assertEqual(args[0], '/bin/bash')
self.assertEqual(args[1], '-l')
self.assertEqual(args[2], '-c')
self.assertEqual(args[3], 'ok\n')
utils.os.execl = execl
s.__exit__('type', 'value', 'tracebook')
def test_noshell(self):
utils.ROCK_SHELL = '/tmp/hopefully-no-exists'
s = utils.Shell()
s.__enter__()
self.assertRaises(ConfigError, s.__exit__, 'type', 'value', 'tracebook')
| Test isexecutable check in utils.Shell | Test isexecutable check in utils.Shell
| Python | mit | silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock | import helper
from rock import utils
+ from rock.exceptions import ConfigError
class UtilsTestCase(helper.unittest.TestCase):
def test_shell(self):
utils.Shell.run = lambda self: self
s = utils.Shell()
self.assertTrue(isinstance(s.__enter__(), utils.Shell))
s.write('ok')
s.__exit__(None, None, None)
self.assertEqual(s.stdin.getvalue(), 'ok\n')
def execl(*args):
self.assertEqual(len(args), 4)
self.assertEqual(args[0], '/bin/bash')
self.assertEqual(args[1], '-l')
self.assertEqual(args[2], '-c')
self.assertEqual(args[3], 'ok\n')
utils.os.execl = execl
s.__exit__('type', 'value', 'tracebook')
+ def test_noshell(self):
+ utils.ROCK_SHELL = '/tmp/hopefully-no-exists'
+ s = utils.Shell()
+ s.__enter__()
+ self.assertRaises(ConfigError, s.__exit__, 'type', 'value', 'tracebook')
+ | Test isexecutable check in utils.Shell | ## Code Before:
import helper
from rock import utils
class UtilsTestCase(helper.unittest.TestCase):
def test_shell(self):
utils.Shell.run = lambda self: self
s = utils.Shell()
self.assertTrue(isinstance(s.__enter__(), utils.Shell))
s.write('ok')
s.__exit__(None, None, None)
self.assertEqual(s.stdin.getvalue(), 'ok\n')
def execl(*args):
self.assertEqual(len(args), 4)
self.assertEqual(args[0], '/bin/bash')
self.assertEqual(args[1], '-l')
self.assertEqual(args[2], '-c')
self.assertEqual(args[3], 'ok\n')
utils.os.execl = execl
s.__exit__('type', 'value', 'tracebook')
## Instruction:
Test isexecutable check in utils.Shell
## Code After:
import helper
from rock import utils
from rock.exceptions import ConfigError
class UtilsTestCase(helper.unittest.TestCase):
def test_shell(self):
utils.Shell.run = lambda self: self
s = utils.Shell()
self.assertTrue(isinstance(s.__enter__(), utils.Shell))
s.write('ok')
s.__exit__(None, None, None)
self.assertEqual(s.stdin.getvalue(), 'ok\n')
def execl(*args):
self.assertEqual(len(args), 4)
self.assertEqual(args[0], '/bin/bash')
self.assertEqual(args[1], '-l')
self.assertEqual(args[2], '-c')
self.assertEqual(args[3], 'ok\n')
utils.os.execl = execl
s.__exit__('type', 'value', 'tracebook')
def test_noshell(self):
utils.ROCK_SHELL = '/tmp/hopefully-no-exists'
s = utils.Shell()
s.__enter__()
self.assertRaises(ConfigError, s.__exit__, 'type', 'value', 'tracebook')
|
fc14e41432fece7d724aef73dd8ad7fef5e85c9a | flow/__init__.py | flow/__init__.py | from model import BaseModel
from feature import Feature,JSONFeature,TextFeature,CompressedFeature,PickleFeature
from extractor import Node,Graph,Aggregator,NotEnoughData
from bytestream import ByteStream,ByteStreamFeature
from data import \
IdProvider,UuidProvider,UserSpecifiedIdProvider,KeyBuilder\
,StringDelimitedKeyBuilder,Database,DataWriter\
,FileSystemDatabase,InMemoryDatabase
from dependency_injection import Registry,dependency,register
from nmpy import StreamingNumpyDecoder, NumpyMetaData
from database_iterator import DatabaseIterator
from decoder import Decoder
from lmdbstore import LmdbDatabase | from model import BaseModel
from feature import Feature,JSONFeature,TextFeature,CompressedFeature,PickleFeature
from extractor import Node,Graph,Aggregator,NotEnoughData
from bytestream import ByteStream,ByteStreamFeature
from data import \
IdProvider,UuidProvider,UserSpecifiedIdProvider,KeyBuilder\
,StringDelimitedKeyBuilder,Database,DataWriter\
,FileSystemDatabase,InMemoryDatabase
from dependency_injection import Registry,dependency,register
from nmpy import StreamingNumpyDecoder, NumpyMetaData
from database_iterator import DatabaseIterator
from encoder import IdentityEncoder
from decoder import Decoder
from lmdbstore import LmdbDatabase | Add IdentityEncoder to top-level exports | Add IdentityEncoder to top-level exports
| Python | mit | JohnVinyard/featureflow,JohnVinyard/featureflow | from model import BaseModel
from feature import Feature,JSONFeature,TextFeature,CompressedFeature,PickleFeature
from extractor import Node,Graph,Aggregator,NotEnoughData
from bytestream import ByteStream,ByteStreamFeature
from data import \
IdProvider,UuidProvider,UserSpecifiedIdProvider,KeyBuilder\
,StringDelimitedKeyBuilder,Database,DataWriter\
,FileSystemDatabase,InMemoryDatabase
from dependency_injection import Registry,dependency,register
from nmpy import StreamingNumpyDecoder, NumpyMetaData
from database_iterator import DatabaseIterator
+ from encoder import IdentityEncoder
+
from decoder import Decoder
from lmdbstore import LmdbDatabase | Add IdentityEncoder to top-level exports | ## Code Before:
from model import BaseModel
from feature import Feature,JSONFeature,TextFeature,CompressedFeature,PickleFeature
from extractor import Node,Graph,Aggregator,NotEnoughData
from bytestream import ByteStream,ByteStreamFeature
from data import \
IdProvider,UuidProvider,UserSpecifiedIdProvider,KeyBuilder\
,StringDelimitedKeyBuilder,Database,DataWriter\
,FileSystemDatabase,InMemoryDatabase
from dependency_injection import Registry,dependency,register
from nmpy import StreamingNumpyDecoder, NumpyMetaData
from database_iterator import DatabaseIterator
from decoder import Decoder
from lmdbstore import LmdbDatabase
## Instruction:
Add IdentityEncoder to top-level exports
## Code After:
from model import BaseModel
from feature import Feature,JSONFeature,TextFeature,CompressedFeature,PickleFeature
from extractor import Node,Graph,Aggregator,NotEnoughData
from bytestream import ByteStream,ByteStreamFeature
from data import \
IdProvider,UuidProvider,UserSpecifiedIdProvider,KeyBuilder\
,StringDelimitedKeyBuilder,Database,DataWriter\
,FileSystemDatabase,InMemoryDatabase
from dependency_injection import Registry,dependency,register
from nmpy import StreamingNumpyDecoder, NumpyMetaData
from database_iterator import DatabaseIterator
from encoder import IdentityEncoder
from decoder import Decoder
from lmdbstore import LmdbDatabase |
ff4477c870b9c618b7432047071792c3a8055eb7 | coffeeraspi/messages.py | coffeeraspi/messages.py | class DrinkOrder():
def __init__(self, mug_size, add_ins, name=None):
self.mug_size = mug_size
self.add_ins = add_ins
self.name = name
@classmethod
def deserialize(cls, data):
return DrinkOrder(data['mug_size'],
data['add_ins'],
data.get('name', None))
| class DrinkOrder():
def __init__(self, mug_size, add_ins, name=None):
self.mug_size = mug_size
self.add_ins = add_ins
self.name = name
@classmethod
def deserialize(cls, data):
return DrinkOrder(data['mug_size'],
data['add_ins'],
data.get('name', None))
def __str__(self):
return 'DrinkOrder("{}")'.format(self.name if self.name else '')
| Add nicer drink order logging | Add nicer drink order logging
| Python | apache-2.0 | umbc-hackafe/htcpcp,umbc-hackafe/htcpcp,umbc-hackafe/htcpcp,umbc-hackafe/htcpcp | class DrinkOrder():
def __init__(self, mug_size, add_ins, name=None):
self.mug_size = mug_size
self.add_ins = add_ins
self.name = name
@classmethod
def deserialize(cls, data):
return DrinkOrder(data['mug_size'],
data['add_ins'],
data.get('name', None))
+ def __str__(self):
+ return 'DrinkOrder("{}")'.format(self.name if self.name else '')
+ | Add nicer drink order logging | ## Code Before:
class DrinkOrder():
def __init__(self, mug_size, add_ins, name=None):
self.mug_size = mug_size
self.add_ins = add_ins
self.name = name
@classmethod
def deserialize(cls, data):
return DrinkOrder(data['mug_size'],
data['add_ins'],
data.get('name', None))
## Instruction:
Add nicer drink order logging
## Code After:
class DrinkOrder():
def __init__(self, mug_size, add_ins, name=None):
self.mug_size = mug_size
self.add_ins = add_ins
self.name = name
@classmethod
def deserialize(cls, data):
return DrinkOrder(data['mug_size'],
data['add_ins'],
data.get('name', None))
def __str__(self):
return 'DrinkOrder("{}")'.format(self.name if self.name else '')
|
58be36ca646c4bb7fd4263a592cf3a240fbca64f | post_tag.py | post_tag.py |
from common import init, globaldata, tag_clean, tag_prefix, tag_post, tagtypes
from bottle import post, request, redirect, mako_view as view
@post("/post-tag")
@view("post-tag")
def r_post_tag():
client = init()
m = request.forms.post
post = client.get_post(m)
tags = request.forms.tags
create = request.forms.getall("create")
ctype = request.forms.getall("ctype")
full = set()
weak = set()
remove = set()
failed = []
for n, t in zip(create, ctype):
if t:
client.add_tag(tag_clean(n), t)
tags += u' ' + n
for t in tags.split():
tag = client.find_tag(tag_clean(t))
if tag:
p = tag_prefix(t)
if p == "~":
weak.add(tag)
elif p == "-":
remove.add(tag)
else:
full.add(tag)
else:
failed.append(t)
tag_post(post, full, weak, remove)
if not failed:
redirect("post/" + m)
data = globaldata()
data.tagtypes = tagtypes()
data.failed = failed
data.m = m
return data
|
from common import init, globaldata, tag_clean, tag_prefix, tag_post, tagtypes
from bottle import post, request, redirect, mako_view as view
@post("/post-tag")
@view("post-tag")
def r_post_tag():
client = init()
m = request.forms.post
post = client.get_post(m)
tags = request.forms.tags
create = [a.decode("utf-8") for a in request.forms.getall("create")]
ctype = [a.decode("utf-8") for a in request.forms.getall("ctype")]
full = set()
weak = set()
remove = set()
failed = []
for n, t in zip(create, ctype):
if t:
client.add_tag(tag_clean(n), t)
tags += u' ' + n
for t in tags.split():
tag = client.find_tag(tag_clean(t))
if tag:
p = tag_prefix(t)
if p == "~":
weak.add(tag)
elif p == "-":
remove.add(tag)
else:
full.add(tag)
else:
failed.append(t)
tag_post(post, full, weak, remove)
if not failed:
redirect("post/" + m)
data = globaldata()
data.tagtypes = tagtypes()
data.failed = failed
data.m = m
return data
| Fix tag creation with non-ascii chars. (Dammit bottle!) | Fix tag creation with non-ascii chars. (Dammit bottle!)
| Python | mit | drougge/wwwwellpapp,drougge/wwwwellpapp,drougge/wwwwellpapp |
from common import init, globaldata, tag_clean, tag_prefix, tag_post, tagtypes
from bottle import post, request, redirect, mako_view as view
@post("/post-tag")
@view("post-tag")
def r_post_tag():
client = init()
m = request.forms.post
post = client.get_post(m)
tags = request.forms.tags
- create = request.forms.getall("create")
- ctype = request.forms.getall("ctype")
+ create = [a.decode("utf-8") for a in request.forms.getall("create")]
+ ctype = [a.decode("utf-8") for a in request.forms.getall("ctype")]
full = set()
weak = set()
remove = set()
failed = []
for n, t in zip(create, ctype):
if t:
client.add_tag(tag_clean(n), t)
tags += u' ' + n
for t in tags.split():
tag = client.find_tag(tag_clean(t))
if tag:
p = tag_prefix(t)
if p == "~":
weak.add(tag)
elif p == "-":
remove.add(tag)
else:
full.add(tag)
else:
failed.append(t)
tag_post(post, full, weak, remove)
if not failed:
redirect("post/" + m)
data = globaldata()
data.tagtypes = tagtypes()
data.failed = failed
data.m = m
return data
| Fix tag creation with non-ascii chars. (Dammit bottle!) | ## Code Before:
from common import init, globaldata, tag_clean, tag_prefix, tag_post, tagtypes
from bottle import post, request, redirect, mako_view as view
@post("/post-tag")
@view("post-tag")
def r_post_tag():
client = init()
m = request.forms.post
post = client.get_post(m)
tags = request.forms.tags
create = request.forms.getall("create")
ctype = request.forms.getall("ctype")
full = set()
weak = set()
remove = set()
failed = []
for n, t in zip(create, ctype):
if t:
client.add_tag(tag_clean(n), t)
tags += u' ' + n
for t in tags.split():
tag = client.find_tag(tag_clean(t))
if tag:
p = tag_prefix(t)
if p == "~":
weak.add(tag)
elif p == "-":
remove.add(tag)
else:
full.add(tag)
else:
failed.append(t)
tag_post(post, full, weak, remove)
if not failed:
redirect("post/" + m)
data = globaldata()
data.tagtypes = tagtypes()
data.failed = failed
data.m = m
return data
## Instruction:
Fix tag creation with non-ascii chars. (Dammit bottle!)
## Code After:
from common import init, globaldata, tag_clean, tag_prefix, tag_post, tagtypes
from bottle import post, request, redirect, mako_view as view
@post("/post-tag")
@view("post-tag")
def r_post_tag():
client = init()
m = request.forms.post
post = client.get_post(m)
tags = request.forms.tags
create = [a.decode("utf-8") for a in request.forms.getall("create")]
ctype = [a.decode("utf-8") for a in request.forms.getall("ctype")]
full = set()
weak = set()
remove = set()
failed = []
for n, t in zip(create, ctype):
if t:
client.add_tag(tag_clean(n), t)
tags += u' ' + n
for t in tags.split():
tag = client.find_tag(tag_clean(t))
if tag:
p = tag_prefix(t)
if p == "~":
weak.add(tag)
elif p == "-":
remove.add(tag)
else:
full.add(tag)
else:
failed.append(t)
tag_post(post, full, weak, remove)
if not failed:
redirect("post/" + m)
data = globaldata()
data.tagtypes = tagtypes()
data.failed = failed
data.m = m
return data
|
bb32f2327d2e3aa386fffd2fd320a7af7b03ce95 | corehq/apps/domain/project_access/middleware.py | corehq/apps/domain/project_access/middleware.py | from __future__ import absolute_import
from __future__ import unicode_literals
from datetime import datetime, timedelta
from django.utils.deprecation import MiddlewareMixin
from corehq.apps.domain.project_access.models import SuperuserProjectEntryRecord, ENTRY_RECORD_FREQUENCY
from corehq.util.quickcache import quickcache
from corehq.apps.users.tasks import update_domain_date
class ProjectAccessMiddleware(MiddlewareMixin):
def process_view(self, request, view_func, view_args, view_kwargs):
if getattr(request, 'couch_user', None) and request.couch_user.is_superuser \
and hasattr(request, 'domain'):
return self.record_entry(request.domain, request.couch_user.username)
if getattr(request, 'couch_user', None) and request.couch_user.is_web_user() \
and hasattr(request, 'domain'):
self.record_web_user_entry(request.couch_user, request.domain)
@quickcache(['domain', 'username'], timeout=ENTRY_RECORD_FREQUENCY.seconds)
def record_entry(self, domain, username):
if not SuperuserProjectEntryRecord.entry_recently_recorded(username, domain):
SuperuserProjectEntryRecord.record_entry(username, domain)
return None
@staticmethod
def record_web_user_entry(user, domain):
yesterday = datetime.today() - timedelta(hours=24)
if domain not in user.domains_accessed or user.domains_accessed[domain] < yesterday:
update_domain_date.delay(user, domain)
| from __future__ import absolute_import
from __future__ import unicode_literals
from datetime import datetime, timedelta
from django.utils.deprecation import MiddlewareMixin
from corehq.apps.domain.project_access.models import SuperuserProjectEntryRecord, ENTRY_RECORD_FREQUENCY
from corehq.util.quickcache import quickcache
from corehq.apps.users.tasks import update_domain_date
class ProjectAccessMiddleware(MiddlewareMixin):
def process_view(self, request, view_func, view_args, view_kwargs):
if getattr(request, 'couch_user', None) and request.couch_user.is_superuser \
and hasattr(request, 'domain'):
self.record_superuser_entry(request.domain, request.couch_user.username)
if getattr(request, 'couch_user', None) and request.couch_user.is_web_user() \
and hasattr(request, 'domain'):
self.record_web_user_entry(request.couch_user, request.domain)
@quickcache(['domain', 'username'], timeout=ENTRY_RECORD_FREQUENCY.seconds)
def record_superuser_entry(self, domain, username):
if not SuperuserProjectEntryRecord.entry_recently_recorded(username, domain):
SuperuserProjectEntryRecord.record_entry(username, domain)
return None
@staticmethod
def record_web_user_entry(user, domain):
yesterday = datetime.today() - timedelta(hours=24)
if domain not in user.domains_accessed or user.domains_accessed[domain] < yesterday:
update_domain_date.delay(user, domain)
| Include superusers in web user domaing access record | Include superusers in web user domaing access record
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | from __future__ import absolute_import
from __future__ import unicode_literals
from datetime import datetime, timedelta
from django.utils.deprecation import MiddlewareMixin
from corehq.apps.domain.project_access.models import SuperuserProjectEntryRecord, ENTRY_RECORD_FREQUENCY
from corehq.util.quickcache import quickcache
from corehq.apps.users.tasks import update_domain_date
class ProjectAccessMiddleware(MiddlewareMixin):
def process_view(self, request, view_func, view_args, view_kwargs):
if getattr(request, 'couch_user', None) and request.couch_user.is_superuser \
and hasattr(request, 'domain'):
- return self.record_entry(request.domain, request.couch_user.username)
+ self.record_superuser_entry(request.domain, request.couch_user.username)
if getattr(request, 'couch_user', None) and request.couch_user.is_web_user() \
and hasattr(request, 'domain'):
self.record_web_user_entry(request.couch_user, request.domain)
@quickcache(['domain', 'username'], timeout=ENTRY_RECORD_FREQUENCY.seconds)
- def record_entry(self, domain, username):
+ def record_superuser_entry(self, domain, username):
if not SuperuserProjectEntryRecord.entry_recently_recorded(username, domain):
SuperuserProjectEntryRecord.record_entry(username, domain)
return None
@staticmethod
def record_web_user_entry(user, domain):
yesterday = datetime.today() - timedelta(hours=24)
if domain not in user.domains_accessed or user.domains_accessed[domain] < yesterday:
update_domain_date.delay(user, domain)
| Include superusers in web user domaing access record | ## Code Before:
from __future__ import absolute_import
from __future__ import unicode_literals
from datetime import datetime, timedelta
from django.utils.deprecation import MiddlewareMixin
from corehq.apps.domain.project_access.models import SuperuserProjectEntryRecord, ENTRY_RECORD_FREQUENCY
from corehq.util.quickcache import quickcache
from corehq.apps.users.tasks import update_domain_date
class ProjectAccessMiddleware(MiddlewareMixin):
def process_view(self, request, view_func, view_args, view_kwargs):
if getattr(request, 'couch_user', None) and request.couch_user.is_superuser \
and hasattr(request, 'domain'):
return self.record_entry(request.domain, request.couch_user.username)
if getattr(request, 'couch_user', None) and request.couch_user.is_web_user() \
and hasattr(request, 'domain'):
self.record_web_user_entry(request.couch_user, request.domain)
@quickcache(['domain', 'username'], timeout=ENTRY_RECORD_FREQUENCY.seconds)
def record_entry(self, domain, username):
if not SuperuserProjectEntryRecord.entry_recently_recorded(username, domain):
SuperuserProjectEntryRecord.record_entry(username, domain)
return None
@staticmethod
def record_web_user_entry(user, domain):
yesterday = datetime.today() - timedelta(hours=24)
if domain not in user.domains_accessed or user.domains_accessed[domain] < yesterday:
update_domain_date.delay(user, domain)
## Instruction:
Include superusers in web user domaing access record
## Code After:
from __future__ import absolute_import
from __future__ import unicode_literals
from datetime import datetime, timedelta
from django.utils.deprecation import MiddlewareMixin
from corehq.apps.domain.project_access.models import SuperuserProjectEntryRecord, ENTRY_RECORD_FREQUENCY
from corehq.util.quickcache import quickcache
from corehq.apps.users.tasks import update_domain_date
class ProjectAccessMiddleware(MiddlewareMixin):
def process_view(self, request, view_func, view_args, view_kwargs):
if getattr(request, 'couch_user', None) and request.couch_user.is_superuser \
and hasattr(request, 'domain'):
self.record_superuser_entry(request.domain, request.couch_user.username)
if getattr(request, 'couch_user', None) and request.couch_user.is_web_user() \
and hasattr(request, 'domain'):
self.record_web_user_entry(request.couch_user, request.domain)
@quickcache(['domain', 'username'], timeout=ENTRY_RECORD_FREQUENCY.seconds)
def record_superuser_entry(self, domain, username):
if not SuperuserProjectEntryRecord.entry_recently_recorded(username, domain):
SuperuserProjectEntryRecord.record_entry(username, domain)
return None
@staticmethod
def record_web_user_entry(user, domain):
yesterday = datetime.today() - timedelta(hours=24)
if domain not in user.domains_accessed or user.domains_accessed[domain] < yesterday:
update_domain_date.delay(user, domain)
|
d9f20935f6a0d5bf4e2c1dd1a3c5b41167f8518b | email_log/migrations/0001_initial.py | email_log/migrations/0001_initial.py | from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Email',
fields=[
(u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=True, primary_key=True)),
('from_email', models.TextField(verbose_name=u'from e-mail')),
('recipients', models.TextField(verbose_name=u'recipients')),
('subject', models.TextField(verbose_name=u'subject')),
('body', models.TextField(verbose_name=u'body')),
('ok', models.BooleanField(default=False, db_index=True, verbose_name=u'ok')),
('date_sent', models.DateTimeField(auto_now_add=True, verbose_name=u'date sent', db_index=True)),
],
options={
u'ordering': (u'-date_sent',),
u'verbose_name': u'e-mail',
u'verbose_name_plural': u'e-mails',
},
bases=(models.Model,),
),
]
| from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Email',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False,
auto_created=True, primary_key=True)),
('from_email', models.TextField(verbose_name='from e-mail')),
('recipients', models.TextField(verbose_name='recipients')),
('subject', models.TextField(verbose_name='subject')),
('body', models.TextField(verbose_name='body')),
('ok', models.BooleanField(default=False, db_index=True,
verbose_name='ok')),
('date_sent', models.DateTimeField(auto_now_add=True,
verbose_name='date sent',
db_index=True)),
],
options={
'ordering': ('-date_sent',),
'verbose_name': 'e-mail',
'verbose_name_plural': 'e-mails',
},
bases=(models.Model,),
),
]
| Fix migration file for Python 3.2 (and PEP8) | Fix migration file for Python 3.2 (and PEP8)
| Python | mit | treyhunner/django-email-log,treyhunner/django-email-log | from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Email',
fields=[
- (u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=True, primary_key=True)),
+ ('id', models.AutoField(verbose_name='ID', serialize=False,
+ auto_created=True, primary_key=True)),
- ('from_email', models.TextField(verbose_name=u'from e-mail')),
+ ('from_email', models.TextField(verbose_name='from e-mail')),
- ('recipients', models.TextField(verbose_name=u'recipients')),
+ ('recipients', models.TextField(verbose_name='recipients')),
- ('subject', models.TextField(verbose_name=u'subject')),
+ ('subject', models.TextField(verbose_name='subject')),
- ('body', models.TextField(verbose_name=u'body')),
+ ('body', models.TextField(verbose_name='body')),
- ('ok', models.BooleanField(default=False, db_index=True, verbose_name=u'ok')),
+ ('ok', models.BooleanField(default=False, db_index=True,
+ verbose_name='ok')),
- ('date_sent', models.DateTimeField(auto_now_add=True, verbose_name=u'date sent', db_index=True)),
+ ('date_sent', models.DateTimeField(auto_now_add=True,
+ verbose_name='date sent',
+ db_index=True)),
],
options={
- u'ordering': (u'-date_sent',),
+ 'ordering': ('-date_sent',),
- u'verbose_name': u'e-mail',
+ 'verbose_name': 'e-mail',
- u'verbose_name_plural': u'e-mails',
+ 'verbose_name_plural': 'e-mails',
},
bases=(models.Model,),
),
]
| Fix migration file for Python 3.2 (and PEP8) | ## Code Before:
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Email',
fields=[
(u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=True, primary_key=True)),
('from_email', models.TextField(verbose_name=u'from e-mail')),
('recipients', models.TextField(verbose_name=u'recipients')),
('subject', models.TextField(verbose_name=u'subject')),
('body', models.TextField(verbose_name=u'body')),
('ok', models.BooleanField(default=False, db_index=True, verbose_name=u'ok')),
('date_sent', models.DateTimeField(auto_now_add=True, verbose_name=u'date sent', db_index=True)),
],
options={
u'ordering': (u'-date_sent',),
u'verbose_name': u'e-mail',
u'verbose_name_plural': u'e-mails',
},
bases=(models.Model,),
),
]
## Instruction:
Fix migration file for Python 3.2 (and PEP8)
## Code After:
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Email',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False,
auto_created=True, primary_key=True)),
('from_email', models.TextField(verbose_name='from e-mail')),
('recipients', models.TextField(verbose_name='recipients')),
('subject', models.TextField(verbose_name='subject')),
('body', models.TextField(verbose_name='body')),
('ok', models.BooleanField(default=False, db_index=True,
verbose_name='ok')),
('date_sent', models.DateTimeField(auto_now_add=True,
verbose_name='date sent',
db_index=True)),
],
options={
'ordering': ('-date_sent',),
'verbose_name': 'e-mail',
'verbose_name_plural': 'e-mails',
},
bases=(models.Model,),
),
]
|