commit
stringlengths 40
40
| old_file
stringlengths 4
118
| new_file
stringlengths 4
118
| old_contents
stringlengths 10
2.94k
| new_contents
stringlengths 21
3.18k
| subject
stringlengths 16
444
| message
stringlengths 17
2.63k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 5
43k
| ndiff
stringlengths 52
3.32k
| instruction
stringlengths 16
444
| content
stringlengths 133
4.32k
| fuzzy_diff
stringlengths 16
3.18k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2800e2cf0a7a998a5081929e6750265f30b09130 | tests/test_bql.py | tests/test_bql.py |
import StringIO
import bayeslite.bql as bql
import bayeslite.parse as parse
import test_smoke
def bql2sql(string):
with test_smoke.t1() as bdb:
phrases = parse.parse_bql_string(string)
out = StringIO.StringIO()
bql.compile_bql(bdb, phrases, out)
return out.getvalue()
def test_select_trivial():
assert bql2sql('select 0;') == 'select 0;'
|
import StringIO
import bayeslite.bql as bql
import bayeslite.parse as parse
import test_smoke
def bql2sql(string):
with test_smoke.t1() as bdb:
phrases = parse.parse_bql_string(string)
out = StringIO.StringIO()
bql.compile_bql(bdb, phrases, out)
return out.getvalue()
def test_select_trivial():
assert bql2sql('select 0;') == 'select 0;'
assert bql2sql('select 0 as z;') == 'select 0 as "z";'
assert bql2sql('select * from t;') == 'select * from "t";'
assert bql2sql('select t.* from t;') == 'select "t".* from "t";'
assert bql2sql('select c from t;') == 'select "c" from "t";'
assert bql2sql('select c as d from t;') == 'select "c" as "d" from "t";'
| Add some more trivial bql2sql tests. | Add some more trivial bql2sql tests.
| Python | apache-2.0 | probcomp/bayeslite,probcomp/bayeslite |
import StringIO
import bayeslite.bql as bql
import bayeslite.parse as parse
import test_smoke
def bql2sql(string):
with test_smoke.t1() as bdb:
phrases = parse.parse_bql_string(string)
out = StringIO.StringIO()
bql.compile_bql(bdb, phrases, out)
return out.getvalue()
def test_select_trivial():
assert bql2sql('select 0;') == 'select 0;'
+ assert bql2sql('select 0 as z;') == 'select 0 as "z";'
+ assert bql2sql('select * from t;') == 'select * from "t";'
+ assert bql2sql('select t.* from t;') == 'select "t".* from "t";'
+ assert bql2sql('select c from t;') == 'select "c" from "t";'
+ assert bql2sql('select c as d from t;') == 'select "c" as "d" from "t";'
| Add some more trivial bql2sql tests. | ## Code Before:
import StringIO
import bayeslite.bql as bql
import bayeslite.parse as parse
import test_smoke
def bql2sql(string):
with test_smoke.t1() as bdb:
phrases = parse.parse_bql_string(string)
out = StringIO.StringIO()
bql.compile_bql(bdb, phrases, out)
return out.getvalue()
def test_select_trivial():
assert bql2sql('select 0;') == 'select 0;'
## Instruction:
Add some more trivial bql2sql tests.
## Code After:
import StringIO
import bayeslite.bql as bql
import bayeslite.parse as parse
import test_smoke
def bql2sql(string):
with test_smoke.t1() as bdb:
phrases = parse.parse_bql_string(string)
out = StringIO.StringIO()
bql.compile_bql(bdb, phrases, out)
return out.getvalue()
def test_select_trivial():
assert bql2sql('select 0;') == 'select 0;'
assert bql2sql('select 0 as z;') == 'select 0 as "z";'
assert bql2sql('select * from t;') == 'select * from "t";'
assert bql2sql('select t.* from t;') == 'select "t".* from "t";'
assert bql2sql('select c from t;') == 'select "c" from "t";'
assert bql2sql('select c as d from t;') == 'select "c" as "d" from "t";'
| # ... existing code ...
assert bql2sql('select 0;') == 'select 0;'
assert bql2sql('select 0 as z;') == 'select 0 as "z";'
assert bql2sql('select * from t;') == 'select * from "t";'
assert bql2sql('select t.* from t;') == 'select "t".* from "t";'
assert bql2sql('select c from t;') == 'select "c" from "t";'
assert bql2sql('select c as d from t;') == 'select "c" as "d" from "t";'
# ... rest of the code ... |
be127957f35a4673c95a81884adf3484943af079 | future/tests/test_imports_urllib.py | future/tests/test_imports_urllib.py | import unittest
import sys
print([m for m in sys.modules if m.startswith('urllib')])
class MyTest(unittest.TestCase):
def test_urllib(self):
import urllib
print(urllib.__file__)
from future import standard_library
with standard_library.hooks():
import urllib.response
print(urllib.__file__)
print(urllib.response.__file__)
unittest.main()
| from __future__ import absolute_import, print_function
import unittest
import sys
print([m for m in sys.modules if m.startswith('urllib')])
class MyTest(unittest.TestCase):
def test_urllib(self):
import urllib
print(urllib.__file__)
from future import standard_library
with standard_library.hooks():
import urllib.response
print(urllib.__file__)
print(urllib.response.__file__)
unittest.main()
| Tweak to a noisy test module | Tweak to a noisy test module
| Python | mit | krischer/python-future,michaelpacer/python-future,krischer/python-future,michaelpacer/python-future,QuLogic/python-future,QuLogic/python-future,PythonCharmers/python-future,PythonCharmers/python-future | + from __future__ import absolute_import, print_function
+
import unittest
import sys
print([m for m in sys.modules if m.startswith('urllib')])
class MyTest(unittest.TestCase):
def test_urllib(self):
import urllib
print(urllib.__file__)
from future import standard_library
with standard_library.hooks():
import urllib.response
print(urllib.__file__)
print(urllib.response.__file__)
unittest.main()
| Tweak to a noisy test module | ## Code Before:
import unittest
import sys
print([m for m in sys.modules if m.startswith('urllib')])
class MyTest(unittest.TestCase):
def test_urllib(self):
import urllib
print(urllib.__file__)
from future import standard_library
with standard_library.hooks():
import urllib.response
print(urllib.__file__)
print(urllib.response.__file__)
unittest.main()
## Instruction:
Tweak to a noisy test module
## Code After:
from __future__ import absolute_import, print_function
import unittest
import sys
print([m for m in sys.modules if m.startswith('urllib')])
class MyTest(unittest.TestCase):
def test_urllib(self):
import urllib
print(urllib.__file__)
from future import standard_library
with standard_library.hooks():
import urllib.response
print(urllib.__file__)
print(urllib.response.__file__)
unittest.main()
| // ... existing code ...
from __future__ import absolute_import, print_function
import unittest
// ... rest of the code ... |
2cc8a541814cc353e7b60767afd2128dce38918a | tests/test_plugins/test_plugin/server.py | tests/test_plugins/test_plugin/server.py |
from girder.api import access
from girder.api.describe import Description
from girder.api.rest import Resource
class CustomAppRoot(object):
"""
The webroot endpoint simply serves the main index HTML file.
"""
exposed = True
def GET(self):
return "hello world"
class Other(Resource):
def __init__(self):
self.resourceName = 'other'
self.route('GET', (), self.getResource)
@access.public
def getResource(self, params):
return ['custom REST route']
getResource.description = Description('Get something.')
def load(info):
info['serverRoot'], info['serverRoot'].girder = CustomAppRoot(), info['serverRoot']
info['serverRoot'].api = info['serverRoot'].girder.api
del info['serverRoot'].girder.api
info['apiRoot'].other = Other()
|
from girder.api import access
from girder.api.describe import Description
from girder.api.rest import Resource
class CustomAppRoot(object):
"""
The webroot endpoint simply serves the main index HTML file.
"""
exposed = True
def GET(self):
return "hello world"
class Other(Resource):
def __init__(self):
self.resourceName = 'other'
self.route('GET', (), self.getResource)
@access.public
def getResource(self, params):
return ['custom REST route']
getResource.description = Description('Get something.')
def load(info):
info['serverRoot'], info['serverRoot'].girder = (
CustomAppRoot(), info['serverRoot'])
info['serverRoot'].api = info['serverRoot'].girder.api
del info['serverRoot'].girder.api
info['apiRoot'].other = Other()
| Fix failing python style test | Fix failing python style test
| Python | apache-2.0 | jbeezley/girder,jcfr/girder,RafaelPalomar/girder,opadron/girder,Kitware/girder,essamjoubori/girder,RafaelPalomar/girder,adsorensen/girder,Xarthisius/girder,adsorensen/girder,data-exp-lab/girder,jcfr/girder,girder/girder,opadron/girder,Xarthisius/girder,data-exp-lab/girder,jcfr/girder,kotfic/girder,manthey/girder,msmolens/girder,salamb/girder,sutartmelson/girder,adsorensen/girder,essamjoubori/girder,data-exp-lab/girder,essamjoubori/girder,chrismattmann/girder,kotfic/girder,opadron/girder,kotfic/girder,Xarthisius/girder,jcfr/girder,data-exp-lab/girder,girder/girder,opadron/girder,girder/girder,manthey/girder,salamb/girder,salamb/girder,adsorensen/girder,kotfic/girder,jbeezley/girder,data-exp-lab/girder,msmolens/girder,msmolens/girder,chrismattmann/girder,essamjoubori/girder,essamjoubori/girder,Kitware/girder,jcfr/girder,Xarthisius/girder,chrismattmann/girder,RafaelPalomar/girder,adsorensen/girder,jbeezley/girder,chrismattmann/girder,sutartmelson/girder,sutartmelson/girder,RafaelPalomar/girder,RafaelPalomar/girder,kotfic/girder,sutartmelson/girder,Xarthisius/girder,Kitware/girder,jbeezley/girder,salamb/girder,manthey/girder,msmolens/girder,chrismattmann/girder,girder/girder,salamb/girder,manthey/girder,sutartmelson/girder,Kitware/girder,opadron/girder,msmolens/girder |
from girder.api import access
from girder.api.describe import Description
from girder.api.rest import Resource
class CustomAppRoot(object):
"""
The webroot endpoint simply serves the main index HTML file.
"""
exposed = True
def GET(self):
return "hello world"
class Other(Resource):
def __init__(self):
self.resourceName = 'other'
self.route('GET', (), self.getResource)
@access.public
def getResource(self, params):
return ['custom REST route']
getResource.description = Description('Get something.')
def load(info):
- info['serverRoot'], info['serverRoot'].girder = CustomAppRoot(), info['serverRoot']
+ info['serverRoot'], info['serverRoot'].girder = (
+ CustomAppRoot(), info['serverRoot'])
info['serverRoot'].api = info['serverRoot'].girder.api
del info['serverRoot'].girder.api
info['apiRoot'].other = Other()
| Fix failing python style test | ## Code Before:
from girder.api import access
from girder.api.describe import Description
from girder.api.rest import Resource
class CustomAppRoot(object):
"""
The webroot endpoint simply serves the main index HTML file.
"""
exposed = True
def GET(self):
return "hello world"
class Other(Resource):
def __init__(self):
self.resourceName = 'other'
self.route('GET', (), self.getResource)
@access.public
def getResource(self, params):
return ['custom REST route']
getResource.description = Description('Get something.')
def load(info):
info['serverRoot'], info['serverRoot'].girder = CustomAppRoot(), info['serverRoot']
info['serverRoot'].api = info['serverRoot'].girder.api
del info['serverRoot'].girder.api
info['apiRoot'].other = Other()
## Instruction:
Fix failing python style test
## Code After:
from girder.api import access
from girder.api.describe import Description
from girder.api.rest import Resource
class CustomAppRoot(object):
"""
The webroot endpoint simply serves the main index HTML file.
"""
exposed = True
def GET(self):
return "hello world"
class Other(Resource):
def __init__(self):
self.resourceName = 'other'
self.route('GET', (), self.getResource)
@access.public
def getResource(self, params):
return ['custom REST route']
getResource.description = Description('Get something.')
def load(info):
info['serverRoot'], info['serverRoot'].girder = (
CustomAppRoot(), info['serverRoot'])
info['serverRoot'].api = info['serverRoot'].girder.api
del info['serverRoot'].girder.api
info['apiRoot'].other = Other()
| // ... existing code ...
def load(info):
info['serverRoot'], info['serverRoot'].girder = (
CustomAppRoot(), info['serverRoot'])
info['serverRoot'].api = info['serverRoot'].girder.api
// ... rest of the code ... |
c3745e7017c1788f4633d09ef4d29a37018b53d3 | populus/cli/main.py | populus/cli/main.py | import click
@click.group()
def main():
"""
Populus
"""
pass
| import click
CONTEXT_SETTINGS = dict(
# Support -h as a shortcut for --help
help_option_names=['-h', '--help'],
)
@click.group(context_settings=CONTEXT_SETTINGS)
def main():
"""
Populus
"""
pass
| Support -h as a shortcut for --help | CLI: Support -h as a shortcut for --help
| Python | mit | pipermerriam/populus,euri10/populus,euri10/populus,pipermerriam/populus,euri10/populus | import click
- @click.group()
+ CONTEXT_SETTINGS = dict(
+ # Support -h as a shortcut for --help
+ help_option_names=['-h', '--help'],
+ )
+
+
+ @click.group(context_settings=CONTEXT_SETTINGS)
def main():
"""
Populus
"""
pass
| Support -h as a shortcut for --help | ## Code Before:
import click
@click.group()
def main():
"""
Populus
"""
pass
## Instruction:
Support -h as a shortcut for --help
## Code After:
import click
CONTEXT_SETTINGS = dict(
# Support -h as a shortcut for --help
help_option_names=['-h', '--help'],
)
@click.group(context_settings=CONTEXT_SETTINGS)
def main():
"""
Populus
"""
pass
| // ... existing code ...
CONTEXT_SETTINGS = dict(
# Support -h as a shortcut for --help
help_option_names=['-h', '--help'],
)
@click.group(context_settings=CONTEXT_SETTINGS)
def main():
// ... rest of the code ... |
e00ad93c1a769a920c7f61eeccec582272766b26 | badgify/templatetags/badgify_tags.py | badgify/templatetags/badgify_tags.py | from django import template
from ..models import Badge, Award
from ..compat import get_user_model
register = template.Library()
@register.assignment_tag
def badgify_badges(**kwargs):
"""
Returns all badges or only awarded badges for the given user.
"""
User = get_user_model()
user = kwargs.get('user', None)
username = kwargs.get('username', None)
if username:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
pass
if user:
awards = Award.objects.filter(user=user)
badges = [award.badge for award in awards]
return badges
return Badge.objects.all()
| from django import template
from ..models import Badge, Award
from ..compat import get_user_model
register = template.Library()
@register.assignment_tag
def badgify_badges(**kwargs):
"""
Returns all badges or only awarded badges for the given user.
"""
User = get_user_model()
user = kwargs.get('user', None)
username = kwargs.get('username', None)
if username:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
pass
if user:
awards = Award.objects.filter(user=user).select_related('badge')
badges = [award.badge for award in awards]
return badges
return Badge.objects.all()
| Add missing select_related to badgify_badges | Add missing select_related to badgify_badges
| Python | mit | ulule/django-badgify,ulule/django-badgify | from django import template
from ..models import Badge, Award
from ..compat import get_user_model
register = template.Library()
@register.assignment_tag
def badgify_badges(**kwargs):
"""
Returns all badges or only awarded badges for the given user.
"""
User = get_user_model()
user = kwargs.get('user', None)
username = kwargs.get('username', None)
if username:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
pass
if user:
- awards = Award.objects.filter(user=user)
+ awards = Award.objects.filter(user=user).select_related('badge')
badges = [award.badge for award in awards]
return badges
return Badge.objects.all()
| Add missing select_related to badgify_badges | ## Code Before:
from django import template
from ..models import Badge, Award
from ..compat import get_user_model
register = template.Library()
@register.assignment_tag
def badgify_badges(**kwargs):
"""
Returns all badges or only awarded badges for the given user.
"""
User = get_user_model()
user = kwargs.get('user', None)
username = kwargs.get('username', None)
if username:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
pass
if user:
awards = Award.objects.filter(user=user)
badges = [award.badge for award in awards]
return badges
return Badge.objects.all()
## Instruction:
Add missing select_related to badgify_badges
## Code After:
from django import template
from ..models import Badge, Award
from ..compat import get_user_model
register = template.Library()
@register.assignment_tag
def badgify_badges(**kwargs):
"""
Returns all badges or only awarded badges for the given user.
"""
User = get_user_model()
user = kwargs.get('user', None)
username = kwargs.get('username', None)
if username:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
pass
if user:
awards = Award.objects.filter(user=user).select_related('badge')
badges = [award.badge for award in awards]
return badges
return Badge.objects.all()
| // ... existing code ...
if user:
awards = Award.objects.filter(user=user).select_related('badge')
badges = [award.badge for award in awards]
// ... rest of the code ... |
023e814e6661c11bfe58a4e3e4ce4167ae63cd7f | rdio_dl/cli.py | rdio_dl/cli.py | import click
import youtube_dl
from .config import storage_load
from .extractor import RdioIE
@click.command()
@click.option(u'-u', u'--user', help=u'A Rdio user')
@click.option(u'-p', u'--password', help=u'The password')
@click.argument(u'urls', required=True, nargs=-1)
def main(user, password, urls):
storage = storage_load()
with youtube_dl.YoutubeDL() as ydl:
ydl.add_info_extractor(RdioIE(storage, user, password))
ydl.download(urls)
| import click
import youtube_dl
from .config import storage_load
from .extractor import RdioIE
def add_info_extractor_above_generic(ydl, ie):
generic = ydl._ies.pop()
ydl.add_info_extractor(ie)
ydl.add_info_extractor(generic)
@click.command()
@click.option(u'-u', u'--user', help=u'A Rdio user')
@click.option(u'-p', u'--password', help=u'The password')
@click.argument(u'urls', required=True, nargs=-1)
def main(user, password, urls):
storage = storage_load()
with youtube_dl.YoutubeDL() as ydl:
add_info_extractor_above_generic(ydl, RdioIE(storage, user, password))
ydl.download(urls)
| Fix generic extractor being always selected | Fix generic extractor being always selected
Turns out our extractor was being inserted *after* the GenericIE.
Now we are inserting our RdioIE right above GenericIE.
| Python | mit | ravishi/rdio-dl | import click
import youtube_dl
from .config import storage_load
from .extractor import RdioIE
+
+
+ def add_info_extractor_above_generic(ydl, ie):
+ generic = ydl._ies.pop()
+ ydl.add_info_extractor(ie)
+ ydl.add_info_extractor(generic)
+
@click.command()
@click.option(u'-u', u'--user', help=u'A Rdio user')
@click.option(u'-p', u'--password', help=u'The password')
@click.argument(u'urls', required=True, nargs=-1)
def main(user, password, urls):
storage = storage_load()
with youtube_dl.YoutubeDL() as ydl:
- ydl.add_info_extractor(RdioIE(storage, user, password))
+ add_info_extractor_above_generic(ydl, RdioIE(storage, user, password))
ydl.download(urls)
| Fix generic extractor being always selected | ## Code Before:
import click
import youtube_dl
from .config import storage_load
from .extractor import RdioIE
@click.command()
@click.option(u'-u', u'--user', help=u'A Rdio user')
@click.option(u'-p', u'--password', help=u'The password')
@click.argument(u'urls', required=True, nargs=-1)
def main(user, password, urls):
storage = storage_load()
with youtube_dl.YoutubeDL() as ydl:
ydl.add_info_extractor(RdioIE(storage, user, password))
ydl.download(urls)
## Instruction:
Fix generic extractor being always selected
## Code After:
import click
import youtube_dl
from .config import storage_load
from .extractor import RdioIE
def add_info_extractor_above_generic(ydl, ie):
generic = ydl._ies.pop()
ydl.add_info_extractor(ie)
ydl.add_info_extractor(generic)
@click.command()
@click.option(u'-u', u'--user', help=u'A Rdio user')
@click.option(u'-p', u'--password', help=u'The password')
@click.argument(u'urls', required=True, nargs=-1)
def main(user, password, urls):
storage = storage_load()
with youtube_dl.YoutubeDL() as ydl:
add_info_extractor_above_generic(ydl, RdioIE(storage, user, password))
ydl.download(urls)
| # ... existing code ...
from .extractor import RdioIE
def add_info_extractor_above_generic(ydl, ie):
generic = ydl._ies.pop()
ydl.add_info_extractor(ie)
ydl.add_info_extractor(generic)
# ... modified code ...
with youtube_dl.YoutubeDL() as ydl:
add_info_extractor_above_generic(ydl, RdioIE(storage, user, password))
ydl.download(urls)
# ... rest of the code ... |
b3d066e9ff5bc0508eec4fc9f317b7df112e2218 | test/test_url_subcommand.py | test/test_url_subcommand.py |
from __future__ import print_function
import path
import pytest
import responses
import simplesqlite
from click.testing import CliRunner
from sqlitebiter._enum import ExitCode
from sqlitebiter.sqlitebiter import cmd
from sqliteschema import SqliteSchemaExtractor
from .common import print_traceback
from .dataset import complex_json
class Test_TableUrlLoader(object):
@responses.activate
def test_normal(self):
url = "https://example.com/complex_jeson.json"
responses.add(
responses.GET,
url,
body=complex_json,
content_type='text/plain; charset=utf-8',
status=200)
runner = CliRunner()
db_path = "test_complex_json.sqlite"
with runner.isolated_filesystem():
result = runner.invoke(cmd, ["url", url, "-o", db_path])
print_traceback(result)
assert result.exit_code == ExitCode.SUCCESS
extractor = SqliteSchemaExtractor(db_path)
con = simplesqlite.SimpleSQLite(db_path, "r")
expected = set([
'ratings', 'screenshots_4', 'screenshots_3', 'screenshots_5', 'screenshots_1',
'screenshots_2', 'tags', 'versions', 'root'])
assert set(con.get_table_name_list()) == expected
|
from __future__ import print_function
import responses
import simplesqlite
from click.testing import CliRunner
from sqlitebiter._enum import ExitCode
from sqlitebiter.sqlitebiter import cmd
from .common import print_traceback
from .dataset import complex_json
class Test_TableUrlLoader(object):
@responses.activate
def test_normal(self):
url = "https://example.com/complex_jeson.json"
responses.add(
responses.GET,
url,
body=complex_json,
content_type='text/plain; charset=utf-8',
status=200)
runner = CliRunner()
db_path = "test_complex_json.sqlite"
with runner.isolated_filesystem():
result = runner.invoke(cmd, ["url", url, "-o", db_path])
print_traceback(result)
assert result.exit_code == ExitCode.SUCCESS
extractor = SqliteSchemaExtractor(db_path)
con = simplesqlite.SimpleSQLite(db_path, "r")
expected = set([
'ratings', 'screenshots_4', 'screenshots_3', 'screenshots_5', 'screenshots_1',
'screenshots_2', 'tags', 'versions', 'root'])
assert set(con.get_table_name_list()) == expected
| Remove imports that no longer used | Remove imports that no longer used
| Python | mit | thombashi/sqlitebiter,thombashi/sqlitebiter |
from __future__ import print_function
- import path
- import pytest
import responses
import simplesqlite
from click.testing import CliRunner
from sqlitebiter._enum import ExitCode
from sqlitebiter.sqlitebiter import cmd
- from sqliteschema import SqliteSchemaExtractor
from .common import print_traceback
from .dataset import complex_json
class Test_TableUrlLoader(object):
@responses.activate
def test_normal(self):
url = "https://example.com/complex_jeson.json"
responses.add(
responses.GET,
url,
body=complex_json,
content_type='text/plain; charset=utf-8',
status=200)
runner = CliRunner()
db_path = "test_complex_json.sqlite"
with runner.isolated_filesystem():
result = runner.invoke(cmd, ["url", url, "-o", db_path])
print_traceback(result)
assert result.exit_code == ExitCode.SUCCESS
extractor = SqliteSchemaExtractor(db_path)
con = simplesqlite.SimpleSQLite(db_path, "r")
expected = set([
'ratings', 'screenshots_4', 'screenshots_3', 'screenshots_5', 'screenshots_1',
'screenshots_2', 'tags', 'versions', 'root'])
assert set(con.get_table_name_list()) == expected
| Remove imports that no longer used | ## Code Before:
from __future__ import print_function
import path
import pytest
import responses
import simplesqlite
from click.testing import CliRunner
from sqlitebiter._enum import ExitCode
from sqlitebiter.sqlitebiter import cmd
from sqliteschema import SqliteSchemaExtractor
from .common import print_traceback
from .dataset import complex_json
class Test_TableUrlLoader(object):
@responses.activate
def test_normal(self):
url = "https://example.com/complex_jeson.json"
responses.add(
responses.GET,
url,
body=complex_json,
content_type='text/plain; charset=utf-8',
status=200)
runner = CliRunner()
db_path = "test_complex_json.sqlite"
with runner.isolated_filesystem():
result = runner.invoke(cmd, ["url", url, "-o", db_path])
print_traceback(result)
assert result.exit_code == ExitCode.SUCCESS
extractor = SqliteSchemaExtractor(db_path)
con = simplesqlite.SimpleSQLite(db_path, "r")
expected = set([
'ratings', 'screenshots_4', 'screenshots_3', 'screenshots_5', 'screenshots_1',
'screenshots_2', 'tags', 'versions', 'root'])
assert set(con.get_table_name_list()) == expected
## Instruction:
Remove imports that no longer used
## Code After:
from __future__ import print_function
import responses
import simplesqlite
from click.testing import CliRunner
from sqlitebiter._enum import ExitCode
from sqlitebiter.sqlitebiter import cmd
from .common import print_traceback
from .dataset import complex_json
class Test_TableUrlLoader(object):
@responses.activate
def test_normal(self):
url = "https://example.com/complex_jeson.json"
responses.add(
responses.GET,
url,
body=complex_json,
content_type='text/plain; charset=utf-8',
status=200)
runner = CliRunner()
db_path = "test_complex_json.sqlite"
with runner.isolated_filesystem():
result = runner.invoke(cmd, ["url", url, "-o", db_path])
print_traceback(result)
assert result.exit_code == ExitCode.SUCCESS
extractor = SqliteSchemaExtractor(db_path)
con = simplesqlite.SimpleSQLite(db_path, "r")
expected = set([
'ratings', 'screenshots_4', 'screenshots_3', 'screenshots_5', 'screenshots_1',
'screenshots_2', 'tags', 'versions', 'root'])
assert set(con.get_table_name_list()) == expected
| # ... existing code ...
import responses
# ... modified code ...
from sqlitebiter.sqlitebiter import cmd
# ... rest of the code ... |
dbc16598a87403f52324bca3d50132fc9303ee90 | reviewboard/hostingsvcs/gitorious.py | reviewboard/hostingsvcs/gitorious.py | from django import forms
from django.utils.translation import ugettext_lazy as _
from reviewboard.hostingsvcs.forms import HostingServiceForm
from reviewboard.hostingsvcs.service import HostingService
class GitoriousForm(HostingServiceForm):
gitorious_project_name = forms.CharField(
label=_('Project name'),
max_length=64,
required=True,
widget=forms.TextInput(attrs={'size': '60'}))
gitorious_repo_name = forms.CharField(
label=_('Repository name'),
max_length=64,
required=True,
widget=forms.TextInput(attrs={'size': '60'}))
class Gitorious(HostingService):
name = 'Gitorious'
form = GitoriousForm
supported_scmtools = ['Git']
supports_repositories = True
repository_fields = {
'Git': {
'path': 'git://gitorious.org/%(gitorious_project_name)s/'
'%(gitorious_repo_name)s.git',
'mirror_path': 'http://git.gitorious.org/'
'%(gitorious_project_name)s/'
'%(gitorious_repo_name)s.git',
'raw_file_url': 'http://git.gitorious.org/'
'%(gitorious_project_name)s/'
'%(gitorious_repo_name)s/blobs/raw/<revision>'
},
}
| from django import forms
from django.utils.translation import ugettext_lazy as _
from reviewboard.hostingsvcs.forms import HostingServiceForm
from reviewboard.hostingsvcs.service import HostingService
class GitoriousForm(HostingServiceForm):
gitorious_project_name = forms.CharField(
label=_('Project name'),
max_length=64,
required=True,
widget=forms.TextInput(attrs={'size': '60'}))
gitorious_repo_name = forms.CharField(
label=_('Repository name'),
max_length=64,
required=True,
widget=forms.TextInput(attrs={'size': '60'}))
class Gitorious(HostingService):
name = 'Gitorious'
form = GitoriousForm
supported_scmtools = ['Git']
supports_repositories = True
repository_fields = {
'Git': {
'path': 'git://gitorious.org/%(gitorious_project_name)s/'
'%(gitorious_repo_name)s.git',
'mirror_path': 'https://gitorious.org/'
'%(gitorious_project_name)s/'
'%(gitorious_repo_name)s.git',
'raw_file_url': 'https://gitorious.org/'
'%(gitorious_project_name)s/'
'%(gitorious_repo_name)s/blobs/raw/<revision>'
},
}
| Fix the raw paths for Gitorious | Fix the raw paths for Gitorious
Gitorious have changed the raw orl paths, making impossible to use a Gitorious
repository.
This patch has been tested in production at
http://reviewboard.chakra-project.org/r/27/diff/#index_header
Reviewed at http://reviews.reviewboard.org/r/3649/diff/#index_header
| Python | mit | KnowNo/reviewboard,brennie/reviewboard,1tush/reviewboard,chipx86/reviewboard,davidt/reviewboard,brennie/reviewboard,bkochendorfer/reviewboard,KnowNo/reviewboard,sgallagher/reviewboard,reviewboard/reviewboard,beol/reviewboard,1tush/reviewboard,brennie/reviewboard,custode/reviewboard,sgallagher/reviewboard,1tush/reviewboard,1tush/reviewboard,chipx86/reviewboard,1tush/reviewboard,davidt/reviewboard,davidt/reviewboard,sgallagher/reviewboard,beol/reviewboard,1tush/reviewboard,reviewboard/reviewboard,1tush/reviewboard,KnowNo/reviewboard,custode/reviewboard,brennie/reviewboard,chipx86/reviewboard,beol/reviewboard,custode/reviewboard,custode/reviewboard,bkochendorfer/reviewboard,reviewboard/reviewboard,1tush/reviewboard,bkochendorfer/reviewboard,chipx86/reviewboard,reviewboard/reviewboard,bkochendorfer/reviewboard,KnowNo/reviewboard,sgallagher/reviewboard,1tush/reviewboard,davidt/reviewboard,beol/reviewboard | from django import forms
from django.utils.translation import ugettext_lazy as _
from reviewboard.hostingsvcs.forms import HostingServiceForm
from reviewboard.hostingsvcs.service import HostingService
class GitoriousForm(HostingServiceForm):
gitorious_project_name = forms.CharField(
label=_('Project name'),
max_length=64,
required=True,
widget=forms.TextInput(attrs={'size': '60'}))
gitorious_repo_name = forms.CharField(
label=_('Repository name'),
max_length=64,
required=True,
widget=forms.TextInput(attrs={'size': '60'}))
class Gitorious(HostingService):
name = 'Gitorious'
form = GitoriousForm
supported_scmtools = ['Git']
supports_repositories = True
repository_fields = {
'Git': {
'path': 'git://gitorious.org/%(gitorious_project_name)s/'
'%(gitorious_repo_name)s.git',
- 'mirror_path': 'http://git.gitorious.org/'
+ 'mirror_path': 'https://gitorious.org/'
'%(gitorious_project_name)s/'
'%(gitorious_repo_name)s.git',
- 'raw_file_url': 'http://git.gitorious.org/'
+ 'raw_file_url': 'https://gitorious.org/'
'%(gitorious_project_name)s/'
'%(gitorious_repo_name)s/blobs/raw/<revision>'
},
}
| Fix the raw paths for Gitorious | ## Code Before:
from django import forms
from django.utils.translation import ugettext_lazy as _
from reviewboard.hostingsvcs.forms import HostingServiceForm
from reviewboard.hostingsvcs.service import HostingService
class GitoriousForm(HostingServiceForm):
gitorious_project_name = forms.CharField(
label=_('Project name'),
max_length=64,
required=True,
widget=forms.TextInput(attrs={'size': '60'}))
gitorious_repo_name = forms.CharField(
label=_('Repository name'),
max_length=64,
required=True,
widget=forms.TextInput(attrs={'size': '60'}))
class Gitorious(HostingService):
name = 'Gitorious'
form = GitoriousForm
supported_scmtools = ['Git']
supports_repositories = True
repository_fields = {
'Git': {
'path': 'git://gitorious.org/%(gitorious_project_name)s/'
'%(gitorious_repo_name)s.git',
'mirror_path': 'http://git.gitorious.org/'
'%(gitorious_project_name)s/'
'%(gitorious_repo_name)s.git',
'raw_file_url': 'http://git.gitorious.org/'
'%(gitorious_project_name)s/'
'%(gitorious_repo_name)s/blobs/raw/<revision>'
},
}
## Instruction:
Fix the raw paths for Gitorious
## Code After:
from django import forms
from django.utils.translation import ugettext_lazy as _
from reviewboard.hostingsvcs.forms import HostingServiceForm
from reviewboard.hostingsvcs.service import HostingService
class GitoriousForm(HostingServiceForm):
gitorious_project_name = forms.CharField(
label=_('Project name'),
max_length=64,
required=True,
widget=forms.TextInput(attrs={'size': '60'}))
gitorious_repo_name = forms.CharField(
label=_('Repository name'),
max_length=64,
required=True,
widget=forms.TextInput(attrs={'size': '60'}))
class Gitorious(HostingService):
name = 'Gitorious'
form = GitoriousForm
supported_scmtools = ['Git']
supports_repositories = True
repository_fields = {
'Git': {
'path': 'git://gitorious.org/%(gitorious_project_name)s/'
'%(gitorious_repo_name)s.git',
'mirror_path': 'https://gitorious.org/'
'%(gitorious_project_name)s/'
'%(gitorious_repo_name)s.git',
'raw_file_url': 'https://gitorious.org/'
'%(gitorious_project_name)s/'
'%(gitorious_repo_name)s/blobs/raw/<revision>'
},
}
| // ... existing code ...
'%(gitorious_repo_name)s.git',
'mirror_path': 'https://gitorious.org/'
'%(gitorious_project_name)s/'
// ... modified code ...
'%(gitorious_repo_name)s.git',
'raw_file_url': 'https://gitorious.org/'
'%(gitorious_project_name)s/'
// ... rest of the code ... |
42465957542fe232739d58c2a46098d13fb9c995 | tests/parser_db.py | tests/parser_db.py | from compiler import error, parse
class ParserDB():
"""A class for parsing with memoized parsers."""
parsers = {}
@classmethod
def _parse(cls, data, start='program'):
mock = error.LoggerMock()
try:
parser = cls.parsers[start]
except KeyError:
parser = cls.parsers[start] = parse.Parser(
logger=mock,
start=start
)
tree = parser.parse(data=data)
return tree
| from compiler import error, parse
class ParserDB():
"""A class for parsing with memoized parsers."""
parsers = {}
@classmethod
def _parse(cls, data, start='program'):
mock = error.LoggerMock()
try:
parser = cls.parsers[start]
except KeyError:
parser = cls.parsers[start] = parse.Parser(
logger=mock,
start=start
)
# Clear previous logger state prior to parsing.
parser.logger.clear()
tree = parser.parse(data=data)
return tree
| Clear previous logger state on each call. | ParserDB: Clear previous logger state on each call.
| Python | mit | Renelvon/llama,dionyziz/llama,dionyziz/llama,Renelvon/llama | from compiler import error, parse
class ParserDB():
"""A class for parsing with memoized parsers."""
parsers = {}
@classmethod
def _parse(cls, data, start='program'):
mock = error.LoggerMock()
try:
parser = cls.parsers[start]
except KeyError:
parser = cls.parsers[start] = parse.Parser(
logger=mock,
start=start
)
+ # Clear previous logger state prior to parsing.
+ parser.logger.clear()
+
tree = parser.parse(data=data)
return tree
| Clear previous logger state on each call. | ## Code Before:
from compiler import error, parse
class ParserDB():
"""A class for parsing with memoized parsers."""
parsers = {}
@classmethod
def _parse(cls, data, start='program'):
mock = error.LoggerMock()
try:
parser = cls.parsers[start]
except KeyError:
parser = cls.parsers[start] = parse.Parser(
logger=mock,
start=start
)
tree = parser.parse(data=data)
return tree
## Instruction:
Clear previous logger state on each call.
## Code After:
from compiler import error, parse
class ParserDB():
"""A class for parsing with memoized parsers."""
parsers = {}
@classmethod
def _parse(cls, data, start='program'):
mock = error.LoggerMock()
try:
parser = cls.parsers[start]
except KeyError:
parser = cls.parsers[start] = parse.Parser(
logger=mock,
start=start
)
# Clear previous logger state prior to parsing.
parser.logger.clear()
tree = parser.parse(data=data)
return tree
| // ... existing code ...
# Clear previous logger state prior to parsing.
parser.logger.clear()
tree = parser.parse(data=data)
// ... rest of the code ... |
db2d8da9109ab4a8aa51acbd80abb2088a7fd299 | campus02/urls.py | campus02/urls.py |
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('django.contrib.auth.urls')),
url(r'^web/', include('campus02.web.urls', namespace='web')),
url(r'^', include('campus02.base.urls', namespace='base')),
)
|
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns(
'',
url(r'^', include('django.contrib.auth.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^web/', include('campus02.web.urls', namespace='web')),
url(r'^', include('campus02.base.urls', namespace='base')),
)
| Rearrange admin URL mount point. | Rearrange admin URL mount point.
| Python | mit | fladi/django-campus02,fladi/django-campus02 |
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns(
'',
+ url(r'^', include('django.contrib.auth.urls')),
url(r'^admin/', include(admin.site.urls)),
- url(r'^', include('django.contrib.auth.urls')),
url(r'^web/', include('campus02.web.urls', namespace='web')),
url(r'^', include('campus02.base.urls', namespace='base')),
)
| Rearrange admin URL mount point. | ## Code Before:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('django.contrib.auth.urls')),
url(r'^web/', include('campus02.web.urls', namespace='web')),
url(r'^', include('campus02.base.urls', namespace='base')),
)
## Instruction:
Rearrange admin URL mount point.
## Code After:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns(
'',
url(r'^', include('django.contrib.auth.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^web/', include('campus02.web.urls', namespace='web')),
url(r'^', include('campus02.base.urls', namespace='base')),
)
| ...
'',
url(r'^', include('django.contrib.auth.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^web/', include('campus02.web.urls', namespace='web')),
... |
26d2e13945f4780ff74dfe99695be7045fb9ed39 | piper/prop.py | piper/prop.py | import facter
from collections import MutableMapping
from piper.abc import DynamicItem
class PropBase(DynamicItem):
def __init__(self):
super(PropBase, self).__init__(None)
self._props = None
@property
def properties(self):
"""
Collect system properties and return a dictionary of them
"""
raise NotImplementedError()
@property
def namespace(self):
return '.'.join((self.__module__, self.__class__.__name__))
# http://stackoverflow.com/questions/6027558
def flatten(self, d, parent_key='', sep='.'):
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, MutableMapping):
items.extend(self.flatten(v, new_key).items())
else:
items.append((new_key, v))
return dict(items)
class FacterProp(PropBase):
"""
Collect properties from facter via facterpy
It should be noted that the current version does not have any typecasting,
so everything is always strings.
See https://github.com/knorby/facterpy/issues/5
"""
@property
def properties(self):
if self._props is None:
facts = facter.Facter().all
self._props = self.flatten(facts)
return self._props
| import facter
from collections import MutableMapping
from piper.abc import DynamicItem
class PropBase(DynamicItem):
def __init__(self):
super(PropBase, self).__init__(None)
self._props = None
@property
def properties(self):
"""
Collect system properties and return a dictionary of them
"""
raise NotImplementedError()
@property
def namespace(self):
return '.'.join((self.__module__, self.__class__.__name__))
# http://stackoverflow.com/questions/6027558
def flatten(self, d, parent_key='', sep='.'):
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, MutableMapping):
items.extend(self.flatten(v, new_key).items())
elif isinstance(v, list):
# Make lists have keys like 'foo.bar.x'
for x, item in enumerate(v):
key = '{2}{0}{1}'.format(sep, x, new_key)
items.append((key, item))
else:
items.append((new_key, v))
return dict(items)
class FacterProp(PropBase):
"""
Collect properties from facter via facterpy
It should be noted that the current version does not have any typecasting,
so everything is always strings.
See https://github.com/knorby/facterpy/issues/5
"""
@property
def properties(self):
if self._props is None:
facts = facter.Facter().all
self._props = self.flatten(facts)
return self._props
| Add PropBase.flatten() support for flattening lists | Add PropBase.flatten() support for flattening lists
| Python | mit | thiderman/piper | import facter
from collections import MutableMapping
from piper.abc import DynamicItem
class PropBase(DynamicItem):
def __init__(self):
super(PropBase, self).__init__(None)
self._props = None
@property
def properties(self):
"""
Collect system properties and return a dictionary of them
"""
raise NotImplementedError()
@property
def namespace(self):
return '.'.join((self.__module__, self.__class__.__name__))
# http://stackoverflow.com/questions/6027558
def flatten(self, d, parent_key='', sep='.'):
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, MutableMapping):
items.extend(self.flatten(v, new_key).items())
+ elif isinstance(v, list):
+ # Make lists have keys like 'foo.bar.x'
+ for x, item in enumerate(v):
+ key = '{2}{0}{1}'.format(sep, x, new_key)
+ items.append((key, item))
else:
items.append((new_key, v))
return dict(items)
class FacterProp(PropBase):
"""
Collect properties from facter via facterpy
It should be noted that the current version does not have any typecasting,
so everything is always strings.
See https://github.com/knorby/facterpy/issues/5
"""
@property
def properties(self):
if self._props is None:
facts = facter.Facter().all
self._props = self.flatten(facts)
return self._props
| Add PropBase.flatten() support for flattening lists | ## Code Before:
import facter
from collections import MutableMapping
from piper.abc import DynamicItem
class PropBase(DynamicItem):
def __init__(self):
super(PropBase, self).__init__(None)
self._props = None
@property
def properties(self):
"""
Collect system properties and return a dictionary of them
"""
raise NotImplementedError()
@property
def namespace(self):
return '.'.join((self.__module__, self.__class__.__name__))
# http://stackoverflow.com/questions/6027558
def flatten(self, d, parent_key='', sep='.'):
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, MutableMapping):
items.extend(self.flatten(v, new_key).items())
else:
items.append((new_key, v))
return dict(items)
class FacterProp(PropBase):
"""
Collect properties from facter via facterpy
It should be noted that the current version does not have any typecasting,
so everything is always strings.
See https://github.com/knorby/facterpy/issues/5
"""
@property
def properties(self):
if self._props is None:
facts = facter.Facter().all
self._props = self.flatten(facts)
return self._props
## Instruction:
Add PropBase.flatten() support for flattening lists
## Code After:
import facter
from collections import MutableMapping
from piper.abc import DynamicItem
class PropBase(DynamicItem):
def __init__(self):
super(PropBase, self).__init__(None)
self._props = None
@property
def properties(self):
"""
Collect system properties and return a dictionary of them
"""
raise NotImplementedError()
@property
def namespace(self):
return '.'.join((self.__module__, self.__class__.__name__))
# http://stackoverflow.com/questions/6027558
def flatten(self, d, parent_key='', sep='.'):
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, MutableMapping):
items.extend(self.flatten(v, new_key).items())
elif isinstance(v, list):
# Make lists have keys like 'foo.bar.x'
for x, item in enumerate(v):
key = '{2}{0}{1}'.format(sep, x, new_key)
items.append((key, item))
else:
items.append((new_key, v))
return dict(items)
class FacterProp(PropBase):
"""
Collect properties from facter via facterpy
It should be noted that the current version does not have any typecasting,
so everything is always strings.
See https://github.com/knorby/facterpy/issues/5
"""
@property
def properties(self):
if self._props is None:
facts = facter.Facter().all
self._props = self.flatten(facts)
return self._props
| # ... existing code ...
items.extend(self.flatten(v, new_key).items())
elif isinstance(v, list):
# Make lists have keys like 'foo.bar.x'
for x, item in enumerate(v):
key = '{2}{0}{1}'.format(sep, x, new_key)
items.append((key, item))
else:
# ... rest of the code ... |
ff138858fdc76527ee9f05f7573ddb00cd7eed21 | conftest.py | conftest.py | import pytest
def pytest_collection_modifyitems(config, items):
try:
import pandas
except ImportError:
pandas = None
try:
import cesium
except ImportError:
cesium = None
if pandas is None:
skip_marker = pytest.mark.skip(reason="pandas not installed!")
for item in items:
if item.name in [
"tslearn.utils.from_tsfresh_dataset",
"tslearn.utils.from_sktime_dataset",
"tslearn.utils.from_pyflux_dataset",
"tslearn.utils.to_cesium_dataset",
"tslearn.utils.from_cesium_dataset",
]:
item.add_marker(skip_marker)
elif cesium is None:
skip_marker = pytest.mark.skip(reason="cesium not installed!")
for item in items:
if item.name in [
"tslearn.utils.to_cesium_dataset",
"tslearn.utils.from_cesium_dataset",
]:
item.add_marker(skip_marker)
| import pytest
def pytest_collection_modifyitems(config, items):
try:
import pandas
except ImportError:
pandas = None
try:
import cesium
except ImportError:
cesium = None
if pandas is None:
skip_marker = pytest.mark.skip(reason="pandas not installed!")
for item in items:
if item.name in [
"tslearn.utils.from_tsfresh_dataset",
"tslearn.utils.to_tsfresh_dataset",
"tslearn.utils.from_sktime_dataset",
"tslearn.utils.to_sktime_dataset",
"tslearn.utils.from_pyflux_dataset",
"tslearn.utils.to_pyflux_dataset",
"tslearn.utils.from_cesium_dataset",
"tslearn.utils.to_cesium_dataset",
]:
item.add_marker(skip_marker)
elif cesium is None:
skip_marker = pytest.mark.skip(reason="cesium not installed!")
for item in items:
if item.name in [
"tslearn.utils.to_cesium_dataset",
"tslearn.utils.from_cesium_dataset",
]:
item.add_marker(skip_marker)
| Add all versions of conversion doctests | Add all versions of conversion doctests
| Python | bsd-2-clause | rtavenar/tslearn | import pytest
def pytest_collection_modifyitems(config, items):
try:
import pandas
except ImportError:
pandas = None
try:
import cesium
except ImportError:
cesium = None
if pandas is None:
skip_marker = pytest.mark.skip(reason="pandas not installed!")
for item in items:
if item.name in [
"tslearn.utils.from_tsfresh_dataset",
+ "tslearn.utils.to_tsfresh_dataset",
"tslearn.utils.from_sktime_dataset",
+ "tslearn.utils.to_sktime_dataset",
"tslearn.utils.from_pyflux_dataset",
+ "tslearn.utils.to_pyflux_dataset",
+ "tslearn.utils.from_cesium_dataset",
"tslearn.utils.to_cesium_dataset",
- "tslearn.utils.from_cesium_dataset",
]:
item.add_marker(skip_marker)
elif cesium is None:
skip_marker = pytest.mark.skip(reason="cesium not installed!")
for item in items:
if item.name in [
"tslearn.utils.to_cesium_dataset",
"tslearn.utils.from_cesium_dataset",
]:
item.add_marker(skip_marker)
| Add all versions of conversion doctests | ## Code Before:
import pytest
def pytest_collection_modifyitems(config, items):
try:
import pandas
except ImportError:
pandas = None
try:
import cesium
except ImportError:
cesium = None
if pandas is None:
skip_marker = pytest.mark.skip(reason="pandas not installed!")
for item in items:
if item.name in [
"tslearn.utils.from_tsfresh_dataset",
"tslearn.utils.from_sktime_dataset",
"tslearn.utils.from_pyflux_dataset",
"tslearn.utils.to_cesium_dataset",
"tslearn.utils.from_cesium_dataset",
]:
item.add_marker(skip_marker)
elif cesium is None:
skip_marker = pytest.mark.skip(reason="cesium not installed!")
for item in items:
if item.name in [
"tslearn.utils.to_cesium_dataset",
"tslearn.utils.from_cesium_dataset",
]:
item.add_marker(skip_marker)
## Instruction:
Add all versions of conversion doctests
## Code After:
import pytest
def pytest_collection_modifyitems(config, items):
try:
import pandas
except ImportError:
pandas = None
try:
import cesium
except ImportError:
cesium = None
if pandas is None:
skip_marker = pytest.mark.skip(reason="pandas not installed!")
for item in items:
if item.name in [
"tslearn.utils.from_tsfresh_dataset",
"tslearn.utils.to_tsfresh_dataset",
"tslearn.utils.from_sktime_dataset",
"tslearn.utils.to_sktime_dataset",
"tslearn.utils.from_pyflux_dataset",
"tslearn.utils.to_pyflux_dataset",
"tslearn.utils.from_cesium_dataset",
"tslearn.utils.to_cesium_dataset",
]:
item.add_marker(skip_marker)
elif cesium is None:
skip_marker = pytest.mark.skip(reason="cesium not installed!")
for item in items:
if item.name in [
"tslearn.utils.to_cesium_dataset",
"tslearn.utils.from_cesium_dataset",
]:
item.add_marker(skip_marker)
| # ... existing code ...
"tslearn.utils.from_tsfresh_dataset",
"tslearn.utils.to_tsfresh_dataset",
"tslearn.utils.from_sktime_dataset",
"tslearn.utils.to_sktime_dataset",
"tslearn.utils.from_pyflux_dataset",
"tslearn.utils.to_pyflux_dataset",
"tslearn.utils.from_cesium_dataset",
"tslearn.utils.to_cesium_dataset",
]:
# ... rest of the code ... |
0c2305db6c6792f624cf09a9134aaa090c82d5c1 | tasks.py | tasks.py | from invoke import task
import jschema
@task
def pip(ctx):
ctx.run("rm -rf dist jschema.egg-info")
ctx.run("./setup.py sdist")
ctx.run("twine upload dist/jschema-{}.tar.gz".format(jschema.__version__))
@task
def doc(ctx):
ctx.run("./setup.py build_sphinx")
ctx.run("./setup.py upload_sphinx")
| from invoke import task
from invoke.util import cd
import jschema
@task
def pip(ctx):
ctx.run("rm -rf dist jschema.egg-info")
ctx.run("./setup.py sdist")
ctx.run("twine upload dist/jschema-{}.tar.gz".format(jschema.__version__))
@task
def doc(ctx):
ctx.run("./setup.py build_sphinx")
ctx.run("./setup.py upload_sphinx")
@task
def mezzo(ctx):
ctx.run("mkdir -p build/jschema")
ctx.run("cp -R jschema setup.py build/jschema")
with cd("build"):
ctx.run("tar cf jschema.tar.gz jschema")
ctx.run("mv jschema.tar.gz /opt/mezzo/dependencies")
ctx.run("rm -rf jschema")
| Add mezzo task, for copy project to mezzo | Add mezzo task, for copy project to mezzo
| Python | mit | stepan-perlov/jschema,stepan-perlov/jschema | from invoke import task
+ from invoke.util import cd
import jschema
@task
def pip(ctx):
ctx.run("rm -rf dist jschema.egg-info")
ctx.run("./setup.py sdist")
ctx.run("twine upload dist/jschema-{}.tar.gz".format(jschema.__version__))
@task
def doc(ctx):
ctx.run("./setup.py build_sphinx")
ctx.run("./setup.py upload_sphinx")
+ @task
+ def mezzo(ctx):
+ ctx.run("mkdir -p build/jschema")
+ ctx.run("cp -R jschema setup.py build/jschema")
+ with cd("build"):
+ ctx.run("tar cf jschema.tar.gz jschema")
+ ctx.run("mv jschema.tar.gz /opt/mezzo/dependencies")
+ ctx.run("rm -rf jschema")
+ | Add mezzo task, for copy project to mezzo | ## Code Before:
from invoke import task
import jschema
@task
def pip(ctx):
ctx.run("rm -rf dist jschema.egg-info")
ctx.run("./setup.py sdist")
ctx.run("twine upload dist/jschema-{}.tar.gz".format(jschema.__version__))
@task
def doc(ctx):
ctx.run("./setup.py build_sphinx")
ctx.run("./setup.py upload_sphinx")
## Instruction:
Add mezzo task, for copy project to mezzo
## Code After:
from invoke import task
from invoke.util import cd
import jschema
@task
def pip(ctx):
ctx.run("rm -rf dist jschema.egg-info")
ctx.run("./setup.py sdist")
ctx.run("twine upload dist/jschema-{}.tar.gz".format(jschema.__version__))
@task
def doc(ctx):
ctx.run("./setup.py build_sphinx")
ctx.run("./setup.py upload_sphinx")
@task
def mezzo(ctx):
ctx.run("mkdir -p build/jschema")
ctx.run("cp -R jschema setup.py build/jschema")
with cd("build"):
ctx.run("tar cf jschema.tar.gz jschema")
ctx.run("mv jschema.tar.gz /opt/mezzo/dependencies")
ctx.run("rm -rf jschema")
| ...
from invoke import task
from invoke.util import cd
import jschema
...
ctx.run("./setup.py upload_sphinx")
@task
def mezzo(ctx):
ctx.run("mkdir -p build/jschema")
ctx.run("cp -R jschema setup.py build/jschema")
with cd("build"):
ctx.run("tar cf jschema.tar.gz jschema")
ctx.run("mv jschema.tar.gz /opt/mezzo/dependencies")
ctx.run("rm -rf jschema")
... |
6b36639cc7ff17f4d74aa0239311867b3937da87 | py/longest-increasing-path-in-a-matrix.py | py/longest-increasing-path-in-a-matrix.py | from collections import defaultdict, Counter
class Solution(object):
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
if not matrix:
return 0
h = len(matrix)
w = len(matrix[0])
neighbors = defaultdict(list)
in_deg = Counter()
longest_length = Counter()
ds = [(0, -1), (0, 1), (1, 0), (-1, 0)]
starts = set(xrange(h * w))
for x, row in enumerate(matrix):
for y, v in enumerate(row):
for dx, dy in ds:
nx, ny = x + dx, y + dy
if 0 <= nx < h and 0 <= ny < w:
if matrix[nx][ny] > v:
neighbors[x * w + y].append(nx * w + ny)
in_deg[nx * w + ny] += 1
starts.discard(nx * w + ny)
for start in starts:
longest_length[start] = 1
q = list(starts)
ans = 1
for v in q:
for neighbor in neighbors[v]:
longest_length[neighbor] = max(longest_length[neighbor], longest_length[v] + 1)
ans = max(longest_length[neighbor], ans)
in_deg[neighbor] -= 1
if in_deg[neighbor] == 0:
q.append(neighbor)
return ans
| from collections import Counter
class Solution(object):
def dfs(self, dp, matrix, x, y, w, h):
v = matrix[x][y]
if dp[x, y] == 0:
dp[x, y] = 1 + max(
0 if x == 0 or matrix[x - 1][y] <= v else self.dfs(dp, matrix, x - 1, y, w, h),
0 if y == 0 or matrix[x][y - 1] <= v else self.dfs(dp, matrix, x, y - 1, w, h),
0 if x == h - 1 or matrix[x + 1][y] <= v else self.dfs(dp, matrix, x + 1, y, w, h),
0 if y == w - 1 or matrix[x][y + 1] <= v else self.dfs(dp, matrix, x, y + 1, w, h)
)
return dp[x, y]
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
if not matrix:
return 0
h = len(matrix)
w = len(matrix[0])
ans = 1
starts = set(xrange(h * w))
dp = Counter()
for x, row in enumerate(matrix):
for y, v in enumerate(row):
ans = max(ans, self.dfs(dp, matrix, x, y, w, h))
return ans
| Add py solution for 329. Longest Increasing Path in a Matrix | Add py solution for 329. Longest Increasing Path in a Matrix
329. Longest Increasing Path in a Matrix: https://leetcode.com/problems/longest-increasing-path-in-a-matrix/
Approach 2:
Top down search
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | - from collections import defaultdict, Counter
+ from collections import Counter
class Solution(object):
+ def dfs(self, dp, matrix, x, y, w, h):
+ v = matrix[x][y]
+ if dp[x, y] == 0:
+ dp[x, y] = 1 + max(
+ 0 if x == 0 or matrix[x - 1][y] <= v else self.dfs(dp, matrix, x - 1, y, w, h),
+ 0 if y == 0 or matrix[x][y - 1] <= v else self.dfs(dp, matrix, x, y - 1, w, h),
+ 0 if x == h - 1 or matrix[x + 1][y] <= v else self.dfs(dp, matrix, x + 1, y, w, h),
+ 0 if y == w - 1 or matrix[x][y + 1] <= v else self.dfs(dp, matrix, x, y + 1, w, h)
+ )
+
+ return dp[x, y]
+
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
if not matrix:
return 0
h = len(matrix)
w = len(matrix[0])
+ ans = 1
- neighbors = defaultdict(list)
- in_deg = Counter()
- longest_length = Counter()
-
- ds = [(0, -1), (0, 1), (1, 0), (-1, 0)]
starts = set(xrange(h * w))
+ dp = Counter()
for x, row in enumerate(matrix):
for y, v in enumerate(row):
+ ans = max(ans, self.dfs(dp, matrix, x, y, w, h))
- for dx, dy in ds:
- nx, ny = x + dx, y + dy
- if 0 <= nx < h and 0 <= ny < w:
- if matrix[nx][ny] > v:
- neighbors[x * w + y].append(nx * w + ny)
- in_deg[nx * w + ny] += 1
- starts.discard(nx * w + ny)
- for start in starts:
- longest_length[start] = 1
-
- q = list(starts)
- ans = 1
- for v in q:
- for neighbor in neighbors[v]:
- longest_length[neighbor] = max(longest_length[neighbor], longest_length[v] + 1)
- ans = max(longest_length[neighbor], ans)
- in_deg[neighbor] -= 1
- if in_deg[neighbor] == 0:
- q.append(neighbor)
return ans
| Add py solution for 329. Longest Increasing Path in a Matrix | ## Code Before:
from collections import defaultdict, Counter
class Solution(object):
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
if not matrix:
return 0
h = len(matrix)
w = len(matrix[0])
neighbors = defaultdict(list)
in_deg = Counter()
longest_length = Counter()
ds = [(0, -1), (0, 1), (1, 0), (-1, 0)]
starts = set(xrange(h * w))
for x, row in enumerate(matrix):
for y, v in enumerate(row):
for dx, dy in ds:
nx, ny = x + dx, y + dy
if 0 <= nx < h and 0 <= ny < w:
if matrix[nx][ny] > v:
neighbors[x * w + y].append(nx * w + ny)
in_deg[nx * w + ny] += 1
starts.discard(nx * w + ny)
for start in starts:
longest_length[start] = 1
q = list(starts)
ans = 1
for v in q:
for neighbor in neighbors[v]:
longest_length[neighbor] = max(longest_length[neighbor], longest_length[v] + 1)
ans = max(longest_length[neighbor], ans)
in_deg[neighbor] -= 1
if in_deg[neighbor] == 0:
q.append(neighbor)
return ans
## Instruction:
Add py solution for 329. Longest Increasing Path in a Matrix
## Code After:
from collections import Counter
class Solution(object):
def dfs(self, dp, matrix, x, y, w, h):
v = matrix[x][y]
if dp[x, y] == 0:
dp[x, y] = 1 + max(
0 if x == 0 or matrix[x - 1][y] <= v else self.dfs(dp, matrix, x - 1, y, w, h),
0 if y == 0 or matrix[x][y - 1] <= v else self.dfs(dp, matrix, x, y - 1, w, h),
0 if x == h - 1 or matrix[x + 1][y] <= v else self.dfs(dp, matrix, x + 1, y, w, h),
0 if y == w - 1 or matrix[x][y + 1] <= v else self.dfs(dp, matrix, x, y + 1, w, h)
)
return dp[x, y]
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
if not matrix:
return 0
h = len(matrix)
w = len(matrix[0])
ans = 1
starts = set(xrange(h * w))
dp = Counter()
for x, row in enumerate(matrix):
for y, v in enumerate(row):
ans = max(ans, self.dfs(dp, matrix, x, y, w, h))
return ans
| ...
from collections import Counter
class Solution(object):
def dfs(self, dp, matrix, x, y, w, h):
v = matrix[x][y]
if dp[x, y] == 0:
dp[x, y] = 1 + max(
0 if x == 0 or matrix[x - 1][y] <= v else self.dfs(dp, matrix, x - 1, y, w, h),
0 if y == 0 or matrix[x][y - 1] <= v else self.dfs(dp, matrix, x, y - 1, w, h),
0 if x == h - 1 or matrix[x + 1][y] <= v else self.dfs(dp, matrix, x + 1, y, w, h),
0 if y == w - 1 or matrix[x][y + 1] <= v else self.dfs(dp, matrix, x, y + 1, w, h)
)
return dp[x, y]
def longestIncreasingPath(self, matrix):
...
w = len(matrix[0])
ans = 1
starts = set(xrange(h * w))
dp = Counter()
for x, row in enumerate(matrix):
...
for y, v in enumerate(row):
ans = max(ans, self.dfs(dp, matrix, x, y, w, h))
return ans
... |
e7805528be294374b128dd6e40e3f8990b03cdac | main.py | main.py |
from importlib import import_module
from bombdefusalmanual.ui.console import ConsoleUI
from bombdefusalmanual.ui.models import Answer
ANSWERS = [
Answer('thebutton', 'The Button'),
Answer('complicatedwires', 'Complicated Wires'),
Answer('morsecode', 'Morse Code'),
Answer('passwords', 'Passwords'),
Answer('whosonfirst', 'Who\'s on First'),
]
def ask_for_subject(ui):
return ui.ask_for_choice('Which subject?', ANSWERS)
def import_subject_module(name):
return import_module('bombdefusalmanual.subjects.{}'.format(name))
if __name__ == '__main__':
ui = ConsoleUI()
subject_name = ask_for_subject(ui)
module = import_subject_module(subject_name)
module.execute(ui)
|
from argparse import ArgumentParser
from importlib import import_module
from bombdefusalmanual.ui.console import ConsoleUI
from bombdefusalmanual.ui.models import Answer
ANSWERS = [
Answer('thebutton', 'The Button'),
Answer('complicatedwires', 'Complicated Wires'),
Answer('morsecode', 'Morse Code'),
Answer('passwords', 'Passwords'),
Answer('whosonfirst', 'Who\'s on First'),
]
def parse_args():
parser = ArgumentParser()
parser.add_argument(
'--gui',
action='store_true',
default=False,
dest='use_gui',
help='use graphical user interface')
return parser.parse_args()
def get_ui(use_gui):
if use_gui:
from bombdefusalmanual.ui.tk import TkGUI
return TkGUI()
else:
return ConsoleUI()
def ask_for_subject(ui):
return ui.ask_for_choice('Which subject?', ANSWERS)
def import_subject_module(name):
return import_module('bombdefusalmanual.subjects.{}'.format(name))
if __name__ == '__main__':
args = parse_args()
ui = get_ui(args.use_gui)
subject_name = ask_for_subject(ui)
module = import_subject_module(subject_name)
module.execute(ui)
| Allow to enable graphical UI via command line option. | Allow to enable graphical UI via command line option.
| Python | mit | homeworkprod/better-bomb-defusal-manual,homeworkprod/better-bomb-defusal-manual |
+ from argparse import ArgumentParser
from importlib import import_module
from bombdefusalmanual.ui.console import ConsoleUI
from bombdefusalmanual.ui.models import Answer
ANSWERS = [
Answer('thebutton', 'The Button'),
Answer('complicatedwires', 'Complicated Wires'),
Answer('morsecode', 'Morse Code'),
Answer('passwords', 'Passwords'),
Answer('whosonfirst', 'Who\'s on First'),
]
+ def parse_args():
+ parser = ArgumentParser()
+
+ parser.add_argument(
+ '--gui',
+ action='store_true',
+ default=False,
+ dest='use_gui',
+ help='use graphical user interface')
+
+ return parser.parse_args()
+
+
+ def get_ui(use_gui):
+ if use_gui:
+ from bombdefusalmanual.ui.tk import TkGUI
+ return TkGUI()
+ else:
+ return ConsoleUI()
+
+
def ask_for_subject(ui):
return ui.ask_for_choice('Which subject?', ANSWERS)
def import_subject_module(name):
return import_module('bombdefusalmanual.subjects.{}'.format(name))
if __name__ == '__main__':
- ui = ConsoleUI()
+ args = parse_args()
+ ui = get_ui(args.use_gui)
+
subject_name = ask_for_subject(ui)
+
module = import_subject_module(subject_name)
module.execute(ui)
| Allow to enable graphical UI via command line option. | ## Code Before:
from importlib import import_module
from bombdefusalmanual.ui.console import ConsoleUI
from bombdefusalmanual.ui.models import Answer
ANSWERS = [
Answer('thebutton', 'The Button'),
Answer('complicatedwires', 'Complicated Wires'),
Answer('morsecode', 'Morse Code'),
Answer('passwords', 'Passwords'),
Answer('whosonfirst', 'Who\'s on First'),
]
def ask_for_subject(ui):
return ui.ask_for_choice('Which subject?', ANSWERS)
def import_subject_module(name):
return import_module('bombdefusalmanual.subjects.{}'.format(name))
if __name__ == '__main__':
ui = ConsoleUI()
subject_name = ask_for_subject(ui)
module = import_subject_module(subject_name)
module.execute(ui)
## Instruction:
Allow to enable graphical UI via command line option.
## Code After:
from argparse import ArgumentParser
from importlib import import_module
from bombdefusalmanual.ui.console import ConsoleUI
from bombdefusalmanual.ui.models import Answer
ANSWERS = [
Answer('thebutton', 'The Button'),
Answer('complicatedwires', 'Complicated Wires'),
Answer('morsecode', 'Morse Code'),
Answer('passwords', 'Passwords'),
Answer('whosonfirst', 'Who\'s on First'),
]
def parse_args():
parser = ArgumentParser()
parser.add_argument(
'--gui',
action='store_true',
default=False,
dest='use_gui',
help='use graphical user interface')
return parser.parse_args()
def get_ui(use_gui):
if use_gui:
from bombdefusalmanual.ui.tk import TkGUI
return TkGUI()
else:
return ConsoleUI()
def ask_for_subject(ui):
return ui.ask_for_choice('Which subject?', ANSWERS)
def import_subject_module(name):
return import_module('bombdefusalmanual.subjects.{}'.format(name))
if __name__ == '__main__':
args = parse_args()
ui = get_ui(args.use_gui)
subject_name = ask_for_subject(ui)
module = import_subject_module(subject_name)
module.execute(ui)
| # ... existing code ...
from argparse import ArgumentParser
from importlib import import_module
# ... modified code ...
def parse_args():
parser = ArgumentParser()
parser.add_argument(
'--gui',
action='store_true',
default=False,
dest='use_gui',
help='use graphical user interface')
return parser.parse_args()
def get_ui(use_gui):
if use_gui:
from bombdefusalmanual.ui.tk import TkGUI
return TkGUI()
else:
return ConsoleUI()
def ask_for_subject(ui):
...
if __name__ == '__main__':
args = parse_args()
ui = get_ui(args.use_gui)
subject_name = ask_for_subject(ui)
module = import_subject_module(subject_name)
# ... rest of the code ... |
7b4f69971684bf2c5abfa50876583eb7c640bdac | kuulemma/views/feedback.py | kuulemma/views/feedback.py | from flask import Blueprint, abort, jsonify, request
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None
| from flask import abort, Blueprint, jsonify, request
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None
| Fix order of imports to comply with isort | Fix order of imports to comply with isort
| Python | agpl-3.0 | City-of-Helsinki/kuulemma,fastmonkeys/kuulemma,City-of-Helsinki/kuulemma,fastmonkeys/kuulemma,City-of-Helsinki/kuulemma,fastmonkeys/kuulemma | - from flask import Blueprint, abort, jsonify, request
+ from flask import abort, Blueprint, jsonify, request
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None
| Fix order of imports to comply with isort | ## Code Before:
from flask import Blueprint, abort, jsonify, request
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None
## Instruction:
Fix order of imports to comply with isort
## Code After:
from flask import abort, Blueprint, jsonify, request
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None
| ...
from flask import abort, Blueprint, jsonify, request
from flask.ext.mail import Message
... |
812d456599e1540e329a4ddc05a7541b5bfdc149 | labonneboite/conf/__init__.py | labonneboite/conf/__init__.py | import imp
import os
from labonneboite.conf.common import settings_common
# Settings
# --------
# Default settings of the application are defined in `labonneboite/conf/common/settings_common.py`.
# A specific environment (staging, production...) can define its custom settings by:
# - creating a specific `settings` file, e.g. `lbb_staging_settings.py`
# - defining an environment variable containing the path to this specific `settings` file
#
# Specific and default settings will be merged, and values found in specific settings will take precedence.
# When no specific settings are found, `labonneboite/conf/local_settings.py` is used.
# Dynamically import LBB_SETTINGS environment variable as the `settings`
# module, or import `local_settings.py` as the `settings` module if it does not
# exist.
settings = settings_common
if settings_common.get_current_env() != settings_common.ENV_TEST:
# Don't override settings in tests
settings_module = os.path.join(os.path.dirname(__file__), 'local_settings.py')
settings_module = os.environ.get('LBB_SETTINGS', settings_module)
settings = imp.load_source('settings', settings_module)
# Iterate over each setting defined in the `settings_common` module and add them to the dynamically
# imported `settings` module if they don't already exist.
for setting in dir(settings_common):
if not hasattr(settings, setting):
setattr(settings, setting, getattr(settings_common, setting))
| import imp
import os
from labonneboite.conf.common import settings_common
# Settings
# --------
# Default settings of the application are defined in `labonneboite/conf/common/settings_common.py`.
# A specific environment (staging, production...) can define its custom settings by:
# - creating a specific `settings` file, e.g. `lbb_staging_settings.py`
# - defining an environment variable containing the path to this specific `settings` file
#
# Specific and default settings will be merged, and values found in specific settings will take precedence.
# When no specific settings are found, `labonneboite/conf/local_settings.py` is used.
# Dynamically import LBB_SETTINGS environment variable as the `settings`
# module, or import `local_settings.py` as the `settings` module if it does not
# exist.
settings = settings_common
if settings_common.get_current_env() != settings_common.ENV_TEST:
# Don't override settings in tests
settings_module = os.path.join(os.path.dirname(__file__), 'local_settings.py')
settings_module = os.environ.get('LBB_SETTINGS', settings_module)
try:
settings = imp.load_source('settings', settings_module)
except FileNotFoundError:
pass
else:
# Iterate over each setting defined in the `settings_common` module and add them to the dynamically
# imported `settings` module if they don't already exist.
for setting in dir(settings_common):
if not hasattr(settings, setting):
setattr(settings, setting, getattr(settings_common, setting))
| Fix FileNotFoundError on missing local_settings.py | Fix FileNotFoundError on missing local_settings.py
This has been broken for a long time... When running LBB without a
local_settings.py and without an LBB_ENV environment variable, importing
local_settings.py was resulting in a FileNotFoundError.
| Python | agpl-3.0 | StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite | import imp
import os
from labonneboite.conf.common import settings_common
# Settings
# --------
# Default settings of the application are defined in `labonneboite/conf/common/settings_common.py`.
# A specific environment (staging, production...) can define its custom settings by:
# - creating a specific `settings` file, e.g. `lbb_staging_settings.py`
# - defining an environment variable containing the path to this specific `settings` file
#
# Specific and default settings will be merged, and values found in specific settings will take precedence.
# When no specific settings are found, `labonneboite/conf/local_settings.py` is used.
# Dynamically import LBB_SETTINGS environment variable as the `settings`
# module, or import `local_settings.py` as the `settings` module if it does not
# exist.
settings = settings_common
if settings_common.get_current_env() != settings_common.ENV_TEST:
# Don't override settings in tests
settings_module = os.path.join(os.path.dirname(__file__), 'local_settings.py')
settings_module = os.environ.get('LBB_SETTINGS', settings_module)
+ try:
- settings = imp.load_source('settings', settings_module)
+ settings = imp.load_source('settings', settings_module)
+ except FileNotFoundError:
+ pass
+ else:
+ # Iterate over each setting defined in the `settings_common` module and add them to the dynamically
+ # imported `settings` module if they don't already exist.
+ for setting in dir(settings_common):
+ if not hasattr(settings, setting):
+ setattr(settings, setting, getattr(settings_common, setting))
- # Iterate over each setting defined in the `settings_common` module and add them to the dynamically
- # imported `settings` module if they don't already exist.
- for setting in dir(settings_common):
- if not hasattr(settings, setting):
- setattr(settings, setting, getattr(settings_common, setting))
- | Fix FileNotFoundError on missing local_settings.py | ## Code Before:
import imp
import os
from labonneboite.conf.common import settings_common
# Settings
# --------
# Default settings of the application are defined in `labonneboite/conf/common/settings_common.py`.
# A specific environment (staging, production...) can define its custom settings by:
# - creating a specific `settings` file, e.g. `lbb_staging_settings.py`
# - defining an environment variable containing the path to this specific `settings` file
#
# Specific and default settings will be merged, and values found in specific settings will take precedence.
# When no specific settings are found, `labonneboite/conf/local_settings.py` is used.
# Dynamically import LBB_SETTINGS environment variable as the `settings`
# module, or import `local_settings.py` as the `settings` module if it does not
# exist.
settings = settings_common
if settings_common.get_current_env() != settings_common.ENV_TEST:
# Don't override settings in tests
settings_module = os.path.join(os.path.dirname(__file__), 'local_settings.py')
settings_module = os.environ.get('LBB_SETTINGS', settings_module)
settings = imp.load_source('settings', settings_module)
# Iterate over each setting defined in the `settings_common` module and add them to the dynamically
# imported `settings` module if they don't already exist.
for setting in dir(settings_common):
if not hasattr(settings, setting):
setattr(settings, setting, getattr(settings_common, setting))
## Instruction:
Fix FileNotFoundError on missing local_settings.py
## Code After:
import imp
import os
from labonneboite.conf.common import settings_common
# Settings
# --------
# Default settings of the application are defined in `labonneboite/conf/common/settings_common.py`.
# A specific environment (staging, production...) can define its custom settings by:
# - creating a specific `settings` file, e.g. `lbb_staging_settings.py`
# - defining an environment variable containing the path to this specific `settings` file
#
# Specific and default settings will be merged, and values found in specific settings will take precedence.
# When no specific settings are found, `labonneboite/conf/local_settings.py` is used.
# Dynamically import LBB_SETTINGS environment variable as the `settings`
# module, or import `local_settings.py` as the `settings` module if it does not
# exist.
settings = settings_common
if settings_common.get_current_env() != settings_common.ENV_TEST:
# Don't override settings in tests
settings_module = os.path.join(os.path.dirname(__file__), 'local_settings.py')
settings_module = os.environ.get('LBB_SETTINGS', settings_module)
try:
settings = imp.load_source('settings', settings_module)
except FileNotFoundError:
pass
else:
# Iterate over each setting defined in the `settings_common` module and add them to the dynamically
# imported `settings` module if they don't already exist.
for setting in dir(settings_common):
if not hasattr(settings, setting):
setattr(settings, setting, getattr(settings_common, setting))
| ...
settings_module = os.environ.get('LBB_SETTINGS', settings_module)
try:
settings = imp.load_source('settings', settings_module)
except FileNotFoundError:
pass
else:
# Iterate over each setting defined in the `settings_common` module and add them to the dynamically
# imported `settings` module if they don't already exist.
for setting in dir(settings_common):
if not hasattr(settings, setting):
setattr(settings, setting, getattr(settings_common, setting))
... |
9c4aefb8ea88fd5505602c95f4762fdeb3aea183 | oslo_versionedobjects/_utils.py | oslo_versionedobjects/_utils.py |
"""Utilities and helper functions."""
# ISO 8601 extended time format without microseconds
_ISO8601_TIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
def isotime(at):
"""Stringify time in ISO 8601 format."""
st = at.strftime(_ISO8601_TIME_FORMAT)
tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC'
st += ('Z' if tz == 'UTC' else tz)
return st
|
"""Utilities and helper functions."""
# ISO 8601 extended time format without microseconds
_ISO8601_TIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
def isotime(at):
"""Stringify time in ISO 8601 format."""
st = at.strftime(_ISO8601_TIME_FORMAT)
tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC'
# Need to handle either iso8601 or python UTC format
st += ('Z' if tz in ['UTC', 'UTC+00:00'] else tz)
return st
| Handle TZ change in iso8601 >=0.1.12 | Handle TZ change in iso8601 >=0.1.12
The iso8601 lib introduced a change such that if running on python
3.2 or later it internally uses the python timezone information
instead of its own implementation. This does not change direct
date handling, but when converting this value there is a slight
difference where now python 2.x will show UTC times as "UTC", but
on python 3 they will end up with "UTC+00:00".
The to_primitive call for DateTime fields was doing an exact match
on "UTC" to determine whether to include "Z" in the resulting string.
This updates that handling to recognize either of the new values.
Change-Id: I71b58e8fd8fee8a57ee275ff3e0b77f165eca836
Closes-bug: #1744160
| Python | apache-2.0 | openstack/oslo.versionedobjects |
"""Utilities and helper functions."""
# ISO 8601 extended time format without microseconds
_ISO8601_TIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
def isotime(at):
"""Stringify time in ISO 8601 format."""
st = at.strftime(_ISO8601_TIME_FORMAT)
tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC'
+ # Need to handle either iso8601 or python UTC format
- st += ('Z' if tz == 'UTC' else tz)
+ st += ('Z' if tz in ['UTC', 'UTC+00:00'] else tz)
return st
| Handle TZ change in iso8601 >=0.1.12 | ## Code Before:
"""Utilities and helper functions."""
# ISO 8601 extended time format without microseconds
_ISO8601_TIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
def isotime(at):
"""Stringify time in ISO 8601 format."""
st = at.strftime(_ISO8601_TIME_FORMAT)
tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC'
st += ('Z' if tz == 'UTC' else tz)
return st
## Instruction:
Handle TZ change in iso8601 >=0.1.12
## Code After:
"""Utilities and helper functions."""
# ISO 8601 extended time format without microseconds
_ISO8601_TIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
def isotime(at):
"""Stringify time in ISO 8601 format."""
st = at.strftime(_ISO8601_TIME_FORMAT)
tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC'
# Need to handle either iso8601 or python UTC format
st += ('Z' if tz in ['UTC', 'UTC+00:00'] else tz)
return st
| # ... existing code ...
tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC'
# Need to handle either iso8601 or python UTC format
st += ('Z' if tz in ['UTC', 'UTC+00:00'] else tz)
return st
# ... rest of the code ... |
7176ec5d4abe678d8f0d01baeacf4dc78204b18f | tests/integration/modules/grains.py | tests/integration/modules/grains.py | '''
Test the grains module
'''
import integration
class TestModulesGrains(integration.ModuleCase):
'''
Test the grains module
'''
def test_items(self):
'''
grains.items
'''
opts = self.minion_opts
self.assertEqual(
self.run_function('grains.items')['test_grain'],
opts['grains']['test_grain']
)
def test_item(self):
'''
grains.item
'''
opts = self.minion_opts
self.assertEqual(
self.run_function('grains.item', ['test_grain']),
opts['grains']['test_grain']
)
def test_ls(self):
'''
grains.ls
'''
check_for = (
'cpuarch',
'cpu_flags',
'cpu_model',
'domain',
'fqdn',
'host',
'kernel',
'kernelrelease',
'localhost',
'mem_total',
'num_cpus',
'os',
'path',
'ps',
'pythonpath',
'pythonversion',
'saltpath',
'saltversion',
'virtual',
)
lsgrains = self.run_function('grains.ls')
for grain_name in check_for:
self.assertTrue(grain_name in lsgrains)
if __name__ == '__main__':
from integration import run_tests
run_tests(TestModulesGrains)
| '''
Test the grains module
'''
import integration
class TestModulesGrains(integration.ModuleCase):
'''
Test the grains module
'''
def test_items(self):
'''
grains.items
'''
opts = self.minion_opts
self.assertEqual(
self.run_function('grains.items')['test_grain'],
opts['grains']['test_grain']
)
def test_item(self):
'''
grains.item
'''
opts = self.minion_opts
self.assertEqual(
self.run_function('grains.item', ['test_grain']),
opts['grains']['test_grain']
)
def test_ls(self):
'''
grains.ls
'''
check_for = (
'cpuarch',
'cpu_flags',
'cpu_model',
'domain',
'fqdn',
'host',
'kernel',
'kernelrelease',
'localhost',
'mem_total',
'num_cpus',
'os',
'os_family',
'path',
'ps',
'pythonpath',
'pythonversion',
'saltpath',
'saltversion',
'virtual',
)
lsgrains = self.run_function('grains.ls')
for grain_name in check_for:
self.assertTrue(grain_name in lsgrains)
if __name__ == '__main__':
from integration import run_tests
run_tests(TestModulesGrains)
| Add test to test if os_family grain is provided. | Add test to test if os_family grain is provided.
Corey Quinn reported a issue where __grains__['os_family'] returned a
KeyError. This commits adds a check to the grains module test to ensure
os_family is present.
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | '''
Test the grains module
'''
import integration
class TestModulesGrains(integration.ModuleCase):
'''
Test the grains module
'''
def test_items(self):
'''
grains.items
'''
opts = self.minion_opts
self.assertEqual(
self.run_function('grains.items')['test_grain'],
opts['grains']['test_grain']
)
def test_item(self):
'''
grains.item
'''
opts = self.minion_opts
self.assertEqual(
self.run_function('grains.item', ['test_grain']),
opts['grains']['test_grain']
)
def test_ls(self):
'''
grains.ls
'''
check_for = (
'cpuarch',
'cpu_flags',
'cpu_model',
'domain',
'fqdn',
'host',
'kernel',
'kernelrelease',
'localhost',
'mem_total',
'num_cpus',
'os',
+ 'os_family',
'path',
'ps',
'pythonpath',
'pythonversion',
'saltpath',
'saltversion',
'virtual',
)
lsgrains = self.run_function('grains.ls')
for grain_name in check_for:
self.assertTrue(grain_name in lsgrains)
if __name__ == '__main__':
from integration import run_tests
run_tests(TestModulesGrains)
| Add test to test if os_family grain is provided. | ## Code Before:
'''
Test the grains module
'''
import integration
class TestModulesGrains(integration.ModuleCase):
'''
Test the grains module
'''
def test_items(self):
'''
grains.items
'''
opts = self.minion_opts
self.assertEqual(
self.run_function('grains.items')['test_grain'],
opts['grains']['test_grain']
)
def test_item(self):
'''
grains.item
'''
opts = self.minion_opts
self.assertEqual(
self.run_function('grains.item', ['test_grain']),
opts['grains']['test_grain']
)
def test_ls(self):
'''
grains.ls
'''
check_for = (
'cpuarch',
'cpu_flags',
'cpu_model',
'domain',
'fqdn',
'host',
'kernel',
'kernelrelease',
'localhost',
'mem_total',
'num_cpus',
'os',
'path',
'ps',
'pythonpath',
'pythonversion',
'saltpath',
'saltversion',
'virtual',
)
lsgrains = self.run_function('grains.ls')
for grain_name in check_for:
self.assertTrue(grain_name in lsgrains)
if __name__ == '__main__':
from integration import run_tests
run_tests(TestModulesGrains)
## Instruction:
Add test to test if os_family grain is provided.
## Code After:
'''
Test the grains module
'''
import integration
class TestModulesGrains(integration.ModuleCase):
'''
Test the grains module
'''
def test_items(self):
'''
grains.items
'''
opts = self.minion_opts
self.assertEqual(
self.run_function('grains.items')['test_grain'],
opts['grains']['test_grain']
)
def test_item(self):
'''
grains.item
'''
opts = self.minion_opts
self.assertEqual(
self.run_function('grains.item', ['test_grain']),
opts['grains']['test_grain']
)
def test_ls(self):
'''
grains.ls
'''
check_for = (
'cpuarch',
'cpu_flags',
'cpu_model',
'domain',
'fqdn',
'host',
'kernel',
'kernelrelease',
'localhost',
'mem_total',
'num_cpus',
'os',
'os_family',
'path',
'ps',
'pythonpath',
'pythonversion',
'saltpath',
'saltversion',
'virtual',
)
lsgrains = self.run_function('grains.ls')
for grain_name in check_for:
self.assertTrue(grain_name in lsgrains)
if __name__ == '__main__':
from integration import run_tests
run_tests(TestModulesGrains)
| # ... existing code ...
'os',
'os_family',
'path',
# ... rest of the code ... |
e7a124628ce06d423425e3012d1b19b25562bdef | Discord/cogs/duelyst.py | Discord/cogs/duelyst.py |
from discord.ext import commands
from utilities import checks
def setup(bot):
bot.add_cog(Duelyst(bot))
class Duelyst(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def cog_check(self, ctx):
return await checks.not_forbidden().predicate(ctx)
@commands.group(invoke_without_command = True, case_insensitive = True)
async def duelyst(self, ctx):
'''Duelyst'''
await ctx.send_help(ctx.command)
@duelyst.group(case_insensitive = True)
async def card(self, ctx, *, name: str):
'''Details of a specific card'''
url = "https://duelyststats.info/scripts/carddata/get.php"
params = {"cardName": name}
async with ctx.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.text()
await ctx.embed_reply(data)
@card.command()
async def card_random(self, ctx):
'''Details of a random card'''
url = "https://duelyststats.info/scripts/carddata/get.php"
params = {"random": 1}
async with ctx.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.text()
await ctx.embed_reply(data)
|
from discord.ext import commands
from utilities import checks
def setup(bot):
bot.add_cog(Duelyst())
class Duelyst(commands.Cog):
async def cog_check(self, ctx):
return await checks.not_forbidden().predicate(ctx)
@commands.group(invoke_without_command = True, case_insensitive = True)
async def duelyst(self, ctx):
'''Duelyst'''
await ctx.send_help(ctx.command)
@duelyst.group(case_insensitive = True)
async def card(self, ctx, *, name: str):
'''Details of a specific card'''
url = "https://duelyststats.info/scripts/carddata/get.php"
params = {"cardName": name}
async with ctx.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.text()
await ctx.embed_reply(data)
@card.command()
async def card_random(self, ctx):
'''Details of a random card'''
url = "https://duelyststats.info/scripts/carddata/get.php"
params = {"random": 1}
async with ctx.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.text()
await ctx.embed_reply(data)
| Remove unused bot attribute from Duelyst cog | [Discord] Remove unused bot attribute from Duelyst cog
| Python | mit | Harmon758/Harmonbot,Harmon758/Harmonbot |
from discord.ext import commands
from utilities import checks
def setup(bot):
- bot.add_cog(Duelyst(bot))
+ bot.add_cog(Duelyst())
class Duelyst(commands.Cog):
-
- def __init__(self, bot):
- self.bot = bot
async def cog_check(self, ctx):
return await checks.not_forbidden().predicate(ctx)
@commands.group(invoke_without_command = True, case_insensitive = True)
async def duelyst(self, ctx):
'''Duelyst'''
await ctx.send_help(ctx.command)
@duelyst.group(case_insensitive = True)
async def card(self, ctx, *, name: str):
'''Details of a specific card'''
url = "https://duelyststats.info/scripts/carddata/get.php"
params = {"cardName": name}
async with ctx.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.text()
await ctx.embed_reply(data)
@card.command()
async def card_random(self, ctx):
'''Details of a random card'''
url = "https://duelyststats.info/scripts/carddata/get.php"
params = {"random": 1}
async with ctx.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.text()
await ctx.embed_reply(data)
| Remove unused bot attribute from Duelyst cog | ## Code Before:
from discord.ext import commands
from utilities import checks
def setup(bot):
bot.add_cog(Duelyst(bot))
class Duelyst(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def cog_check(self, ctx):
return await checks.not_forbidden().predicate(ctx)
@commands.group(invoke_without_command = True, case_insensitive = True)
async def duelyst(self, ctx):
'''Duelyst'''
await ctx.send_help(ctx.command)
@duelyst.group(case_insensitive = True)
async def card(self, ctx, *, name: str):
'''Details of a specific card'''
url = "https://duelyststats.info/scripts/carddata/get.php"
params = {"cardName": name}
async with ctx.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.text()
await ctx.embed_reply(data)
@card.command()
async def card_random(self, ctx):
'''Details of a random card'''
url = "https://duelyststats.info/scripts/carddata/get.php"
params = {"random": 1}
async with ctx.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.text()
await ctx.embed_reply(data)
## Instruction:
Remove unused bot attribute from Duelyst cog
## Code After:
from discord.ext import commands
from utilities import checks
def setup(bot):
bot.add_cog(Duelyst())
class Duelyst(commands.Cog):
async def cog_check(self, ctx):
return await checks.not_forbidden().predicate(ctx)
@commands.group(invoke_without_command = True, case_insensitive = True)
async def duelyst(self, ctx):
'''Duelyst'''
await ctx.send_help(ctx.command)
@duelyst.group(case_insensitive = True)
async def card(self, ctx, *, name: str):
'''Details of a specific card'''
url = "https://duelyststats.info/scripts/carddata/get.php"
params = {"cardName": name}
async with ctx.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.text()
await ctx.embed_reply(data)
@card.command()
async def card_random(self, ctx):
'''Details of a random card'''
url = "https://duelyststats.info/scripts/carddata/get.php"
params = {"random": 1}
async with ctx.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.text()
await ctx.embed_reply(data)
| // ... existing code ...
def setup(bot):
bot.add_cog(Duelyst())
// ... modified code ...
class Duelyst(commands.Cog):
// ... rest of the code ... |
de2e3dd947660b4b1222820141c5c7cd66098349 | django_split/models.py | django_split/models.py | from django.db import models
class ExperimentGroup(models.Model):
experiment = models.CharField(max_length=48)
user = models.ForeignKey('auth.User', related_name=None)
group = models.IntegerField()
class Meta:
unique_together = (
('experiment', 'user'),
)
class ExperimentState(models.Model):
experiment = models.CharField(max_length=48, primary_key=True)
started = models.DateTimeField(null=True)
completed = models.DateTimeField(null=True)
class ExperimentResult(models.Model):
experiment = models.CharField(max_length=48)
group = models.IntegerField()
metric = models.IntegerField()
percentile = models.IntegerField()
value = models.FloatField()
class Meta:
unique_together = (
('experiment', 'group', 'metric', 'percentile'),
)
| from django.db import models
class ExperimentGroup(models.Model):
experiment = models.CharField(max_length=48)
user = models.ForeignKey(
'auth.User',
related_name='django_split_experiment_groups',
)
group = models.IntegerField()
class Meta:
unique_together = (
('experiment', 'user'),
)
class ExperimentState(models.Model):
experiment = models.CharField(max_length=48, primary_key=True)
started = models.DateTimeField(null=True)
completed = models.DateTimeField(null=True)
class ExperimentResult(models.Model):
experiment = models.CharField(max_length=48)
group = models.IntegerField()
metric = models.IntegerField()
percentile = models.IntegerField()
value = models.FloatField()
class Meta:
unique_together = (
('experiment', 'group', 'metric', 'percentile'),
)
| Add an explicit related name | Add an explicit related name
| Python | mit | prophile/django_split | from django.db import models
class ExperimentGroup(models.Model):
experiment = models.CharField(max_length=48)
- user = models.ForeignKey('auth.User', related_name=None)
+ user = models.ForeignKey(
+ 'auth.User',
+ related_name='django_split_experiment_groups',
+ )
group = models.IntegerField()
class Meta:
unique_together = (
('experiment', 'user'),
)
class ExperimentState(models.Model):
experiment = models.CharField(max_length=48, primary_key=True)
started = models.DateTimeField(null=True)
completed = models.DateTimeField(null=True)
class ExperimentResult(models.Model):
experiment = models.CharField(max_length=48)
group = models.IntegerField()
metric = models.IntegerField()
percentile = models.IntegerField()
value = models.FloatField()
class Meta:
unique_together = (
('experiment', 'group', 'metric', 'percentile'),
)
| Add an explicit related name | ## Code Before:
from django.db import models
class ExperimentGroup(models.Model):
experiment = models.CharField(max_length=48)
user = models.ForeignKey('auth.User', related_name=None)
group = models.IntegerField()
class Meta:
unique_together = (
('experiment', 'user'),
)
class ExperimentState(models.Model):
experiment = models.CharField(max_length=48, primary_key=True)
started = models.DateTimeField(null=True)
completed = models.DateTimeField(null=True)
class ExperimentResult(models.Model):
experiment = models.CharField(max_length=48)
group = models.IntegerField()
metric = models.IntegerField()
percentile = models.IntegerField()
value = models.FloatField()
class Meta:
unique_together = (
('experiment', 'group', 'metric', 'percentile'),
)
## Instruction:
Add an explicit related name
## Code After:
from django.db import models
class ExperimentGroup(models.Model):
experiment = models.CharField(max_length=48)
user = models.ForeignKey(
'auth.User',
related_name='django_split_experiment_groups',
)
group = models.IntegerField()
class Meta:
unique_together = (
('experiment', 'user'),
)
class ExperimentState(models.Model):
experiment = models.CharField(max_length=48, primary_key=True)
started = models.DateTimeField(null=True)
completed = models.DateTimeField(null=True)
class ExperimentResult(models.Model):
experiment = models.CharField(max_length=48)
group = models.IntegerField()
metric = models.IntegerField()
percentile = models.IntegerField()
value = models.FloatField()
class Meta:
unique_together = (
('experiment', 'group', 'metric', 'percentile'),
)
| # ... existing code ...
user = models.ForeignKey(
'auth.User',
related_name='django_split_experiment_groups',
)
# ... rest of the code ... |
8b3132f9aec26d71498a153a29ea8d2049f07da6 | studygroups/admin.py | studygroups/admin.py | from django.contrib import admin
# Register your models here.
from studygroups.models import Course, StudyGroup, StudyGroupSignup, Application
class CourseAdmin(admin.ModelAdmin):
pass
class StudyGroupSignupInline(admin.TabularInline):
model = StudyGroupSignup
class StudyGroupAdmin(admin.ModelAdmin):
inlines = [StudyGroupSignupInline]
class StudyGroupSignupAdmin(admin.ModelAdmin):
pass
class ApplicationAdmin(admin.ModelAdmin):
pass
admin.site.register(Course, CourseAdmin)
admin.site.register(Application, ApplicationAdmin)
admin.site.register(StudyGroup, StudyGroupAdmin)
admin.site.register(StudyGroupSignup, StudyGroupSignupAdmin)
| from django.contrib import admin
# Register your models here.
from studygroups.models import Course, StudyGroup, StudyGroupSignup, Application
class StudyGroupSignupInline(admin.TabularInline):
model = StudyGroupSignup
class ApplicationInline(admin.TabularInline):
model = Application.study_groups.through
readonly_fields = ['user_name']
def user_name(self, instance):
return instance.application.name
user_name.short_description = 'user name'
class StudyGroupAdmin(admin.ModelAdmin):
inlines = [
#StudyGroupSignupInline,
ApplicationInline,
]
class StudyGroupSignupAdmin(admin.ModelAdmin):
pass
class CourseAdmin(admin.ModelAdmin):
pass
class ApplicationAdmin(admin.ModelAdmin):
list_display = ('name', 'contact_method', 'created_at')
admin.site.register(Course, CourseAdmin)
admin.site.register(Application, ApplicationAdmin)
admin.site.register(StudyGroup, StudyGroupAdmin)
admin.site.register(StudyGroupSignup, StudyGroupSignupAdmin)
| Add applications to study groups | Add applications to study groups
| Python | mit | p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles | from django.contrib import admin
# Register your models here.
from studygroups.models import Course, StudyGroup, StudyGroupSignup, Application
- class CourseAdmin(admin.ModelAdmin):
- pass
-
class StudyGroupSignupInline(admin.TabularInline):
model = StudyGroupSignup
+ class ApplicationInline(admin.TabularInline):
+ model = Application.study_groups.through
+ readonly_fields = ['user_name']
+ def user_name(self, instance):
+ return instance.application.name
+ user_name.short_description = 'user name'
+
class StudyGroupAdmin(admin.ModelAdmin):
- inlines = [StudyGroupSignupInline]
+ inlines = [
+ #StudyGroupSignupInline,
+ ApplicationInline,
+ ]
class StudyGroupSignupAdmin(admin.ModelAdmin):
pass
+ class CourseAdmin(admin.ModelAdmin):
+ pass
+
class ApplicationAdmin(admin.ModelAdmin):
- pass
+ list_display = ('name', 'contact_method', 'created_at')
+
admin.site.register(Course, CourseAdmin)
admin.site.register(Application, ApplicationAdmin)
admin.site.register(StudyGroup, StudyGroupAdmin)
admin.site.register(StudyGroupSignup, StudyGroupSignupAdmin)
| Add applications to study groups | ## Code Before:
from django.contrib import admin
# Register your models here.
from studygroups.models import Course, StudyGroup, StudyGroupSignup, Application
class CourseAdmin(admin.ModelAdmin):
pass
class StudyGroupSignupInline(admin.TabularInline):
model = StudyGroupSignup
class StudyGroupAdmin(admin.ModelAdmin):
inlines = [StudyGroupSignupInline]
class StudyGroupSignupAdmin(admin.ModelAdmin):
pass
class ApplicationAdmin(admin.ModelAdmin):
pass
admin.site.register(Course, CourseAdmin)
admin.site.register(Application, ApplicationAdmin)
admin.site.register(StudyGroup, StudyGroupAdmin)
admin.site.register(StudyGroupSignup, StudyGroupSignupAdmin)
## Instruction:
Add applications to study groups
## Code After:
from django.contrib import admin
# Register your models here.
from studygroups.models import Course, StudyGroup, StudyGroupSignup, Application
class StudyGroupSignupInline(admin.TabularInline):
model = StudyGroupSignup
class ApplicationInline(admin.TabularInline):
model = Application.study_groups.through
readonly_fields = ['user_name']
def user_name(self, instance):
return instance.application.name
user_name.short_description = 'user name'
class StudyGroupAdmin(admin.ModelAdmin):
inlines = [
#StudyGroupSignupInline,
ApplicationInline,
]
class StudyGroupSignupAdmin(admin.ModelAdmin):
pass
class CourseAdmin(admin.ModelAdmin):
pass
class ApplicationAdmin(admin.ModelAdmin):
list_display = ('name', 'contact_method', 'created_at')
admin.site.register(Course, CourseAdmin)
admin.site.register(Application, ApplicationAdmin)
admin.site.register(StudyGroup, StudyGroupAdmin)
admin.site.register(StudyGroupSignup, StudyGroupSignupAdmin)
| ...
class StudyGroupSignupInline(admin.TabularInline):
...
class ApplicationInline(admin.TabularInline):
model = Application.study_groups.through
readonly_fields = ['user_name']
def user_name(self, instance):
return instance.application.name
user_name.short_description = 'user name'
class StudyGroupAdmin(admin.ModelAdmin):
inlines = [
#StudyGroupSignupInline,
ApplicationInline,
]
...
class CourseAdmin(admin.ModelAdmin):
pass
class ApplicationAdmin(admin.ModelAdmin):
list_display = ('name', 'contact_method', 'created_at')
... |
470b7313fa9b176fa4492ac9f355acd21542265d | tests/test_lib_fallback.py | tests/test_lib_fallback.py | from mock import patch
from pytest import raises
from tvrenamr.errors import NoMoreLibrariesException
from tvrenamr.main import Episode
from .base import BaseTest
from .mock_requests import initially_bad_xml, invalid_xml
class TestLibrariesFallback(BaseTest):
@patch('tvrenamr.libraries.requests.get', new=invalid_xml)
def test_rename_with_all_libraries_returning_invalid_xml(self):
with raises(NoMoreLibrariesException):
self.tv.retrieve_episode_title(self._file.episodes[0])
@patch('tvrenamr.libraries.requests.get', new=initially_bad_xml)
def test_rename_with_tvdb_falling_over(self):
episode = Episode(self._file, '8')
title = self.tv.retrieve_episode_title(episode)
assert title == 'The Adhesive Duck Deficiency'
| from mock import patch
from pytest import raises
from tvrenamr.errors import NoMoreLibrariesException
from tvrenamr.libraries import TheTvDb, TvRage
from tvrenamr.main import Episode
from .base import BaseTest
from .mock_requests import initially_bad_xml, invalid_xml
class TestLibrariesFallback(BaseTest):
@patch('tvrenamr.libraries.requests.get', new=invalid_xml)
def test_rename_with_all_libraries_returning_invalid_xml(self):
with raises(NoMoreLibrariesException):
self.tv.retrieve_episode_title(self._file.episodes[0])
@patch('tvrenamr.libraries.requests.get', new=initially_bad_xml)
def test_rename_with_tvdb_falling_over(self):
episode = Episode(self._file, '8')
title = self.tv.retrieve_episode_title(episode)
assert title == 'The Adhesive Duck Deficiency'
def test_setting_library_stops_fallback(self):
libraries = self.tv._get_libraries('thetvdb')
assert type(libraries) == list
assert len(libraries) == 1
assert libraries[0] == TheTvDb
libraries = self.tv._get_libraries('tvrage')
assert type(libraries) == list
assert len(libraries) == 1
assert libraries[0] == TvRage
| Test library fallback is overridden by setting a library | Test library fallback is overridden by setting a library
| Python | mit | wintersandroid/tvrenamr,ghickman/tvrenamr | from mock import patch
from pytest import raises
from tvrenamr.errors import NoMoreLibrariesException
+ from tvrenamr.libraries import TheTvDb, TvRage
from tvrenamr.main import Episode
from .base import BaseTest
from .mock_requests import initially_bad_xml, invalid_xml
class TestLibrariesFallback(BaseTest):
@patch('tvrenamr.libraries.requests.get', new=invalid_xml)
def test_rename_with_all_libraries_returning_invalid_xml(self):
with raises(NoMoreLibrariesException):
self.tv.retrieve_episode_title(self._file.episodes[0])
@patch('tvrenamr.libraries.requests.get', new=initially_bad_xml)
def test_rename_with_tvdb_falling_over(self):
episode = Episode(self._file, '8')
title = self.tv.retrieve_episode_title(episode)
assert title == 'The Adhesive Duck Deficiency'
+ def test_setting_library_stops_fallback(self):
+ libraries = self.tv._get_libraries('thetvdb')
+ assert type(libraries) == list
+ assert len(libraries) == 1
+ assert libraries[0] == TheTvDb
+
+ libraries = self.tv._get_libraries('tvrage')
+ assert type(libraries) == list
+ assert len(libraries) == 1
+ assert libraries[0] == TvRage
+ | Test library fallback is overridden by setting a library | ## Code Before:
from mock import patch
from pytest import raises
from tvrenamr.errors import NoMoreLibrariesException
from tvrenamr.main import Episode
from .base import BaseTest
from .mock_requests import initially_bad_xml, invalid_xml
class TestLibrariesFallback(BaseTest):
@patch('tvrenamr.libraries.requests.get', new=invalid_xml)
def test_rename_with_all_libraries_returning_invalid_xml(self):
with raises(NoMoreLibrariesException):
self.tv.retrieve_episode_title(self._file.episodes[0])
@patch('tvrenamr.libraries.requests.get', new=initially_bad_xml)
def test_rename_with_tvdb_falling_over(self):
episode = Episode(self._file, '8')
title = self.tv.retrieve_episode_title(episode)
assert title == 'The Adhesive Duck Deficiency'
## Instruction:
Test library fallback is overridden by setting a library
## Code After:
from mock import patch
from pytest import raises
from tvrenamr.errors import NoMoreLibrariesException
from tvrenamr.libraries import TheTvDb, TvRage
from tvrenamr.main import Episode
from .base import BaseTest
from .mock_requests import initially_bad_xml, invalid_xml
class TestLibrariesFallback(BaseTest):
@patch('tvrenamr.libraries.requests.get', new=invalid_xml)
def test_rename_with_all_libraries_returning_invalid_xml(self):
with raises(NoMoreLibrariesException):
self.tv.retrieve_episode_title(self._file.episodes[0])
@patch('tvrenamr.libraries.requests.get', new=initially_bad_xml)
def test_rename_with_tvdb_falling_over(self):
episode = Episode(self._file, '8')
title = self.tv.retrieve_episode_title(episode)
assert title == 'The Adhesive Duck Deficiency'
def test_setting_library_stops_fallback(self):
libraries = self.tv._get_libraries('thetvdb')
assert type(libraries) == list
assert len(libraries) == 1
assert libraries[0] == TheTvDb
libraries = self.tv._get_libraries('tvrage')
assert type(libraries) == list
assert len(libraries) == 1
assert libraries[0] == TvRage
| ...
from tvrenamr.errors import NoMoreLibrariesException
from tvrenamr.libraries import TheTvDb, TvRage
from tvrenamr.main import Episode
...
assert title == 'The Adhesive Duck Deficiency'
def test_setting_library_stops_fallback(self):
libraries = self.tv._get_libraries('thetvdb')
assert type(libraries) == list
assert len(libraries) == 1
assert libraries[0] == TheTvDb
libraries = self.tv._get_libraries('tvrage')
assert type(libraries) == list
assert len(libraries) == 1
assert libraries[0] == TvRage
... |
1f1e1a78f56e890777ca6f88cc30be7710275aea | blackbelt/deployment.py | blackbelt/deployment.py | from subprocess import check_call
from blackbelt.handle_github import get_current_branch
from blackbelt.messages import post_message
def deploy_staging():
branch_name = get_current_branch()
post_message("Deploying branch %s to staging" % branch_name, "#deploy-queue")
check_call(['grunt', 'deploy', '--app=apiary-staging', '--force', "--branch=%s" % branch_name])
def deploy_production():
post_message("Deploying to production", "#deploy-queue")
check_call(['grunt', 'deploy'])
| from subprocess import check_call
from blackbelt.handle_github import get_current_branch
from blackbelt.messages import post_message
def deploy_staging():
branch_name = get_current_branch()
post_message("Deploying branch %s to staging" % branch_name, "#deploy-queue")
check_call(['grunt', 'deploy', '--app=apiary-staging-pool1', '--force', "--branch=%s" % branch_name])
def deploy_production():
post_message("Deploying to production", "#deploy-queue")
check_call(['grunt', 'deploy'])
check_call(['grunt', 'deploy', '--app=apiary-staging'])
| Update deploy and stage with new environ | feat: Update deploy and stage with new environ | Python | mit | apiaryio/black-belt | from subprocess import check_call
from blackbelt.handle_github import get_current_branch
from blackbelt.messages import post_message
def deploy_staging():
branch_name = get_current_branch()
post_message("Deploying branch %s to staging" % branch_name, "#deploy-queue")
- check_call(['grunt', 'deploy', '--app=apiary-staging', '--force', "--branch=%s" % branch_name])
+ check_call(['grunt', 'deploy', '--app=apiary-staging-pool1', '--force', "--branch=%s" % branch_name])
def deploy_production():
post_message("Deploying to production", "#deploy-queue")
check_call(['grunt', 'deploy'])
+ check_call(['grunt', 'deploy', '--app=apiary-staging'])
| Update deploy and stage with new environ | ## Code Before:
from subprocess import check_call
from blackbelt.handle_github import get_current_branch
from blackbelt.messages import post_message
def deploy_staging():
branch_name = get_current_branch()
post_message("Deploying branch %s to staging" % branch_name, "#deploy-queue")
check_call(['grunt', 'deploy', '--app=apiary-staging', '--force', "--branch=%s" % branch_name])
def deploy_production():
post_message("Deploying to production", "#deploy-queue")
check_call(['grunt', 'deploy'])
## Instruction:
Update deploy and stage with new environ
## Code After:
from subprocess import check_call
from blackbelt.handle_github import get_current_branch
from blackbelt.messages import post_message
def deploy_staging():
branch_name = get_current_branch()
post_message("Deploying branch %s to staging" % branch_name, "#deploy-queue")
check_call(['grunt', 'deploy', '--app=apiary-staging-pool1', '--force', "--branch=%s" % branch_name])
def deploy_production():
post_message("Deploying to production", "#deploy-queue")
check_call(['grunt', 'deploy'])
check_call(['grunt', 'deploy', '--app=apiary-staging'])
| ...
check_call(['grunt', 'deploy', '--app=apiary-staging-pool1', '--force', "--branch=%s" % branch_name])
...
check_call(['grunt', 'deploy'])
check_call(['grunt', 'deploy', '--app=apiary-staging'])
... |
67752442760221c2e53990bb5dd10f1e045d74a1 | nltk_training/information_extraction.py | nltk_training/information_extraction.py |
from __future__ import division
import feedparser, os
from BeautifulSoup import BeautifulSoup
import nltk, re, pprint
from nltk import word_tokenize
# from urllib2 import Request as request
import urllib2
def ie_preprocess(document):
sentences = nltk.sent_tokenize(document) [1]
sentences = [nltk.word_tokenize(sent) for sent in sentences] [2]
sentences = [nltk.pos_tag(sent) for sent in sentences]
return sentences
dir_path = os.path.dirname(os.path.realpath(__file__))
with open(dir_path+"/../bible_fulltext/Bible_French_djvu.txt") as file:
ie_preprocess(file.read().decode('utf8'))
|
from __future__ import division
import feedparser, os
from BeautifulSoup import BeautifulSoup
import nltk, re, pprint
from nltk import word_tokenize
# from urllib2 import Request as request
import urllib2
def ie_preprocess(document):
sentences = nltk.sent_tokenize(document)
sentences = [nltk.word_tokenize(sent) for sent in sentences]
sentences = [nltk.pos_tag(sent) for sent in sentences]
return sentences
dir_path = os.path.dirname(os.path.realpath(__file__))
with open(dir_path+"/../bible_fulltext/Bible_French_djvu_Genesis.txt") as file:
sentences = ie_preprocess(file.read().decode('utf8'))
cp = nltk.RegexpParser('CHUNK: {<V.*> <TO> <V.*>}')
for sent in sentences:
#print sent
tree = cp.parse(sent)
for subtree in tree.subtrees():
if subtree.label() == 'CHUNK': print (subtree)
| Add lastest updates to script | Add lastest updates to script
| Python | apache-2.0 | fullbright/gary-reporter,fullbright/gary-reporter |
from __future__ import division
import feedparser, os
from BeautifulSoup import BeautifulSoup
import nltk, re, pprint
from nltk import word_tokenize
# from urllib2 import Request as request
import urllib2
def ie_preprocess(document):
- sentences = nltk.sent_tokenize(document) [1]
+ sentences = nltk.sent_tokenize(document)
- sentences = [nltk.word_tokenize(sent) for sent in sentences] [2]
+ sentences = [nltk.word_tokenize(sent) for sent in sentences]
sentences = [nltk.pos_tag(sent) for sent in sentences]
return sentences
dir_path = os.path.dirname(os.path.realpath(__file__))
- with open(dir_path+"/../bible_fulltext/Bible_French_djvu.txt") as file:
+ with open(dir_path+"/../bible_fulltext/Bible_French_djvu_Genesis.txt") as file:
- ie_preprocess(file.read().decode('utf8'))
+ sentences = ie_preprocess(file.read().decode('utf8'))
+ cp = nltk.RegexpParser('CHUNK: {<V.*> <TO> <V.*>}')
+ for sent in sentences:
+ #print sent
+ tree = cp.parse(sent)
+ for subtree in tree.subtrees():
+ if subtree.label() == 'CHUNK': print (subtree)
| Add lastest updates to script | ## Code Before:
from __future__ import division
import feedparser, os
from BeautifulSoup import BeautifulSoup
import nltk, re, pprint
from nltk import word_tokenize
# from urllib2 import Request as request
import urllib2
def ie_preprocess(document):
sentences = nltk.sent_tokenize(document) [1]
sentences = [nltk.word_tokenize(sent) for sent in sentences] [2]
sentences = [nltk.pos_tag(sent) for sent in sentences]
return sentences
dir_path = os.path.dirname(os.path.realpath(__file__))
with open(dir_path+"/../bible_fulltext/Bible_French_djvu.txt") as file:
ie_preprocess(file.read().decode('utf8'))
## Instruction:
Add lastest updates to script
## Code After:
from __future__ import division
import feedparser, os
from BeautifulSoup import BeautifulSoup
import nltk, re, pprint
from nltk import word_tokenize
# from urllib2 import Request as request
import urllib2
def ie_preprocess(document):
sentences = nltk.sent_tokenize(document)
sentences = [nltk.word_tokenize(sent) for sent in sentences]
sentences = [nltk.pos_tag(sent) for sent in sentences]
return sentences
dir_path = os.path.dirname(os.path.realpath(__file__))
with open(dir_path+"/../bible_fulltext/Bible_French_djvu_Genesis.txt") as file:
sentences = ie_preprocess(file.read().decode('utf8'))
cp = nltk.RegexpParser('CHUNK: {<V.*> <TO> <V.*>}')
for sent in sentences:
#print sent
tree = cp.parse(sent)
for subtree in tree.subtrees():
if subtree.label() == 'CHUNK': print (subtree)
| // ... existing code ...
def ie_preprocess(document):
sentences = nltk.sent_tokenize(document)
sentences = [nltk.word_tokenize(sent) for sent in sentences]
sentences = [nltk.pos_tag(sent) for sent in sentences]
// ... modified code ...
dir_path = os.path.dirname(os.path.realpath(__file__))
with open(dir_path+"/../bible_fulltext/Bible_French_djvu_Genesis.txt") as file:
sentences = ie_preprocess(file.read().decode('utf8'))
cp = nltk.RegexpParser('CHUNK: {<V.*> <TO> <V.*>}')
for sent in sentences:
#print sent
tree = cp.parse(sent)
for subtree in tree.subtrees():
if subtree.label() == 'CHUNK': print (subtree)
// ... rest of the code ... |
c5158020475e62d7e8b86a613a02c0a659038f88 | formish/tests/testish/testish/lib/xformish.py | formish/tests/testish/testish/lib/xformish.py |
from formish import validation, widgets, Form
class DateParts(widgets.DateParts):
def __init__(self, **k):
k['day_first'] = k.pop('l10n').is_day_first()
super(DateParts, self).__init__(**k)
class ApproximateDateParts(widgets.DateParts):
_template = 'ApproximateDateParts'
def pre_render(self, schema_type, data):
if data is None:
return {'year': [''], 'month': [''], 'day': ['']}
parts = [i for i in data.split('-')]
parts.extend(['']*(3-len(parts)))
return {'year': [parts[0]], 'month': [parts[1]], 'day': [parts[2]]}
def convert(self, schema_type, data):
# Collect all the parts from the request.
parts = (data['year'][0].strip(), data['month'][0], data['day'][0])
if not parts[0] and (parts[1] or parts[2]):
raise validation.FieldValidationError("Invalid date")
elif not parts[1] and parts[2]:
raise validation.FieldValidationError("Invalid date")
# Discard the unspecified parts
parts = [p for p in parts if p]
# Ensure they're all integers (don't record the result, we don't care).
try:
[int(p) for p in parts]
except ValueError:
raise validation.FieldValidationError("Invalid date")
return '-'.join(parts)
|
from formish import validation, widgets, Form
from convertish.convert import ConvertError
class DateParts(widgets.DateParts):
def __init__(self, **k):
k['day_first'] = k.pop('l10n').is_day_first()
super(DateParts, self).__init__(**k)
class ApproximateDateParts(widgets.DateParts):
_template = 'ApproximateDateParts'
def pre_render(self, schema_type, data):
if data is None:
return {'year': [''], 'month': [''], 'day': ['']}
parts = [i for i in data.split('-')]
parts.extend(['']*(3-len(parts)))
return {'year': [parts[0]], 'month': [parts[1]], 'day': [parts[2]]}
def convert(self, schema_type, data):
# Collect all the parts from the request.
parts = (data['year'][0].strip(), data['month'][0], data['day'][0])
if not parts[0] and (parts[1] or parts[2]):
raise ConvertError("Invalid date")
elif not parts[1] and parts[2]:
raise ConvertError("Invalid date")
# Discard the unspecified parts
parts = [p for p in parts if p]
# Ensure they're all integers (don't record the result, we don't care).
try:
[int(p) for p in parts]
except ValueError:
raise ConvertError("Invalid date")
return '-'.join(parts)
| Fix custom widget to raise correct exception type. | Fix custom widget to raise correct exception type.
| Python | bsd-3-clause | ish/formish,ish/formish,ish/formish |
from formish import validation, widgets, Form
+ from convertish.convert import ConvertError
class DateParts(widgets.DateParts):
def __init__(self, **k):
k['day_first'] = k.pop('l10n').is_day_first()
super(DateParts, self).__init__(**k)
class ApproximateDateParts(widgets.DateParts):
_template = 'ApproximateDateParts'
def pre_render(self, schema_type, data):
if data is None:
return {'year': [''], 'month': [''], 'day': ['']}
parts = [i for i in data.split('-')]
parts.extend(['']*(3-len(parts)))
return {'year': [parts[0]], 'month': [parts[1]], 'day': [parts[2]]}
def convert(self, schema_type, data):
# Collect all the parts from the request.
parts = (data['year'][0].strip(), data['month'][0], data['day'][0])
if not parts[0] and (parts[1] or parts[2]):
- raise validation.FieldValidationError("Invalid date")
+ raise ConvertError("Invalid date")
elif not parts[1] and parts[2]:
- raise validation.FieldValidationError("Invalid date")
+ raise ConvertError("Invalid date")
# Discard the unspecified parts
parts = [p for p in parts if p]
# Ensure they're all integers (don't record the result, we don't care).
try:
[int(p) for p in parts]
except ValueError:
- raise validation.FieldValidationError("Invalid date")
+ raise ConvertError("Invalid date")
return '-'.join(parts)
| Fix custom widget to raise correct exception type. | ## Code Before:
from formish import validation, widgets, Form
class DateParts(widgets.DateParts):
def __init__(self, **k):
k['day_first'] = k.pop('l10n').is_day_first()
super(DateParts, self).__init__(**k)
class ApproximateDateParts(widgets.DateParts):
_template = 'ApproximateDateParts'
def pre_render(self, schema_type, data):
if data is None:
return {'year': [''], 'month': [''], 'day': ['']}
parts = [i for i in data.split('-')]
parts.extend(['']*(3-len(parts)))
return {'year': [parts[0]], 'month': [parts[1]], 'day': [parts[2]]}
def convert(self, schema_type, data):
# Collect all the parts from the request.
parts = (data['year'][0].strip(), data['month'][0], data['day'][0])
if not parts[0] and (parts[1] or parts[2]):
raise validation.FieldValidationError("Invalid date")
elif not parts[1] and parts[2]:
raise validation.FieldValidationError("Invalid date")
# Discard the unspecified parts
parts = [p for p in parts if p]
# Ensure they're all integers (don't record the result, we don't care).
try:
[int(p) for p in parts]
except ValueError:
raise validation.FieldValidationError("Invalid date")
return '-'.join(parts)
## Instruction:
Fix custom widget to raise correct exception type.
## Code After:
from formish import validation, widgets, Form
from convertish.convert import ConvertError
class DateParts(widgets.DateParts):
def __init__(self, **k):
k['day_first'] = k.pop('l10n').is_day_first()
super(DateParts, self).__init__(**k)
class ApproximateDateParts(widgets.DateParts):
_template = 'ApproximateDateParts'
def pre_render(self, schema_type, data):
if data is None:
return {'year': [''], 'month': [''], 'day': ['']}
parts = [i for i in data.split('-')]
parts.extend(['']*(3-len(parts)))
return {'year': [parts[0]], 'month': [parts[1]], 'day': [parts[2]]}
def convert(self, schema_type, data):
# Collect all the parts from the request.
parts = (data['year'][0].strip(), data['month'][0], data['day'][0])
if not parts[0] and (parts[1] or parts[2]):
raise ConvertError("Invalid date")
elif not parts[1] and parts[2]:
raise ConvertError("Invalid date")
# Discard the unspecified parts
parts = [p for p in parts if p]
# Ensure they're all integers (don't record the result, we don't care).
try:
[int(p) for p in parts]
except ValueError:
raise ConvertError("Invalid date")
return '-'.join(parts)
| # ... existing code ...
from formish import validation, widgets, Form
from convertish.convert import ConvertError
# ... modified code ...
if not parts[0] and (parts[1] or parts[2]):
raise ConvertError("Invalid date")
elif not parts[1] and parts[2]:
raise ConvertError("Invalid date")
# Discard the unspecified parts
...
except ValueError:
raise ConvertError("Invalid date")
return '-'.join(parts)
# ... rest of the code ... |
20cc6c1edca69c946261c6bd8587d6cf5bb7a6e8 | tests/core/eth-module/test_eth_contract.py | tests/core/eth-module/test_eth_contract.py | import sys
import pytest
if sys.version_info >= (3, 3):
from unittest.mock import Mock
ABI = [{}]
ADDRESS = '0xd3cda913deb6f67967b99d67acdfa1712c293601'
INVALID_CHECKSUM_ADDRESS = '0xd3CDA913deB6f67967B99D67aCDFa1712C293601'
@pytest.mark.parametrize(
'args,kwargs,expected',
(
((ADDRESS,), {}, None),
((INVALID_CHECKSUM_ADDRESS,), {}, ValueError),
((), {'address': INVALID_CHECKSUM_ADDRESS}, ValueError),
((), {'address': INVALID_CHECKSUM_ADDRESS}, ValueError),
)
)
def test_contract_address_validation(web3, args, kwargs, expected):
if isinstance(expected, type) and issubclass(expected, Exception):
with pytest.raises(expected):
web3.eth.contract(*args, **kwargs)
return
# run without errors
web3.eth.contract(*args, **kwargs)
@pytest.mark.skipif(sys.version_info < (3, 3), reason="needs Mock library from 3.3")
def test_set_contract_factory(web3):
factoryClass = Mock()
web3.eth.setContractFactory(factoryClass)
web3.eth.contract(contract_name='myname')
factoryClass.factory.assert_called_once_with(web3, contract_name='myname')
| import sys
import pytest
if sys.version_info >= (3, 3):
from unittest.mock import Mock
ABI = [{}]
ADDRESS = '0xd3cda913deb6f67967b99d67acdfa1712c293601'
INVALID_CHECKSUM_ADDRESS = '0xd3CDA913deB6f67967B99D67aCDFa1712C293601'
@pytest.mark.parametrize(
'args,kwargs,expected',
(
((ADDRESS,), {}, None),
((INVALID_CHECKSUM_ADDRESS,), {}, ValueError),
((), {'address': ADDRESS}, None),
((), {'address': INVALID_CHECKSUM_ADDRESS}, ValueError),
)
)
def test_contract_address_validation(web3, args, kwargs, expected):
if isinstance(expected, type) and issubclass(expected, Exception):
with pytest.raises(expected):
web3.eth.contract(*args, **kwargs)
return
# run without errors
web3.eth.contract(*args, **kwargs)
@pytest.mark.skipif(sys.version_info < (3, 3), reason="needs Mock library from 3.3")
def test_set_contract_factory(web3):
factoryClass = Mock()
web3.eth.setContractFactory(factoryClass)
web3.eth.contract(contract_name='myname')
factoryClass.factory.assert_called_once_with(web3, contract_name='myname')
| Replace duplicate test with valid address kwarg | Replace duplicate test with valid address kwarg
| Python | mit | pipermerriam/web3.py | import sys
import pytest
if sys.version_info >= (3, 3):
from unittest.mock import Mock
ABI = [{}]
ADDRESS = '0xd3cda913deb6f67967b99d67acdfa1712c293601'
INVALID_CHECKSUM_ADDRESS = '0xd3CDA913deB6f67967B99D67aCDFa1712C293601'
@pytest.mark.parametrize(
'args,kwargs,expected',
(
((ADDRESS,), {}, None),
((INVALID_CHECKSUM_ADDRESS,), {}, ValueError),
- ((), {'address': INVALID_CHECKSUM_ADDRESS}, ValueError),
+ ((), {'address': ADDRESS}, None),
((), {'address': INVALID_CHECKSUM_ADDRESS}, ValueError),
)
)
def test_contract_address_validation(web3, args, kwargs, expected):
if isinstance(expected, type) and issubclass(expected, Exception):
with pytest.raises(expected):
web3.eth.contract(*args, **kwargs)
return
# run without errors
web3.eth.contract(*args, **kwargs)
@pytest.mark.skipif(sys.version_info < (3, 3), reason="needs Mock library from 3.3")
def test_set_contract_factory(web3):
factoryClass = Mock()
web3.eth.setContractFactory(factoryClass)
web3.eth.contract(contract_name='myname')
factoryClass.factory.assert_called_once_with(web3, contract_name='myname')
| Replace duplicate test with valid address kwarg | ## Code Before:
import sys
import pytest
if sys.version_info >= (3, 3):
from unittest.mock import Mock
ABI = [{}]
ADDRESS = '0xd3cda913deb6f67967b99d67acdfa1712c293601'
INVALID_CHECKSUM_ADDRESS = '0xd3CDA913deB6f67967B99D67aCDFa1712C293601'
@pytest.mark.parametrize(
'args,kwargs,expected',
(
((ADDRESS,), {}, None),
((INVALID_CHECKSUM_ADDRESS,), {}, ValueError),
((), {'address': INVALID_CHECKSUM_ADDRESS}, ValueError),
((), {'address': INVALID_CHECKSUM_ADDRESS}, ValueError),
)
)
def test_contract_address_validation(web3, args, kwargs, expected):
if isinstance(expected, type) and issubclass(expected, Exception):
with pytest.raises(expected):
web3.eth.contract(*args, **kwargs)
return
# run without errors
web3.eth.contract(*args, **kwargs)
@pytest.mark.skipif(sys.version_info < (3, 3), reason="needs Mock library from 3.3")
def test_set_contract_factory(web3):
factoryClass = Mock()
web3.eth.setContractFactory(factoryClass)
web3.eth.contract(contract_name='myname')
factoryClass.factory.assert_called_once_with(web3, contract_name='myname')
## Instruction:
Replace duplicate test with valid address kwarg
## Code After:
import sys
import pytest
if sys.version_info >= (3, 3):
from unittest.mock import Mock
ABI = [{}]
ADDRESS = '0xd3cda913deb6f67967b99d67acdfa1712c293601'
INVALID_CHECKSUM_ADDRESS = '0xd3CDA913deB6f67967B99D67aCDFa1712C293601'
@pytest.mark.parametrize(
'args,kwargs,expected',
(
((ADDRESS,), {}, None),
((INVALID_CHECKSUM_ADDRESS,), {}, ValueError),
((), {'address': ADDRESS}, None),
((), {'address': INVALID_CHECKSUM_ADDRESS}, ValueError),
)
)
def test_contract_address_validation(web3, args, kwargs, expected):
if isinstance(expected, type) and issubclass(expected, Exception):
with pytest.raises(expected):
web3.eth.contract(*args, **kwargs)
return
# run without errors
web3.eth.contract(*args, **kwargs)
@pytest.mark.skipif(sys.version_info < (3, 3), reason="needs Mock library from 3.3")
def test_set_contract_factory(web3):
factoryClass = Mock()
web3.eth.setContractFactory(factoryClass)
web3.eth.contract(contract_name='myname')
factoryClass.factory.assert_called_once_with(web3, contract_name='myname')
| ...
((INVALID_CHECKSUM_ADDRESS,), {}, ValueError),
((), {'address': ADDRESS}, None),
((), {'address': INVALID_CHECKSUM_ADDRESS}, ValueError),
... |
6af918668cddf30c12a10fe46bc174e110bf04c3 | red_api.py | red_api.py | import os
from pymongo import MongoClient
MONGO_USER = os.getenv('MONGO_USER')
MONGO_PASSWORD = os.getenv('MONGO_PASSWORD')
MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD)
# Open a connection to Mongo once
#
mongo_client = MongoClient(MONGO_URI)
red_john_tweets = mongo_client.redjohn.tweets
suspects = [
'partridge', 'kirkland', 'bertram', 'stiles', 'haffner',
'mcallister', 'smith'
]
def get_suspect_mentions():
suspect_mentions = {}
for suspect in suspects:
mentions = red_john_tweets.find({
'suspect': suspect
}).count()
suspect_mentions[suspect] = mentions
return suspect_mentions
def get_tweet_count():
return red_john_tweets.count()
def get_suspect_tweets(suspect, limit=5):
tweets = red_john_tweets.find({
'suspect': suspect
})[:limit]
return list(tweets) | import os
from pymongo import DESCENDING
from pymongo import MongoClient
from bson.json_util import dumps
MONGO_USER = os.getenv('MONGO_USER')
MONGO_PASSWORD = os.getenv('MONGO_PASSWORD')
MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD)
# Open a connection to Mongo once
#
mongo_client = MongoClient(MONGO_URI)
red_john_tweets = mongo_client.redjohn.tweets
suspects = [
'partridge', 'kirkland', 'bertram', 'stiles', 'haffner',
'mcallister', 'smith'
]
def get_suspect_mentions():
suspect_mentions = {}
for suspect in suspects:
mentions = red_john_tweets.find({
'suspect': suspect
}).count()
suspect_mentions[suspect] = mentions
return suspect_mentions
def get_tweet_count():
return red_john_tweets.count()
def get_suspect_tweets(suspect, limit=5):
tweets = red_john_tweets.find({
'suspect': suspect
}).sort('entry_time', DESCENDING)[:limit]
return dumps(tweets) | Use bson's JSON util to handle ObjectIds in a JSON context | Use bson's JSON util to handle ObjectIds in a JSON context
| Python | mit | AnSavvides/redjohn,AnSavvides/redjohn | import os
+ from pymongo import DESCENDING
from pymongo import MongoClient
+ from bson.json_util import dumps
MONGO_USER = os.getenv('MONGO_USER')
MONGO_PASSWORD = os.getenv('MONGO_PASSWORD')
MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD)
# Open a connection to Mongo once
#
mongo_client = MongoClient(MONGO_URI)
red_john_tweets = mongo_client.redjohn.tweets
suspects = [
'partridge', 'kirkland', 'bertram', 'stiles', 'haffner',
'mcallister', 'smith'
]
def get_suspect_mentions():
suspect_mentions = {}
for suspect in suspects:
mentions = red_john_tweets.find({
'suspect': suspect
}).count()
suspect_mentions[suspect] = mentions
return suspect_mentions
def get_tweet_count():
return red_john_tweets.count()
def get_suspect_tweets(suspect, limit=5):
tweets = red_john_tweets.find({
'suspect': suspect
- })[:limit]
+ }).sort('entry_time', DESCENDING)[:limit]
- return list(tweets)
+ return dumps(tweets) | Use bson's JSON util to handle ObjectIds in a JSON context | ## Code Before:
import os
from pymongo import MongoClient
MONGO_USER = os.getenv('MONGO_USER')
MONGO_PASSWORD = os.getenv('MONGO_PASSWORD')
MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD)
# Open a connection to Mongo once
#
mongo_client = MongoClient(MONGO_URI)
red_john_tweets = mongo_client.redjohn.tweets
suspects = [
'partridge', 'kirkland', 'bertram', 'stiles', 'haffner',
'mcallister', 'smith'
]
def get_suspect_mentions():
suspect_mentions = {}
for suspect in suspects:
mentions = red_john_tweets.find({
'suspect': suspect
}).count()
suspect_mentions[suspect] = mentions
return suspect_mentions
def get_tweet_count():
return red_john_tweets.count()
def get_suspect_tweets(suspect, limit=5):
tweets = red_john_tweets.find({
'suspect': suspect
})[:limit]
return list(tweets)
## Instruction:
Use bson's JSON util to handle ObjectIds in a JSON context
## Code After:
import os
from pymongo import DESCENDING
from pymongo import MongoClient
from bson.json_util import dumps
MONGO_USER = os.getenv('MONGO_USER')
MONGO_PASSWORD = os.getenv('MONGO_PASSWORD')
MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD)
# Open a connection to Mongo once
#
mongo_client = MongoClient(MONGO_URI)
red_john_tweets = mongo_client.redjohn.tweets
suspects = [
'partridge', 'kirkland', 'bertram', 'stiles', 'haffner',
'mcallister', 'smith'
]
def get_suspect_mentions():
suspect_mentions = {}
for suspect in suspects:
mentions = red_john_tweets.find({
'suspect': suspect
}).count()
suspect_mentions[suspect] = mentions
return suspect_mentions
def get_tweet_count():
return red_john_tweets.count()
def get_suspect_tweets(suspect, limit=5):
tweets = red_john_tweets.find({
'suspect': suspect
}).sort('entry_time', DESCENDING)[:limit]
return dumps(tweets) | ...
import os
from pymongo import DESCENDING
from pymongo import MongoClient
from bson.json_util import dumps
...
'suspect': suspect
}).sort('entry_time', DESCENDING)[:limit]
return dumps(tweets)
... |
18332cdac7c7dcb2ef64e3a9ad17b8b229387af8 | spraakbanken/s5/spr_local/reconstruct_corpus.py | spraakbanken/s5/spr_local/reconstruct_corpus.py |
import argparse
import collections
import random
import sys
def reconstruct(f_in, f_out):
sentence_starts = []
contexts = {}
for line in f_in:
parts = line.split()
words = parts[:-1]
count = int(parts[-1])
if words[0] == "<s>" and words[-1] == "</s>":
for _ in range(count):
print(" ".join(words), file=f_out)
continue
context = tuple(words[:-1])
if context not in contexts:
contexts[context] = collections.Counter()
contexts[context][words[-1]] += count
random.shuffle(sentence_starts)
c = len(sentence_starts[0]) - 1
for start in sentence_starts:
line = list(start)
while line[-1] != "</s>":
context = line[:-c]
next_word = contexts[context].most_common(1)[0][0]
contexts[context][next_word] -= 1
line.append(next_word)
print(" ".join(line), file=f_out)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Construct corpus')
parser.add_argument('infile', nargs='?', type=argparse.FileType('r', encoding='utf-8'), default=sys.stdin)
parser.add_argument('outfile', nargs='?', type=argparse.FileType('w', encoding='utf-8'), default=sys.stdout)
args = parser.parse_args()
reconstruct(args.infile, args.outfile)
|
from __future__ import print_function
import argparse
import collections
import random
import sys
def reconstruct(f_in, f_out):
sentence_starts = []
contexts = {}
for line in f_in:
parts = line.split()
words = parts[:-1]
count = int(parts[-1])
if words[0] == "<s>" and words[-1] == "</s>":
for _ in range(count):
print(" ".join(words), file=f_out)
continue
context = tuple(words[:-1])
if context not in contexts:
contexts[context] = collections.Counter()
contexts[context][words[-1]] += count
random.shuffle(sentence_starts)
c = len(sentence_starts[0]) - 1
for start in sentence_starts:
line = list(start)
while line[-1] != "</s>":
context = line[:-c]
next_word = contexts[context].most_common(1)[0][0]
contexts[context][next_word] -= 1
line.append(next_word)
print(" ".join(line), file=f_out)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Construct corpus')
parser.add_argument('infile', nargs='?', type=argparse.FileType('r', encoding='utf-8'), default=sys.stdin)
parser.add_argument('outfile', nargs='?', type=argparse.FileType('w', encoding='utf-8'), default=sys.stdout)
args = parser.parse_args()
reconstruct(args.infile, args.outfile)
| Add reconstruct corpus as a test | Add reconstruct corpus as a test
| Python | apache-2.0 | psmit/kaldi-recipes,phsmit/kaldi-recipes,psmit/kaldi-recipes,psmit/kaldi-recipes,phsmit/kaldi-recipes | +
+ from __future__ import print_function
import argparse
import collections
import random
import sys
def reconstruct(f_in, f_out):
sentence_starts = []
contexts = {}
for line in f_in:
parts = line.split()
words = parts[:-1]
count = int(parts[-1])
if words[0] == "<s>" and words[-1] == "</s>":
for _ in range(count):
print(" ".join(words), file=f_out)
continue
context = tuple(words[:-1])
if context not in contexts:
contexts[context] = collections.Counter()
contexts[context][words[-1]] += count
random.shuffle(sentence_starts)
c = len(sentence_starts[0]) - 1
for start in sentence_starts:
line = list(start)
while line[-1] != "</s>":
context = line[:-c]
next_word = contexts[context].most_common(1)[0][0]
contexts[context][next_word] -= 1
line.append(next_word)
print(" ".join(line), file=f_out)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Construct corpus')
parser.add_argument('infile', nargs='?', type=argparse.FileType('r', encoding='utf-8'), default=sys.stdin)
parser.add_argument('outfile', nargs='?', type=argparse.FileType('w', encoding='utf-8'), default=sys.stdout)
args = parser.parse_args()
reconstruct(args.infile, args.outfile)
| Add reconstruct corpus as a test | ## Code Before:
import argparse
import collections
import random
import sys
def reconstruct(f_in, f_out):
sentence_starts = []
contexts = {}
for line in f_in:
parts = line.split()
words = parts[:-1]
count = int(parts[-1])
if words[0] == "<s>" and words[-1] == "</s>":
for _ in range(count):
print(" ".join(words), file=f_out)
continue
context = tuple(words[:-1])
if context not in contexts:
contexts[context] = collections.Counter()
contexts[context][words[-1]] += count
random.shuffle(sentence_starts)
c = len(sentence_starts[0]) - 1
for start in sentence_starts:
line = list(start)
while line[-1] != "</s>":
context = line[:-c]
next_word = contexts[context].most_common(1)[0][0]
contexts[context][next_word] -= 1
line.append(next_word)
print(" ".join(line), file=f_out)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Construct corpus')
parser.add_argument('infile', nargs='?', type=argparse.FileType('r', encoding='utf-8'), default=sys.stdin)
parser.add_argument('outfile', nargs='?', type=argparse.FileType('w', encoding='utf-8'), default=sys.stdout)
args = parser.parse_args()
reconstruct(args.infile, args.outfile)
## Instruction:
Add reconstruct corpus as a test
## Code After:
from __future__ import print_function
import argparse
import collections
import random
import sys
def reconstruct(f_in, f_out):
sentence_starts = []
contexts = {}
for line in f_in:
parts = line.split()
words = parts[:-1]
count = int(parts[-1])
if words[0] == "<s>" and words[-1] == "</s>":
for _ in range(count):
print(" ".join(words), file=f_out)
continue
context = tuple(words[:-1])
if context not in contexts:
contexts[context] = collections.Counter()
contexts[context][words[-1]] += count
random.shuffle(sentence_starts)
c = len(sentence_starts[0]) - 1
for start in sentence_starts:
line = list(start)
while line[-1] != "</s>":
context = line[:-c]
next_word = contexts[context].most_common(1)[0][0]
contexts[context][next_word] -= 1
line.append(next_word)
print(" ".join(line), file=f_out)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Construct corpus')
parser.add_argument('infile', nargs='?', type=argparse.FileType('r', encoding='utf-8'), default=sys.stdin)
parser.add_argument('outfile', nargs='?', type=argparse.FileType('w', encoding='utf-8'), default=sys.stdout)
args = parser.parse_args()
reconstruct(args.infile, args.outfile)
| # ... existing code ...
from __future__ import print_function
# ... rest of the code ... |
aff5a09eb3d61f77cb277b076820481b8ba145d5 | tests/test_coroutine.py | tests/test_coroutine.py | import tests
try:
import asyncio
exec('''if 1:
def hello_world(result, delay):
result.append("Hello")
# retrieve the event loop from the policy
yield from asyncio.sleep(delay)
result.append('World')
''')
except ImportError:
import trollius as asyncio
from trollius import From
def hello_world(result, delay):
result.append("Hello")
# retrieve the event loop from the policy
yield From(asyncio.sleep(delay))
result.append('World')
class CallbackTests(tests.TestCase):
def test_hello_world(self):
result = []
self.loop.run_until_complete(hello_world(result, 0.001))
self.assertEqual(result, ['Hello', 'World'])
if __name__ == '__main__':
import unittest
unittest.main()
| import tests
try:
import asyncio
exec('''if 1:
def hello_world(result, delay):
result.append("Hello")
# retrieve the event loop from the policy
yield from asyncio.sleep(delay)
result.append('World')
return "."
def waiter(result):
loop = asyncio.get_event_loop()
fut = asyncio.Future(loop=loop)
loop.call_soon(fut.set_result, "Future")
value = yield from fut
result.append(value)
value = yield from hello_world(result, 0.001)
result.append(value)
''')
except ImportError:
import trollius as asyncio
from trollius import From, Return
def hello_world(result, delay):
result.append("Hello")
# retrieve the event loop from the policy
yield From(asyncio.sleep(delay))
result.append('World')
raise Return(".")
def waiter(result):
loop = asyncio.get_event_loop()
fut = asyncio.Future(loop=loop)
loop.call_soon(fut.set_result, "Future")
value = yield From(fut)
result.append(value)
value = yield From(hello_world(result, 0.001))
result.append(value)
class CallbackTests(tests.TestCase):
def test_hello_world(self):
result = []
self.loop.run_until_complete(hello_world(result, 0.001))
self.assertEqual(result, ['Hello', 'World'])
def test_waiter(self):
result = []
self.loop.run_until_complete(waiter(result))
self.assertEqual(result, ['Future', 'Hello', 'World', '.'])
if __name__ == '__main__':
import unittest
unittest.main()
| Add more complex coroutine example | Add more complex coroutine example
| Python | apache-2.0 | overcastcloud/aioeventlet | import tests
try:
import asyncio
exec('''if 1:
def hello_world(result, delay):
result.append("Hello")
# retrieve the event loop from the policy
yield from asyncio.sleep(delay)
result.append('World')
+ return "."
+
+ def waiter(result):
+ loop = asyncio.get_event_loop()
+ fut = asyncio.Future(loop=loop)
+ loop.call_soon(fut.set_result, "Future")
+
+ value = yield from fut
+ result.append(value)
+
+ value = yield from hello_world(result, 0.001)
+ result.append(value)
''')
except ImportError:
import trollius as asyncio
- from trollius import From
+ from trollius import From, Return
def hello_world(result, delay):
result.append("Hello")
# retrieve the event loop from the policy
yield From(asyncio.sleep(delay))
result.append('World')
+ raise Return(".")
+
+ def waiter(result):
+ loop = asyncio.get_event_loop()
+ fut = asyncio.Future(loop=loop)
+ loop.call_soon(fut.set_result, "Future")
+
+ value = yield From(fut)
+ result.append(value)
+
+ value = yield From(hello_world(result, 0.001))
+ result.append(value)
+
class CallbackTests(tests.TestCase):
def test_hello_world(self):
result = []
self.loop.run_until_complete(hello_world(result, 0.001))
self.assertEqual(result, ['Hello', 'World'])
+ def test_waiter(self):
+ result = []
+ self.loop.run_until_complete(waiter(result))
+ self.assertEqual(result, ['Future', 'Hello', 'World', '.'])
+
if __name__ == '__main__':
import unittest
unittest.main()
| Add more complex coroutine example | ## Code Before:
import tests
try:
import asyncio
exec('''if 1:
def hello_world(result, delay):
result.append("Hello")
# retrieve the event loop from the policy
yield from asyncio.sleep(delay)
result.append('World')
''')
except ImportError:
import trollius as asyncio
from trollius import From
def hello_world(result, delay):
result.append("Hello")
# retrieve the event loop from the policy
yield From(asyncio.sleep(delay))
result.append('World')
class CallbackTests(tests.TestCase):
def test_hello_world(self):
result = []
self.loop.run_until_complete(hello_world(result, 0.001))
self.assertEqual(result, ['Hello', 'World'])
if __name__ == '__main__':
import unittest
unittest.main()
## Instruction:
Add more complex coroutine example
## Code After:
import tests
try:
import asyncio
exec('''if 1:
def hello_world(result, delay):
result.append("Hello")
# retrieve the event loop from the policy
yield from asyncio.sleep(delay)
result.append('World')
return "."
def waiter(result):
loop = asyncio.get_event_loop()
fut = asyncio.Future(loop=loop)
loop.call_soon(fut.set_result, "Future")
value = yield from fut
result.append(value)
value = yield from hello_world(result, 0.001)
result.append(value)
''')
except ImportError:
import trollius as asyncio
from trollius import From, Return
def hello_world(result, delay):
result.append("Hello")
# retrieve the event loop from the policy
yield From(asyncio.sleep(delay))
result.append('World')
raise Return(".")
def waiter(result):
loop = asyncio.get_event_loop()
fut = asyncio.Future(loop=loop)
loop.call_soon(fut.set_result, "Future")
value = yield From(fut)
result.append(value)
value = yield From(hello_world(result, 0.001))
result.append(value)
class CallbackTests(tests.TestCase):
def test_hello_world(self):
result = []
self.loop.run_until_complete(hello_world(result, 0.001))
self.assertEqual(result, ['Hello', 'World'])
def test_waiter(self):
result = []
self.loop.run_until_complete(waiter(result))
self.assertEqual(result, ['Future', 'Hello', 'World', '.'])
if __name__ == '__main__':
import unittest
unittest.main()
| ...
result.append('World')
return "."
def waiter(result):
loop = asyncio.get_event_loop()
fut = asyncio.Future(loop=loop)
loop.call_soon(fut.set_result, "Future")
value = yield from fut
result.append(value)
value = yield from hello_world(result, 0.001)
result.append(value)
''')
...
import trollius as asyncio
from trollius import From, Return
...
result.append('World')
raise Return(".")
def waiter(result):
loop = asyncio.get_event_loop()
fut = asyncio.Future(loop=loop)
loop.call_soon(fut.set_result, "Future")
value = yield From(fut)
result.append(value)
value = yield From(hello_world(result, 0.001))
result.append(value)
...
def test_waiter(self):
result = []
self.loop.run_until_complete(waiter(result))
self.assertEqual(result, ['Future', 'Hello', 'World', '.'])
... |
d20347f4a57bb195291ebc79fc1ca0858b3f1d65 | PyLunch/pylunch/specials/models.py | PyLunch/pylunch/specials/models.py | from django.db import models
MAX_PRICE_FORMAT = {
'max_digits': 5,
'decimal_places': 2
}
SPECIAL_TYPES = (
('LU', 'Lunch'),
('BR', 'Breakfast'),
('DI', 'Dinner'),
)
MAX_RESTAURANT_NAME_LENGTH = 50
MAX_DESCRIPTION_LENGTH = 500
class Restaurant(models.Model):
name = models.CharField(max_length=MAX_RESTAURANT_NAME_LENGTH)
description = models.CharField(max_length=MAX_DESCRIPTION_LENGTH)
class Special(models.Model):
restaurant = models.ForeignKey(Restaurant)
description = models.CharField(max_length=MAX_DESCRIPTION_LENGTH)
special_type = models.CharField(max_length=2, choices=SPECIAL_TYPES)
special_price = models.DecimalField(**MAX_PRICE_FORMAT)
normal_price = models.DecimalField(**MAX_PRICE_FORMAT) | from django.db import models
MAX_PRICE_FORMAT = {
'max_digits': 5,
'decimal_places': 2
}
SPECIAL_TYPES = (
('LU', 'Lunch'),
('BR', 'Breakfast'),
('DI', 'Dinner'),
)
MAX_RESTAURANT_NAME_LENGTH = 50
MAX_DESCRIPTION_LENGTH = 500
class Restaurant(models.Model):
name = models.CharField(max_length=MAX_RESTAURANT_NAME_LENGTH)
description = models.CharField(max_length=MAX_DESCRIPTION_LENGTH)
def __unicode__(self):
return self.name
class Special(models.Model):
restaurant = models.ForeignKey(Restaurant)
description = models.CharField(max_length=MAX_DESCRIPTION_LENGTH)
special_type = models.CharField(max_length=2, choices=SPECIAL_TYPES)
special_price = models.DecimalField(**MAX_PRICE_FORMAT)
normal_price = models.DecimalField(**MAX_PRICE_FORMAT)
valid_from = models.DateField()
valid_until = models.DateField()
def __unicode__(self):
return "%s: %s" % (self.restaurant.name, self.description) | Add fields to Special model | Add fields to Special model
| Python | unlicense | wiehan-a/pylunch | from django.db import models
MAX_PRICE_FORMAT = {
'max_digits': 5,
'decimal_places': 2
}
SPECIAL_TYPES = (
('LU', 'Lunch'),
('BR', 'Breakfast'),
('DI', 'Dinner'),
)
MAX_RESTAURANT_NAME_LENGTH = 50
MAX_DESCRIPTION_LENGTH = 500
class Restaurant(models.Model):
name = models.CharField(max_length=MAX_RESTAURANT_NAME_LENGTH)
description = models.CharField(max_length=MAX_DESCRIPTION_LENGTH)
+ def __unicode__(self):
+ return self.name
+
class Special(models.Model):
restaurant = models.ForeignKey(Restaurant)
description = models.CharField(max_length=MAX_DESCRIPTION_LENGTH)
special_type = models.CharField(max_length=2, choices=SPECIAL_TYPES)
special_price = models.DecimalField(**MAX_PRICE_FORMAT)
normal_price = models.DecimalField(**MAX_PRICE_FORMAT)
+
+ valid_from = models.DateField()
+ valid_until = models.DateField()
+
+ def __unicode__(self):
+ return "%s: %s" % (self.restaurant.name, self.description) | Add fields to Special model | ## Code Before:
from django.db import models
MAX_PRICE_FORMAT = {
'max_digits': 5,
'decimal_places': 2
}
SPECIAL_TYPES = (
('LU', 'Lunch'),
('BR', 'Breakfast'),
('DI', 'Dinner'),
)
MAX_RESTAURANT_NAME_LENGTH = 50
MAX_DESCRIPTION_LENGTH = 500
class Restaurant(models.Model):
name = models.CharField(max_length=MAX_RESTAURANT_NAME_LENGTH)
description = models.CharField(max_length=MAX_DESCRIPTION_LENGTH)
class Special(models.Model):
restaurant = models.ForeignKey(Restaurant)
description = models.CharField(max_length=MAX_DESCRIPTION_LENGTH)
special_type = models.CharField(max_length=2, choices=SPECIAL_TYPES)
special_price = models.DecimalField(**MAX_PRICE_FORMAT)
normal_price = models.DecimalField(**MAX_PRICE_FORMAT)
## Instruction:
Add fields to Special model
## Code After:
from django.db import models
MAX_PRICE_FORMAT = {
'max_digits': 5,
'decimal_places': 2
}
SPECIAL_TYPES = (
('LU', 'Lunch'),
('BR', 'Breakfast'),
('DI', 'Dinner'),
)
MAX_RESTAURANT_NAME_LENGTH = 50
MAX_DESCRIPTION_LENGTH = 500
class Restaurant(models.Model):
name = models.CharField(max_length=MAX_RESTAURANT_NAME_LENGTH)
description = models.CharField(max_length=MAX_DESCRIPTION_LENGTH)
def __unicode__(self):
return self.name
class Special(models.Model):
restaurant = models.ForeignKey(Restaurant)
description = models.CharField(max_length=MAX_DESCRIPTION_LENGTH)
special_type = models.CharField(max_length=2, choices=SPECIAL_TYPES)
special_price = models.DecimalField(**MAX_PRICE_FORMAT)
normal_price = models.DecimalField(**MAX_PRICE_FORMAT)
valid_from = models.DateField()
valid_until = models.DateField()
def __unicode__(self):
return "%s: %s" % (self.restaurant.name, self.description) | ...
def __unicode__(self):
return self.name
class Special(models.Model):
...
normal_price = models.DecimalField(**MAX_PRICE_FORMAT)
valid_from = models.DateField()
valid_until = models.DateField()
def __unicode__(self):
return "%s: %s" % (self.restaurant.name, self.description)
... |
2b3406a46625fd5350200dcb6d2dc32224d3c609 | warehouse/defaults.py | warehouse/defaults.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///warehouse"
# The URI for our Redis database.
REDIS_URI = "redis://localhost:6379/0"
# The amount of time (in seconds) that synchronizing each project can take
# before timing out.
SYNCHRONIZATION_TIMEOUT = 60 * 15
# The type of Storage to use.
STORAGE = "stockpile.filesystem:HashedFileSystem"
# Options to pass into the stockpile storage backend
STORAGE_OPTIONS = {
"location": "data",
"hash_algorithm": "md5",
}
| from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///warehouse"
# The URI for our Redis database.
REDIS_URI = "redis://localhost:6379/0"
# The type of Storage to use.
STORAGE = "stockpile.filesystem:HashedFileSystem"
# Options to pass into the stockpile storage backend
STORAGE_OPTIONS = {
"location": "data",
"hash_algorithm": "md5",
}
| Remove a no longer used setting | Remove a no longer used setting
With the removal of eventlet there is no longer a mechanism for
timing out a synchronization.
| Python | bsd-2-clause | davidfischer/warehouse | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///warehouse"
# The URI for our Redis database.
REDIS_URI = "redis://localhost:6379/0"
- # The amount of time (in seconds) that synchronizing each project can take
- # before timing out.
- SYNCHRONIZATION_TIMEOUT = 60 * 15
-
# The type of Storage to use.
STORAGE = "stockpile.filesystem:HashedFileSystem"
# Options to pass into the stockpile storage backend
STORAGE_OPTIONS = {
"location": "data",
"hash_algorithm": "md5",
}
| Remove a no longer used setting | ## Code Before:
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///warehouse"
# The URI for our Redis database.
REDIS_URI = "redis://localhost:6379/0"
# The amount of time (in seconds) that synchronizing each project can take
# before timing out.
SYNCHRONIZATION_TIMEOUT = 60 * 15
# The type of Storage to use.
STORAGE = "stockpile.filesystem:HashedFileSystem"
# Options to pass into the stockpile storage backend
STORAGE_OPTIONS = {
"location": "data",
"hash_algorithm": "md5",
}
## Instruction:
Remove a no longer used setting
## Code After:
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///warehouse"
# The URI for our Redis database.
REDIS_URI = "redis://localhost:6379/0"
# The type of Storage to use.
STORAGE = "stockpile.filesystem:HashedFileSystem"
# Options to pass into the stockpile storage backend
STORAGE_OPTIONS = {
"location": "data",
"hash_algorithm": "md5",
}
| # ... existing code ...
# The type of Storage to use.
# ... rest of the code ... |
ff3c3c3842790cc9eb06f1241d6da77f828859c1 | IPython/external/qt.py | IPython/external/qt.py |
import os
# Use PyQt by default until PySide is stable.
qt_api = os.environ.get('QT_API', 'pyqt')
if qt_api == 'pyqt':
# For PySide compatibility, use the new string API that automatically
# converts QStrings to unicode Python strings.
import sip
sip.setapi('QString', 2)
from PyQt4 import QtCore, QtGui, QtSvg
# Alias PyQt-specific functions for PySide compatibility.
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
else:
from PySide import QtCore, QtGui, QtSvg
|
import os
# Available APIs.
QT_API_PYQT = 'pyqt'
QT_API_PYSIDE = 'pyside'
# Use PyQt by default until PySide is stable.
QT_API = os.environ.get('QT_API', QT_API_PYQT)
if QT_API == QT_API_PYQT:
# For PySide compatibility, use the new string API that automatically
# converts QStrings to Unicode Python strings.
import sip
sip.setapi('QString', 2)
from PyQt4 import QtCore, QtGui, QtSvg
# Alias PyQt-specific functions for PySide compatibility.
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
elif QT_API == QT_API_PYSIDE:
from PySide import QtCore, QtGui, QtSvg
else:
raise RuntimeError('Invalid Qt API "%s"' % QT_API)
| Clean up in Qt API switcher. | Clean up in Qt API switcher.
| Python | bsd-3-clause | ipython/ipython,ipython/ipython |
import os
+ # Available APIs.
+ QT_API_PYQT = 'pyqt'
+ QT_API_PYSIDE = 'pyside'
+
# Use PyQt by default until PySide is stable.
- qt_api = os.environ.get('QT_API', 'pyqt')
+ QT_API = os.environ.get('QT_API', QT_API_PYQT)
- if qt_api == 'pyqt':
+ if QT_API == QT_API_PYQT:
# For PySide compatibility, use the new string API that automatically
- # converts QStrings to unicode Python strings.
+ # converts QStrings to Unicode Python strings.
import sip
sip.setapi('QString', 2)
from PyQt4 import QtCore, QtGui, QtSvg
# Alias PyQt-specific functions for PySide compatibility.
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
- else:
+ elif QT_API == QT_API_PYSIDE:
from PySide import QtCore, QtGui, QtSvg
+ else:
+ raise RuntimeError('Invalid Qt API "%s"' % QT_API)
+ | Clean up in Qt API switcher. | ## Code Before:
import os
# Use PyQt by default until PySide is stable.
qt_api = os.environ.get('QT_API', 'pyqt')
if qt_api == 'pyqt':
# For PySide compatibility, use the new string API that automatically
# converts QStrings to unicode Python strings.
import sip
sip.setapi('QString', 2)
from PyQt4 import QtCore, QtGui, QtSvg
# Alias PyQt-specific functions for PySide compatibility.
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
else:
from PySide import QtCore, QtGui, QtSvg
## Instruction:
Clean up in Qt API switcher.
## Code After:
import os
# Available APIs.
QT_API_PYQT = 'pyqt'
QT_API_PYSIDE = 'pyside'
# Use PyQt by default until PySide is stable.
QT_API = os.environ.get('QT_API', QT_API_PYQT)
if QT_API == QT_API_PYQT:
# For PySide compatibility, use the new string API that automatically
# converts QStrings to Unicode Python strings.
import sip
sip.setapi('QString', 2)
from PyQt4 import QtCore, QtGui, QtSvg
# Alias PyQt-specific functions for PySide compatibility.
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
elif QT_API == QT_API_PYSIDE:
from PySide import QtCore, QtGui, QtSvg
else:
raise RuntimeError('Invalid Qt API "%s"' % QT_API)
| # ... existing code ...
# Available APIs.
QT_API_PYQT = 'pyqt'
QT_API_PYSIDE = 'pyside'
# Use PyQt by default until PySide is stable.
QT_API = os.environ.get('QT_API', QT_API_PYQT)
if QT_API == QT_API_PYQT:
# For PySide compatibility, use the new string API that automatically
# converts QStrings to Unicode Python strings.
import sip
# ... modified code ...
elif QT_API == QT_API_PYSIDE:
from PySide import QtCore, QtGui, QtSvg
else:
raise RuntimeError('Invalid Qt API "%s"' % QT_API)
# ... rest of the code ... |
f7a1a849161007e3703b41758e99dd45609c9753 | renovation_tax_be/models/account_invoice.py | renovation_tax_be/models/account_invoice.py | from odoo import models, api
class AccountInvoice(models.Model):
_inherit = "account.invoice"
@api.onchange('fiscal_position_id')
def somko_update_tax(self):
for line in self.invoice_line_ids:
line._onchange_product_id()
| from odoo import models, api
class AccountInvoice(models.Model):
_inherit = "account.invoice"
@api.onchange('fiscal_position_id')
def somko_update_tax(self):
for line in self.invoice_line_ids:
price = line.unit_price
line._onchange_product_id()
line.unit_price = price
| Fix loss of unit price if edited | Fix loss of unit price if edited
| Python | agpl-3.0 | Somko/Odoo-Public,Somko/Odoo-Public | from odoo import models, api
class AccountInvoice(models.Model):
_inherit = "account.invoice"
@api.onchange('fiscal_position_id')
def somko_update_tax(self):
for line in self.invoice_line_ids:
+ price = line.unit_price
line._onchange_product_id()
+ line.unit_price = price
| Fix loss of unit price if edited | ## Code Before:
from odoo import models, api
class AccountInvoice(models.Model):
_inherit = "account.invoice"
@api.onchange('fiscal_position_id')
def somko_update_tax(self):
for line in self.invoice_line_ids:
line._onchange_product_id()
## Instruction:
Fix loss of unit price if edited
## Code After:
from odoo import models, api
class AccountInvoice(models.Model):
_inherit = "account.invoice"
@api.onchange('fiscal_position_id')
def somko_update_tax(self):
for line in self.invoice_line_ids:
price = line.unit_price
line._onchange_product_id()
line.unit_price = price
| ...
for line in self.invoice_line_ids:
price = line.unit_price
line._onchange_product_id()
line.unit_price = price
... |
3f394b37174d97b53fdef8ce662e258c6b2aa337 | src/appleseed.python/studio/__init__.py | src/appleseed.python/studio/__init__.py |
import os
# Prevent Qt.py importing PySide2 and PyQt5.
if not os.getenv("QT_PREFERRED_BINDING"):
os.environ["QT_PREFERRED_BINDING"] = "PyQt4"
from _appleseedstudio import *
|
import os
# Prevent Qt.py importing PySide2 and PyQt5.
if not os.getenv("QT_PREFERRED_BINDING"):
os.environ["QT_PREFERRED_BINDING"] = os.pathsep.join(["PySide", "PyQt4"])
from _appleseedstudio import *
| Add PySide to as.studio init preferred binding | Add PySide to as.studio init preferred binding
| Python | mit | luisbarrancos/appleseed,est77/appleseed,appleseedhq/appleseed,pjessesco/appleseed,gospodnetic/appleseed,Vertexwahn/appleseed,appleseedhq/appleseed,dictoon/appleseed,Aakash1312/appleseed,Biart95/appleseed,Vertexwahn/appleseed,dictoon/appleseed,Biart95/appleseed,aytekaman/appleseed,pjessesco/appleseed,aytekaman/appleseed,est77/appleseed,Biart95/appleseed,pjessesco/appleseed,Biart95/appleseed,gospodnetic/appleseed,dictoon/appleseed,pjessesco/appleseed,luisbarrancos/appleseed,Vertexwahn/appleseed,dictoon/appleseed,luisbarrancos/appleseed,appleseedhq/appleseed,Biart95/appleseed,luisbarrancos/appleseed,est77/appleseed,luisbarrancos/appleseed,pjessesco/appleseed,Aakash1312/appleseed,aytekaman/appleseed,gospodnetic/appleseed,Vertexwahn/appleseed,gospodnetic/appleseed,Aakash1312/appleseed,Aakash1312/appleseed,est77/appleseed,appleseedhq/appleseed,est77/appleseed,Vertexwahn/appleseed,aytekaman/appleseed,Aakash1312/appleseed,appleseedhq/appleseed,aytekaman/appleseed,gospodnetic/appleseed,dictoon/appleseed |
import os
# Prevent Qt.py importing PySide2 and PyQt5.
if not os.getenv("QT_PREFERRED_BINDING"):
- os.environ["QT_PREFERRED_BINDING"] = "PyQt4"
+ os.environ["QT_PREFERRED_BINDING"] = os.pathsep.join(["PySide", "PyQt4"])
from _appleseedstudio import *
| Add PySide to as.studio init preferred binding | ## Code Before:
import os
# Prevent Qt.py importing PySide2 and PyQt5.
if not os.getenv("QT_PREFERRED_BINDING"):
os.environ["QT_PREFERRED_BINDING"] = "PyQt4"
from _appleseedstudio import *
## Instruction:
Add PySide to as.studio init preferred binding
## Code After:
import os
# Prevent Qt.py importing PySide2 and PyQt5.
if not os.getenv("QT_PREFERRED_BINDING"):
os.environ["QT_PREFERRED_BINDING"] = os.pathsep.join(["PySide", "PyQt4"])
from _appleseedstudio import *
| # ... existing code ...
if not os.getenv("QT_PREFERRED_BINDING"):
os.environ["QT_PREFERRED_BINDING"] = os.pathsep.join(["PySide", "PyQt4"])
# ... rest of the code ... |
a4e402caf7b5a90607b6a206046c96c53a37e860 | slack_client/exceptions.py | slack_client/exceptions.py | class SlackError(Exception):
pass
class SlackNo(SlackError):
def __init__(self, msg_error):
self.msg = msg_error
def __str__(self):
return repr(self.msg)
class SlackTooManyRequests(SlackError):
def __init__(self, time_to_wait):
self.time_to_wait = time_to_wait
def __str__(self):
return ("Too many requests. Wait %d seconds before trying again" \
% (self.time_to_wait))
| class SlackError(Exception):
pass
class SlackNo(SlackError):
pass
class SlackMissingAPI(SlackError):
pass
| Add a custom exception (SlackMissingAPI) | Add a custom exception (SlackMissingAPI)
This exception is raised when a SlackObject is created without
any way to get an API.
Remove custom implementation for exceptions. There is no reason strong
enough for this.
| Python | mit | Shir0kamii/slack-client | class SlackError(Exception):
pass
class SlackNo(SlackError):
+ pass
- def __init__(self, msg_error):
- self.msg = msg_error
- def __str__(self):
- return repr(self.msg)
+ class SlackMissingAPI(SlackError):
+ pass
- class SlackTooManyRequests(SlackError):
- def __init__(self, time_to_wait):
- self.time_to_wait = time_to_wait
-
- def __str__(self):
- return ("Too many requests. Wait %d seconds before trying again" \
- % (self.time_to_wait))
- | Add a custom exception (SlackMissingAPI) | ## Code Before:
class SlackError(Exception):
pass
class SlackNo(SlackError):
def __init__(self, msg_error):
self.msg = msg_error
def __str__(self):
return repr(self.msg)
class SlackTooManyRequests(SlackError):
def __init__(self, time_to_wait):
self.time_to_wait = time_to_wait
def __str__(self):
return ("Too many requests. Wait %d seconds before trying again" \
% (self.time_to_wait))
## Instruction:
Add a custom exception (SlackMissingAPI)
## Code After:
class SlackError(Exception):
pass
class SlackNo(SlackError):
pass
class SlackMissingAPI(SlackError):
pass
| // ... existing code ...
class SlackNo(SlackError):
pass
class SlackMissingAPI(SlackError):
pass
// ... rest of the code ... |
154b64b2ee56fa4391251268ba4a85d178bedd60 | djangoautoconf/urls.py | djangoautoconf/urls.py | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
# from mezzanine.core.views import direct_to_template
admin.autodiscover()
# Must be defined before auto discover and urlpatterns var. So when there is root url
# injection, we first insert root url to this, then the last line will insert it to real urlpatterns
default_app_url_patterns = []
from djangoautoconf import auto_conf_urls
auto_conf_urls.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^default_django_15_and_below/', include('default_django_15_and_below.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
# url(r'^', include('demo.urls')),
# url(r'^obj_sys/', include('obj_sys.urls')),
# url("^$", direct_to_template, {"template": "index.html"}, name="home"),
)
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += default_app_url_patterns
| from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
# from mezzanine.core.views import direct_to_template
admin.autodiscover()
# Must be defined before auto discover and urlpatterns var. So when there is root url
# injection, we first insert root url to this, then the last line will insert it to real urlpatterns
default_app_url_patterns = []
from djangoautoconf import auto_conf_urls
auto_conf_urls.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^default_django_15_and_below/', include('default_django_15_and_below.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
# url(r'^', include('demo.urls')),
# url(r'^obj_sys/', include('obj_sys.urls')),
# url("^$", direct_to_template, {"template": "index.html"}, name="home"),
)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += default_app_url_patterns
| Fix the issue of override url by mistake. | Fix the issue of override url by mistake.
| Python | bsd-3-clause | weijia/djangoautoconf,weijia/djangoautoconf | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
# from mezzanine.core.views import direct_to_template
admin.autodiscover()
# Must be defined before auto discover and urlpatterns var. So when there is root url
# injection, we first insert root url to this, then the last line will insert it to real urlpatterns
default_app_url_patterns = []
from djangoautoconf import auto_conf_urls
auto_conf_urls.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^default_django_15_and_below/', include('default_django_15_and_below.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
# url(r'^', include('demo.urls')),
# url(r'^obj_sys/', include('obj_sys.urls')),
# url("^$", direct_to_template, {"template": "index.html"}, name="home"),
)
- urlpatterns = [
- # ... the rest of your URLconf goes here ...
- ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
+ urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += default_app_url_patterns
| Fix the issue of override url by mistake. | ## Code Before:
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
# from mezzanine.core.views import direct_to_template
admin.autodiscover()
# Must be defined before auto discover and urlpatterns var. So when there is root url
# injection, we first insert root url to this, then the last line will insert it to real urlpatterns
default_app_url_patterns = []
from djangoautoconf import auto_conf_urls
auto_conf_urls.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^default_django_15_and_below/', include('default_django_15_and_below.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
# url(r'^', include('demo.urls')),
# url(r'^obj_sys/', include('obj_sys.urls')),
# url("^$", direct_to_template, {"template": "index.html"}, name="home"),
)
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += default_app_url_patterns
## Instruction:
Fix the issue of override url by mistake.
## Code After:
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
# from mezzanine.core.views import direct_to_template
admin.autodiscover()
# Must be defined before auto discover and urlpatterns var. So when there is root url
# injection, we first insert root url to this, then the last line will insert it to real urlpatterns
default_app_url_patterns = []
from djangoautoconf import auto_conf_urls
auto_conf_urls.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^default_django_15_and_below/', include('default_django_15_and_below.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
# url(r'^', include('demo.urls')),
# url(r'^obj_sys/', include('obj_sys.urls')),
# url("^$", direct_to_template, {"template": "index.html"}, name="home"),
)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += default_app_url_patterns
| ...
)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
... |
661299275942813a0c45aa90db64c9603d287839 | lib_common/src/d1_common/iter/string.py | lib_common/src/d1_common/iter/string.py | """Iterate over string"""
from __future__ import absolute_import
import StringIO
import d1_common.const
class StringIterator(object):
"""Generator that returns the bytes of a string in chunks"""
def __init__(self, string, chunk_size=d1_common.const.DEFAULT_CHUNK_SIZE):
self._string = string
self._chunk_size = chunk_size
def __iter__(self):
f = StringIO.StringIO(self._string)
while True:
chunk_str = f.read(self._chunk_size)
if not chunk_str:
break
yield chunk_str
| """Iterate over string"""
from __future__ import absolute_import
import StringIO
import d1_common.const
class StringIterator(object):
"""Generator that returns the bytes of a string in chunks"""
def __init__(self, string, chunk_size=d1_common.const.DEFAULT_CHUNK_SIZE):
self._string = string
self._chunk_size = chunk_size
def __iter__(self):
f = StringIO.StringIO(self._string)
while True:
chunk_str = f.read(self._chunk_size)
if not chunk_str:
break
yield chunk_str
def __len__(self):
return len(self._string)
@property
def size(self):
return len(self._string)
| Improve StringIterator to allow for more general usage | Improve StringIterator to allow for more general usage
| Python | apache-2.0 | DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python | """Iterate over string"""
from __future__ import absolute_import
import StringIO
import d1_common.const
class StringIterator(object):
"""Generator that returns the bytes of a string in chunks"""
def __init__(self, string, chunk_size=d1_common.const.DEFAULT_CHUNK_SIZE):
self._string = string
self._chunk_size = chunk_size
def __iter__(self):
f = StringIO.StringIO(self._string)
while True:
chunk_str = f.read(self._chunk_size)
if not chunk_str:
break
yield chunk_str
+ def __len__(self):
+ return len(self._string)
+
+ @property
+ def size(self):
+ return len(self._string)
+ | Improve StringIterator to allow for more general usage | ## Code Before:
"""Iterate over string"""
from __future__ import absolute_import
import StringIO
import d1_common.const
class StringIterator(object):
"""Generator that returns the bytes of a string in chunks"""
def __init__(self, string, chunk_size=d1_common.const.DEFAULT_CHUNK_SIZE):
self._string = string
self._chunk_size = chunk_size
def __iter__(self):
f = StringIO.StringIO(self._string)
while True:
chunk_str = f.read(self._chunk_size)
if not chunk_str:
break
yield chunk_str
## Instruction:
Improve StringIterator to allow for more general usage
## Code After:
"""Iterate over string"""
from __future__ import absolute_import
import StringIO
import d1_common.const
class StringIterator(object):
"""Generator that returns the bytes of a string in chunks"""
def __init__(self, string, chunk_size=d1_common.const.DEFAULT_CHUNK_SIZE):
self._string = string
self._chunk_size = chunk_size
def __iter__(self):
f = StringIO.StringIO(self._string)
while True:
chunk_str = f.read(self._chunk_size)
if not chunk_str:
break
yield chunk_str
def __len__(self):
return len(self._string)
@property
def size(self):
return len(self._string)
| // ... existing code ...
yield chunk_str
def __len__(self):
return len(self._string)
@property
def size(self):
return len(self._string)
// ... rest of the code ... |
8d5ac7efd98426394040fb01f0096f35a804b1b7 | tests/plugins/test_generic.py | tests/plugins/test_generic.py | import pytest
from detectem.core import MATCHERS
from detectem.plugin import load_plugins, GenericPlugin
from .utils import create_har_entry
class TestGenericPlugin(object):
@pytest.fixture
def plugins(self):
return load_plugins()
def test_generic_plugin(self):
class MyGenericPlugin(GenericPlugin):
pass
x = MyGenericPlugin()
with pytest.raises(NotImplementedError):
x.get_information(entry=None)
assert x.ptype == 'generic'
@pytest.mark.parametrize('plugin_name,indicator,name', [
(
'wordpress_generic',
{'url': 'http://domain.tld/wp-content/plugins/example/'},
'example',
)
])
def test_real_generic_plugin(self, plugin_name, indicator, name, plugins):
plugin = plugins.get(plugin_name)
matcher_type = [k for k in indicator.keys()][0]
har_entry = create_har_entry(indicator, matcher_type)
matchers_in_plugin = plugin._get_matchers(matcher_type, 'indicators')
# Call presence method in related matcher class
matcher_instance = MATCHERS[matcher_type]
assert matcher_instance.check_presence(har_entry, *matchers_in_plugin)
assert plugin.get_information(har_entry)['name'] == name
| import pytest
from detectem.core import MATCHERS
from detectem.plugin import load_plugins, GenericPlugin
from tests import create_pm
from .utils import create_har_entry
class TestGenericPlugin:
@pytest.fixture
def plugins(self):
return load_plugins()
def test_generic_plugin(self):
class MyGenericPlugin(GenericPlugin):
pass
x = MyGenericPlugin()
with pytest.raises(NotImplementedError):
x.get_information(entry=None)
assert x.ptype == 'generic'
@pytest.mark.parametrize(
'plugin_name,matcher_type,har_content,name', [(
'wordpress_generic',
'url',
'http://domain.tld/wp-content/plugins/example/',
'example',
)]
)
def test_real_generic_plugin(
self, plugin_name, matcher_type, har_content, name, plugins
):
plugin = plugins.get(plugin_name)
har_entry = create_har_entry(matcher_type, value=har_content)
# Verify presence using matcher class
matchers = plugin.get_matchers(matcher_type)
matcher_instance = MATCHERS[matcher_type]
assert matcher_instance.get_info(
har_entry,
*matchers,
) == create_pm(presence=True)
assert plugin.get_information(har_entry)['name'] == name
| Fix test for generic plugins | Fix test for generic plugins
| Python | mit | spectresearch/detectem | import pytest
from detectem.core import MATCHERS
from detectem.plugin import load_plugins, GenericPlugin
+ from tests import create_pm
from .utils import create_har_entry
- class TestGenericPlugin(object):
+ class TestGenericPlugin:
@pytest.fixture
def plugins(self):
return load_plugins()
def test_generic_plugin(self):
class MyGenericPlugin(GenericPlugin):
pass
x = MyGenericPlugin()
with pytest.raises(NotImplementedError):
x.get_information(entry=None)
assert x.ptype == 'generic'
- @pytest.mark.parametrize('plugin_name,indicator,name', [
- (
+ @pytest.mark.parametrize(
+ 'plugin_name,matcher_type,har_content,name', [(
'wordpress_generic',
+ 'url',
- {'url': 'http://domain.tld/wp-content/plugins/example/'},
+ 'http://domain.tld/wp-content/plugins/example/',
'example',
- )
+ )]
- ])
+ )
- def test_real_generic_plugin(self, plugin_name, indicator, name, plugins):
+ def test_real_generic_plugin(
+ self, plugin_name, matcher_type, har_content, name, plugins
+ ):
plugin = plugins.get(plugin_name)
- matcher_type = [k for k in indicator.keys()][0]
+ har_entry = create_har_entry(matcher_type, value=har_content)
- har_entry = create_har_entry(indicator, matcher_type)
+ # Verify presence using matcher class
- matchers_in_plugin = plugin._get_matchers(matcher_type, 'indicators')
+ matchers = plugin.get_matchers(matcher_type)
+ matcher_instance = MATCHERS[matcher_type]
- # Call presence method in related matcher class
- matcher_instance = MATCHERS[matcher_type]
- assert matcher_instance.check_presence(har_entry, *matchers_in_plugin)
+ assert matcher_instance.get_info(
+ har_entry,
+ *matchers,
+ ) == create_pm(presence=True)
assert plugin.get_information(har_entry)['name'] == name
| Fix test for generic plugins | ## Code Before:
import pytest
from detectem.core import MATCHERS
from detectem.plugin import load_plugins, GenericPlugin
from .utils import create_har_entry
class TestGenericPlugin(object):
@pytest.fixture
def plugins(self):
return load_plugins()
def test_generic_plugin(self):
class MyGenericPlugin(GenericPlugin):
pass
x = MyGenericPlugin()
with pytest.raises(NotImplementedError):
x.get_information(entry=None)
assert x.ptype == 'generic'
@pytest.mark.parametrize('plugin_name,indicator,name', [
(
'wordpress_generic',
{'url': 'http://domain.tld/wp-content/plugins/example/'},
'example',
)
])
def test_real_generic_plugin(self, plugin_name, indicator, name, plugins):
plugin = plugins.get(plugin_name)
matcher_type = [k for k in indicator.keys()][0]
har_entry = create_har_entry(indicator, matcher_type)
matchers_in_plugin = plugin._get_matchers(matcher_type, 'indicators')
# Call presence method in related matcher class
matcher_instance = MATCHERS[matcher_type]
assert matcher_instance.check_presence(har_entry, *matchers_in_plugin)
assert plugin.get_information(har_entry)['name'] == name
## Instruction:
Fix test for generic plugins
## Code After:
import pytest
from detectem.core import MATCHERS
from detectem.plugin import load_plugins, GenericPlugin
from tests import create_pm
from .utils import create_har_entry
class TestGenericPlugin:
@pytest.fixture
def plugins(self):
return load_plugins()
def test_generic_plugin(self):
class MyGenericPlugin(GenericPlugin):
pass
x = MyGenericPlugin()
with pytest.raises(NotImplementedError):
x.get_information(entry=None)
assert x.ptype == 'generic'
@pytest.mark.parametrize(
'plugin_name,matcher_type,har_content,name', [(
'wordpress_generic',
'url',
'http://domain.tld/wp-content/plugins/example/',
'example',
)]
)
def test_real_generic_plugin(
self, plugin_name, matcher_type, har_content, name, plugins
):
plugin = plugins.get(plugin_name)
har_entry = create_har_entry(matcher_type, value=har_content)
# Verify presence using matcher class
matchers = plugin.get_matchers(matcher_type)
matcher_instance = MATCHERS[matcher_type]
assert matcher_instance.get_info(
har_entry,
*matchers,
) == create_pm(presence=True)
assert plugin.get_information(har_entry)['name'] == name
| // ... existing code ...
from detectem.plugin import load_plugins, GenericPlugin
from tests import create_pm
from .utils import create_har_entry
// ... modified code ...
class TestGenericPlugin:
@pytest.fixture
...
@pytest.mark.parametrize(
'plugin_name,matcher_type,har_content,name', [(
'wordpress_generic',
'url',
'http://domain.tld/wp-content/plugins/example/',
'example',
)]
)
def test_real_generic_plugin(
self, plugin_name, matcher_type, har_content, name, plugins
):
plugin = plugins.get(plugin_name)
har_entry = create_har_entry(matcher_type, value=har_content)
# Verify presence using matcher class
matchers = plugin.get_matchers(matcher_type)
matcher_instance = MATCHERS[matcher_type]
assert matcher_instance.get_info(
har_entry,
*matchers,
) == create_pm(presence=True)
// ... rest of the code ... |
84ec75ff6262d7926c0de87dffbeddb223fd190b | core/settings.py | core/settings.py |
from enum import IntEnum
class LogType(IntEnum):
CVN_STATUS = 0
AUTH_ERROR = 1
LOG_TYPE = (
(LogType.CVN_STATUS, 'CVN_STATUS'),
(LogType.AUTH_ERROR, 'AUTH_ERROR'),
)
BASE_URL_FLATPAGES = '/investigacion/faq/'
|
from enum import IntEnum
class LogType(IntEnum):
CVN_STATUS = 0
AUTH_ERROR = 1
LOG_TYPE = (
(LogType.CVN_STATUS.value, 'CVN_STATUS'),
(LogType.AUTH_ERROR.value, 'AUTH_ERROR'),
)
BASE_URL_FLATPAGES = '/investigacion/faq/'
| Fix a bug in LogType that broke migrations creation | Fix a bug in LogType that broke migrations creation
| Python | agpl-3.0 | tic-ull/portal-del-investigador,tic-ull/portal-del-investigador,tic-ull/portal-del-investigador,tic-ull/portal-del-investigador |
from enum import IntEnum
class LogType(IntEnum):
CVN_STATUS = 0
AUTH_ERROR = 1
LOG_TYPE = (
- (LogType.CVN_STATUS, 'CVN_STATUS'),
+ (LogType.CVN_STATUS.value, 'CVN_STATUS'),
- (LogType.AUTH_ERROR, 'AUTH_ERROR'),
+ (LogType.AUTH_ERROR.value, 'AUTH_ERROR'),
)
BASE_URL_FLATPAGES = '/investigacion/faq/'
| Fix a bug in LogType that broke migrations creation | ## Code Before:
from enum import IntEnum
class LogType(IntEnum):
CVN_STATUS = 0
AUTH_ERROR = 1
LOG_TYPE = (
(LogType.CVN_STATUS, 'CVN_STATUS'),
(LogType.AUTH_ERROR, 'AUTH_ERROR'),
)
BASE_URL_FLATPAGES = '/investigacion/faq/'
## Instruction:
Fix a bug in LogType that broke migrations creation
## Code After:
from enum import IntEnum
class LogType(IntEnum):
CVN_STATUS = 0
AUTH_ERROR = 1
LOG_TYPE = (
(LogType.CVN_STATUS.value, 'CVN_STATUS'),
(LogType.AUTH_ERROR.value, 'AUTH_ERROR'),
)
BASE_URL_FLATPAGES = '/investigacion/faq/'
| ...
LOG_TYPE = (
(LogType.CVN_STATUS.value, 'CVN_STATUS'),
(LogType.AUTH_ERROR.value, 'AUTH_ERROR'),
)
... |
ea4949dab887a14a0ca8f5ffbcd3c578c61c005e | api/urls.py | api/urls.py | from django.conf.urls import include, url
from api import views
urlpatterns = [
url(r'^services/$', views.services, name='api-services'),
url(r'^collect/$', views.collect_response, name='api-collect'),
url(r'^search/text/$', views.text_search, name='api-text-search'),
url(r'^license/$', views.licensing, name='api-licensing'),
# Oauth2 urls
url(r'^o/', include('api.oauth2_urls', namespace='oauth2_provider')),
]
| from django.conf.urls import include, url
from api import views
urlpatterns = [
url(r'^v1/services/$', views.services, name='api-services'),
url(r'^v1/collect/$', views.collect_response, name='api-collect'),
url(r'^v1/search/text/$', views.text_search, name='api-text-search'),
url(r'^v1/license/$', views.licensing, name='api-licensing'),
# Oauth2 urls
url(r'^o/', include('api.oauth2_urls', namespace='oauth2_provider')),
]
| Add API versioning at the url | Add API versioning at the url
https://github.com/AudioCommons/ac-mediator/issues/13
| Python | apache-2.0 | AudioCommons/ac-mediator,AudioCommons/ac-mediator,AudioCommons/ac-mediator | from django.conf.urls import include, url
from api import views
urlpatterns = [
- url(r'^services/$', views.services, name='api-services'),
+ url(r'^v1/services/$', views.services, name='api-services'),
- url(r'^collect/$', views.collect_response, name='api-collect'),
+ url(r'^v1/collect/$', views.collect_response, name='api-collect'),
- url(r'^search/text/$', views.text_search, name='api-text-search'),
+ url(r'^v1/search/text/$', views.text_search, name='api-text-search'),
- url(r'^license/$', views.licensing, name='api-licensing'),
+ url(r'^v1/license/$', views.licensing, name='api-licensing'),
# Oauth2 urls
url(r'^o/', include('api.oauth2_urls', namespace='oauth2_provider')),
]
| Add API versioning at the url | ## Code Before:
from django.conf.urls import include, url
from api import views
urlpatterns = [
url(r'^services/$', views.services, name='api-services'),
url(r'^collect/$', views.collect_response, name='api-collect'),
url(r'^search/text/$', views.text_search, name='api-text-search'),
url(r'^license/$', views.licensing, name='api-licensing'),
# Oauth2 urls
url(r'^o/', include('api.oauth2_urls', namespace='oauth2_provider')),
]
## Instruction:
Add API versioning at the url
## Code After:
from django.conf.urls import include, url
from api import views
urlpatterns = [
url(r'^v1/services/$', views.services, name='api-services'),
url(r'^v1/collect/$', views.collect_response, name='api-collect'),
url(r'^v1/search/text/$', views.text_search, name='api-text-search'),
url(r'^v1/license/$', views.licensing, name='api-licensing'),
# Oauth2 urls
url(r'^o/', include('api.oauth2_urls', namespace='oauth2_provider')),
]
| ...
urlpatterns = [
url(r'^v1/services/$', views.services, name='api-services'),
url(r'^v1/collect/$', views.collect_response, name='api-collect'),
url(r'^v1/search/text/$', views.text_search, name='api-text-search'),
url(r'^v1/license/$', views.licensing, name='api-licensing'),
... |
5476145559e0e47dac47b41dd4bfdb9fd41bfe29 | setup.py | setup.py |
"""Setup script for the pyparsing module distribution."""
from distutils.core import setup
from pyparsing import __version__
setup(# Distribution meta-data
name = "pyparsing",
version = __version__,
description = "Python parsing module",
author = "Paul McGuire",
author_email = "ptmcg@users.sourceforge.net",
url = "http://pyparsing.wikispaces.com/",
download_url = "http://sourceforge.net/project/showfiles.php?group_id=97203",
license = "MIT License",
py_modules = ["pyparsing"],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
]
)
|
"""Setup script for the pyparsing module distribution."""
from distutils.core import setup
from pyparsing import __version__
setup(# Distribution meta-data
name = "pyparsing",
version = __version__,
description = "Python parsing module",
author = "Paul McGuire",
author_email = "ptmcg@users.sourceforge.net",
url = "http://pyparsing.wikispaces.com/",
download_url = "http://sourceforge.net/project/showfiles.php?group_id=97203",
license = "MIT License",
py_modules = ["pyparsing", "pyparsing_py3"],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
]
)
| Add change to ship both pyparsing and pyparsing_py3 modules. | Add change to ship both pyparsing and pyparsing_py3 modules.
| Python | mit | 5monkeys/pyparsing | -
+
"""Setup script for the pyparsing module distribution."""
- from distutils.core import setup
+ from distutils.core import setup
-
+
from pyparsing import __version__
setup(# Distribution meta-data
- name = "pyparsing",
+ name = "pyparsing",
version = __version__,
- description = "Python parsing module",
+ description = "Python parsing module",
- author = "Paul McGuire",
+ author = "Paul McGuire",
- author_email = "ptmcg@users.sourceforge.net",
+ author_email = "ptmcg@users.sourceforge.net",
url = "http://pyparsing.wikispaces.com/",
download_url = "http://sourceforge.net/project/showfiles.php?group_id=97203",
- license = "MIT License",
+ license = "MIT License",
- py_modules = ["pyparsing"],
+ py_modules = ["pyparsing", "pyparsing_py3"],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
]
- )
+ )
| Add change to ship both pyparsing and pyparsing_py3 modules. | ## Code Before:
"""Setup script for the pyparsing module distribution."""
from distutils.core import setup
from pyparsing import __version__
setup(# Distribution meta-data
name = "pyparsing",
version = __version__,
description = "Python parsing module",
author = "Paul McGuire",
author_email = "ptmcg@users.sourceforge.net",
url = "http://pyparsing.wikispaces.com/",
download_url = "http://sourceforge.net/project/showfiles.php?group_id=97203",
license = "MIT License",
py_modules = ["pyparsing"],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
]
)
## Instruction:
Add change to ship both pyparsing and pyparsing_py3 modules.
## Code After:
"""Setup script for the pyparsing module distribution."""
from distutils.core import setup
from pyparsing import __version__
setup(# Distribution meta-data
name = "pyparsing",
version = __version__,
description = "Python parsing module",
author = "Paul McGuire",
author_email = "ptmcg@users.sourceforge.net",
url = "http://pyparsing.wikispaces.com/",
download_url = "http://sourceforge.net/project/showfiles.php?group_id=97203",
license = "MIT License",
py_modules = ["pyparsing", "pyparsing_py3"],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
]
)
| # ... existing code ...
license = "MIT License",
py_modules = ["pyparsing", "pyparsing_py3"],
classifiers=[
# ... rest of the code ... |
916441874a3bca016e950557230f7b3a84b3ee97 | packages/grid/backend/grid/utils.py | packages/grid/backend/grid/utils.py | from typing import Any
from typing import Optional
# third party
from nacl.signing import SigningKey
# syft absolute
from syft import flags
from syft.core.common.message import SyftMessage
from syft.core.io.address import Address
from syft.core.node.common.action.exception_action import ExceptionMessage
from syft.lib.python.dict import Dict
# grid absolute
from grid.core.node import get_client
def send_message_with_reply(
signing_key: SigningKey,
message_type: SyftMessage,
address: Optional[Address] = None,
reply_to: Optional[Address] = None,
**content: Any
) -> Dict:
client = get_client(signing_key)
if address is None:
address = client.address
if reply_to is None:
reply_to = client.address
if flags.USE_NEW_SERVICE:
msg = message_type(address=address, reply_to=reply_to, kwargs=content).sign(
signing_key=signing_key
)
reply = client.send_immediate_msg_with_reply(msg=msg)
reply = reply.payload
else:
msg = message_type(address=address, reply_to=reply_to, **content)
reply = client.send_immediate_msg_with_reply(msg=msg)
check_if_syft_reply_is_exception(reply)
return reply
def check_if_syft_reply_is_exception(reply: Dict) -> None:
if isinstance(reply, ExceptionMessage):
raise Exception(reply.exception_msg)
| from typing import Any
from typing import Optional
# third party
from nacl.signing import SigningKey
# syft absolute
from syft.core.common.message import SyftMessage
from syft.core.io.address import Address
from syft.core.node.common.action.exception_action import ExceptionMessage
from syft.lib.python.dict import Dict
# grid absolute
from grid.core.node import node
def send_message_with_reply(
signing_key: SigningKey,
message_type: SyftMessage,
address: Optional[Address] = None,
reply_to: Optional[Address] = None,
**content: Any
) -> Dict:
if not address:
address = node.address
if not reply_to:
reply_to = node.address
# if flags.USE_NEW_SERVICE:
msg = message_type(address=address, reply_to=reply_to, kwargs=content).sign(
signing_key=signing_key
)
reply = node.recv_immediate_msg_with_reply(msg=msg)
reply = reply.message
check_if_syft_reply_is_exception(reply)
reply = reply.payload
return reply
def check_if_syft_reply_is_exception(reply: Dict) -> None:
if isinstance(reply, ExceptionMessage):
raise Exception(reply.exception_msg)
| Replace SyftClient calls -> Direct Node calls - This avoids to build client ast for every single request making the backend faster | Replace SyftClient calls -> Direct Node calls
- This avoids to build client ast for every single request
making the backend faster
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft | from typing import Any
from typing import Optional
# third party
from nacl.signing import SigningKey
# syft absolute
- from syft import flags
from syft.core.common.message import SyftMessage
from syft.core.io.address import Address
from syft.core.node.common.action.exception_action import ExceptionMessage
from syft.lib.python.dict import Dict
# grid absolute
- from grid.core.node import get_client
+ from grid.core.node import node
def send_message_with_reply(
signing_key: SigningKey,
message_type: SyftMessage,
address: Optional[Address] = None,
reply_to: Optional[Address] = None,
**content: Any
) -> Dict:
- client = get_client(signing_key)
+ if not address:
+ address = node.address
+ if not reply_to:
+ reply_to = node.address
+ # if flags.USE_NEW_SERVICE:
+ msg = message_type(address=address, reply_to=reply_to, kwargs=content).sign(
+ signing_key=signing_key
+ )
- if address is None:
- address = client.address
- if reply_to is None:
- reply_to = client.address
-
- if flags.USE_NEW_SERVICE:
- msg = message_type(address=address, reply_to=reply_to, kwargs=content).sign(
- signing_key=signing_key
- )
- reply = client.send_immediate_msg_with_reply(msg=msg)
+ reply = node.recv_immediate_msg_with_reply(msg=msg)
+ reply = reply.message
- reply = reply.payload
- else:
- msg = message_type(address=address, reply_to=reply_to, **content)
- reply = client.send_immediate_msg_with_reply(msg=msg)
-
check_if_syft_reply_is_exception(reply)
+ reply = reply.payload
return reply
def check_if_syft_reply_is_exception(reply: Dict) -> None:
if isinstance(reply, ExceptionMessage):
raise Exception(reply.exception_msg)
| Replace SyftClient calls -> Direct Node calls - This avoids to build client ast for every single request making the backend faster | ## Code Before:
from typing import Any
from typing import Optional
# third party
from nacl.signing import SigningKey
# syft absolute
from syft import flags
from syft.core.common.message import SyftMessage
from syft.core.io.address import Address
from syft.core.node.common.action.exception_action import ExceptionMessage
from syft.lib.python.dict import Dict
# grid absolute
from grid.core.node import get_client
def send_message_with_reply(
signing_key: SigningKey,
message_type: SyftMessage,
address: Optional[Address] = None,
reply_to: Optional[Address] = None,
**content: Any
) -> Dict:
client = get_client(signing_key)
if address is None:
address = client.address
if reply_to is None:
reply_to = client.address
if flags.USE_NEW_SERVICE:
msg = message_type(address=address, reply_to=reply_to, kwargs=content).sign(
signing_key=signing_key
)
reply = client.send_immediate_msg_with_reply(msg=msg)
reply = reply.payload
else:
msg = message_type(address=address, reply_to=reply_to, **content)
reply = client.send_immediate_msg_with_reply(msg=msg)
check_if_syft_reply_is_exception(reply)
return reply
def check_if_syft_reply_is_exception(reply: Dict) -> None:
if isinstance(reply, ExceptionMessage):
raise Exception(reply.exception_msg)
## Instruction:
Replace SyftClient calls -> Direct Node calls - This avoids to build client ast for every single request making the backend faster
## Code After:
from typing import Any
from typing import Optional
# third party
from nacl.signing import SigningKey
# syft absolute
from syft.core.common.message import SyftMessage
from syft.core.io.address import Address
from syft.core.node.common.action.exception_action import ExceptionMessage
from syft.lib.python.dict import Dict
# grid absolute
from grid.core.node import node
def send_message_with_reply(
signing_key: SigningKey,
message_type: SyftMessage,
address: Optional[Address] = None,
reply_to: Optional[Address] = None,
**content: Any
) -> Dict:
if not address:
address = node.address
if not reply_to:
reply_to = node.address
# if flags.USE_NEW_SERVICE:
msg = message_type(address=address, reply_to=reply_to, kwargs=content).sign(
signing_key=signing_key
)
reply = node.recv_immediate_msg_with_reply(msg=msg)
reply = reply.message
check_if_syft_reply_is_exception(reply)
reply = reply.payload
return reply
def check_if_syft_reply_is_exception(reply: Dict) -> None:
if isinstance(reply, ExceptionMessage):
raise Exception(reply.exception_msg)
| ...
# syft absolute
from syft.core.common.message import SyftMessage
...
# grid absolute
from grid.core.node import node
...
) -> Dict:
if not address:
address = node.address
if not reply_to:
reply_to = node.address
# if flags.USE_NEW_SERVICE:
msg = message_type(address=address, reply_to=reply_to, kwargs=content).sign(
signing_key=signing_key
)
reply = node.recv_immediate_msg_with_reply(msg=msg)
reply = reply.message
check_if_syft_reply_is_exception(reply)
reply = reply.payload
return reply
... |
b5d3425ae0a4a42e85748e494c3ddfaa7511f7b7 | ocradmin/lib/nodetree/cache.py | ocradmin/lib/nodetree/cache.py |
class BasicCacher(object):
"""
Basic in-memory caching.
"""
def __init__(self, logger=None):
self._cache = {}
self.logger = logger
def set_cache(self, node, data):
"""
Store some data on the object.
"""
self._cache[node.label] = data
def get_cache(self, node):
"""
Return cached data.
"""
return self._cache.get(node.label)
def has_cache(self, node):
return self._cache.get(node.label) is not None
def clear_cache(self, node):
del self._cache[node.label]
def clear(self):
self._cache = {}
def __repr__(self):
return "<%s>" % self.__class__.__name__
|
class BasicCacher(object):
"""
Basic in-memory caching.
"""
def __init__(self, logger=None):
self._cache = {}
self.logger = logger
def set_cache(self, node, data):
"""
Store some data on the object.
"""
self._cache[node.label] = data
def get_cache(self, node):
"""
Return cached data.
"""
return self._cache.get(node.label)
def has_cache(self, node):
return self._cache.get(node.label) is not None
def clear_cache(self, node):
if self._cache.get(node.label):
del self._cache[node.label]
def clear(self):
self._cache = {}
def __repr__(self):
return "<%s>" % self.__class__.__name__
| Test for existence of node before clearing it | Test for existence of node before clearing it
| Python | apache-2.0 | vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium |
class BasicCacher(object):
"""
Basic in-memory caching.
"""
def __init__(self, logger=None):
self._cache = {}
self.logger = logger
def set_cache(self, node, data):
"""
Store some data on the object.
"""
self._cache[node.label] = data
def get_cache(self, node):
"""
Return cached data.
"""
return self._cache.get(node.label)
def has_cache(self, node):
return self._cache.get(node.label) is not None
def clear_cache(self, node):
+ if self._cache.get(node.label):
- del self._cache[node.label]
+ del self._cache[node.label]
def clear(self):
self._cache = {}
def __repr__(self):
return "<%s>" % self.__class__.__name__
| Test for existence of node before clearing it | ## Code Before:
class BasicCacher(object):
"""
Basic in-memory caching.
"""
def __init__(self, logger=None):
self._cache = {}
self.logger = logger
def set_cache(self, node, data):
"""
Store some data on the object.
"""
self._cache[node.label] = data
def get_cache(self, node):
"""
Return cached data.
"""
return self._cache.get(node.label)
def has_cache(self, node):
return self._cache.get(node.label) is not None
def clear_cache(self, node):
del self._cache[node.label]
def clear(self):
self._cache = {}
def __repr__(self):
return "<%s>" % self.__class__.__name__
## Instruction:
Test for existence of node before clearing it
## Code After:
class BasicCacher(object):
"""
Basic in-memory caching.
"""
def __init__(self, logger=None):
self._cache = {}
self.logger = logger
def set_cache(self, node, data):
"""
Store some data on the object.
"""
self._cache[node.label] = data
def get_cache(self, node):
"""
Return cached data.
"""
return self._cache.get(node.label)
def has_cache(self, node):
return self._cache.get(node.label) is not None
def clear_cache(self, node):
if self._cache.get(node.label):
del self._cache[node.label]
def clear(self):
self._cache = {}
def __repr__(self):
return "<%s>" % self.__class__.__name__
| // ... existing code ...
def clear_cache(self, node):
if self._cache.get(node.label):
del self._cache[node.label]
// ... rest of the code ... |
3681b5a485662656d6419d95ad89f1fbdb7a2a50 | myuw/context_processors.py | myuw/context_processors.py |
def is_hybrid(request):
return {
'is_hybrid': 'HTTP_MYUW_HYBRID' in request.META
}
|
def is_hybrid(request):
return {
'is_hybrid': 'MyUW_Hybrid/1.0' in request.META['HTTP_USER_AGENT']
}
| Update context processer to check for custom hybrid user agent. | Update context processer to check for custom hybrid user agent.
| Python | apache-2.0 | uw-it-aca/myuw,uw-it-aca/myuw,uw-it-aca/myuw,uw-it-aca/myuw |
def is_hybrid(request):
return {
- 'is_hybrid': 'HTTP_MYUW_HYBRID' in request.META
+ 'is_hybrid': 'MyUW_Hybrid/1.0' in request.META['HTTP_USER_AGENT']
}
| Update context processer to check for custom hybrid user agent. | ## Code Before:
def is_hybrid(request):
return {
'is_hybrid': 'HTTP_MYUW_HYBRID' in request.META
}
## Instruction:
Update context processer to check for custom hybrid user agent.
## Code After:
def is_hybrid(request):
return {
'is_hybrid': 'MyUW_Hybrid/1.0' in request.META['HTTP_USER_AGENT']
}
| # ... existing code ...
return {
'is_hybrid': 'MyUW_Hybrid/1.0' in request.META['HTTP_USER_AGENT']
}
# ... rest of the code ... |
ad2b0447afbee92684ab0b4f14dc0d45a28f3ba2 | tests/foomodulegen-auto.py | tests/foomodulegen-auto.py |
import sys
import re
import pybindgen
from pybindgen.typehandlers import base as typehandlers
from pybindgen import (ReturnValue, Parameter, Module, Function, FileCodeSink)
from pybindgen import (CppMethod, CppConstructor, CppClass, Enum)
from pybindgen.gccxmlparser import ModuleParser
from pybindgen.function import CustomFunctionWrapper
from pybindgen.cppmethod import CustomCppMethodWrapper
import foomodulegen_common
def my_module_gen():
out = FileCodeSink(sys.stdout)
pygen_file = open(sys.argv[2], "wt")
module_parser = ModuleParser('foo2', '::')
module = module_parser.parse([sys.argv[1]], includes=['"foo.h"'], pygen_sink=FileCodeSink(pygen_file))
pygen_file.close()
foomodulegen_common.customize_module(module)
module.generate(out)
if __name__ == '__main__':
try:
import cProfile as profile
except ImportError:
my_module_gen()
else:
print >> sys.stderr, "** running under profiler"
profile.run('my_module_gen()', 'foomodulegen-auto.pstat')
|
import sys
import re
import pybindgen
from pybindgen.typehandlers import base as typehandlers
from pybindgen import (ReturnValue, Parameter, Module, Function, FileCodeSink)
from pybindgen import (CppMethod, CppConstructor, CppClass, Enum)
from pybindgen.gccxmlparser import ModuleParser
from pybindgen.function import CustomFunctionWrapper
from pybindgen.cppmethod import CustomCppMethodWrapper
import foomodulegen_common
def my_module_gen():
out = FileCodeSink(sys.stdout)
pygen_file = open(sys.argv[2], "wt")
module_parser = ModuleParser('foo2', '::')
module = module_parser.parse([sys.argv[1]], includes=['"foo.h"'], pygen_sink=FileCodeSink(pygen_file))
pygen_file.close()
foomodulegen_common.customize_module(module)
module.generate(out)
def main():
if sys.argv[1] == '-d':
del sys.argv[1]
import pdb
pdb.set_trace()
my_module_gen()
else:
try:
import cProfile as profile
except ImportError:
my_module_gen()
else:
print >> sys.stderr, "** running under profiler"
profile.run('my_module_gen()', 'foomodulegen-auto.pstat')
if __name__ == '__main__':
main()
| Add a debug switch (-d) to enable debugger | Add a debug switch (-d) to enable debugger
| Python | lgpl-2.1 | cawka/pybindgen,caramucho/pybindgen,caramucho/pybindgen,cawka/pybindgen,cawka/pybindgen,caramucho/pybindgen,cawka/pybindgen,caramucho/pybindgen |
import sys
import re
import pybindgen
from pybindgen.typehandlers import base as typehandlers
from pybindgen import (ReturnValue, Parameter, Module, Function, FileCodeSink)
from pybindgen import (CppMethod, CppConstructor, CppClass, Enum)
from pybindgen.gccxmlparser import ModuleParser
from pybindgen.function import CustomFunctionWrapper
from pybindgen.cppmethod import CustomCppMethodWrapper
import foomodulegen_common
def my_module_gen():
out = FileCodeSink(sys.stdout)
pygen_file = open(sys.argv[2], "wt")
module_parser = ModuleParser('foo2', '::')
module = module_parser.parse([sys.argv[1]], includes=['"foo.h"'], pygen_sink=FileCodeSink(pygen_file))
pygen_file.close()
foomodulegen_common.customize_module(module)
module.generate(out)
- if __name__ == '__main__':
- try:
- import cProfile as profile
- except ImportError:
+ def main():
+ if sys.argv[1] == '-d':
+ del sys.argv[1]
+ import pdb
+ pdb.set_trace()
my_module_gen()
else:
+ try:
+ import cProfile as profile
+ except ImportError:
+ my_module_gen()
+ else:
- print >> sys.stderr, "** running under profiler"
+ print >> sys.stderr, "** running under profiler"
- profile.run('my_module_gen()', 'foomodulegen-auto.pstat')
+ profile.run('my_module_gen()', 'foomodulegen-auto.pstat')
+
+ if __name__ == '__main__':
+ main()
| Add a debug switch (-d) to enable debugger | ## Code Before:
import sys
import re
import pybindgen
from pybindgen.typehandlers import base as typehandlers
from pybindgen import (ReturnValue, Parameter, Module, Function, FileCodeSink)
from pybindgen import (CppMethod, CppConstructor, CppClass, Enum)
from pybindgen.gccxmlparser import ModuleParser
from pybindgen.function import CustomFunctionWrapper
from pybindgen.cppmethod import CustomCppMethodWrapper
import foomodulegen_common
def my_module_gen():
out = FileCodeSink(sys.stdout)
pygen_file = open(sys.argv[2], "wt")
module_parser = ModuleParser('foo2', '::')
module = module_parser.parse([sys.argv[1]], includes=['"foo.h"'], pygen_sink=FileCodeSink(pygen_file))
pygen_file.close()
foomodulegen_common.customize_module(module)
module.generate(out)
if __name__ == '__main__':
try:
import cProfile as profile
except ImportError:
my_module_gen()
else:
print >> sys.stderr, "** running under profiler"
profile.run('my_module_gen()', 'foomodulegen-auto.pstat')
## Instruction:
Add a debug switch (-d) to enable debugger
## Code After:
import sys
import re
import pybindgen
from pybindgen.typehandlers import base as typehandlers
from pybindgen import (ReturnValue, Parameter, Module, Function, FileCodeSink)
from pybindgen import (CppMethod, CppConstructor, CppClass, Enum)
from pybindgen.gccxmlparser import ModuleParser
from pybindgen.function import CustomFunctionWrapper
from pybindgen.cppmethod import CustomCppMethodWrapper
import foomodulegen_common
def my_module_gen():
out = FileCodeSink(sys.stdout)
pygen_file = open(sys.argv[2], "wt")
module_parser = ModuleParser('foo2', '::')
module = module_parser.parse([sys.argv[1]], includes=['"foo.h"'], pygen_sink=FileCodeSink(pygen_file))
pygen_file.close()
foomodulegen_common.customize_module(module)
module.generate(out)
def main():
if sys.argv[1] == '-d':
del sys.argv[1]
import pdb
pdb.set_trace()
my_module_gen()
else:
try:
import cProfile as profile
except ImportError:
my_module_gen()
else:
print >> sys.stderr, "** running under profiler"
profile.run('my_module_gen()', 'foomodulegen-auto.pstat')
if __name__ == '__main__':
main()
| ...
def main():
if sys.argv[1] == '-d':
del sys.argv[1]
import pdb
pdb.set_trace()
my_module_gen()
...
else:
try:
import cProfile as profile
except ImportError:
my_module_gen()
else:
print >> sys.stderr, "** running under profiler"
profile.run('my_module_gen()', 'foomodulegen-auto.pstat')
if __name__ == '__main__':
main()
... |
2fc71f9b83db5d0ff9e73572ceb49011f916bcf5 | calebasse/views.py | calebasse/views.py |
from django.shortcuts import render, redirect
from django.template.defaultfilters import slugify
from cbv import HOME_SERVICE_COOKIE, TemplateView
from calebasse.ressources.models import Service
APPLICATIONS = (
(u'Gestion des dossiers', 'dossiers'),
(u'Agenda', 'agenda'),
(u'Saisie des actes', 'actes'),
(u'Facturation et décompte', 'facturation'),
(u'Gestion des personnes', 'personnes'),
(u'Gestion des ressources', 'ressources'),
)
def redirect_to_homepage(request):
service_name = request.COOKIES.get(HOME_SERVICE_COOKIE, 'cmpp').lower()
return redirect('homepage', service=service_name)
class Homepage(TemplateView):
template_name='calebasse/homepage.html'
def get_context_data(self, **kwargs):
services = Service.objects.values_list('name', 'slug')
ctx = super(Homepage, self).get_context_data(**kwargs)
ctx.update({
'applications': APPLICATIONS,
'services': services,
'service_name': self.service.name,
})
return ctx
homepage = Homepage.as_view()
|
from django.shortcuts import render, redirect
from django.template.defaultfilters import slugify
from cbv import HOME_SERVICE_COOKIE, TemplateView
from calebasse.ressources.models import Service
APPLICATIONS = (
(u'Gestion des dossiers', 'dossiers'),
(u'Agenda', 'agenda'),
(u'Saisie des actes', 'actes'),
(u'Facturation et décompte', 'facturation'),
(u'Gestion des personnes', 'personnes'),
(u'Gestion des ressources', 'ressources'),
)
def redirect_to_homepage(request):
service_name = request.COOKIES.get(HOME_SERVICE_COOKIE, 'cmpp').lower()
return redirect('homepage', service=service_name)
class Homepage(TemplateView):
template_name='calebasse/homepage.html'
def get_context_data(self, **kwargs):
services = Service.objects.values_list('name', 'slug')
services = sorted(services, key=lambda tup: tup[0])
ctx = super(Homepage, self).get_context_data(**kwargs)
ctx.update({
'applications': APPLICATIONS,
'services': services,
'service_name': self.service.name,
})
return ctx
homepage = Homepage.as_view()
| Reorder the service buttons display. | Reorder the service buttons display.
| Python | agpl-3.0 | ZTH1970/alcide,ZTH1970/alcide,ZTH1970/alcide,ZTH1970/alcide,ZTH1970/alcide |
from django.shortcuts import render, redirect
from django.template.defaultfilters import slugify
from cbv import HOME_SERVICE_COOKIE, TemplateView
from calebasse.ressources.models import Service
APPLICATIONS = (
(u'Gestion des dossiers', 'dossiers'),
(u'Agenda', 'agenda'),
(u'Saisie des actes', 'actes'),
(u'Facturation et décompte', 'facturation'),
(u'Gestion des personnes', 'personnes'),
(u'Gestion des ressources', 'ressources'),
)
def redirect_to_homepage(request):
service_name = request.COOKIES.get(HOME_SERVICE_COOKIE, 'cmpp').lower()
return redirect('homepage', service=service_name)
class Homepage(TemplateView):
template_name='calebasse/homepage.html'
def get_context_data(self, **kwargs):
services = Service.objects.values_list('name', 'slug')
+ services = sorted(services, key=lambda tup: tup[0])
ctx = super(Homepage, self).get_context_data(**kwargs)
ctx.update({
'applications': APPLICATIONS,
'services': services,
'service_name': self.service.name,
})
return ctx
homepage = Homepage.as_view()
| Reorder the service buttons display. | ## Code Before:
from django.shortcuts import render, redirect
from django.template.defaultfilters import slugify
from cbv import HOME_SERVICE_COOKIE, TemplateView
from calebasse.ressources.models import Service
APPLICATIONS = (
(u'Gestion des dossiers', 'dossiers'),
(u'Agenda', 'agenda'),
(u'Saisie des actes', 'actes'),
(u'Facturation et décompte', 'facturation'),
(u'Gestion des personnes', 'personnes'),
(u'Gestion des ressources', 'ressources'),
)
def redirect_to_homepage(request):
service_name = request.COOKIES.get(HOME_SERVICE_COOKIE, 'cmpp').lower()
return redirect('homepage', service=service_name)
class Homepage(TemplateView):
template_name='calebasse/homepage.html'
def get_context_data(self, **kwargs):
services = Service.objects.values_list('name', 'slug')
ctx = super(Homepage, self).get_context_data(**kwargs)
ctx.update({
'applications': APPLICATIONS,
'services': services,
'service_name': self.service.name,
})
return ctx
homepage = Homepage.as_view()
## Instruction:
Reorder the service buttons display.
## Code After:
from django.shortcuts import render, redirect
from django.template.defaultfilters import slugify
from cbv import HOME_SERVICE_COOKIE, TemplateView
from calebasse.ressources.models import Service
APPLICATIONS = (
(u'Gestion des dossiers', 'dossiers'),
(u'Agenda', 'agenda'),
(u'Saisie des actes', 'actes'),
(u'Facturation et décompte', 'facturation'),
(u'Gestion des personnes', 'personnes'),
(u'Gestion des ressources', 'ressources'),
)
def redirect_to_homepage(request):
service_name = request.COOKIES.get(HOME_SERVICE_COOKIE, 'cmpp').lower()
return redirect('homepage', service=service_name)
class Homepage(TemplateView):
template_name='calebasse/homepage.html'
def get_context_data(self, **kwargs):
services = Service.objects.values_list('name', 'slug')
services = sorted(services, key=lambda tup: tup[0])
ctx = super(Homepage, self).get_context_data(**kwargs)
ctx.update({
'applications': APPLICATIONS,
'services': services,
'service_name': self.service.name,
})
return ctx
homepage = Homepage.as_view()
| # ... existing code ...
services = Service.objects.values_list('name', 'slug')
services = sorted(services, key=lambda tup: tup[0])
ctx = super(Homepage, self).get_context_data(**kwargs)
# ... rest of the code ... |
d42b9da06d5cde89a6116d711fc6ae216256cabc | shell/view/home/IconLayout.py | shell/view/home/IconLayout.py | import random
class IconLayout:
def __init__(self, width, height):
self._icons = []
self._width = width
self._height = height
def add_icon(self, icon):
self._icons.append(icon)
self._layout_icon(icon)
def remove_icon(self, icon):
self._icons.remove(icon)
def _is_valid_position(self, icon, x, y):
icon_size = icon.props.size
border = 20
if not (border < x < self._width - icon_size - border and \
border < y < self._height - icon_size - border):
return False
return True
def _layout_icon(self, icon):
while True:
x = random.random() * self._width
y = random.random() * self._height
if self._is_valid_position(icon, x, y):
break
icon.props.x = x
icon.props.y = y
| import random
class IconLayout:
def __init__(self, width, height):
self._icons = []
self._width = width
self._height = height
def add_icon(self, icon):
self._icons.append(icon)
self._layout_icon(icon)
def remove_icon(self, icon):
self._icons.remove(icon)
def _is_valid_position(self, icon, x, y):
icon_size = icon.get_property('size')
border = 20
if not (border < x < self._width - icon_size - border and \
border < y < self._height - icon_size - border):
return False
return True
def _layout_icon(self, icon):
while True:
x = random.random() * self._width
y = random.random() * self._height
if self._is_valid_position(icon, x, y):
break
icon.set_property('x', x)
icon.set_property('y', y)
| Use get/set_property rather than direct accessors | Use get/set_property rather than direct accessors
| Python | lgpl-2.1 | Daksh/sugar-toolkit-gtk3,manuq/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit,quozl/sugar-toolkit-gtk3,godiard/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit,tchx84/debian-pkg-sugar-toolkit,ceibal-tatu/sugar-toolkit,gusDuarte/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit,tchx84/debian-pkg-sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit-gtk3,manuq/sugar-toolkit-gtk3,samdroid-apps/sugar-toolkit-gtk3,puneetgkaur/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit-gtk3,samdroid-apps/sugar-toolkit-gtk3,godiard/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit,i5o/sugar-toolkit-gtk3,Daksh/sugar-toolkit-gtk3,godiard/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit,gusDuarte/sugar-toolkit-gtk3,puneetgkaur/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,Daksh/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit-gtk3,samdroid-apps/sugar-toolkit-gtk3,puneetgkaur/sugar-toolkit-gtk3,samdroid-apps/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit,sugarlabs/sugar-toolkit,sugarlabs/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,manuq/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit,puneetgkaur/backup_sugar_sugartoolkit,sugarlabs/sugar-toolkit,ceibal-tatu/sugar-toolkit,tchx84/sugar-toolkit-gtk3 | import random
class IconLayout:
def __init__(self, width, height):
self._icons = []
self._width = width
self._height = height
def add_icon(self, icon):
self._icons.append(icon)
self._layout_icon(icon)
def remove_icon(self, icon):
self._icons.remove(icon)
def _is_valid_position(self, icon, x, y):
- icon_size = icon.props.size
+ icon_size = icon.get_property('size')
border = 20
if not (border < x < self._width - icon_size - border and \
border < y < self._height - icon_size - border):
return False
return True
def _layout_icon(self, icon):
while True:
x = random.random() * self._width
y = random.random() * self._height
if self._is_valid_position(icon, x, y):
break
- icon.props.x = x
- icon.props.y = y
+ icon.set_property('x', x)
+ icon.set_property('y', y)
| Use get/set_property rather than direct accessors | ## Code Before:
import random
class IconLayout:
def __init__(self, width, height):
self._icons = []
self._width = width
self._height = height
def add_icon(self, icon):
self._icons.append(icon)
self._layout_icon(icon)
def remove_icon(self, icon):
self._icons.remove(icon)
def _is_valid_position(self, icon, x, y):
icon_size = icon.props.size
border = 20
if not (border < x < self._width - icon_size - border and \
border < y < self._height - icon_size - border):
return False
return True
def _layout_icon(self, icon):
while True:
x = random.random() * self._width
y = random.random() * self._height
if self._is_valid_position(icon, x, y):
break
icon.props.x = x
icon.props.y = y
## Instruction:
Use get/set_property rather than direct accessors
## Code After:
import random
class IconLayout:
def __init__(self, width, height):
self._icons = []
self._width = width
self._height = height
def add_icon(self, icon):
self._icons.append(icon)
self._layout_icon(icon)
def remove_icon(self, icon):
self._icons.remove(icon)
def _is_valid_position(self, icon, x, y):
icon_size = icon.get_property('size')
border = 20
if not (border < x < self._width - icon_size - border and \
border < y < self._height - icon_size - border):
return False
return True
def _layout_icon(self, icon):
while True:
x = random.random() * self._width
y = random.random() * self._height
if self._is_valid_position(icon, x, y):
break
icon.set_property('x', x)
icon.set_property('y', y)
| ...
def _is_valid_position(self, icon, x, y):
icon_size = icon.get_property('size')
border = 20
...
icon.set_property('x', x)
icon.set_property('y', y)
... |
bb0b72333b715956740373c3ba80a8193b99a8cc | app/services/updater_service.py | app/services/updater_service.py | from app.system.updater import check_updates, do_upgrade, run_ansible
from app.views import SimpleBackgroundView
from .base import BaseService, BlockingServiceStart
class UpdaterService(BaseService, BlockingServiceStart):
def __init__(self, observer=None):
super().__init__(observer=observer)
self._view = SimpleBackgroundView("Checking for updates.")
def on_service_start(self):
values = check_updates()
for val in values:
self._view.args["subtitle"] = "Working with: " + str(val)
do_upgrade([val])
if values:
run_ansible()
def view(self):
return self._view
| from app.system.updater import check_updates, do_upgrade, run_ansible
from app.views import SimpleBackgroundView
from .base import BaseService, BlockingServiceStart
class UpdaterService(BaseService, BlockingServiceStart):
def __init__(self, observer=None):
super().__init__(observer=observer)
self._view = SimpleBackgroundView("Checking for updates.")
def on_service_start(self):
values = check_updates()
for val in values:
self._view.args["subtitle"] = "Working with: " + str(val)
do_upgrade([val])
if values:
self._view.args["subtitle"] = "Finishing up..."
run_ansible()
def view(self):
return self._view
| Add message before running ansible. | Add message before running ansible.
| Python | mit | supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer | from app.system.updater import check_updates, do_upgrade, run_ansible
from app.views import SimpleBackgroundView
from .base import BaseService, BlockingServiceStart
class UpdaterService(BaseService, BlockingServiceStart):
def __init__(self, observer=None):
super().__init__(observer=observer)
self._view = SimpleBackgroundView("Checking for updates.")
def on_service_start(self):
values = check_updates()
for val in values:
self._view.args["subtitle"] = "Working with: " + str(val)
do_upgrade([val])
if values:
+ self._view.args["subtitle"] = "Finishing up..."
run_ansible()
def view(self):
return self._view
| Add message before running ansible. | ## Code Before:
from app.system.updater import check_updates, do_upgrade, run_ansible
from app.views import SimpleBackgroundView
from .base import BaseService, BlockingServiceStart
class UpdaterService(BaseService, BlockingServiceStart):
def __init__(self, observer=None):
super().__init__(observer=observer)
self._view = SimpleBackgroundView("Checking for updates.")
def on_service_start(self):
values = check_updates()
for val in values:
self._view.args["subtitle"] = "Working with: " + str(val)
do_upgrade([val])
if values:
run_ansible()
def view(self):
return self._view
## Instruction:
Add message before running ansible.
## Code After:
from app.system.updater import check_updates, do_upgrade, run_ansible
from app.views import SimpleBackgroundView
from .base import BaseService, BlockingServiceStart
class UpdaterService(BaseService, BlockingServiceStart):
def __init__(self, observer=None):
super().__init__(observer=observer)
self._view = SimpleBackgroundView("Checking for updates.")
def on_service_start(self):
values = check_updates()
for val in values:
self._view.args["subtitle"] = "Working with: " + str(val)
do_upgrade([val])
if values:
self._view.args["subtitle"] = "Finishing up..."
run_ansible()
def view(self):
return self._view
| ...
if values:
self._view.args["subtitle"] = "Finishing up..."
run_ansible()
... |
5442d45689a567528753a0e705733f86eac37220 | buckets/test/views.py | buckets/test/views.py | from django.core.files.storage import default_storage
from django.views.decorators.http import require_POST
from django.http import HttpResponse
@require_POST
def fake_s3_upload(request):
key = request.POST.get('key')
file = request.FILES.get('file')
default_storage.save(key, file.read())
return HttpResponse('', status=204)
| from django.core.files.storage import default_storage
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.http import HttpResponse
@csrf_exempt
@require_POST
def fake_s3_upload(request):
key = request.POST.get('key')
file = request.FILES.get('file')
default_storage.save(key, file.read())
return HttpResponse('', status=204)
| Set fake_s3_upload view to be CSRF exempt | Set fake_s3_upload view to be CSRF exempt
| Python | agpl-3.0 | Cadasta/django-buckets,Cadasta/django-buckets,Cadasta/django-buckets | from django.core.files.storage import default_storage
+ from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.http import HttpResponse
+ @csrf_exempt
@require_POST
def fake_s3_upload(request):
key = request.POST.get('key')
file = request.FILES.get('file')
default_storage.save(key, file.read())
return HttpResponse('', status=204)
| Set fake_s3_upload view to be CSRF exempt | ## Code Before:
from django.core.files.storage import default_storage
from django.views.decorators.http import require_POST
from django.http import HttpResponse
@require_POST
def fake_s3_upload(request):
key = request.POST.get('key')
file = request.FILES.get('file')
default_storage.save(key, file.read())
return HttpResponse('', status=204)
## Instruction:
Set fake_s3_upload view to be CSRF exempt
## Code After:
from django.core.files.storage import default_storage
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.http import HttpResponse
@csrf_exempt
@require_POST
def fake_s3_upload(request):
key = request.POST.get('key')
file = request.FILES.get('file')
default_storage.save(key, file.read())
return HttpResponse('', status=204)
| ...
from django.core.files.storage import default_storage
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
...
@csrf_exempt
@require_POST
... |
990e33af851172ea3d79e591bde52af554d0eb50 | common/util.py | common/util.py |
import sys
def log(msg, *args):
if args:
msg = msg % args
print >>sys.stderr, 'webpipe:', msg
|
import os
import sys
basename = os.path.basename(sys.argv[0])
prefix, _ = os.path.splitext(basename)
def log(msg, *args):
if args:
msg = msg % args
print >>sys.stderr, prefix + ': ' + msg
| Use the program name as the prefix. | Use the program name as the prefix.
| Python | bsd-3-clause | andychu/webpipe,andychu/webpipe,andychu/webpipe,andychu/webpipe,andychu/webpipe |
+ import os
import sys
+ basename = os.path.basename(sys.argv[0])
+ prefix, _ = os.path.splitext(basename)
def log(msg, *args):
if args:
msg = msg % args
- print >>sys.stderr, 'webpipe:', msg
+ print >>sys.stderr, prefix + ': ' + msg
- | Use the program name as the prefix. | ## Code Before:
import sys
def log(msg, *args):
if args:
msg = msg % args
print >>sys.stderr, 'webpipe:', msg
## Instruction:
Use the program name as the prefix.
## Code After:
import os
import sys
basename = os.path.basename(sys.argv[0])
prefix, _ = os.path.splitext(basename)
def log(msg, *args):
if args:
msg = msg % args
print >>sys.stderr, prefix + ': ' + msg
| ...
import os
import sys
...
basename = os.path.basename(sys.argv[0])
prefix, _ = os.path.splitext(basename)
...
msg = msg % args
print >>sys.stderr, prefix + ': ' + msg
... |
95b08a7cb2d473c25c1d326b0394336955b47af4 | appy/models.py | appy/models.py | from django.db import models
from django.contrib.auth.models import User
class Tag(models.Model):
description = models.TextField()
class Position(models.Model):
company = models.TextField()
job_title = models.TextField()
description = models.TextField()
tags = models.ManyToManyField(Tag)
class Application(models.Model):
user = models.ForeignKey(User)
position = models.ForeignKey(Position)
APPLIED = 'APP'
REJECTED = 'REJ'
INTERVIEWING = 'INT'
NEGOTIATING = 'NEG'
STATUS_CHOICES = (
(APPLIED, 'Applied'),
(REJECTED, 'Rejected'),
(INTERVIEWING, 'Interviewing'),
(NEGOTIATING, 'Negotiating'),
)
status = models.CharField(max_length=3, choices=STATUS_CHOICES, default=APPLIED)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
| from django.db import models
from django.contrib.auth.models import User
class Tag(models.Model):
description = models.TextField()
def __unicode__(self):
return self.description
class Position(models.Model):
company = models.TextField()
job_title = models.TextField()
description = models.TextField()
tags = models.ManyToManyField(Tag)
def __unicode__(self):
return u'%s at %s' % (self.job_title, self.company)
class Application(models.Model):
user = models.ForeignKey(User)
position = models.ForeignKey(Position)
APPLIED = 'APP'
REJECTED = 'REJ'
INTERVIEWING = 'INT'
NEGOTIATING = 'NEG'
STATUS_CHOICES = (
(APPLIED, 'Applied'),
(REJECTED, 'Rejected'),
(INTERVIEWING, 'Interviewing'),
(NEGOTIATING, 'Negotiating'),
)
status = models.CharField(max_length=3, choices=STATUS_CHOICES, default=APPLIED)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
| Add unicode representations for tags/positions | Add unicode representations for tags/positions
| Python | mit | merdey/ApPy,merdey/ApPy | from django.db import models
from django.contrib.auth.models import User
class Tag(models.Model):
description = models.TextField()
+ def __unicode__(self):
+ return self.description
+
class Position(models.Model):
company = models.TextField()
job_title = models.TextField()
description = models.TextField()
tags = models.ManyToManyField(Tag)
+
+ def __unicode__(self):
+ return u'%s at %s' % (self.job_title, self.company)
class Application(models.Model):
user = models.ForeignKey(User)
position = models.ForeignKey(Position)
APPLIED = 'APP'
REJECTED = 'REJ'
INTERVIEWING = 'INT'
NEGOTIATING = 'NEG'
STATUS_CHOICES = (
(APPLIED, 'Applied'),
(REJECTED, 'Rejected'),
(INTERVIEWING, 'Interviewing'),
(NEGOTIATING, 'Negotiating'),
)
status = models.CharField(max_length=3, choices=STATUS_CHOICES, default=APPLIED)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
| Add unicode representations for tags/positions | ## Code Before:
from django.db import models
from django.contrib.auth.models import User
class Tag(models.Model):
description = models.TextField()
class Position(models.Model):
company = models.TextField()
job_title = models.TextField()
description = models.TextField()
tags = models.ManyToManyField(Tag)
class Application(models.Model):
user = models.ForeignKey(User)
position = models.ForeignKey(Position)
APPLIED = 'APP'
REJECTED = 'REJ'
INTERVIEWING = 'INT'
NEGOTIATING = 'NEG'
STATUS_CHOICES = (
(APPLIED, 'Applied'),
(REJECTED, 'Rejected'),
(INTERVIEWING, 'Interviewing'),
(NEGOTIATING, 'Negotiating'),
)
status = models.CharField(max_length=3, choices=STATUS_CHOICES, default=APPLIED)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
## Instruction:
Add unicode representations for tags/positions
## Code After:
from django.db import models
from django.contrib.auth.models import User
class Tag(models.Model):
description = models.TextField()
def __unicode__(self):
return self.description
class Position(models.Model):
company = models.TextField()
job_title = models.TextField()
description = models.TextField()
tags = models.ManyToManyField(Tag)
def __unicode__(self):
return u'%s at %s' % (self.job_title, self.company)
class Application(models.Model):
user = models.ForeignKey(User)
position = models.ForeignKey(Position)
APPLIED = 'APP'
REJECTED = 'REJ'
INTERVIEWING = 'INT'
NEGOTIATING = 'NEG'
STATUS_CHOICES = (
(APPLIED, 'Applied'),
(REJECTED, 'Rejected'),
(INTERVIEWING, 'Interviewing'),
(NEGOTIATING, 'Negotiating'),
)
status = models.CharField(max_length=3, choices=STATUS_CHOICES, default=APPLIED)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
| ...
def __unicode__(self):
return self.description
...
tags = models.ManyToManyField(Tag)
def __unicode__(self):
return u'%s at %s' % (self.job_title, self.company)
... |
4c6784bd17113261b95178deadd037ef3c8ea830 | normandy/recipes/tests/__init__.py | normandy/recipes/tests/__init__.py | import factory
from normandy.base.tests import FuzzyUnicode
from normandy.recipes.models import Action, Recipe, RecipeAction
class RecipeFactory(factory.DjangoModelFactory):
class Meta:
model = Recipe
name = FuzzyUnicode()
enabled = True
class ActionFactory(factory.DjangoModelFactory):
class Meta:
model = Action
name = FuzzyUnicode()
implementation = FuzzyUnicode(prefix='// ')
class RecipeActionFactory(factory.DjangoModelFactory):
class Meta:
model = RecipeAction
action = factory.SubFactory(ActionFactory)
recipe = factory.SubFactory(RecipeFactory)
| import factory
from normandy.base.tests import FuzzyUnicode
from normandy.recipes.models import Action, Locale, Recipe, RecipeAction
class RecipeFactory(factory.DjangoModelFactory):
class Meta:
model = Recipe
name = FuzzyUnicode()
enabled = True
@factory.post_generation
def locale(self, create, extracted, **kwargs):
if not create:
return
if extracted and isinstance(extracted, str):
self.locale, _ = Locale.objects.get_or_create(code=extracted)
class ActionFactory(factory.DjangoModelFactory):
class Meta:
model = Action
name = FuzzyUnicode()
implementation = FuzzyUnicode(prefix='// ')
class RecipeActionFactory(factory.DjangoModelFactory):
class Meta:
model = RecipeAction
action = factory.SubFactory(ActionFactory)
recipe = factory.SubFactory(RecipeFactory)
class LocaleFactory(factory.DjangoModelFactory):
class Meta:
model = Locale
| Fix tests to handle Locale as a foreign key. | Fix tests to handle Locale as a foreign key.
| Python | mpl-2.0 | mozilla/normandy,Osmose/normandy,Osmose/normandy,Osmose/normandy,mozilla/normandy,mozilla/normandy,mozilla/normandy,Osmose/normandy | import factory
from normandy.base.tests import FuzzyUnicode
- from normandy.recipes.models import Action, Recipe, RecipeAction
+ from normandy.recipes.models import Action, Locale, Recipe, RecipeAction
class RecipeFactory(factory.DjangoModelFactory):
class Meta:
model = Recipe
name = FuzzyUnicode()
enabled = True
+
+ @factory.post_generation
+ def locale(self, create, extracted, **kwargs):
+ if not create:
+ return
+
+ if extracted and isinstance(extracted, str):
+ self.locale, _ = Locale.objects.get_or_create(code=extracted)
class ActionFactory(factory.DjangoModelFactory):
class Meta:
model = Action
name = FuzzyUnicode()
implementation = FuzzyUnicode(prefix='// ')
class RecipeActionFactory(factory.DjangoModelFactory):
class Meta:
model = RecipeAction
action = factory.SubFactory(ActionFactory)
recipe = factory.SubFactory(RecipeFactory)
+
+ class LocaleFactory(factory.DjangoModelFactory):
+ class Meta:
+ model = Locale
+ | Fix tests to handle Locale as a foreign key. | ## Code Before:
import factory
from normandy.base.tests import FuzzyUnicode
from normandy.recipes.models import Action, Recipe, RecipeAction
class RecipeFactory(factory.DjangoModelFactory):
class Meta:
model = Recipe
name = FuzzyUnicode()
enabled = True
class ActionFactory(factory.DjangoModelFactory):
class Meta:
model = Action
name = FuzzyUnicode()
implementation = FuzzyUnicode(prefix='// ')
class RecipeActionFactory(factory.DjangoModelFactory):
class Meta:
model = RecipeAction
action = factory.SubFactory(ActionFactory)
recipe = factory.SubFactory(RecipeFactory)
## Instruction:
Fix tests to handle Locale as a foreign key.
## Code After:
import factory
from normandy.base.tests import FuzzyUnicode
from normandy.recipes.models import Action, Locale, Recipe, RecipeAction
class RecipeFactory(factory.DjangoModelFactory):
class Meta:
model = Recipe
name = FuzzyUnicode()
enabled = True
@factory.post_generation
def locale(self, create, extracted, **kwargs):
if not create:
return
if extracted and isinstance(extracted, str):
self.locale, _ = Locale.objects.get_or_create(code=extracted)
class ActionFactory(factory.DjangoModelFactory):
class Meta:
model = Action
name = FuzzyUnicode()
implementation = FuzzyUnicode(prefix='// ')
class RecipeActionFactory(factory.DjangoModelFactory):
class Meta:
model = RecipeAction
action = factory.SubFactory(ActionFactory)
recipe = factory.SubFactory(RecipeFactory)
class LocaleFactory(factory.DjangoModelFactory):
class Meta:
model = Locale
| ...
from normandy.base.tests import FuzzyUnicode
from normandy.recipes.models import Action, Locale, Recipe, RecipeAction
...
enabled = True
@factory.post_generation
def locale(self, create, extracted, **kwargs):
if not create:
return
if extracted and isinstance(extracted, str):
self.locale, _ = Locale.objects.get_or_create(code=extracted)
...
recipe = factory.SubFactory(RecipeFactory)
class LocaleFactory(factory.DjangoModelFactory):
class Meta:
model = Locale
... |
85d0bc9fbb20daeff9aa48a83be1823fa346cb9c | tests/test_helpers.py | tests/test_helpers.py | from __future__ import unicode_literals
import pytest
import types
from rakuten_ws.webservice import RakutenWebService
from rakuten_ws.base import RakutenAPIResponse
@pytest.mark.online
def test_response(credentials):
ws = RakutenWebService(**credentials)
response = ws.ichiba.item.search(keyword="Naruto")
assert isinstance(response, RakutenAPIResponse)
@pytest.mark.online
def test_single_item(credentials):
ws = RakutenWebService(**credentials)
response = ws.ichiba.item.search(keyword="Naruto")
item = response['Items'][0]
assert item['itemName'] == 'NARUTO THE BEST (期間生産限定盤) [ (アニメーション) ]' # noqa
@pytest.mark.online
def test_item_pages(credentials):
ws = RakutenWebService(**credentials)
response = ws.ichiba.item.search(keyword="Naruto")
items = response.pages()
# search should also allow to retrieve all the available responses
# within a generator
assert isinstance(items, types.GeneratorType)
# The iteration should switch to the next page
assert items.next()['page'] == 1
assert items.next()['page'] == 2
| from __future__ import unicode_literals
import pytest
import types
from rakuten_ws.webservice import RakutenWebService
from rakuten_ws.base import RakutenAPIResponse
@pytest.mark.online
def test_response(credentials):
ws = RakutenWebService(**credentials)
response = ws.ichiba.item.search(keyword="Naruto")
assert isinstance(response, RakutenAPIResponse)
@pytest.mark.online
def test_single_item(credentials):
ws = RakutenWebService(**credentials)
response = ws.ichiba.item.search(keyword="Naruto")
item = response['Items'][0]
assert item['itemName'] == 'NARUTO THE BEST (期間生産限定盤) [ (アニメーション) ]' # noqa
@pytest.mark.online
def test_item_pages(credentials):
ws = RakutenWebService(**credentials)
response = ws.ichiba.item.search(keyword="Naruto")
items = response.pages()
# search should also allow to retrieve all the available responses
# within a generator
assert isinstance(items, types.GeneratorType)
# The iteration should switch to the next page
assert next(items)['page'] == 1
assert next(items)['page'] == 2
| Fix tests for Python 3 | Fix tests for Python 3
| Python | mit | alexandriagroup/rakuten-ws | from __future__ import unicode_literals
import pytest
import types
from rakuten_ws.webservice import RakutenWebService
from rakuten_ws.base import RakutenAPIResponse
@pytest.mark.online
def test_response(credentials):
ws = RakutenWebService(**credentials)
response = ws.ichiba.item.search(keyword="Naruto")
assert isinstance(response, RakutenAPIResponse)
@pytest.mark.online
def test_single_item(credentials):
ws = RakutenWebService(**credentials)
response = ws.ichiba.item.search(keyword="Naruto")
item = response['Items'][0]
assert item['itemName'] == 'NARUTO THE BEST (期間生産限定盤) [ (アニメーション) ]' # noqa
@pytest.mark.online
def test_item_pages(credentials):
ws = RakutenWebService(**credentials)
response = ws.ichiba.item.search(keyword="Naruto")
items = response.pages()
# search should also allow to retrieve all the available responses
# within a generator
assert isinstance(items, types.GeneratorType)
# The iteration should switch to the next page
- assert items.next()['page'] == 1
+ assert next(items)['page'] == 1
- assert items.next()['page'] == 2
+ assert next(items)['page'] == 2
| Fix tests for Python 3 | ## Code Before:
from __future__ import unicode_literals
import pytest
import types
from rakuten_ws.webservice import RakutenWebService
from rakuten_ws.base import RakutenAPIResponse
@pytest.mark.online
def test_response(credentials):
ws = RakutenWebService(**credentials)
response = ws.ichiba.item.search(keyword="Naruto")
assert isinstance(response, RakutenAPIResponse)
@pytest.mark.online
def test_single_item(credentials):
ws = RakutenWebService(**credentials)
response = ws.ichiba.item.search(keyword="Naruto")
item = response['Items'][0]
assert item['itemName'] == 'NARUTO THE BEST (期間生産限定盤) [ (アニメーション) ]' # noqa
@pytest.mark.online
def test_item_pages(credentials):
ws = RakutenWebService(**credentials)
response = ws.ichiba.item.search(keyword="Naruto")
items = response.pages()
# search should also allow to retrieve all the available responses
# within a generator
assert isinstance(items, types.GeneratorType)
# The iteration should switch to the next page
assert items.next()['page'] == 1
assert items.next()['page'] == 2
## Instruction:
Fix tests for Python 3
## Code After:
from __future__ import unicode_literals
import pytest
import types
from rakuten_ws.webservice import RakutenWebService
from rakuten_ws.base import RakutenAPIResponse
@pytest.mark.online
def test_response(credentials):
ws = RakutenWebService(**credentials)
response = ws.ichiba.item.search(keyword="Naruto")
assert isinstance(response, RakutenAPIResponse)
@pytest.mark.online
def test_single_item(credentials):
ws = RakutenWebService(**credentials)
response = ws.ichiba.item.search(keyword="Naruto")
item = response['Items'][0]
assert item['itemName'] == 'NARUTO THE BEST (期間生産限定盤) [ (アニメーション) ]' # noqa
@pytest.mark.online
def test_item_pages(credentials):
ws = RakutenWebService(**credentials)
response = ws.ichiba.item.search(keyword="Naruto")
items = response.pages()
# search should also allow to retrieve all the available responses
# within a generator
assert isinstance(items, types.GeneratorType)
# The iteration should switch to the next page
assert next(items)['page'] == 1
assert next(items)['page'] == 2
| // ... existing code ...
# The iteration should switch to the next page
assert next(items)['page'] == 1
assert next(items)['page'] == 2
// ... rest of the code ... |
3990e3aa64cff288def07ee36e24026cc15282c0 | taiga/projects/issues/serializers.py | taiga/projects/issues/serializers.py |
from rest_framework import serializers
from taiga.base.serializers import PickleField, NeighborsSerializerMixin
from . import models
class IssueSerializer(serializers.ModelSerializer):
tags = PickleField(required=False)
comment = serializers.SerializerMethodField("get_comment")
is_closed = serializers.Field(source="is_closed")
class Meta:
model = models.Issue
def get_comment(self, obj):
return ""
class IssueNeighborsSerializer(NeighborsSerializerMixin, IssueSerializer):
def serialize_neighbor(self, neighbor):
return NeighborIssueSerializer(neighbor).data
class NeighborIssueSerializer(serializers.ModelSerializer):
class Meta:
model = models.Issue
fields = ("id", "ref", "subject")
depth = 0
|
from rest_framework import serializers
from taiga.base.serializers import PickleField, NeighborsSerializerMixin
from . import models
class IssueSerializer(serializers.ModelSerializer):
tags = PickleField(required=False)
is_closed = serializers.Field(source="is_closed")
class Meta:
model = models.Issue
class IssueNeighborsSerializer(NeighborsSerializerMixin, IssueSerializer):
def serialize_neighbor(self, neighbor):
return NeighborIssueSerializer(neighbor).data
class NeighborIssueSerializer(serializers.ModelSerializer):
class Meta:
model = models.Issue
fields = ("id", "ref", "subject")
depth = 0
| Remove unnecessary field from IssueSerializer | Remove unnecessary field from IssueSerializer
| Python | agpl-3.0 | forging2012/taiga-back,EvgeneOskin/taiga-back,xdevelsistemas/taiga-back-community,seanchen/taiga-back,bdang2012/taiga-back-casting,Rademade/taiga-back,crr0004/taiga-back,dayatz/taiga-back,rajiteh/taiga-back,dycodedev/taiga-back,crr0004/taiga-back,obimod/taiga-back,Zaneh-/bearded-tribble-back,seanchen/taiga-back,gauravjns/taiga-back,joshisa/taiga-back,19kestier/taiga-back,jeffdwyatt/taiga-back,taigaio/taiga-back,WALR/taiga-back,joshisa/taiga-back,astronaut1712/taiga-back,taigaio/taiga-back,coopsource/taiga-back,gam-phon/taiga-back,Rademade/taiga-back,obimod/taiga-back,obimod/taiga-back,CMLL/taiga-back,frt-arch/taiga-back,dycodedev/taiga-back,bdang2012/taiga-back-casting,Tigerwhit4/taiga-back,19kestier/taiga-back,EvgeneOskin/taiga-back,EvgeneOskin/taiga-back,astagi/taiga-back,bdang2012/taiga-back-casting,Zaneh-/bearded-tribble-back,dayatz/taiga-back,CoolCloud/taiga-back,astronaut1712/taiga-back,jeffdwyatt/taiga-back,crr0004/taiga-back,WALR/taiga-back,gam-phon/taiga-back,CMLL/taiga-back,seanchen/taiga-back,astagi/taiga-back,gauravjns/taiga-back,gam-phon/taiga-back,WALR/taiga-back,jeffdwyatt/taiga-back,Tigerwhit4/taiga-back,Zaneh-/bearded-tribble-back,seanchen/taiga-back,xdevelsistemas/taiga-back-community,coopsource/taiga-back,astagi/taiga-back,EvgeneOskin/taiga-back,obimod/taiga-back,gam-phon/taiga-back,coopsource/taiga-back,CoolCloud/taiga-back,rajiteh/taiga-back,dycodedev/taiga-back,bdang2012/taiga-back-casting,19kestier/taiga-back,astronaut1712/taiga-back,forging2012/taiga-back,CMLL/taiga-back,frt-arch/taiga-back,astagi/taiga-back,WALR/taiga-back,forging2012/taiga-back,rajiteh/taiga-back,frt-arch/taiga-back,Rademade/taiga-back,xdevelsistemas/taiga-back-community,taigaio/taiga-back,joshisa/taiga-back,gauravjns/taiga-back,Rademade/taiga-back,crr0004/taiga-back,forging2012/taiga-back,joshisa/taiga-back,CMLL/taiga-back,dycodedev/taiga-back,coopsource/taiga-back,CoolCloud/taiga-back,Rademade/taiga-back,astronaut1712/taiga-back,jeffdwyatt/taiga-back,CoolCloud/taiga-back,gauravjns/taiga-back,rajiteh/taiga-back,dayatz/taiga-back,Tigerwhit4/taiga-back,Tigerwhit4/taiga-back |
from rest_framework import serializers
from taiga.base.serializers import PickleField, NeighborsSerializerMixin
from . import models
class IssueSerializer(serializers.ModelSerializer):
tags = PickleField(required=False)
- comment = serializers.SerializerMethodField("get_comment")
is_closed = serializers.Field(source="is_closed")
class Meta:
model = models.Issue
-
- def get_comment(self, obj):
- return ""
class IssueNeighborsSerializer(NeighborsSerializerMixin, IssueSerializer):
def serialize_neighbor(self, neighbor):
return NeighborIssueSerializer(neighbor).data
class NeighborIssueSerializer(serializers.ModelSerializer):
class Meta:
model = models.Issue
fields = ("id", "ref", "subject")
depth = 0
| Remove unnecessary field from IssueSerializer | ## Code Before:
from rest_framework import serializers
from taiga.base.serializers import PickleField, NeighborsSerializerMixin
from . import models
class IssueSerializer(serializers.ModelSerializer):
tags = PickleField(required=False)
comment = serializers.SerializerMethodField("get_comment")
is_closed = serializers.Field(source="is_closed")
class Meta:
model = models.Issue
def get_comment(self, obj):
return ""
class IssueNeighborsSerializer(NeighborsSerializerMixin, IssueSerializer):
def serialize_neighbor(self, neighbor):
return NeighborIssueSerializer(neighbor).data
class NeighborIssueSerializer(serializers.ModelSerializer):
class Meta:
model = models.Issue
fields = ("id", "ref", "subject")
depth = 0
## Instruction:
Remove unnecessary field from IssueSerializer
## Code After:
from rest_framework import serializers
from taiga.base.serializers import PickleField, NeighborsSerializerMixin
from . import models
class IssueSerializer(serializers.ModelSerializer):
tags = PickleField(required=False)
is_closed = serializers.Field(source="is_closed")
class Meta:
model = models.Issue
class IssueNeighborsSerializer(NeighborsSerializerMixin, IssueSerializer):
def serialize_neighbor(self, neighbor):
return NeighborIssueSerializer(neighbor).data
class NeighborIssueSerializer(serializers.ModelSerializer):
class Meta:
model = models.Issue
fields = ("id", "ref", "subject")
depth = 0
| ...
tags = PickleField(required=False)
is_closed = serializers.Field(source="is_closed")
...
model = models.Issue
... |
e4fe21b1e1366a1676d2129575ee7c19f6fc6547 | models.py | models.py | class Color(object):
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
class Line(object):
def __init__(self, name, api_code, bg_color, fg_color):
self.name = name
self.api_code = api_code
self.bg_color = bg_color
self.fg_color = fg_color
self.stations = set()
def __repr__(self):
return self.name
__unicode__ = __repr__
class Station(object):
def __init__(self, name, api_code):
self.name = name
self.api_code = api_code
self.connections = {}
def __repr__(self):
return self.name
__unicode__ = __repr__
@property
def lines(self):
return self.connections.keys()
class Map(object):
pass
| class Color(object):
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
def __repr__(self):
return '%s,%s,%s' % (self.r, self.g, self.b)
__unicode__ = __repr__
class Line(object):
def __init__(self, name, api_code, bg_color, fg_color):
self.name = name
self.api_code = api_code
self.bg_color = bg_color
self.fg_color = fg_color
self.stations = set()
def __repr__(self):
return self.name
__unicode__ = __repr__
class Station(object):
def __init__(self, name, api_code):
self.name = name
self.api_code = api_code
self.connections = {}
def __repr__(self):
return self.name
__unicode__ = __repr__
@property
def lines(self):
return self.connections.keys()
class Map(object):
pass
| Add string representation for colors | Add string representation for colors
| Python | mit | kirberich/tube_status | class Color(object):
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
+
+ def __repr__(self):
+ return '%s,%s,%s' % (self.r, self.g, self.b)
+ __unicode__ = __repr__
class Line(object):
def __init__(self, name, api_code, bg_color, fg_color):
self.name = name
self.api_code = api_code
self.bg_color = bg_color
self.fg_color = fg_color
self.stations = set()
def __repr__(self):
return self.name
__unicode__ = __repr__
class Station(object):
def __init__(self, name, api_code):
self.name = name
self.api_code = api_code
self.connections = {}
def __repr__(self):
return self.name
__unicode__ = __repr__
@property
def lines(self):
return self.connections.keys()
class Map(object):
pass
| Add string representation for colors | ## Code Before:
class Color(object):
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
class Line(object):
def __init__(self, name, api_code, bg_color, fg_color):
self.name = name
self.api_code = api_code
self.bg_color = bg_color
self.fg_color = fg_color
self.stations = set()
def __repr__(self):
return self.name
__unicode__ = __repr__
class Station(object):
def __init__(self, name, api_code):
self.name = name
self.api_code = api_code
self.connections = {}
def __repr__(self):
return self.name
__unicode__ = __repr__
@property
def lines(self):
return self.connections.keys()
class Map(object):
pass
## Instruction:
Add string representation for colors
## Code After:
class Color(object):
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
def __repr__(self):
return '%s,%s,%s' % (self.r, self.g, self.b)
__unicode__ = __repr__
class Line(object):
def __init__(self, name, api_code, bg_color, fg_color):
self.name = name
self.api_code = api_code
self.bg_color = bg_color
self.fg_color = fg_color
self.stations = set()
def __repr__(self):
return self.name
__unicode__ = __repr__
class Station(object):
def __init__(self, name, api_code):
self.name = name
self.api_code = api_code
self.connections = {}
def __repr__(self):
return self.name
__unicode__ = __repr__
@property
def lines(self):
return self.connections.keys()
class Map(object):
pass
| # ... existing code ...
self.b = b
def __repr__(self):
return '%s,%s,%s' % (self.r, self.g, self.b)
__unicode__ = __repr__
# ... rest of the code ... |
6da0aaf77fe221286981b94eaf7d304568f55957 | examples/stories/movie_lister/movies/__init__.py | examples/stories/movie_lister/movies/__init__.py |
from . import finders
from . import listers
from . import models
from dependency_injector import catalogs
from dependency_injector import providers
class MoviesModule(catalogs.DeclarativeCatalog):
"""Catalog of movies module components."""
movie_model = providers.DelegatedFactory(models.Movie)
movie_finder = providers.Factory(finders.MovieFinder,
movie_model=movie_model)
movie_lister = providers.Factory(listers.MovieLister,
movie_finder=movie_finder)
|
from dependency_injector import catalogs
from dependency_injector import providers
from . import finders
from . import listers
from . import models
class MoviesModule(catalogs.DeclarativeCatalog):
"""Catalog of movies module components."""
movie_model = providers.DelegatedFactory(models.Movie)
movie_finder = providers.Factory(finders.MovieFinder,
movie_model=movie_model)
movie_lister = providers.Factory(listers.MovieLister,
movie_finder=movie_finder)
| Update imports for MovieLister standrard module | Update imports for MovieLister standrard module
| Python | bsd-3-clause | rmk135/objects,ets-labs/python-dependency-injector,ets-labs/dependency_injector,rmk135/dependency_injector | +
+ from dependency_injector import catalogs
+ from dependency_injector import providers
from . import finders
from . import listers
from . import models
-
- from dependency_injector import catalogs
- from dependency_injector import providers
class MoviesModule(catalogs.DeclarativeCatalog):
"""Catalog of movies module components."""
movie_model = providers.DelegatedFactory(models.Movie)
movie_finder = providers.Factory(finders.MovieFinder,
movie_model=movie_model)
movie_lister = providers.Factory(listers.MovieLister,
movie_finder=movie_finder)
| Update imports for MovieLister standrard module | ## Code Before:
from . import finders
from . import listers
from . import models
from dependency_injector import catalogs
from dependency_injector import providers
class MoviesModule(catalogs.DeclarativeCatalog):
"""Catalog of movies module components."""
movie_model = providers.DelegatedFactory(models.Movie)
movie_finder = providers.Factory(finders.MovieFinder,
movie_model=movie_model)
movie_lister = providers.Factory(listers.MovieLister,
movie_finder=movie_finder)
## Instruction:
Update imports for MovieLister standrard module
## Code After:
from dependency_injector import catalogs
from dependency_injector import providers
from . import finders
from . import listers
from . import models
class MoviesModule(catalogs.DeclarativeCatalog):
"""Catalog of movies module components."""
movie_model = providers.DelegatedFactory(models.Movie)
movie_finder = providers.Factory(finders.MovieFinder,
movie_model=movie_model)
movie_lister = providers.Factory(listers.MovieLister,
movie_finder=movie_finder)
| // ... existing code ...
from dependency_injector import catalogs
from dependency_injector import providers
// ... modified code ...
from . import models
// ... rest of the code ... |
92e96c010b54bf4c9e35d49de492cf9f061f345a | micromodels/models.py | micromodels/models.py | from fields import FieldBase
class Model(object):
class __metaclass__(type):
def __init__(cls, name, bases, attrs):
fields = {}
for name, value in attrs.items():
if isinstance(value, FieldBase):
fields[name] = value
setattr(cls, '_fields', fields)
def __init__(self, data):
"""Create an instance of the model subclass. The constructor should
be passed a dictionary of data to provide values for its fields.
For each field defined on the class (and stored in the _fields
property by the metaclass), a property is created on the instance
which contains the converted value from the source data.
"""
for name, field in self._fields.items():
key = field.source or name
field.populate(data.get(key))
value = field.to_python()
setattr(self, name, value)
self._data = data
| from fields import FieldBase
class Model(object):
class __metaclass__(type):
def __init__(cls, name, bases, attrs):
cls._fields = {}
for name, value in attrs.items():
if isinstance(value, FieldBase):
cls._fields[name] = value
def __init__(self, data):
"""Create an instance of the model subclass. The constructor should
be passed a dictionary of data to provide values for its fields.
For each field defined on the class (and stored in the _fields
property by the metaclass), a property is created on the instance
which contains the converted value from the source data.
"""
for name, field in self._fields.items():
key = field.source or name
field.populate(data.get(key))
value = field.to_python()
setattr(self, name, value)
self._data = data
| Change to make metaclass clearer | Change to make metaclass clearer
| Python | unlicense | j4mie/micromodels | from fields import FieldBase
class Model(object):
class __metaclass__(type):
def __init__(cls, name, bases, attrs):
- fields = {}
+ cls._fields = {}
for name, value in attrs.items():
if isinstance(value, FieldBase):
- fields[name] = value
+ cls._fields[name] = value
- setattr(cls, '_fields', fields)
def __init__(self, data):
"""Create an instance of the model subclass. The constructor should
be passed a dictionary of data to provide values for its fields.
For each field defined on the class (and stored in the _fields
property by the metaclass), a property is created on the instance
which contains the converted value from the source data.
"""
for name, field in self._fields.items():
key = field.source or name
field.populate(data.get(key))
value = field.to_python()
setattr(self, name, value)
self._data = data
| Change to make metaclass clearer | ## Code Before:
from fields import FieldBase
class Model(object):
class __metaclass__(type):
def __init__(cls, name, bases, attrs):
fields = {}
for name, value in attrs.items():
if isinstance(value, FieldBase):
fields[name] = value
setattr(cls, '_fields', fields)
def __init__(self, data):
"""Create an instance of the model subclass. The constructor should
be passed a dictionary of data to provide values for its fields.
For each field defined on the class (and stored in the _fields
property by the metaclass), a property is created on the instance
which contains the converted value from the source data.
"""
for name, field in self._fields.items():
key = field.source or name
field.populate(data.get(key))
value = field.to_python()
setattr(self, name, value)
self._data = data
## Instruction:
Change to make metaclass clearer
## Code After:
from fields import FieldBase
class Model(object):
class __metaclass__(type):
def __init__(cls, name, bases, attrs):
cls._fields = {}
for name, value in attrs.items():
if isinstance(value, FieldBase):
cls._fields[name] = value
def __init__(self, data):
"""Create an instance of the model subclass. The constructor should
be passed a dictionary of data to provide values for its fields.
For each field defined on the class (and stored in the _fields
property by the metaclass), a property is created on the instance
which contains the converted value from the source data.
"""
for name, field in self._fields.items():
key = field.source or name
field.populate(data.get(key))
value = field.to_python()
setattr(self, name, value)
self._data = data
| # ... existing code ...
def __init__(cls, name, bases, attrs):
cls._fields = {}
for name, value in attrs.items():
# ... modified code ...
if isinstance(value, FieldBase):
cls._fields[name] = value
# ... rest of the code ... |
cb52e7b1a507ca7b6065c6994d11d3c07a41e6f1 | uniqueids/tasks.py | uniqueids/tasks.py | from celery.task import Task
from celery.utils.log import get_task_logger
from hellomama_registration import utils
logger = get_task_logger(__name__)
class AddUniqueIDToIdentity(Task):
def run(self, identity, unique_id, write_to, **kwargs):
"""
identity: the identity to receive the payload.
unique_id: the unique_id to add to the identity
write_to: the key to write the unique_id to
"""
full_identity = utils.get_identity(identity)
if "details" in full_identity:
# not a 404
partial_identity = {
"details": full_identity["details"]
}
partial_identity["details"][write_to] = unique_id
utils.patch_identity(identity, partial_identity)
return "Identity <%s> now has <%s> of <%s>" % (
identity, write_to, str(unique_id))
else:
return "Identity <%s> not found" % (identity,)
add_unique_id_to_identity = AddUniqueIDToIdentity()
| from celery.task import Task
from celery.utils.log import get_task_logger
from hellomama_registration import utils
logger = get_task_logger(__name__)
class AddUniqueIDToIdentity(Task):
def run(self, identity, unique_id, write_to, **kwargs):
"""
identity: the identity to receive the payload.
unique_id: the unique_id to add to the identity
write_to: the key to write the unique_id to
"""
full_identity = utils.get_identity(identity)
if "details" in full_identity:
# not a 404
partial_identity = {
"details": full_identity["details"]
}
# convert to string to enable Django filter lookups
partial_identity["details"][write_to] = str(unique_id)
utils.patch_identity(identity, partial_identity)
return "Identity <%s> now has <%s> of <%s>" % (
identity, write_to, str(unique_id))
else:
return "Identity <%s> not found" % (identity,)
add_unique_id_to_identity = AddUniqueIDToIdentity()
| Make auto gen ID's strings on save to Identity | Make auto gen ID's strings on save to Identity
| Python | bsd-3-clause | praekelt/hellomama-registration,praekelt/hellomama-registration | from celery.task import Task
from celery.utils.log import get_task_logger
from hellomama_registration import utils
logger = get_task_logger(__name__)
class AddUniqueIDToIdentity(Task):
def run(self, identity, unique_id, write_to, **kwargs):
"""
identity: the identity to receive the payload.
unique_id: the unique_id to add to the identity
write_to: the key to write the unique_id to
"""
full_identity = utils.get_identity(identity)
if "details" in full_identity:
# not a 404
partial_identity = {
"details": full_identity["details"]
}
+ # convert to string to enable Django filter lookups
- partial_identity["details"][write_to] = unique_id
+ partial_identity["details"][write_to] = str(unique_id)
utils.patch_identity(identity, partial_identity)
return "Identity <%s> now has <%s> of <%s>" % (
identity, write_to, str(unique_id))
else:
return "Identity <%s> not found" % (identity,)
add_unique_id_to_identity = AddUniqueIDToIdentity()
| Make auto gen ID's strings on save to Identity | ## Code Before:
from celery.task import Task
from celery.utils.log import get_task_logger
from hellomama_registration import utils
logger = get_task_logger(__name__)
class AddUniqueIDToIdentity(Task):
def run(self, identity, unique_id, write_to, **kwargs):
"""
identity: the identity to receive the payload.
unique_id: the unique_id to add to the identity
write_to: the key to write the unique_id to
"""
full_identity = utils.get_identity(identity)
if "details" in full_identity:
# not a 404
partial_identity = {
"details": full_identity["details"]
}
partial_identity["details"][write_to] = unique_id
utils.patch_identity(identity, partial_identity)
return "Identity <%s> now has <%s> of <%s>" % (
identity, write_to, str(unique_id))
else:
return "Identity <%s> not found" % (identity,)
add_unique_id_to_identity = AddUniqueIDToIdentity()
## Instruction:
Make auto gen ID's strings on save to Identity
## Code After:
from celery.task import Task
from celery.utils.log import get_task_logger
from hellomama_registration import utils
logger = get_task_logger(__name__)
class AddUniqueIDToIdentity(Task):
def run(self, identity, unique_id, write_to, **kwargs):
"""
identity: the identity to receive the payload.
unique_id: the unique_id to add to the identity
write_to: the key to write the unique_id to
"""
full_identity = utils.get_identity(identity)
if "details" in full_identity:
# not a 404
partial_identity = {
"details": full_identity["details"]
}
# convert to string to enable Django filter lookups
partial_identity["details"][write_to] = str(unique_id)
utils.patch_identity(identity, partial_identity)
return "Identity <%s> now has <%s> of <%s>" % (
identity, write_to, str(unique_id))
else:
return "Identity <%s> not found" % (identity,)
add_unique_id_to_identity = AddUniqueIDToIdentity()
| // ... existing code ...
}
# convert to string to enable Django filter lookups
partial_identity["details"][write_to] = str(unique_id)
utils.patch_identity(identity, partial_identity)
// ... rest of the code ... |
6b4e34a5091ec00dffb1add55fa8dc279cbc2c89 | scattertext/frequencyreaders/DefaultBackgroundFrequencies.py | scattertext/frequencyreaders/DefaultBackgroundFrequencies.py | import pkgutil
from io import StringIO
import pandas as pd
from scipy.stats import rankdata
class BackgroundFrequencies(object):
@staticmethod
def get_background_frequency_df(frequency_path=None):
raise Exception
@classmethod
def get_background_rank_df(cls, frequency_path=None):
df = cls.get_background_frequency_df(frequency_path)
df['rank'] = rankdata(df.background, method='dense')
df['background'] = df['rank'] / df['rank'].max()
return df[['background']]
class DefaultBackgroundFrequencies(BackgroundFrequencies):
@staticmethod
def get_background_frequency_df(frequency_path=None):
if frequency_path:
unigram_freq_table_buf = open(frequency_path)
else:
unigram_freq_table_buf = StringIO(pkgutil.get_data('scattertext', 'data/count_1w.txt')
.decode('utf-8'))
to_ret = (pd.read_table(unigram_freq_table_buf,
names=['word', 'background'])
.sort_values(ascending=False, by='background')
.drop_duplicates(['word'])
.set_index('word'))
return to_ret
| import pkgutil
from io import StringIO
import pandas as pd
from scipy.stats import rankdata
class BackgroundFrequencies(object):
@staticmethod
def get_background_frequency_df(frequency_path=None):
raise Exception
@classmethod
def get_background_rank_df(cls, frequency_path=None):
df = cls.get_background_frequency_df(frequency_path)
df['rank'] = rankdata(df.background, method='dense')
df['background'] = df['rank'] / df['rank'].max()
return df[['background']]
class DefaultBackgroundFrequencies(BackgroundFrequencies):
@staticmethod
def get_background_frequency_df(frequency_path=None):
if frequency_path:
unigram_freq_table_buf = open(frequency_path)
else:
unigram_freq_table_buf = StringIO(pkgutil.get_data('scattertext', 'data/count_1w.txt')
.decode('utf-8'))
to_ret = (pd.read_csv(unigram_freq_table_buf,
sep='\t',
names=['word', 'background'])
.sort_values(ascending=False, by='background')
.drop_duplicates(['word'])
.set_index('word'))
return to_ret
| Fix FutureWarning: read_table is deprecated, use read_csv instead, passing sep='\t' | Fix FutureWarning: read_table is deprecated, use read_csv instead, passing sep='\t'
| Python | apache-2.0 | JasonKessler/scattertext,JasonKessler/scattertext,JasonKessler/scattertext,JasonKessler/scattertext | import pkgutil
from io import StringIO
import pandas as pd
from scipy.stats import rankdata
class BackgroundFrequencies(object):
- @staticmethod
+ @staticmethod
- def get_background_frequency_df(frequency_path=None):
+ def get_background_frequency_df(frequency_path=None):
- raise Exception
+ raise Exception
- @classmethod
+ @classmethod
- def get_background_rank_df(cls, frequency_path=None):
+ def get_background_rank_df(cls, frequency_path=None):
- df = cls.get_background_frequency_df(frequency_path)
+ df = cls.get_background_frequency_df(frequency_path)
- df['rank'] = rankdata(df.background, method='dense')
+ df['rank'] = rankdata(df.background, method='dense')
- df['background'] = df['rank'] / df['rank'].max()
+ df['background'] = df['rank'] / df['rank'].max()
- return df[['background']]
+ return df[['background']]
class DefaultBackgroundFrequencies(BackgroundFrequencies):
- @staticmethod
+ @staticmethod
- def get_background_frequency_df(frequency_path=None):
+ def get_background_frequency_df(frequency_path=None):
- if frequency_path:
+ if frequency_path:
- unigram_freq_table_buf = open(frequency_path)
+ unigram_freq_table_buf = open(frequency_path)
- else:
+ else:
- unigram_freq_table_buf = StringIO(pkgutil.get_data('scattertext', 'data/count_1w.txt')
+ unigram_freq_table_buf = StringIO(pkgutil.get_data('scattertext', 'data/count_1w.txt')
- .decode('utf-8'))
+ .decode('utf-8'))
- to_ret = (pd.read_table(unigram_freq_table_buf,
+ to_ret = (pd.read_csv(unigram_freq_table_buf,
+ sep='\t',
- names=['word', 'background'])
+ names=['word', 'background'])
- .sort_values(ascending=False, by='background')
+ .sort_values(ascending=False, by='background')
- .drop_duplicates(['word'])
+ .drop_duplicates(['word'])
- .set_index('word'))
+ .set_index('word'))
- return to_ret
+ return to_ret
| Fix FutureWarning: read_table is deprecated, use read_csv instead, passing sep='\t' | ## Code Before:
import pkgutil
from io import StringIO
import pandas as pd
from scipy.stats import rankdata
class BackgroundFrequencies(object):
@staticmethod
def get_background_frequency_df(frequency_path=None):
raise Exception
@classmethod
def get_background_rank_df(cls, frequency_path=None):
df = cls.get_background_frequency_df(frequency_path)
df['rank'] = rankdata(df.background, method='dense')
df['background'] = df['rank'] / df['rank'].max()
return df[['background']]
class DefaultBackgroundFrequencies(BackgroundFrequencies):
@staticmethod
def get_background_frequency_df(frequency_path=None):
if frequency_path:
unigram_freq_table_buf = open(frequency_path)
else:
unigram_freq_table_buf = StringIO(pkgutil.get_data('scattertext', 'data/count_1w.txt')
.decode('utf-8'))
to_ret = (pd.read_table(unigram_freq_table_buf,
names=['word', 'background'])
.sort_values(ascending=False, by='background')
.drop_duplicates(['word'])
.set_index('word'))
return to_ret
## Instruction:
Fix FutureWarning: read_table is deprecated, use read_csv instead, passing sep='\t'
## Code After:
import pkgutil
from io import StringIO
import pandas as pd
from scipy.stats import rankdata
class BackgroundFrequencies(object):
@staticmethod
def get_background_frequency_df(frequency_path=None):
raise Exception
@classmethod
def get_background_rank_df(cls, frequency_path=None):
df = cls.get_background_frequency_df(frequency_path)
df['rank'] = rankdata(df.background, method='dense')
df['background'] = df['rank'] / df['rank'].max()
return df[['background']]
class DefaultBackgroundFrequencies(BackgroundFrequencies):
@staticmethod
def get_background_frequency_df(frequency_path=None):
if frequency_path:
unigram_freq_table_buf = open(frequency_path)
else:
unigram_freq_table_buf = StringIO(pkgutil.get_data('scattertext', 'data/count_1w.txt')
.decode('utf-8'))
to_ret = (pd.read_csv(unigram_freq_table_buf,
sep='\t',
names=['word', 'background'])
.sort_values(ascending=False, by='background')
.drop_duplicates(['word'])
.set_index('word'))
return to_ret
| # ... existing code ...
class BackgroundFrequencies(object):
@staticmethod
def get_background_frequency_df(frequency_path=None):
raise Exception
@classmethod
def get_background_rank_df(cls, frequency_path=None):
df = cls.get_background_frequency_df(frequency_path)
df['rank'] = rankdata(df.background, method='dense')
df['background'] = df['rank'] / df['rank'].max()
return df[['background']]
# ... modified code ...
class DefaultBackgroundFrequencies(BackgroundFrequencies):
@staticmethod
def get_background_frequency_df(frequency_path=None):
if frequency_path:
unigram_freq_table_buf = open(frequency_path)
else:
unigram_freq_table_buf = StringIO(pkgutil.get_data('scattertext', 'data/count_1w.txt')
.decode('utf-8'))
to_ret = (pd.read_csv(unigram_freq_table_buf,
sep='\t',
names=['word', 'background'])
.sort_values(ascending=False, by='background')
.drop_duplicates(['word'])
.set_index('word'))
return to_ret
# ... rest of the code ... |
d3a203725d13a7abef091f0070f90826d3225dbc | settings_travis.py | settings_travis.py | import ssl
LDAP_SERVER = 'ldap.rserver.de'
LDAP_PORT = 3389
LDAP_SSL_PORT = 6636
LDAP_REQUIRE_CERT = ssl.CERT_NONE
| import ssl
LDAP_SERVER = 'ldap.rserver.de'
LDAP_PORT = 3389
LDAP_SSL_PORT = 6636
LDAP_REQUIRE_CERT = ssl.CERT_NONE
LDAP_TLS_VERSION = ssl.PROTOCOL_TLSv1
| Fix travis unit test for python 3.3 | Fix travis unit test for python 3.3
| Python | bsd-2-clause | rroemhild/flask-ldapconn | import ssl
LDAP_SERVER = 'ldap.rserver.de'
LDAP_PORT = 3389
LDAP_SSL_PORT = 6636
LDAP_REQUIRE_CERT = ssl.CERT_NONE
+ LDAP_TLS_VERSION = ssl.PROTOCOL_TLSv1
| Fix travis unit test for python 3.3 | ## Code Before:
import ssl
LDAP_SERVER = 'ldap.rserver.de'
LDAP_PORT = 3389
LDAP_SSL_PORT = 6636
LDAP_REQUIRE_CERT = ssl.CERT_NONE
## Instruction:
Fix travis unit test for python 3.3
## Code After:
import ssl
LDAP_SERVER = 'ldap.rserver.de'
LDAP_PORT = 3389
LDAP_SSL_PORT = 6636
LDAP_REQUIRE_CERT = ssl.CERT_NONE
LDAP_TLS_VERSION = ssl.PROTOCOL_TLSv1
| ...
LDAP_REQUIRE_CERT = ssl.CERT_NONE
LDAP_TLS_VERSION = ssl.PROTOCOL_TLSv1
... |
4dd28beddc2df9efeef798491d1963800113f801 | django_bootstrap_calendar/models.py | django_bootstrap_calendar/models.py | __author__ = 'sandlbn'
from django.db import models
from django.utils.translation import ugettext_lazy as _
from utils import datetime_to_timestamp
class CalendarEvent(models.Model):
"""
Calendar Events
"""
CSS_CLASS_CHOICES = (
('', _('Normal')),
('event-warning', _('Warning')),
('event-info', _('Info')),
('event-success', _('Success')),
('event-inverse', _('Inverse')),
('event-special', _('Special')),
('event-important', _('Important')),
)
title = models.CharField(max_length=255, verbose_name=_('Title'))
url = models.URLField(verbose_name=_('URL'), null=True, blank=True)
css_class = models.CharField(max_length=20, verbose_name=_('CSS Class'),
choices=CSS_CLASS_CHOICES)
start = models.DateTimeField(verbose_name=_('Start Date'))
end = models.DateTimeField(verbose_name=_('End Date'), null=True,
blank=True)
@property
def start_timestamp(self):
"""
Return end date as timestamp
"""
return datetime_to_timestamp(self.start)
@property
def end_timestamp(self):
"""
Return end date as timestamp
"""
return datetime_to_timestamp(self.end)
def __unicode__(self):
return self.title
| __author__ = 'sandlbn'
from django.db import models
from django.utils.translation import ugettext_lazy as _
from utils import datetime_to_timestamp
class CalendarEvent(models.Model):
"""
Calendar Events
"""
CSS_CLASS_CHOICES = (
('', _('Normal')),
('event-warning', _('Warning')),
('event-info', _('Info')),
('event-success', _('Success')),
('event-inverse', _('Inverse')),
('event-special', _('Special')),
('event-important', _('Important')),
)
title = models.CharField(max_length=255, verbose_name=_('Title'))
url = models.URLField(verbose_name=_('URL'), null=True, blank=True)
css_class = models.CharField(blank=True, max_length=20, verbose_name=_('CSS Class'),
choices=CSS_CLASS_CHOICES)
start = models.DateTimeField(verbose_name=_('Start Date'))
end = models.DateTimeField(verbose_name=_('End Date'), null=True,
blank=True)
@property
def start_timestamp(self):
"""
Return end date as timestamp
"""
return datetime_to_timestamp(self.start)
@property
def end_timestamp(self):
"""
Return end date as timestamp
"""
return datetime_to_timestamp(self.end)
def __unicode__(self):
return self.title
| Allow `css_class` to have blank value. | Allow `css_class` to have blank value.
Currently the default value for the `css_class` field (name `Normal`)
has the value of a blank string. To allow the value to be used
`blank=True` must be set.
| Python | bsd-3-clause | sandlbn/django-bootstrap-calendar,sandlbn/django-bootstrap-calendar,sandlbn/django-bootstrap-calendar | __author__ = 'sandlbn'
from django.db import models
from django.utils.translation import ugettext_lazy as _
from utils import datetime_to_timestamp
class CalendarEvent(models.Model):
"""
Calendar Events
"""
CSS_CLASS_CHOICES = (
('', _('Normal')),
('event-warning', _('Warning')),
('event-info', _('Info')),
('event-success', _('Success')),
('event-inverse', _('Inverse')),
('event-special', _('Special')),
('event-important', _('Important')),
)
title = models.CharField(max_length=255, verbose_name=_('Title'))
url = models.URLField(verbose_name=_('URL'), null=True, blank=True)
- css_class = models.CharField(max_length=20, verbose_name=_('CSS Class'),
+ css_class = models.CharField(blank=True, max_length=20, verbose_name=_('CSS Class'),
choices=CSS_CLASS_CHOICES)
start = models.DateTimeField(verbose_name=_('Start Date'))
end = models.DateTimeField(verbose_name=_('End Date'), null=True,
blank=True)
@property
def start_timestamp(self):
"""
Return end date as timestamp
"""
return datetime_to_timestamp(self.start)
@property
def end_timestamp(self):
"""
Return end date as timestamp
"""
return datetime_to_timestamp(self.end)
def __unicode__(self):
return self.title
| Allow `css_class` to have blank value. | ## Code Before:
__author__ = 'sandlbn'
from django.db import models
from django.utils.translation import ugettext_lazy as _
from utils import datetime_to_timestamp
class CalendarEvent(models.Model):
"""
Calendar Events
"""
CSS_CLASS_CHOICES = (
('', _('Normal')),
('event-warning', _('Warning')),
('event-info', _('Info')),
('event-success', _('Success')),
('event-inverse', _('Inverse')),
('event-special', _('Special')),
('event-important', _('Important')),
)
title = models.CharField(max_length=255, verbose_name=_('Title'))
url = models.URLField(verbose_name=_('URL'), null=True, blank=True)
css_class = models.CharField(max_length=20, verbose_name=_('CSS Class'),
choices=CSS_CLASS_CHOICES)
start = models.DateTimeField(verbose_name=_('Start Date'))
end = models.DateTimeField(verbose_name=_('End Date'), null=True,
blank=True)
@property
def start_timestamp(self):
"""
Return end date as timestamp
"""
return datetime_to_timestamp(self.start)
@property
def end_timestamp(self):
"""
Return end date as timestamp
"""
return datetime_to_timestamp(self.end)
def __unicode__(self):
return self.title
## Instruction:
Allow `css_class` to have blank value.
## Code After:
__author__ = 'sandlbn'
from django.db import models
from django.utils.translation import ugettext_lazy as _
from utils import datetime_to_timestamp
class CalendarEvent(models.Model):
"""
Calendar Events
"""
CSS_CLASS_CHOICES = (
('', _('Normal')),
('event-warning', _('Warning')),
('event-info', _('Info')),
('event-success', _('Success')),
('event-inverse', _('Inverse')),
('event-special', _('Special')),
('event-important', _('Important')),
)
title = models.CharField(max_length=255, verbose_name=_('Title'))
url = models.URLField(verbose_name=_('URL'), null=True, blank=True)
css_class = models.CharField(blank=True, max_length=20, verbose_name=_('CSS Class'),
choices=CSS_CLASS_CHOICES)
start = models.DateTimeField(verbose_name=_('Start Date'))
end = models.DateTimeField(verbose_name=_('End Date'), null=True,
blank=True)
@property
def start_timestamp(self):
"""
Return end date as timestamp
"""
return datetime_to_timestamp(self.start)
@property
def end_timestamp(self):
"""
Return end date as timestamp
"""
return datetime_to_timestamp(self.end)
def __unicode__(self):
return self.title
| # ... existing code ...
url = models.URLField(verbose_name=_('URL'), null=True, blank=True)
css_class = models.CharField(blank=True, max_length=20, verbose_name=_('CSS Class'),
choices=CSS_CLASS_CHOICES)
# ... rest of the code ... |
5346741d0d5360cdf776252dcbe400ff839ab9fc | hs_core/tests/api/rest/test_resource_types.py | hs_core/tests/api/rest/test_resource_types.py | import json
from rest_framework.test import APIClient
from rest_framework import status
from rest_framework.test import APITestCase
from hs_core.hydroshare.utils import get_resource_types
class TestResourceTypes(APITestCase):
def setUp(self):
self.client = APIClient()
def test_resource_typelist(self):
resource_types = set([t.__name__ for t in get_resource_types()])
response = self.client.get('/hsapi/resourceTypes/', format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
content = json.loads(response.content)
rest_resource_types = set([t['resource_type'] for t in content])
self.assertEqual(resource_types, rest_resource_types) | import json
from rest_framework.test import APIClient
from rest_framework import status
from rest_framework.test import APITestCase
class TestResourceTypes(APITestCase):
def setUp(self):
self.client = APIClient()
# Use a static list so that this test breaks when a resource type is
# added or removed (so that the test can be updated)
self.resource_types = {'GenericResource',
'RasterResource',
'RefTimeSeriesResource',
'TimeSeriesResource',
'NetcdfResource',
'ModelProgramResource',
'ModelInstanceResource',
'ToolResource',
'SWATModelInstanceResource',
'GeographicFeatureResource',
'ScriptResource'}
def test_resource_typelist(self):
response = self.client.get('/hsapi/resourceTypes/', format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
content = json.loads(response.content)
rest_resource_types = set([t['resource_type'] for t in content])
self.assertEqual(self.resource_types, rest_resource_types)
| Make resource type list static | Make resource type list static
| Python | bsd-3-clause | FescueFungiShare/hydroshare,hydroshare/hydroshare,FescueFungiShare/hydroshare,hydroshare/hydroshare,ResearchSoftwareInstitute/MyHPOM,ResearchSoftwareInstitute/MyHPOM,FescueFungiShare/hydroshare,ResearchSoftwareInstitute/MyHPOM,RENCI/xDCIShare,RENCI/xDCIShare,FescueFungiShare/hydroshare,hydroshare/hydroshare,hydroshare/hydroshare,RENCI/xDCIShare,ResearchSoftwareInstitute/MyHPOM,RENCI/xDCIShare,FescueFungiShare/hydroshare,hydroshare/hydroshare,RENCI/xDCIShare,ResearchSoftwareInstitute/MyHPOM | import json
from rest_framework.test import APIClient
from rest_framework import status
from rest_framework.test import APITestCase
-
- from hs_core.hydroshare.utils import get_resource_types
class TestResourceTypes(APITestCase):
def setUp(self):
self.client = APIClient()
+ # Use a static list so that this test breaks when a resource type is
+ # added or removed (so that the test can be updated)
+ self.resource_types = {'GenericResource',
+ 'RasterResource',
+ 'RefTimeSeriesResource',
+ 'TimeSeriesResource',
+ 'NetcdfResource',
+ 'ModelProgramResource',
+ 'ModelInstanceResource',
+ 'ToolResource',
+ 'SWATModelInstanceResource',
+ 'GeographicFeatureResource',
+ 'ScriptResource'}
+
def test_resource_typelist(self):
- resource_types = set([t.__name__ for t in get_resource_types()])
-
response = self.client.get('/hsapi/resourceTypes/', format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
content = json.loads(response.content)
rest_resource_types = set([t['resource_type'] for t in content])
- self.assertEqual(resource_types, rest_resource_types)
+ self.assertEqual(self.resource_types, rest_resource_types)
+ | Make resource type list static | ## Code Before:
import json
from rest_framework.test import APIClient
from rest_framework import status
from rest_framework.test import APITestCase
from hs_core.hydroshare.utils import get_resource_types
class TestResourceTypes(APITestCase):
def setUp(self):
self.client = APIClient()
def test_resource_typelist(self):
resource_types = set([t.__name__ for t in get_resource_types()])
response = self.client.get('/hsapi/resourceTypes/', format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
content = json.loads(response.content)
rest_resource_types = set([t['resource_type'] for t in content])
self.assertEqual(resource_types, rest_resource_types)
## Instruction:
Make resource type list static
## Code After:
import json
from rest_framework.test import APIClient
from rest_framework import status
from rest_framework.test import APITestCase
class TestResourceTypes(APITestCase):
def setUp(self):
self.client = APIClient()
# Use a static list so that this test breaks when a resource type is
# added or removed (so that the test can be updated)
self.resource_types = {'GenericResource',
'RasterResource',
'RefTimeSeriesResource',
'TimeSeriesResource',
'NetcdfResource',
'ModelProgramResource',
'ModelInstanceResource',
'ToolResource',
'SWATModelInstanceResource',
'GeographicFeatureResource',
'ScriptResource'}
def test_resource_typelist(self):
response = self.client.get('/hsapi/resourceTypes/', format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
content = json.loads(response.content)
rest_resource_types = set([t['resource_type'] for t in content])
self.assertEqual(self.resource_types, rest_resource_types)
| // ... existing code ...
from rest_framework.test import APITestCase
// ... modified code ...
# Use a static list so that this test breaks when a resource type is
# added or removed (so that the test can be updated)
self.resource_types = {'GenericResource',
'RasterResource',
'RefTimeSeriesResource',
'TimeSeriesResource',
'NetcdfResource',
'ModelProgramResource',
'ModelInstanceResource',
'ToolResource',
'SWATModelInstanceResource',
'GeographicFeatureResource',
'ScriptResource'}
def test_resource_typelist(self):
response = self.client.get('/hsapi/resourceTypes/', format='json')
...
self.assertEqual(self.resource_types, rest_resource_types)
// ... rest of the code ... |
601b35c2ad07d7927c9473c6cbf500d1fec3e307 | tests/test_invariants.py | tests/test_invariants.py | from collections import deque
from hypothesis import given
from hypothesis.strategies import (frozensets, integers, lists, one_of, sets,
tuples)
from tests.hypothesis2 import examples
from tests.hypothesis2.strategies import deques, optionals
from tests.test_entities import (DataClassWithDeque, DataClassWithFrozenSet,
DataClassWithList, DataClassWithOptional,
DataClassWithSet, DataClassWithTuple)
conss_to_strategies = [(DataClassWithList, lists, list),
(DataClassWithSet, sets, set),
(DataClassWithTuple, tuples, tuple),
(DataClassWithFrozenSet, frozensets,
frozenset),
(DataClassWithDeque, deques, deque),
(DataClassWithOptional, optionals,
lambda x: x)]
example_input = [1]
@given(one_of(*[strategy_fn(integers()).map(cons)
for cons, strategy_fn, _ in conss_to_strategies]))
@examples(*[cons(f(example_input)) for cons, _, f in conss_to_strategies])
def test_generic_encode_and_decode_are_inverses(dc):
assert dc.from_json(dc.to_json()) == dc
| from collections import deque
from hypothesis import given
from hypothesis.strategies import (frozensets, integers, lists, one_of, sets,
tuples)
from tests.hypothesis2 import examples
from tests.hypothesis2.strategies import deques, optionals
from tests.test_entities import (DataClassWithDeque, DataClassWithFrozenSet,
DataClassWithList, DataClassWithOptional,
DataClassWithSet, DataClassWithTuple)
dcconss_strategies_conss = [(DataClassWithList, lists, list),
(DataClassWithSet, sets, set),
(DataClassWithTuple, tuples, tuple),
(DataClassWithFrozenSet, frozensets, frozenset),
(DataClassWithDeque, deques, deque),
(DataClassWithOptional, optionals, lambda x: x)]
example_input = [1]
@given(one_of(*[strategy_fn(integers()).map(dccons)
for dccons, strategy_fn, _ in dcconss_strategies_conss]))
@examples(*[dccons(cons(example_input))
for dccons, _, cons in dcconss_strategies_conss])
def test_generic_encode_and_decode_are_inverses(dc):
assert dc.from_json(dc.to_json()) == dc
| Rename encode/decode parameterization in test | Rename encode/decode parameterization in test
| Python | mit | lidatong/dataclasses-json,lidatong/dataclasses-json | from collections import deque
from hypothesis import given
from hypothesis.strategies import (frozensets, integers, lists, one_of, sets,
tuples)
from tests.hypothesis2 import examples
from tests.hypothesis2.strategies import deques, optionals
from tests.test_entities import (DataClassWithDeque, DataClassWithFrozenSet,
DataClassWithList, DataClassWithOptional,
DataClassWithSet, DataClassWithTuple)
- conss_to_strategies = [(DataClassWithList, lists, list),
+ dcconss_strategies_conss = [(DataClassWithList, lists, list),
- (DataClassWithSet, sets, set),
+ (DataClassWithSet, sets, set),
- (DataClassWithTuple, tuples, tuple),
+ (DataClassWithTuple, tuples, tuple),
- (DataClassWithFrozenSet, frozensets,
+ (DataClassWithFrozenSet, frozensets, frozenset),
- frozenset),
- (DataClassWithDeque, deques, deque),
+ (DataClassWithDeque, deques, deque),
- (DataClassWithOptional, optionals,
+ (DataClassWithOptional, optionals, lambda x: x)]
- lambda x: x)]
example_input = [1]
- @given(one_of(*[strategy_fn(integers()).map(cons)
+ @given(one_of(*[strategy_fn(integers()).map(dccons)
- for cons, strategy_fn, _ in conss_to_strategies]))
+ for dccons, strategy_fn, _ in dcconss_strategies_conss]))
- @examples(*[cons(f(example_input)) for cons, _, f in conss_to_strategies])
+ @examples(*[dccons(cons(example_input))
+ for dccons, _, cons in dcconss_strategies_conss])
def test_generic_encode_and_decode_are_inverses(dc):
assert dc.from_json(dc.to_json()) == dc
| Rename encode/decode parameterization in test | ## Code Before:
from collections import deque
from hypothesis import given
from hypothesis.strategies import (frozensets, integers, lists, one_of, sets,
tuples)
from tests.hypothesis2 import examples
from tests.hypothesis2.strategies import deques, optionals
from tests.test_entities import (DataClassWithDeque, DataClassWithFrozenSet,
DataClassWithList, DataClassWithOptional,
DataClassWithSet, DataClassWithTuple)
conss_to_strategies = [(DataClassWithList, lists, list),
(DataClassWithSet, sets, set),
(DataClassWithTuple, tuples, tuple),
(DataClassWithFrozenSet, frozensets,
frozenset),
(DataClassWithDeque, deques, deque),
(DataClassWithOptional, optionals,
lambda x: x)]
example_input = [1]
@given(one_of(*[strategy_fn(integers()).map(cons)
for cons, strategy_fn, _ in conss_to_strategies]))
@examples(*[cons(f(example_input)) for cons, _, f in conss_to_strategies])
def test_generic_encode_and_decode_are_inverses(dc):
assert dc.from_json(dc.to_json()) == dc
## Instruction:
Rename encode/decode parameterization in test
## Code After:
from collections import deque
from hypothesis import given
from hypothesis.strategies import (frozensets, integers, lists, one_of, sets,
tuples)
from tests.hypothesis2 import examples
from tests.hypothesis2.strategies import deques, optionals
from tests.test_entities import (DataClassWithDeque, DataClassWithFrozenSet,
DataClassWithList, DataClassWithOptional,
DataClassWithSet, DataClassWithTuple)
dcconss_strategies_conss = [(DataClassWithList, lists, list),
(DataClassWithSet, sets, set),
(DataClassWithTuple, tuples, tuple),
(DataClassWithFrozenSet, frozensets, frozenset),
(DataClassWithDeque, deques, deque),
(DataClassWithOptional, optionals, lambda x: x)]
example_input = [1]
@given(one_of(*[strategy_fn(integers()).map(dccons)
for dccons, strategy_fn, _ in dcconss_strategies_conss]))
@examples(*[dccons(cons(example_input))
for dccons, _, cons in dcconss_strategies_conss])
def test_generic_encode_and_decode_are_inverses(dc):
assert dc.from_json(dc.to_json()) == dc
| // ... existing code ...
dcconss_strategies_conss = [(DataClassWithList, lists, list),
(DataClassWithSet, sets, set),
(DataClassWithTuple, tuples, tuple),
(DataClassWithFrozenSet, frozensets, frozenset),
(DataClassWithDeque, deques, deque),
(DataClassWithOptional, optionals, lambda x: x)]
example_input = [1]
// ... modified code ...
@given(one_of(*[strategy_fn(integers()).map(dccons)
for dccons, strategy_fn, _ in dcconss_strategies_conss]))
@examples(*[dccons(cons(example_input))
for dccons, _, cons in dcconss_strategies_conss])
def test_generic_encode_and_decode_are_inverses(dc):
// ... rest of the code ... |
0b4097394fd05da204624d1c6093176feb158bb1 | ajaxuploader/backends/thumbnail.py | ajaxuploader/backends/thumbnail.py | import os
from sorl.thumbnail import get_thumbnail
from ajaxuploader.backends.local import LocalUploadBackend
class ThumbnailUploadBackend(LocalUploadBackend):
def __init__(self, dimension):
self._dimension = dimension
def upload_complete(self, request, filename):
thumbnail = get_thumbnail(self._filename, self._dimension)
os.unlink(self._filename)
return {"path": thumbnail.name}
| import os
from django.conf import settings
from sorl.thumbnail import get_thumbnail
from ajaxuploader.backends.local import LocalUploadBackend
class ThumbnailUploadBackend(LocalUploadBackend):
DIMENSION = "100x100"
def upload_complete(self, request, filename):
thumbnail = get_thumbnail(self._path, self.DIMENSION)
os.unlink(self._path)
return {"path": settings.MEDIA_URL + thumbnail.name}
| Use dimension as a constant, so we keep same interface for all backends; also returns full path to the place where image was saved | Use dimension as a constant, so we keep same interface for all backends; also returns full path to the place where image was saved
| Python | bsd-3-clause | OnlyInAmerica/django-ajax-uploader,derek-adair/django-ajax-uploader,derek-adair/django-ajax-uploader,skoczen/django-ajax-uploader,brilliant-org/django-ajax-uploader,derek-adair/django-ajax-uploader,brilliant-org/django-ajax-uploader,skoczen/django-ajax-uploader,OnlyInAmerica/django-ajax-uploader,brilliant-org/django-ajax-uploader | import os
+ from django.conf import settings
from sorl.thumbnail import get_thumbnail
from ajaxuploader.backends.local import LocalUploadBackend
class ThumbnailUploadBackend(LocalUploadBackend):
+ DIMENSION = "100x100"
+
- def __init__(self, dimension):
- self._dimension = dimension
-
def upload_complete(self, request, filename):
- thumbnail = get_thumbnail(self._filename, self._dimension)
+ thumbnail = get_thumbnail(self._path, self.DIMENSION)
- os.unlink(self._filename)
+ os.unlink(self._path)
- return {"path": thumbnail.name}
+ return {"path": settings.MEDIA_URL + thumbnail.name}
| Use dimension as a constant, so we keep same interface for all backends; also returns full path to the place where image was saved | ## Code Before:
import os
from sorl.thumbnail import get_thumbnail
from ajaxuploader.backends.local import LocalUploadBackend
class ThumbnailUploadBackend(LocalUploadBackend):
def __init__(self, dimension):
self._dimension = dimension
def upload_complete(self, request, filename):
thumbnail = get_thumbnail(self._filename, self._dimension)
os.unlink(self._filename)
return {"path": thumbnail.name}
## Instruction:
Use dimension as a constant, so we keep same interface for all backends; also returns full path to the place where image was saved
## Code After:
import os
from django.conf import settings
from sorl.thumbnail import get_thumbnail
from ajaxuploader.backends.local import LocalUploadBackend
class ThumbnailUploadBackend(LocalUploadBackend):
DIMENSION = "100x100"
def upload_complete(self, request, filename):
thumbnail = get_thumbnail(self._path, self.DIMENSION)
os.unlink(self._path)
return {"path": settings.MEDIA_URL + thumbnail.name}
| # ... existing code ...
from django.conf import settings
from sorl.thumbnail import get_thumbnail
# ... modified code ...
class ThumbnailUploadBackend(LocalUploadBackend):
DIMENSION = "100x100"
def upload_complete(self, request, filename):
thumbnail = get_thumbnail(self._path, self.DIMENSION)
os.unlink(self._path)
return {"path": settings.MEDIA_URL + thumbnail.name}
# ... rest of the code ... |
600839e3c51d2091a6c434ac31ea11dc9ed2db85 | foialist/forms.py | foialist/forms.py | from django import forms
from foialist.models import *
class FileForm(forms.ModelForm):
class Meta:
model = File
exclude = ('entry', 'size')
class EntryForm(forms.ModelForm):
govt_entity = forms.CharField(label="Gov't. entity")
class Meta:
model = Entry
# exclude = ('slug', 'poster_slug', 'show', 'date_posted', 'entity')
fields = ('title', 'narrative', 'government_entity', 'date_requested', 'date_filed', 'poster', 'email')
class CommentForm(forms.ModelForm):
poster = forms.CharField()
class Meta:
model = Comment | from django import forms
from foialist.models import *
class FileForm(forms.ModelForm):
class Meta:
model = File
exclude = ('entry', 'size')
class EntryForm(forms.ModelForm):
govt_entity = forms.CharField(label="Gov't. entity")
class Meta:
model = Entry
fields = ('title', 'narrative', 'govt_entity', 'date_requested',
'date_filed', 'poster', 'email')
class CommentForm(forms.ModelForm):
poster = forms.CharField()
class Meta:
model = Comment | Correct mismatched field names in EntryForm. | Correct mismatched field names in EntryForm.
| Python | bsd-3-clause | a2civictech/a2docs-sources,a2civictech/a2docs-sources,a2civictech/a2docs-sources | from django import forms
from foialist.models import *
class FileForm(forms.ModelForm):
class Meta:
model = File
exclude = ('entry', 'size')
class EntryForm(forms.ModelForm):
govt_entity = forms.CharField(label="Gov't. entity")
class Meta:
model = Entry
- # exclude = ('slug', 'poster_slug', 'show', 'date_posted', 'entity')
- fields = ('title', 'narrative', 'government_entity', 'date_requested', 'date_filed', 'poster', 'email')
+ fields = ('title', 'narrative', 'govt_entity', 'date_requested',
+ 'date_filed', 'poster', 'email')
class CommentForm(forms.ModelForm):
poster = forms.CharField()
class Meta:
model = Comment | Correct mismatched field names in EntryForm. | ## Code Before:
from django import forms
from foialist.models import *
class FileForm(forms.ModelForm):
class Meta:
model = File
exclude = ('entry', 'size')
class EntryForm(forms.ModelForm):
govt_entity = forms.CharField(label="Gov't. entity")
class Meta:
model = Entry
# exclude = ('slug', 'poster_slug', 'show', 'date_posted', 'entity')
fields = ('title', 'narrative', 'government_entity', 'date_requested', 'date_filed', 'poster', 'email')
class CommentForm(forms.ModelForm):
poster = forms.CharField()
class Meta:
model = Comment
## Instruction:
Correct mismatched field names in EntryForm.
## Code After:
from django import forms
from foialist.models import *
class FileForm(forms.ModelForm):
class Meta:
model = File
exclude = ('entry', 'size')
class EntryForm(forms.ModelForm):
govt_entity = forms.CharField(label="Gov't. entity")
class Meta:
model = Entry
fields = ('title', 'narrative', 'govt_entity', 'date_requested',
'date_filed', 'poster', 'email')
class CommentForm(forms.ModelForm):
poster = forms.CharField()
class Meta:
model = Comment | # ... existing code ...
model = Entry
fields = ('title', 'narrative', 'govt_entity', 'date_requested',
'date_filed', 'poster', 'email')
# ... rest of the code ... |
4c4022e3a215b9b591220cd19fedbc501b63a1b2 | virtualenv/builders/base.py | virtualenv/builders/base.py | import sys
class BaseBuilder(object):
def __init__(self, python, system_site_packages=False, clear=False):
# We default to sys.executable if we're not given a Python.
if python is None:
python = sys.executable
self.python = python
self.system_site_packages = system_site_packages
self.clear = clear
def create(self, destination):
# Actually Create the virtual environment
self.create_virtual_environment(destination)
def create_virtual_environment(self, destination):
raise NotImplementedError
| import sys
class BaseBuilder(object):
def __init__(self, python, system_site_packages=False, clear=False):
# We default to sys.executable if we're not given a Python.
if python is None:
python = sys.executable
self.python = python
self.system_site_packages = system_site_packages
self.clear = clear
def create(self, destination):
# Actually Create the virtual environment
self.create_virtual_environment(destination)
# Install our activate scripts into the virtual environment
self.install_scripts(destination)
def create_virtual_environment(self, destination):
raise NotImplementedError
def install_scripts(self, destination):
pass
| Add a hook we'll eventually use to install the activate scripts | Add a hook we'll eventually use to install the activate scripts
| Python | mit | ionelmc/virtualenv,ionelmc/virtualenv,ionelmc/virtualenv | import sys
class BaseBuilder(object):
def __init__(self, python, system_site_packages=False, clear=False):
# We default to sys.executable if we're not given a Python.
if python is None:
python = sys.executable
self.python = python
self.system_site_packages = system_site_packages
self.clear = clear
def create(self, destination):
# Actually Create the virtual environment
self.create_virtual_environment(destination)
+ # Install our activate scripts into the virtual environment
+ self.install_scripts(destination)
+
def create_virtual_environment(self, destination):
raise NotImplementedError
+ def install_scripts(self, destination):
+ pass
+ | Add a hook we'll eventually use to install the activate scripts | ## Code Before:
import sys
class BaseBuilder(object):
def __init__(self, python, system_site_packages=False, clear=False):
# We default to sys.executable if we're not given a Python.
if python is None:
python = sys.executable
self.python = python
self.system_site_packages = system_site_packages
self.clear = clear
def create(self, destination):
# Actually Create the virtual environment
self.create_virtual_environment(destination)
def create_virtual_environment(self, destination):
raise NotImplementedError
## Instruction:
Add a hook we'll eventually use to install the activate scripts
## Code After:
import sys
class BaseBuilder(object):
def __init__(self, python, system_site_packages=False, clear=False):
# We default to sys.executable if we're not given a Python.
if python is None:
python = sys.executable
self.python = python
self.system_site_packages = system_site_packages
self.clear = clear
def create(self, destination):
# Actually Create the virtual environment
self.create_virtual_environment(destination)
# Install our activate scripts into the virtual environment
self.install_scripts(destination)
def create_virtual_environment(self, destination):
raise NotImplementedError
def install_scripts(self, destination):
pass
| # ... existing code ...
# Install our activate scripts into the virtual environment
self.install_scripts(destination)
def create_virtual_environment(self, destination):
# ... modified code ...
raise NotImplementedError
def install_scripts(self, destination):
pass
# ... rest of the code ... |
205616b0a23143cdc5ceb6fb8333cf6074ce737b | kitchen/pycompat25/collections/__init__.py | kitchen/pycompat25/collections/__init__.py | try:
from collections import defaultdict
except ImportError:
from _defaultdict import defaultdict
__all__ = ('defaultdict',)
| try:
#:E0611: deafultdict doesn't exist in python-2.4 or less but that's why we
# have it in a try: except:. So we can use our version if necessary.
from collections import defaultdict
except ImportError:
from kitchen.pycompat25.collections._defaultdict import defaultdict
__all__ = ('defaultdict',)
| Fix pylint error in this module | Fix pylint error in this module
| Python | lgpl-2.1 | fedora-infra/kitchen,fedora-infra/kitchen | try:
+ #:E0611: deafultdict doesn't exist in python-2.4 or less but that's why we
+ # have it in a try: except:. So we can use our version if necessary.
from collections import defaultdict
except ImportError:
- from _defaultdict import defaultdict
+ from kitchen.pycompat25.collections._defaultdict import defaultdict
__all__ = ('defaultdict',)
| Fix pylint error in this module | ## Code Before:
try:
from collections import defaultdict
except ImportError:
from _defaultdict import defaultdict
__all__ = ('defaultdict',)
## Instruction:
Fix pylint error in this module
## Code After:
try:
#:E0611: deafultdict doesn't exist in python-2.4 or less but that's why we
# have it in a try: except:. So we can use our version if necessary.
from collections import defaultdict
except ImportError:
from kitchen.pycompat25.collections._defaultdict import defaultdict
__all__ = ('defaultdict',)
| // ... existing code ...
try:
#:E0611: deafultdict doesn't exist in python-2.4 or less but that's why we
# have it in a try: except:. So we can use our version if necessary.
from collections import defaultdict
// ... modified code ...
except ImportError:
from kitchen.pycompat25.collections._defaultdict import defaultdict
// ... rest of the code ... |
ffa6417b30517569cadff00aec839d968f3c91d7 | bisnode/constants.py | bisnode/constants.py | COMPANY_STANDARD_REPORT = "NRGCompanyReportStandard"
COMPANY_RATING_REPORT = "NRGCompanyReportRating"
HIGH = 'AAA'
GOOD = 'AA'
WORTHY = 'A'
BELOW_AVERAGE = 'B'
BAD = 'C'
MISSING = '-'
RATING_CHOICES = (
(HIGH, "high"),
(GOOD, "good"),
(WORTHY, "worthy"),
(BELOW_AVERAGE, "below average"),
(BAD, "bad"),
(MISSING, "missing"),
)
| COMPANY_STANDARD_REPORT = "NRGCompanyReportStandard"
COMPANY_RATING_REPORT = "NRGCompanyReportRating"
HIGH = 'AAA'
GOOD = 'AA'
WORTHY = 'A'
NEW = 'AN'
BELOW_AVERAGE = 'B'
BAD = 'C'
MISSING = '-'
RATING_CHOICES = (
(HIGH, "high"),
(GOOD, "good"),
(WORTHY, "worthy"),
(NEW, "new"),
(BELOW_AVERAGE, "below average"),
(BAD, "bad"),
(MISSING, "missing"),
)
| Add a new rating code | Add a new rating code
| Python | mit | FundedByMe/django-bisnode | COMPANY_STANDARD_REPORT = "NRGCompanyReportStandard"
COMPANY_RATING_REPORT = "NRGCompanyReportRating"
HIGH = 'AAA'
GOOD = 'AA'
WORTHY = 'A'
+ NEW = 'AN'
BELOW_AVERAGE = 'B'
BAD = 'C'
MISSING = '-'
RATING_CHOICES = (
(HIGH, "high"),
(GOOD, "good"),
(WORTHY, "worthy"),
+ (NEW, "new"),
(BELOW_AVERAGE, "below average"),
(BAD, "bad"),
(MISSING, "missing"),
)
| Add a new rating code | ## Code Before:
COMPANY_STANDARD_REPORT = "NRGCompanyReportStandard"
COMPANY_RATING_REPORT = "NRGCompanyReportRating"
HIGH = 'AAA'
GOOD = 'AA'
WORTHY = 'A'
BELOW_AVERAGE = 'B'
BAD = 'C'
MISSING = '-'
RATING_CHOICES = (
(HIGH, "high"),
(GOOD, "good"),
(WORTHY, "worthy"),
(BELOW_AVERAGE, "below average"),
(BAD, "bad"),
(MISSING, "missing"),
)
## Instruction:
Add a new rating code
## Code After:
COMPANY_STANDARD_REPORT = "NRGCompanyReportStandard"
COMPANY_RATING_REPORT = "NRGCompanyReportRating"
HIGH = 'AAA'
GOOD = 'AA'
WORTHY = 'A'
NEW = 'AN'
BELOW_AVERAGE = 'B'
BAD = 'C'
MISSING = '-'
RATING_CHOICES = (
(HIGH, "high"),
(GOOD, "good"),
(WORTHY, "worthy"),
(NEW, "new"),
(BELOW_AVERAGE, "below average"),
(BAD, "bad"),
(MISSING, "missing"),
)
| // ... existing code ...
WORTHY = 'A'
NEW = 'AN'
BELOW_AVERAGE = 'B'
// ... modified code ...
(WORTHY, "worthy"),
(NEW, "new"),
(BELOW_AVERAGE, "below average"),
// ... rest of the code ... |
310cebbe1f4a4d92c8f181d7e4de9cc4f75a14dc | indra/assemblers/__init__.py | indra/assemblers/__init__.py | try:
from pysb_assembler import PysbAssembler
except ImportError:
pass
try:
from graph_assembler import GraphAssembler
except ImportError:
pass
try:
from sif_assembler import SifAssembler
except ImportError:
pass
try:
from cx_assembler import CxAssembler
except ImportError:
pass
try:
from english_assembler import EnglishAssembler
except ImportError:
pass
try:
from sbgn_assembler import SBGNAssembler
except ImportError:
pass
try:
from index_card_assembler import IndexCardAssembler
except ImportError:
pass
| try:
from indra.assemblers.pysb_assembler import PysbAssembler
except ImportError:
pass
try:
from indra.assemblers.graph_assembler import GraphAssembler
except ImportError:
pass
try:
from indra.assemblers.sif_assembler import SifAssembler
except ImportError:
pass
try:
from indra.assemblers.cx_assembler import CxAssembler
except ImportError:
pass
try:
from indra.assemblers.english_assembler import EnglishAssembler
except ImportError:
pass
try:
from indra.assemblers.sbgn_assembler import SBGNAssembler
except ImportError:
pass
try:
from indra.assemblers.index_card_assembler import IndexCardAssembler
except ImportError:
pass
| Update to absolute imports in assemblers | Update to absolute imports in assemblers
| Python | bsd-2-clause | johnbachman/indra,bgyori/indra,sorgerlab/belpy,sorgerlab/indra,pvtodorov/indra,pvtodorov/indra,pvtodorov/indra,johnbachman/indra,bgyori/indra,jmuhlich/indra,pvtodorov/indra,sorgerlab/indra,jmuhlich/indra,johnbachman/belpy,johnbachman/belpy,sorgerlab/belpy,johnbachman/indra,sorgerlab/belpy,johnbachman/belpy,jmuhlich/indra,bgyori/indra,sorgerlab/indra | try:
- from pysb_assembler import PysbAssembler
+ from indra.assemblers.pysb_assembler import PysbAssembler
except ImportError:
pass
try:
- from graph_assembler import GraphAssembler
+ from indra.assemblers.graph_assembler import GraphAssembler
except ImportError:
pass
try:
- from sif_assembler import SifAssembler
+ from indra.assemblers.sif_assembler import SifAssembler
except ImportError:
pass
try:
- from cx_assembler import CxAssembler
+ from indra.assemblers.cx_assembler import CxAssembler
except ImportError:
pass
try:
- from english_assembler import EnglishAssembler
+ from indra.assemblers.english_assembler import EnglishAssembler
except ImportError:
pass
try:
- from sbgn_assembler import SBGNAssembler
+ from indra.assemblers.sbgn_assembler import SBGNAssembler
except ImportError:
pass
try:
- from index_card_assembler import IndexCardAssembler
+ from indra.assemblers.index_card_assembler import IndexCardAssembler
except ImportError:
pass
| Update to absolute imports in assemblers | ## Code Before:
try:
from pysb_assembler import PysbAssembler
except ImportError:
pass
try:
from graph_assembler import GraphAssembler
except ImportError:
pass
try:
from sif_assembler import SifAssembler
except ImportError:
pass
try:
from cx_assembler import CxAssembler
except ImportError:
pass
try:
from english_assembler import EnglishAssembler
except ImportError:
pass
try:
from sbgn_assembler import SBGNAssembler
except ImportError:
pass
try:
from index_card_assembler import IndexCardAssembler
except ImportError:
pass
## Instruction:
Update to absolute imports in assemblers
## Code After:
try:
from indra.assemblers.pysb_assembler import PysbAssembler
except ImportError:
pass
try:
from indra.assemblers.graph_assembler import GraphAssembler
except ImportError:
pass
try:
from indra.assemblers.sif_assembler import SifAssembler
except ImportError:
pass
try:
from indra.assemblers.cx_assembler import CxAssembler
except ImportError:
pass
try:
from indra.assemblers.english_assembler import EnglishAssembler
except ImportError:
pass
try:
from indra.assemblers.sbgn_assembler import SBGNAssembler
except ImportError:
pass
try:
from indra.assemblers.index_card_assembler import IndexCardAssembler
except ImportError:
pass
| // ... existing code ...
try:
from indra.assemblers.pysb_assembler import PysbAssembler
except ImportError:
// ... modified code ...
try:
from indra.assemblers.graph_assembler import GraphAssembler
except ImportError:
...
try:
from indra.assemblers.sif_assembler import SifAssembler
except ImportError:
...
try:
from indra.assemblers.cx_assembler import CxAssembler
except ImportError:
...
try:
from indra.assemblers.english_assembler import EnglishAssembler
except ImportError:
...
try:
from indra.assemblers.sbgn_assembler import SBGNAssembler
except ImportError:
...
try:
from indra.assemblers.index_card_assembler import IndexCardAssembler
except ImportError:
// ... rest of the code ... |
cc9084c744b3ba3525f464adeaa7edaea64abf41 | torchtext/data/pipeline.py | torchtext/data/pipeline.py | class Pipeline(object):
"""Defines a pipeline for transforming sequence data."""
def __init__(self, convert_token=None):
if convert_token is None:
self.convert_token = lambda x: x
elif callable(convert_token):
self.convert_token = convert_token
else:
raise ValueError("Pipeline input convert_token {} is not None "
"or callable".format(convert_token))
self.pipes = [self]
def __call__(self, x, *args):
for pipe in self.pipes:
x = pipe.call(x, *args)
return x
def call(self, x, *args):
if isinstance(x, list):
return [self(tok, *args) for tok in x]
return self.convert_token(x, *args)
def add_before(self, pipeline):
"""Add `pipeline` before this processing pipeline."""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
self.pipes = pipeline.pipes[:] + self.pipes[:]
return self
def add_after(self, pipeline):
"""Add `pipeline` after this processing pipeline."""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
self.pipes = self.pipes[:] + pipeline.pipes[:]
return self
| class Pipeline(object):
"""Defines a pipeline for transforming sequence data."""
def __init__(self, convert_token=None):
if convert_token is None:
self.convert_token = lambda x: x
elif callable(convert_token):
self.convert_token = convert_token
else:
raise ValueError("Pipeline input convert_token {} is not None "
"or callable".format(convert_token))
self.pipes = [self]
def __call__(self, x, *args):
for pipe in self.pipes:
x = pipe.call(x, *args)
return x
def call(self, x, *args):
if isinstance(x, list):
return [self.convert_token(tok, *args) for tok in x]
return self.convert_token(x, *args)
def add_before(self, pipeline):
"""Add `pipeline` before this processing pipeline."""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
self.pipes = pipeline.pipes[:] + self.pipes[:]
return self
def add_after(self, pipeline):
"""Add `pipeline` after this processing pipeline."""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
self.pipes = self.pipes[:] + pipeline.pipes[:]
return self
| Fix bug in Pipeline call where we run the whole Pipeline on list input | Fix bug in Pipeline call where we run the whole Pipeline on list input
| Python | bsd-3-clause | pytorch/text,pytorch/text,pytorch/text,pytorch/text | class Pipeline(object):
"""Defines a pipeline for transforming sequence data."""
def __init__(self, convert_token=None):
if convert_token is None:
self.convert_token = lambda x: x
elif callable(convert_token):
self.convert_token = convert_token
else:
raise ValueError("Pipeline input convert_token {} is not None "
"or callable".format(convert_token))
self.pipes = [self]
def __call__(self, x, *args):
for pipe in self.pipes:
x = pipe.call(x, *args)
return x
def call(self, x, *args):
if isinstance(x, list):
- return [self(tok, *args) for tok in x]
+ return [self.convert_token(tok, *args) for tok in x]
return self.convert_token(x, *args)
def add_before(self, pipeline):
"""Add `pipeline` before this processing pipeline."""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
self.pipes = pipeline.pipes[:] + self.pipes[:]
return self
def add_after(self, pipeline):
"""Add `pipeline` after this processing pipeline."""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
self.pipes = self.pipes[:] + pipeline.pipes[:]
return self
| Fix bug in Pipeline call where we run the whole Pipeline on list input | ## Code Before:
class Pipeline(object):
"""Defines a pipeline for transforming sequence data."""
def __init__(self, convert_token=None):
if convert_token is None:
self.convert_token = lambda x: x
elif callable(convert_token):
self.convert_token = convert_token
else:
raise ValueError("Pipeline input convert_token {} is not None "
"or callable".format(convert_token))
self.pipes = [self]
def __call__(self, x, *args):
for pipe in self.pipes:
x = pipe.call(x, *args)
return x
def call(self, x, *args):
if isinstance(x, list):
return [self(tok, *args) for tok in x]
return self.convert_token(x, *args)
def add_before(self, pipeline):
"""Add `pipeline` before this processing pipeline."""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
self.pipes = pipeline.pipes[:] + self.pipes[:]
return self
def add_after(self, pipeline):
"""Add `pipeline` after this processing pipeline."""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
self.pipes = self.pipes[:] + pipeline.pipes[:]
return self
## Instruction:
Fix bug in Pipeline call where we run the whole Pipeline on list input
## Code After:
class Pipeline(object):
"""Defines a pipeline for transforming sequence data."""
def __init__(self, convert_token=None):
if convert_token is None:
self.convert_token = lambda x: x
elif callable(convert_token):
self.convert_token = convert_token
else:
raise ValueError("Pipeline input convert_token {} is not None "
"or callable".format(convert_token))
self.pipes = [self]
def __call__(self, x, *args):
for pipe in self.pipes:
x = pipe.call(x, *args)
return x
def call(self, x, *args):
if isinstance(x, list):
return [self.convert_token(tok, *args) for tok in x]
return self.convert_token(x, *args)
def add_before(self, pipeline):
"""Add `pipeline` before this processing pipeline."""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
self.pipes = pipeline.pipes[:] + self.pipes[:]
return self
def add_after(self, pipeline):
"""Add `pipeline` after this processing pipeline."""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
self.pipes = self.pipes[:] + pipeline.pipes[:]
return self
| ...
if isinstance(x, list):
return [self.convert_token(tok, *args) for tok in x]
return self.convert_token(x, *args)
... |
97c26c367c2c4597842356e677064a012ea19cb6 | events/forms.py | events/forms.py | from django import forms
from events.models import Event, City
class EventForm(forms.ModelForm):
city = forms.ModelChoiceField(City.objects.all(), empty_label=None, label="Ville")
class Meta:
model = Event
exclude = ('submission_time', 'updated_time', 'decision_time',
'moderator', 'moderated', 'latitude', 'longitude')
| from django import forms
from events.models import Event, City
from django.forms.util import ErrorList
from datetime import datetime
class EventForm(forms.ModelForm):
city = forms.ModelChoiceField(City.objects.all(), empty_label=None, label="Ville")
class Meta:
model = Event
exclude = ('submission_time', 'updated_time', 'decision_time',
'moderator', 'moderated', 'latitude', 'longitude')
def clean(self):
cleaned_data = self.cleaned_data
start_time = cleaned_data.get("start_time")
end_time = cleaned_data.get("end_time")
if start_time >= end_time:
msg = u"L'évènement ne peut se terminer avant son début"
self._errors["start_time"] = ErrorList([msg])
self._errors["end_time"] = ErrorList([msg])
del cleaned_data["start_time"]
del cleaned_data["end_time"]
elif start_time < datetime.today():
msg = u"Seul les évènements à venir sont acceptés"
self._errors["start_time"] = ErrorList([msg])
del cleaned_data["start_time"]
return cleaned_data
| Validate entered dates in Event form | Validate entered dates in Event form
| Python | agpl-3.0 | vcorreze/agendaEteAccoord,mlhamel/agendadulibre,vcorreze/agendaEteAccoord,mlhamel/agendadulibre,mlhamel/agendadulibre,vcorreze/agendaEteAccoord | from django import forms
from events.models import Event, City
+ from django.forms.util import ErrorList
+ from datetime import datetime
class EventForm(forms.ModelForm):
- city = forms.ModelChoiceField(City.objects.all(), empty_label=None, label="Ville")
+ city = forms.ModelChoiceField(City.objects.all(), empty_label=None, label="Ville")
- class Meta:
+ class Meta:
- model = Event
+ model = Event
- exclude = ('submission_time', 'updated_time', 'decision_time',
+ exclude = ('submission_time', 'updated_time', 'decision_time',
- 'moderator', 'moderated', 'latitude', 'longitude')
+ 'moderator', 'moderated', 'latitude', 'longitude')
+ def clean(self):
+ cleaned_data = self.cleaned_data
+ start_time = cleaned_data.get("start_time")
+ end_time = cleaned_data.get("end_time")
+ if start_time >= end_time:
+ msg = u"L'évènement ne peut se terminer avant son début"
+ self._errors["start_time"] = ErrorList([msg])
+ self._errors["end_time"] = ErrorList([msg])
+
+ del cleaned_data["start_time"]
+ del cleaned_data["end_time"]
+
+ elif start_time < datetime.today():
+ msg = u"Seul les évènements à venir sont acceptés"
+ self._errors["start_time"] = ErrorList([msg])
+
+ del cleaned_data["start_time"]
+
+ return cleaned_data
+ | Validate entered dates in Event form | ## Code Before:
from django import forms
from events.models import Event, City
class EventForm(forms.ModelForm):
city = forms.ModelChoiceField(City.objects.all(), empty_label=None, label="Ville")
class Meta:
model = Event
exclude = ('submission_time', 'updated_time', 'decision_time',
'moderator', 'moderated', 'latitude', 'longitude')
## Instruction:
Validate entered dates in Event form
## Code After:
from django import forms
from events.models import Event, City
from django.forms.util import ErrorList
from datetime import datetime
class EventForm(forms.ModelForm):
city = forms.ModelChoiceField(City.objects.all(), empty_label=None, label="Ville")
class Meta:
model = Event
exclude = ('submission_time', 'updated_time', 'decision_time',
'moderator', 'moderated', 'latitude', 'longitude')
def clean(self):
cleaned_data = self.cleaned_data
start_time = cleaned_data.get("start_time")
end_time = cleaned_data.get("end_time")
if start_time >= end_time:
msg = u"L'évènement ne peut se terminer avant son début"
self._errors["start_time"] = ErrorList([msg])
self._errors["end_time"] = ErrorList([msg])
del cleaned_data["start_time"]
del cleaned_data["end_time"]
elif start_time < datetime.today():
msg = u"Seul les évènements à venir sont acceptés"
self._errors["start_time"] = ErrorList([msg])
del cleaned_data["start_time"]
return cleaned_data
| ...
from events.models import Event, City
from django.forms.util import ErrorList
from datetime import datetime
...
class EventForm(forms.ModelForm):
city = forms.ModelChoiceField(City.objects.all(), empty_label=None, label="Ville")
class Meta:
model = Event
exclude = ('submission_time', 'updated_time', 'decision_time',
'moderator', 'moderated', 'latitude', 'longitude')
def clean(self):
cleaned_data = self.cleaned_data
start_time = cleaned_data.get("start_time")
end_time = cleaned_data.get("end_time")
if start_time >= end_time:
msg = u"L'évènement ne peut se terminer avant son début"
self._errors["start_time"] = ErrorList([msg])
self._errors["end_time"] = ErrorList([msg])
del cleaned_data["start_time"]
del cleaned_data["end_time"]
elif start_time < datetime.today():
msg = u"Seul les évènements à venir sont acceptés"
self._errors["start_time"] = ErrorList([msg])
del cleaned_data["start_time"]
return cleaned_data
... |
d0b2b0aa3674fb6b85fd788e88a3a54f4cc22046 | pytablewriter/_excel_workbook.py | pytablewriter/_excel_workbook.py |
from __future__ import absolute_import
import xlsxwriter
class ExcelWorkbookXlsx(object):
@property
def workbook(self):
return self.__workbook
@property
def file_path(self):
return self.__file_path
def __init__(self, file_path):
self.open(file_path)
def __del__(self):
self.close()
def open(self, file_path):
self.__file_path = file_path
self.__workbook = xlsxwriter.Workbook(file_path)
def close(self):
if self.workbook is None:
return
self.__workbook.close()
self.__clear()
def add_worksheet(self, worksheet_name):
worksheet = self.__workbook.add_worksheet(worksheet_name)
return worksheet
def __clear(self):
self.__workbook = None
self.__file_path = None
|
from __future__ import absolute_import
import abc
import six
import xlsxwriter
@six.add_metaclass(abc.ABCMeta)
class ExcelWorkbookInterface(object):
@abc.abstractproperty
def workbook(self):
pass
@abc.abstractproperty
def file_path(self):
pass
@abc.abstractmethod
def open(self, file_path):
pass
@abc.abstractmethod
def close(self):
pass
class ExcelWorkbook(ExcelWorkbookInterface):
@property
def workbook(self):
return self._workbook
@property
def file_path(self):
return self._file_path
def _clear(self):
self._workbook = None
self._file_path = None
class ExcelWorkbookXlsx(ExcelWorkbook):
def __init__(self, file_path):
self.open(file_path)
def __del__(self):
self.close()
def open(self, file_path):
self._file_path = file_path
self._workbook = xlsxwriter.Workbook(file_path)
def close(self):
if self.workbook is None:
return
self._workbook.close()
self._clear()
def add_worksheet(self, worksheet_name):
worksheet = self.workbook.add_worksheet(worksheet_name)
return worksheet
| Add an interface class and a base class of for Excel Workbook | Add an interface class and a base class of for Excel Workbook
| Python | mit | thombashi/pytablewriter |
from __future__ import absolute_import
+ import abc
+ import six
import xlsxwriter
+ @six.add_metaclass(abc.ABCMeta)
- class ExcelWorkbookXlsx(object):
+ class ExcelWorkbookInterface(object):
+
+ @abc.abstractproperty
+ def workbook(self):
+ pass
+
+ @abc.abstractproperty
+ def file_path(self):
+ pass
+
+ @abc.abstractmethod
+ def open(self, file_path):
+ pass
+
+ @abc.abstractmethod
+ def close(self):
+ pass
+
+
+ class ExcelWorkbook(ExcelWorkbookInterface):
@property
def workbook(self):
- return self.__workbook
+ return self._workbook
@property
def file_path(self):
- return self.__file_path
+ return self._file_path
+
+ def _clear(self):
+ self._workbook = None
+ self._file_path = None
+
+
+ class ExcelWorkbookXlsx(ExcelWorkbook):
def __init__(self, file_path):
self.open(file_path)
def __del__(self):
self.close()
def open(self, file_path):
- self.__file_path = file_path
+ self._file_path = file_path
- self.__workbook = xlsxwriter.Workbook(file_path)
+ self._workbook = xlsxwriter.Workbook(file_path)
def close(self):
if self.workbook is None:
return
- self.__workbook.close()
+ self._workbook.close()
- self.__clear()
+ self._clear()
def add_worksheet(self, worksheet_name):
- worksheet = self.__workbook.add_worksheet(worksheet_name)
+ worksheet = self.workbook.add_worksheet(worksheet_name)
return worksheet
- def __clear(self):
- self.__workbook = None
- self.__file_path = None
- | Add an interface class and a base class of for Excel Workbook | ## Code Before:
from __future__ import absolute_import
import xlsxwriter
class ExcelWorkbookXlsx(object):
@property
def workbook(self):
return self.__workbook
@property
def file_path(self):
return self.__file_path
def __init__(self, file_path):
self.open(file_path)
def __del__(self):
self.close()
def open(self, file_path):
self.__file_path = file_path
self.__workbook = xlsxwriter.Workbook(file_path)
def close(self):
if self.workbook is None:
return
self.__workbook.close()
self.__clear()
def add_worksheet(self, worksheet_name):
worksheet = self.__workbook.add_worksheet(worksheet_name)
return worksheet
def __clear(self):
self.__workbook = None
self.__file_path = None
## Instruction:
Add an interface class and a base class of for Excel Workbook
## Code After:
from __future__ import absolute_import
import abc
import six
import xlsxwriter
@six.add_metaclass(abc.ABCMeta)
class ExcelWorkbookInterface(object):
@abc.abstractproperty
def workbook(self):
pass
@abc.abstractproperty
def file_path(self):
pass
@abc.abstractmethod
def open(self, file_path):
pass
@abc.abstractmethod
def close(self):
pass
class ExcelWorkbook(ExcelWorkbookInterface):
@property
def workbook(self):
return self._workbook
@property
def file_path(self):
return self._file_path
def _clear(self):
self._workbook = None
self._file_path = None
class ExcelWorkbookXlsx(ExcelWorkbook):
def __init__(self, file_path):
self.open(file_path)
def __del__(self):
self.close()
def open(self, file_path):
self._file_path = file_path
self._workbook = xlsxwriter.Workbook(file_path)
def close(self):
if self.workbook is None:
return
self._workbook.close()
self._clear()
def add_worksheet(self, worksheet_name):
worksheet = self.workbook.add_worksheet(worksheet_name)
return worksheet
| // ... existing code ...
from __future__ import absolute_import
import abc
import six
import xlsxwriter
// ... modified code ...
@six.add_metaclass(abc.ABCMeta)
class ExcelWorkbookInterface(object):
@abc.abstractproperty
def workbook(self):
pass
@abc.abstractproperty
def file_path(self):
pass
@abc.abstractmethod
def open(self, file_path):
pass
@abc.abstractmethod
def close(self):
pass
class ExcelWorkbook(ExcelWorkbookInterface):
...
def workbook(self):
return self._workbook
...
def file_path(self):
return self._file_path
def _clear(self):
self._workbook = None
self._file_path = None
class ExcelWorkbookXlsx(ExcelWorkbook):
...
def open(self, file_path):
self._file_path = file_path
self._workbook = xlsxwriter.Workbook(file_path)
...
self._workbook.close()
self._clear()
...
def add_worksheet(self, worksheet_name):
worksheet = self.workbook.add_worksheet(worksheet_name)
...
return worksheet
// ... rest of the code ... |
d52c4340a62802bcd0fcbd68516c5ac66fb10436 | ftfy/streamtester/__init__.py | ftfy/streamtester/__init__.py | from __future__ import print_function, unicode_literals
from ftfy.fixes import fix_text_encoding
from ftfy.chardata import possible_encoding
class StreamTester:
"""
Take in a sequence of texts, and show the ones that will be changed by
ftfy. This will also periodically show updates, such as the proportion of
texts that changed.
"""
def __init__(self):
self.num_fixed = 0
self.count = 0
def check_ftfy(self, text):
"""
Given a single text input, check whether `ftfy.fix_text_encoding`
would change it. If so, display the change.
"""
self.count += 1
if not possible_encoding(text, 'ascii'):
fixed = fix_text_encoding(text)
if text != fixed:
# possibly filter common bots before printing
print(u'\nText:\t{text}\nFixed:\t{fixed}\n'.format(
text=text, fixed=fixed
))
self.num_fixed += 1
# Print status updates once in a while
if self.count % 100 == 0:
print('.', end='', flush=True)
if self.count % 10000 == 0:
print('\n%d/%d fixed' % (self.num_fixed, self.count))
| from __future__ import print_function, unicode_literals
from ftfy.fixes import fix_encoding
from ftfy.chardata import possible_encoding
class StreamTester:
"""
Take in a sequence of texts, and show the ones that will be changed by
ftfy. This will also periodically show updates, such as the proportion of
texts that changed.
"""
def __init__(self):
self.num_fixed = 0
self.count = 0
def check_ftfy(self, text):
"""
Given a single text input, check whether `ftfy.fix_text_encoding`
would change it. If so, display the change.
"""
self.count += 1
if not possible_encoding(text, 'ascii'):
fixed = fix_encoding(text)
if text != fixed:
# possibly filter common bots before printing
print(u'\nText:\t{text}\nFixed:\t{fixed}\n'.format(
text=text, fixed=fixed
))
self.num_fixed += 1
# Print status updates once in a while
if self.count % 100 == 0:
print('.', end='', flush=True)
if self.count % 10000 == 0:
print('\n%d/%d fixed' % (self.num_fixed, self.count))
| Update function name used in the streamtester | Update function name used in the streamtester
| Python | mit | LuminosoInsight/python-ftfy | from __future__ import print_function, unicode_literals
- from ftfy.fixes import fix_text_encoding
+ from ftfy.fixes import fix_encoding
from ftfy.chardata import possible_encoding
class StreamTester:
"""
Take in a sequence of texts, and show the ones that will be changed by
ftfy. This will also periodically show updates, such as the proportion of
texts that changed.
"""
def __init__(self):
self.num_fixed = 0
self.count = 0
def check_ftfy(self, text):
"""
Given a single text input, check whether `ftfy.fix_text_encoding`
would change it. If so, display the change.
"""
self.count += 1
if not possible_encoding(text, 'ascii'):
- fixed = fix_text_encoding(text)
+ fixed = fix_encoding(text)
if text != fixed:
# possibly filter common bots before printing
print(u'\nText:\t{text}\nFixed:\t{fixed}\n'.format(
text=text, fixed=fixed
))
self.num_fixed += 1
# Print status updates once in a while
if self.count % 100 == 0:
print('.', end='', flush=True)
if self.count % 10000 == 0:
print('\n%d/%d fixed' % (self.num_fixed, self.count))
| Update function name used in the streamtester | ## Code Before:
from __future__ import print_function, unicode_literals
from ftfy.fixes import fix_text_encoding
from ftfy.chardata import possible_encoding
class StreamTester:
"""
Take in a sequence of texts, and show the ones that will be changed by
ftfy. This will also periodically show updates, such as the proportion of
texts that changed.
"""
def __init__(self):
self.num_fixed = 0
self.count = 0
def check_ftfy(self, text):
"""
Given a single text input, check whether `ftfy.fix_text_encoding`
would change it. If so, display the change.
"""
self.count += 1
if not possible_encoding(text, 'ascii'):
fixed = fix_text_encoding(text)
if text != fixed:
# possibly filter common bots before printing
print(u'\nText:\t{text}\nFixed:\t{fixed}\n'.format(
text=text, fixed=fixed
))
self.num_fixed += 1
# Print status updates once in a while
if self.count % 100 == 0:
print('.', end='', flush=True)
if self.count % 10000 == 0:
print('\n%d/%d fixed' % (self.num_fixed, self.count))
## Instruction:
Update function name used in the streamtester
## Code After:
from __future__ import print_function, unicode_literals
from ftfy.fixes import fix_encoding
from ftfy.chardata import possible_encoding
class StreamTester:
"""
Take in a sequence of texts, and show the ones that will be changed by
ftfy. This will also periodically show updates, such as the proportion of
texts that changed.
"""
def __init__(self):
self.num_fixed = 0
self.count = 0
def check_ftfy(self, text):
"""
Given a single text input, check whether `ftfy.fix_text_encoding`
would change it. If so, display the change.
"""
self.count += 1
if not possible_encoding(text, 'ascii'):
fixed = fix_encoding(text)
if text != fixed:
# possibly filter common bots before printing
print(u'\nText:\t{text}\nFixed:\t{fixed}\n'.format(
text=text, fixed=fixed
))
self.num_fixed += 1
# Print status updates once in a while
if self.count % 100 == 0:
print('.', end='', flush=True)
if self.count % 10000 == 0:
print('\n%d/%d fixed' % (self.num_fixed, self.count))
| # ... existing code ...
from __future__ import print_function, unicode_literals
from ftfy.fixes import fix_encoding
from ftfy.chardata import possible_encoding
# ... modified code ...
if not possible_encoding(text, 'ascii'):
fixed = fix_encoding(text)
if text != fixed:
# ... rest of the code ... |
4f4ba39bf2d270ef1cb34afe1a5ebe7816d448b7 | manage.py | manage.py | from werkzeug import script
def make_app():
from cadorsfeed.application import CadorsFeed
return CadorsFeed()
def make_shell():
from cadorsfeed import utils
application = make_app()
return locals()
action_runserver = script.make_runserver(make_app, use_reloader=True)
action_shell = script.make_shell(make_shell)
script.run()
| from werkzeug import script
def make_app():
from cadorsfeed.application import CadorsFeed
return CadorsFeed()
def make_shell():
from cadorsfeed import utils
application = make_app()
return locals()
action_runserver = script.make_runserver(make_app, use_reloader=True, hostname='')
action_shell = script.make_shell(make_shell)
script.run()
| Set hostname to '' so the server binds to all interfaces. | Set hostname to '' so the server binds to all interfaces.
| Python | mit | kurtraschke/cadors-parse,kurtraschke/cadors-parse | from werkzeug import script
def make_app():
from cadorsfeed.application import CadorsFeed
return CadorsFeed()
def make_shell():
from cadorsfeed import utils
application = make_app()
return locals()
- action_runserver = script.make_runserver(make_app, use_reloader=True)
+ action_runserver = script.make_runserver(make_app, use_reloader=True, hostname='')
action_shell = script.make_shell(make_shell)
script.run()
| Set hostname to '' so the server binds to all interfaces. | ## Code Before:
from werkzeug import script
def make_app():
from cadorsfeed.application import CadorsFeed
return CadorsFeed()
def make_shell():
from cadorsfeed import utils
application = make_app()
return locals()
action_runserver = script.make_runserver(make_app, use_reloader=True)
action_shell = script.make_shell(make_shell)
script.run()
## Instruction:
Set hostname to '' so the server binds to all interfaces.
## Code After:
from werkzeug import script
def make_app():
from cadorsfeed.application import CadorsFeed
return CadorsFeed()
def make_shell():
from cadorsfeed import utils
application = make_app()
return locals()
action_runserver = script.make_runserver(make_app, use_reloader=True, hostname='')
action_shell = script.make_shell(make_shell)
script.run()
| # ... existing code ...
action_runserver = script.make_runserver(make_app, use_reloader=True, hostname='')
action_shell = script.make_shell(make_shell)
# ... rest of the code ... |
f525d04e978c35132db6ff77f455cf22b486482f | mod/httpserver.py | mod/httpserver.py | """wrap SimpleHTTPServer and prevent Ctrl-C stack trace output"""
import SimpleHTTPServer
import SocketServer
import log
try :
log.colored(log.GREEN, 'serving on http://localhost:8000 (Ctrl-C to quit)')
httpd = SocketServer.TCPServer(('localhost', 8000), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.serve_forever()
except KeyboardInterrupt:
log.colored(log.GREEN, '\nhttp server stopped')
exit(0)
| """wrap SimpleHTTPServer and prevent Ctrl-C stack trace output"""
import SimpleHTTPServer
import SocketServer
import log
try :
log.colored(log.GREEN, 'serving on http://localhost:8000 (Ctrl-C to quit)')
SocketServer.TCPServer.allow_reuse_address = True
httpd = SocketServer.TCPServer(('localhost', 8000), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.serve_forever()
except KeyboardInterrupt:
httpd.shutdown()
httpd.server_close()
log.colored(log.GREEN, '\nhttp server stopped')
exit(0)
| Allow resuse-addr at http server start | Allow resuse-addr at http server start
| Python | mit | floooh/fips,floooh/fips,michaKFromParis/fips,floooh/fips,michaKFromParis/fips,anthraxx/fips,mgerhardy/fips,anthraxx/fips,mgerhardy/fips,code-disaster/fips,code-disaster/fips | """wrap SimpleHTTPServer and prevent Ctrl-C stack trace output"""
import SimpleHTTPServer
import SocketServer
import log
try :
log.colored(log.GREEN, 'serving on http://localhost:8000 (Ctrl-C to quit)')
+ SocketServer.TCPServer.allow_reuse_address = True
httpd = SocketServer.TCPServer(('localhost', 8000), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.serve_forever()
except KeyboardInterrupt:
+ httpd.shutdown()
+ httpd.server_close()
log.colored(log.GREEN, '\nhttp server stopped')
exit(0)
| Allow resuse-addr at http server start | ## Code Before:
"""wrap SimpleHTTPServer and prevent Ctrl-C stack trace output"""
import SimpleHTTPServer
import SocketServer
import log
try :
log.colored(log.GREEN, 'serving on http://localhost:8000 (Ctrl-C to quit)')
httpd = SocketServer.TCPServer(('localhost', 8000), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.serve_forever()
except KeyboardInterrupt:
log.colored(log.GREEN, '\nhttp server stopped')
exit(0)
## Instruction:
Allow resuse-addr at http server start
## Code After:
"""wrap SimpleHTTPServer and prevent Ctrl-C stack trace output"""
import SimpleHTTPServer
import SocketServer
import log
try :
log.colored(log.GREEN, 'serving on http://localhost:8000 (Ctrl-C to quit)')
SocketServer.TCPServer.allow_reuse_address = True
httpd = SocketServer.TCPServer(('localhost', 8000), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.serve_forever()
except KeyboardInterrupt:
httpd.shutdown()
httpd.server_close()
log.colored(log.GREEN, '\nhttp server stopped')
exit(0)
| ...
log.colored(log.GREEN, 'serving on http://localhost:8000 (Ctrl-C to quit)')
SocketServer.TCPServer.allow_reuse_address = True
httpd = SocketServer.TCPServer(('localhost', 8000), SimpleHTTPServer.SimpleHTTPRequestHandler)
...
except KeyboardInterrupt:
httpd.shutdown()
httpd.server_close()
log.colored(log.GREEN, '\nhttp server stopped')
... |
39c777d6fc5555534628113190bb543c6225c07e | uncurl/bin.py | uncurl/bin.py | from __future__ import print_function
import sys
from .api import parse
def main():
result = parse(sys.argv[1])
print(result)
| from __future__ import print_function
import sys
from .api import parse
def main():
if sys.stdin.isatty():
result = parse(sys.argv[1])
else:
result = parse(sys.stdin.read())
print(result)
| Read from stdin if available. | Read from stdin if available.
| Python | apache-2.0 | weinerjm/uncurl,spulec/uncurl | from __future__ import print_function
import sys
from .api import parse
def main():
+ if sys.stdin.isatty():
- result = parse(sys.argv[1])
+ result = parse(sys.argv[1])
+ else:
+ result = parse(sys.stdin.read())
print(result)
| Read from stdin if available. | ## Code Before:
from __future__ import print_function
import sys
from .api import parse
def main():
result = parse(sys.argv[1])
print(result)
## Instruction:
Read from stdin if available.
## Code After:
from __future__ import print_function
import sys
from .api import parse
def main():
if sys.stdin.isatty():
result = parse(sys.argv[1])
else:
result = parse(sys.stdin.read())
print(result)
| # ... existing code ...
def main():
if sys.stdin.isatty():
result = parse(sys.argv[1])
else:
result = parse(sys.stdin.read())
print(result)
# ... rest of the code ... |
8d831e4834b61c04b3f5f2d8a812095eea8c022f | personDb.py | personDb.py | import pickle
class PersonDb(object):
def __init__(self, dbName, autoload = True):
self.dbName = dbName
self.db = None
if autoload:
self.setup()
def setup(self):
self.db = PersonDb.load(self.dbName)
self.getGroups()
def getGroups(self):
tmp = set()
for person in self.db:
for group in person.group:
tmp.append(person)
self.groups = tmp
def save(data, fileName = 'database'):
filen = PersonDb.fileExtension(fileName)
with open(filen,"wb") as pickleOut:
pickle.dump(data, pickleOut)
def load(fileName = 'database'):
filen = PersonDb.fileExtension(fileName)
with open(filen, "rb") as pickleIn:
data = pickle.load(pickleIn)
return data
def fileExtension(fileName):
result = fileName.strip()
if '.json' not in result:
result += '.json'
return result
| import pickle
import os
class PersonDb(object):
def __init__(self, dbName, autoload = True):
self.dbName = dbName
self.db = None
if autoload:
self.setup()
def setup(self):
self.db = PersonDb.load(self.dbName)
self.getGroups()
def getGroups(self):
tmp = set()
for person in self.db:
for group in person.group:
tmp.append(person)
self.groups = tmp
def save(data, fileName = 'database'):
filen = PersonDb.fileExtension(fileName)
with open(filen,"wb") as pickleOut:
pickle.dump(data, pickleOut)
def load(fileName = 'database'):
filen = PersonDb.fileExtension(fileName)
if os.path.exists(filen):
with open(filen, "rb") as pickleIn:
data = pickle.load(pickleIn)
return data
else:
return []
def fileExtension(fileName):
result = fileName.strip()
if '.json' not in result:
result += '.json'
return result
| Add handling of not present file. | Add handling of not present file.
Signed-off-by: Matej Dujava <03ce64f61b3ea1fda633fb2a103b989e3272d16b@gmail.com>
| Python | mit | matejd11/birthdayNotify | import pickle
+ import os
class PersonDb(object):
def __init__(self, dbName, autoload = True):
self.dbName = dbName
self.db = None
if autoload:
self.setup()
def setup(self):
self.db = PersonDb.load(self.dbName)
self.getGroups()
def getGroups(self):
tmp = set()
for person in self.db:
for group in person.group:
tmp.append(person)
self.groups = tmp
def save(data, fileName = 'database'):
filen = PersonDb.fileExtension(fileName)
with open(filen,"wb") as pickleOut:
pickle.dump(data, pickleOut)
def load(fileName = 'database'):
filen = PersonDb.fileExtension(fileName)
+ if os.path.exists(filen):
- with open(filen, "rb") as pickleIn:
+ with open(filen, "rb") as pickleIn:
- data = pickle.load(pickleIn)
+ data = pickle.load(pickleIn)
- return data
+ return data
+ else:
+ return []
def fileExtension(fileName):
result = fileName.strip()
if '.json' not in result:
result += '.json'
return result
| Add handling of not present file. | ## Code Before:
import pickle
class PersonDb(object):
def __init__(self, dbName, autoload = True):
self.dbName = dbName
self.db = None
if autoload:
self.setup()
def setup(self):
self.db = PersonDb.load(self.dbName)
self.getGroups()
def getGroups(self):
tmp = set()
for person in self.db:
for group in person.group:
tmp.append(person)
self.groups = tmp
def save(data, fileName = 'database'):
filen = PersonDb.fileExtension(fileName)
with open(filen,"wb") as pickleOut:
pickle.dump(data, pickleOut)
def load(fileName = 'database'):
filen = PersonDb.fileExtension(fileName)
with open(filen, "rb") as pickleIn:
data = pickle.load(pickleIn)
return data
def fileExtension(fileName):
result = fileName.strip()
if '.json' not in result:
result += '.json'
return result
## Instruction:
Add handling of not present file.
## Code After:
import pickle
import os
class PersonDb(object):
def __init__(self, dbName, autoload = True):
self.dbName = dbName
self.db = None
if autoload:
self.setup()
def setup(self):
self.db = PersonDb.load(self.dbName)
self.getGroups()
def getGroups(self):
tmp = set()
for person in self.db:
for group in person.group:
tmp.append(person)
self.groups = tmp
def save(data, fileName = 'database'):
filen = PersonDb.fileExtension(fileName)
with open(filen,"wb") as pickleOut:
pickle.dump(data, pickleOut)
def load(fileName = 'database'):
filen = PersonDb.fileExtension(fileName)
if os.path.exists(filen):
with open(filen, "rb") as pickleIn:
data = pickle.load(pickleIn)
return data
else:
return []
def fileExtension(fileName):
result = fileName.strip()
if '.json' not in result:
result += '.json'
return result
| # ... existing code ...
import pickle
import os
# ... modified code ...
filen = PersonDb.fileExtension(fileName)
if os.path.exists(filen):
with open(filen, "rb") as pickleIn:
data = pickle.load(pickleIn)
return data
else:
return []
# ... rest of the code ... |
2fc3ee4edc4b7a1842fca369620c790244000f11 | flask_apidoc/commands.py | flask_apidoc/commands.py |
try:
import flask_script
except ImportError:
raise ImportError('Missing flask-script library (pip install flask-script)')
import subprocess
from flask_script import Command
class GenerateApiDoc(Command):
def __init__(self, input_path=None, output_path=None, template_path=None):
super().__init__()
self.input_path = input_path
self.output_path = output_path
self.template_path = template_path
def run(self):
cmd = ['apidoc']
if self.input_path:
cmd.append('--input')
cmd.append(self.input_path)
if self.output_path:
cmd.append('--output')
cmd.append(self.output_path)
if self.template_path:
cmd.append('--template')
cmd.append(self.template_path)
return subprocess.call(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
|
try:
import flask_script
except ImportError:
raise ImportError('Missing flask-script library (pip install flask-script)')
import subprocess
from flask_script import Command
class GenerateApiDoc(Command):
def __init__(self, input_path=None, output_path=None, template_path=None):
super().__init__()
self.input_path = input_path
self.output_path = output_path or 'static/docs'
self.template_path = template_path
def run(self):
cmd = ['apidoc']
if self.input_path:
cmd.append('--input')
cmd.append(self.input_path)
if self.output_path:
cmd.append('--output')
cmd.append(self.output_path)
if self.template_path:
cmd.append('--template')
cmd.append(self.template_path)
return subprocess.call(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
| Set static/docs as the default folder to generate the apidoc's files | Set static/docs as the default folder to generate the apidoc's files
| Python | mit | viniciuschiele/flask-apidoc |
try:
import flask_script
except ImportError:
raise ImportError('Missing flask-script library (pip install flask-script)')
import subprocess
from flask_script import Command
class GenerateApiDoc(Command):
def __init__(self, input_path=None, output_path=None, template_path=None):
super().__init__()
self.input_path = input_path
- self.output_path = output_path
+ self.output_path = output_path or 'static/docs'
self.template_path = template_path
def run(self):
cmd = ['apidoc']
if self.input_path:
cmd.append('--input')
cmd.append(self.input_path)
if self.output_path:
cmd.append('--output')
cmd.append(self.output_path)
if self.template_path:
cmd.append('--template')
cmd.append(self.template_path)
return subprocess.call(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
| Set static/docs as the default folder to generate the apidoc's files | ## Code Before:
try:
import flask_script
except ImportError:
raise ImportError('Missing flask-script library (pip install flask-script)')
import subprocess
from flask_script import Command
class GenerateApiDoc(Command):
def __init__(self, input_path=None, output_path=None, template_path=None):
super().__init__()
self.input_path = input_path
self.output_path = output_path
self.template_path = template_path
def run(self):
cmd = ['apidoc']
if self.input_path:
cmd.append('--input')
cmd.append(self.input_path)
if self.output_path:
cmd.append('--output')
cmd.append(self.output_path)
if self.template_path:
cmd.append('--template')
cmd.append(self.template_path)
return subprocess.call(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
## Instruction:
Set static/docs as the default folder to generate the apidoc's files
## Code After:
try:
import flask_script
except ImportError:
raise ImportError('Missing flask-script library (pip install flask-script)')
import subprocess
from flask_script import Command
class GenerateApiDoc(Command):
def __init__(self, input_path=None, output_path=None, template_path=None):
super().__init__()
self.input_path = input_path
self.output_path = output_path or 'static/docs'
self.template_path = template_path
def run(self):
cmd = ['apidoc']
if self.input_path:
cmd.append('--input')
cmd.append(self.input_path)
if self.output_path:
cmd.append('--output')
cmd.append(self.output_path)
if self.template_path:
cmd.append('--template')
cmd.append(self.template_path)
return subprocess.call(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
| # ... existing code ...
self.input_path = input_path
self.output_path = output_path or 'static/docs'
self.template_path = template_path
# ... rest of the code ... |
c3a184a188d18f87bad2d7f34a2dfd3a7cca4827 | signac/common/errors.py | signac/common/errors.py |
class Error(Exception):
pass
class ConfigError(Error, RuntimeError):
pass
class AuthenticationError(Error, RuntimeError):
def __str__(self):
if len(self.args) > 0:
return "Failed to authenticate with host '{}'.".format(
self.args[0])
else:
return "Failed to authenticate with host."
class ExportError(Error, RuntimeError):
pass
class FileNotFoundError(Error, FileNotFoundError):
pass
class FetchError(FileNotFoundError):
pass
| from . import six
class Error(Exception):
pass
class ConfigError(Error, RuntimeError):
pass
class AuthenticationError(Error, RuntimeError):
def __str__(self):
if len(self.args) > 0:
return "Failed to authenticate with host '{}'.".format(
self.args[0])
else:
return "Failed to authenticate with host."
class ExportError(Error, RuntimeError):
pass
if six.PY2:
class FileNotFoundError(Error, IOError):
pass
else:
class FileNotFoundError(Error, FileNotFoundError):
pass
class FetchError(FileNotFoundError):
pass
| Fix py27 issue in error module. | Fix py27 issue in error module.
Inherit signac internal FileNotFoundError class from IOError
instead of FileNotFoundError in python 2.7.
| Python | bsd-3-clause | csadorf/signac,csadorf/signac | -
+ from . import six
class Error(Exception):
pass
class ConfigError(Error, RuntimeError):
pass
class AuthenticationError(Error, RuntimeError):
def __str__(self):
if len(self.args) > 0:
return "Failed to authenticate with host '{}'.".format(
self.args[0])
else:
return "Failed to authenticate with host."
class ExportError(Error, RuntimeError):
pass
+ if six.PY2:
+ class FileNotFoundError(Error, IOError):
+ pass
+ else:
- class FileNotFoundError(Error, FileNotFoundError):
+ class FileNotFoundError(Error, FileNotFoundError):
- pass
+ pass
class FetchError(FileNotFoundError):
pass
| Fix py27 issue in error module. | ## Code Before:
class Error(Exception):
pass
class ConfigError(Error, RuntimeError):
pass
class AuthenticationError(Error, RuntimeError):
def __str__(self):
if len(self.args) > 0:
return "Failed to authenticate with host '{}'.".format(
self.args[0])
else:
return "Failed to authenticate with host."
class ExportError(Error, RuntimeError):
pass
class FileNotFoundError(Error, FileNotFoundError):
pass
class FetchError(FileNotFoundError):
pass
## Instruction:
Fix py27 issue in error module.
## Code After:
from . import six
class Error(Exception):
pass
class ConfigError(Error, RuntimeError):
pass
class AuthenticationError(Error, RuntimeError):
def __str__(self):
if len(self.args) > 0:
return "Failed to authenticate with host '{}'.".format(
self.args[0])
else:
return "Failed to authenticate with host."
class ExportError(Error, RuntimeError):
pass
if six.PY2:
class FileNotFoundError(Error, IOError):
pass
else:
class FileNotFoundError(Error, FileNotFoundError):
pass
class FetchError(FileNotFoundError):
pass
| # ... existing code ...
from . import six
# ... modified code ...
if six.PY2:
class FileNotFoundError(Error, IOError):
pass
else:
class FileNotFoundError(Error, FileNotFoundError):
pass
# ... rest of the code ... |
8a522bc92bbf5bee8bc32a0cc332dc77fa86fcd6 | drcontroller/http_server.py | drcontroller/http_server.py | import eventlet
import os
import commands
from eventlet import wsgi
from paste.deploy import loadapp
def main():
conf = "conf/api-paste.ini"
appname = "main"
commands.getoutput('mkdir -p ../logs')
app = loadapp("config:%s" % os.path.abspath(conf), appname)
wsgi.server(eventlet.listen(('', 80)), app)
if __name__ == '__main__':
main()
| import eventlet
import os
import commands
from eventlet import wsgi
from paste.deploy import loadapp
# Monkey patch socket, time, select, threads
eventlet.patcher.monkey_patch(all=False, socket=True, time=True,
select=True, thread=True, os=True)
def main():
conf = "conf/api-paste.ini"
appname = "main"
commands.getoutput('mkdir -p ../logs')
app = loadapp("config:%s" % os.path.abspath(conf), appname)
wsgi.server(eventlet.listen(('', 80)), app)
if __name__ == '__main__':
main()
| Update http server to un-blocking | Update http server to un-blocking
| Python | apache-2.0 | fs714/drcontroller | import eventlet
import os
import commands
from eventlet import wsgi
from paste.deploy import loadapp
+
+
+ # Monkey patch socket, time, select, threads
+ eventlet.patcher.monkey_patch(all=False, socket=True, time=True,
+ select=True, thread=True, os=True)
def main():
conf = "conf/api-paste.ini"
appname = "main"
commands.getoutput('mkdir -p ../logs')
app = loadapp("config:%s" % os.path.abspath(conf), appname)
wsgi.server(eventlet.listen(('', 80)), app)
if __name__ == '__main__':
main()
| Update http server to un-blocking | ## Code Before:
import eventlet
import os
import commands
from eventlet import wsgi
from paste.deploy import loadapp
def main():
conf = "conf/api-paste.ini"
appname = "main"
commands.getoutput('mkdir -p ../logs')
app = loadapp("config:%s" % os.path.abspath(conf), appname)
wsgi.server(eventlet.listen(('', 80)), app)
if __name__ == '__main__':
main()
## Instruction:
Update http server to un-blocking
## Code After:
import eventlet
import os
import commands
from eventlet import wsgi
from paste.deploy import loadapp
# Monkey patch socket, time, select, threads
eventlet.patcher.monkey_patch(all=False, socket=True, time=True,
select=True, thread=True, os=True)
def main():
conf = "conf/api-paste.ini"
appname = "main"
commands.getoutput('mkdir -p ../logs')
app = loadapp("config:%s" % os.path.abspath(conf), appname)
wsgi.server(eventlet.listen(('', 80)), app)
if __name__ == '__main__':
main()
| # ... existing code ...
from paste.deploy import loadapp
# Monkey patch socket, time, select, threads
eventlet.patcher.monkey_patch(all=False, socket=True, time=True,
select=True, thread=True, os=True)
# ... rest of the code ... |
0b1813bef37819209ed9fb5b06eb7495d0e0e1fb | netmiko/arista/arista_ssh.py | netmiko/arista/arista_ssh.py | from netmiko.ssh_connection import SSHConnection
class AristaSSH(SSHConnection):
pass
| import time
from netmiko.ssh_connection import SSHConnection
class AristaSSH(SSHConnection):
def special_login_handler(self, delay_factor=1):
"""
Arista adds a "Last login: " message that doesn't always have sufficient time to be handled
"""
time.sleep(3 * delay_factor)
self.clear_buffer()
| Improve Arista reliability on slow login | Improve Arista reliability on slow login
| Python | mit | fooelisa/netmiko,ktbyers/netmiko,shamanu4/netmiko,ktbyers/netmiko,shamanu4/netmiko,shsingh/netmiko,shsingh/netmiko,isidroamv/netmiko,fooelisa/netmiko,isidroamv/netmiko | + import time
from netmiko.ssh_connection import SSHConnection
class AristaSSH(SSHConnection):
- pass
+ def special_login_handler(self, delay_factor=1):
+ """
+ Arista adds a "Last login: " message that doesn't always have sufficient time to be handled
+ """
+ time.sleep(3 * delay_factor)
+ self.clear_buffer()
| Improve Arista reliability on slow login | ## Code Before:
from netmiko.ssh_connection import SSHConnection
class AristaSSH(SSHConnection):
pass
## Instruction:
Improve Arista reliability on slow login
## Code After:
import time
from netmiko.ssh_connection import SSHConnection
class AristaSSH(SSHConnection):
def special_login_handler(self, delay_factor=1):
"""
Arista adds a "Last login: " message that doesn't always have sufficient time to be handled
"""
time.sleep(3 * delay_factor)
self.clear_buffer()
| // ... existing code ...
import time
from netmiko.ssh_connection import SSHConnection
// ... modified code ...
class AristaSSH(SSHConnection):
def special_login_handler(self, delay_factor=1):
"""
Arista adds a "Last login: " message that doesn't always have sufficient time to be handled
"""
time.sleep(3 * delay_factor)
self.clear_buffer()
// ... rest of the code ... |
095d77b74a3bfad6d97387a860ac67f82f31c478 | test/conftest.py | test/conftest.py | import pytest
def pytest_addoption(parser):
parser.addoption("--travis", action="store_true", default=False,
help="Only run tests marked for Travis")
def pytest_configure(config):
config.addinivalue_line("markers",
"not_travis: Mark a test that should not be run on Travis")
def pytest_runtest_setup(item):
not_travis = item.get_marker("not_travis")
if not_travis is not None and item.config.getoption("--travis"):
pytest.skip("Skipping test marked not for Travis")
| import pytest
def pytest_addoption(parser):
parser.addoption("--travis", action="store_true", default=False,
help="Only run tests marked for Travis")
def pytest_configure(config):
config.addinivalue_line("markers",
"not_travis: Mark a test that should not be run on Travis")
def pytest_runtest_setup(item):
not_travis = item.get_marker("not_travis")
if not_travis is not None and item.config.getoption("--travis"):
pytest.skip("Skipping test marked not for Travis")
# Print a progress "." once a minute when running in travis mode
# This is an attempt to stop travis timing the builds out due to lack
# of output.
progress_process = None
def pytest_configure(config):
global progress_process
if config.getoption("--travis") and progress_process is None:
import multiprocessing
import py
terminal = py.io.TerminalWriter()
def writer():
import time
while True:
terminal.write("still alive\n")
time.sleep(60)
progress_process = multiprocessing.Process(target=writer)
progress_process.daemon = True
progress_process.start()
def pytest_unconfigure(config):
global progress_process
if config.getoption("--travis") and progress_process is not None:
progress_process.terminate()
| Print "still alive" progress when testing on travis | test: Print "still alive" progress when testing on travis
| Python | mit | tkarna/cofs | import pytest
def pytest_addoption(parser):
parser.addoption("--travis", action="store_true", default=False,
help="Only run tests marked for Travis")
def pytest_configure(config):
config.addinivalue_line("markers",
"not_travis: Mark a test that should not be run on Travis")
def pytest_runtest_setup(item):
not_travis = item.get_marker("not_travis")
if not_travis is not None and item.config.getoption("--travis"):
pytest.skip("Skipping test marked not for Travis")
+
+ # Print a progress "." once a minute when running in travis mode
+ # This is an attempt to stop travis timing the builds out due to lack
+ # of output.
+ progress_process = None
+
+
+ def pytest_configure(config):
+ global progress_process
+ if config.getoption("--travis") and progress_process is None:
+ import multiprocessing
+ import py
+ terminal = py.io.TerminalWriter()
+ def writer():
+ import time
+ while True:
+ terminal.write("still alive\n")
+ time.sleep(60)
+ progress_process = multiprocessing.Process(target=writer)
+ progress_process.daemon = True
+ progress_process.start()
+
+
+ def pytest_unconfigure(config):
+ global progress_process
+ if config.getoption("--travis") and progress_process is not None:
+ progress_process.terminate()
+ | Print "still alive" progress when testing on travis | ## Code Before:
import pytest
def pytest_addoption(parser):
parser.addoption("--travis", action="store_true", default=False,
help="Only run tests marked for Travis")
def pytest_configure(config):
config.addinivalue_line("markers",
"not_travis: Mark a test that should not be run on Travis")
def pytest_runtest_setup(item):
not_travis = item.get_marker("not_travis")
if not_travis is not None and item.config.getoption("--travis"):
pytest.skip("Skipping test marked not for Travis")
## Instruction:
Print "still alive" progress when testing on travis
## Code After:
import pytest
def pytest_addoption(parser):
parser.addoption("--travis", action="store_true", default=False,
help="Only run tests marked for Travis")
def pytest_configure(config):
config.addinivalue_line("markers",
"not_travis: Mark a test that should not be run on Travis")
def pytest_runtest_setup(item):
not_travis = item.get_marker("not_travis")
if not_travis is not None and item.config.getoption("--travis"):
pytest.skip("Skipping test marked not for Travis")
# Print a progress "." once a minute when running in travis mode
# This is an attempt to stop travis timing the builds out due to lack
# of output.
progress_process = None
def pytest_configure(config):
global progress_process
if config.getoption("--travis") and progress_process is None:
import multiprocessing
import py
terminal = py.io.TerminalWriter()
def writer():
import time
while True:
terminal.write("still alive\n")
time.sleep(60)
progress_process = multiprocessing.Process(target=writer)
progress_process.daemon = True
progress_process.start()
def pytest_unconfigure(config):
global progress_process
if config.getoption("--travis") and progress_process is not None:
progress_process.terminate()
| ...
pytest.skip("Skipping test marked not for Travis")
# Print a progress "." once a minute when running in travis mode
# This is an attempt to stop travis timing the builds out due to lack
# of output.
progress_process = None
def pytest_configure(config):
global progress_process
if config.getoption("--travis") and progress_process is None:
import multiprocessing
import py
terminal = py.io.TerminalWriter()
def writer():
import time
while True:
terminal.write("still alive\n")
time.sleep(60)
progress_process = multiprocessing.Process(target=writer)
progress_process.daemon = True
progress_process.start()
def pytest_unconfigure(config):
global progress_process
if config.getoption("--travis") and progress_process is not None:
progress_process.terminate()
... |
a81c5bf24ab0271c60ed1db97d93c7d2e5ec6234 | cutplanner/planner.py | cutplanner/planner.py | import collections
# simple structure to keep track of a specific piece
Piece = collections.namedtuple('Piece', 'id, length')
class Planner(object):
def __init__(self, sizes, needed, loss=0.25):
self.stock = []
self.stock_sizes = sorted(sizes)
self.pieces_needed = needed
self.cut_loss = loss
self.cur_stock = None
def get_largest_stock(self):
return self.stock_sizes[-1]
def cut_piece(self, piece):
""" Record the cut for the given piece """
cur_stock.cut(piece, self.cut_loss)
| import collections
# simple structure to keep track of a specific piece
Piece = collections.namedtuple('Piece', 'id, length')
class Planner(object):
def __init__(self, sizes, needed, loss=0.25):
self.stock = []
self.stock_sizes = sorted(sizes)
self.pieces_needed = needed
self.cut_loss = loss
self.cur_stock = None
@property
def largest_stock(self):
return self.stock_sizes[-1]
def cut_piece(self, piece):
""" Record the cut for the given piece """
cur_stock.cut(piece, self.cut_loss)
| Make largest stock a property | Make largest stock a property
| Python | mit | alanc10n/py-cutplanner | import collections
# simple structure to keep track of a specific piece
Piece = collections.namedtuple('Piece', 'id, length')
class Planner(object):
def __init__(self, sizes, needed, loss=0.25):
self.stock = []
self.stock_sizes = sorted(sizes)
self.pieces_needed = needed
self.cut_loss = loss
self.cur_stock = None
+ @property
- def get_largest_stock(self):
+ def largest_stock(self):
return self.stock_sizes[-1]
def cut_piece(self, piece):
""" Record the cut for the given piece """
cur_stock.cut(piece, self.cut_loss)
| Make largest stock a property | ## Code Before:
import collections
# simple structure to keep track of a specific piece
Piece = collections.namedtuple('Piece', 'id, length')
class Planner(object):
def __init__(self, sizes, needed, loss=0.25):
self.stock = []
self.stock_sizes = sorted(sizes)
self.pieces_needed = needed
self.cut_loss = loss
self.cur_stock = None
def get_largest_stock(self):
return self.stock_sizes[-1]
def cut_piece(self, piece):
""" Record the cut for the given piece """
cur_stock.cut(piece, self.cut_loss)
## Instruction:
Make largest stock a property
## Code After:
import collections
# simple structure to keep track of a specific piece
Piece = collections.namedtuple('Piece', 'id, length')
class Planner(object):
def __init__(self, sizes, needed, loss=0.25):
self.stock = []
self.stock_sizes = sorted(sizes)
self.pieces_needed = needed
self.cut_loss = loss
self.cur_stock = None
@property
def largest_stock(self):
return self.stock_sizes[-1]
def cut_piece(self, piece):
""" Record the cut for the given piece """
cur_stock.cut(piece, self.cut_loss)
| # ... existing code ...
@property
def largest_stock(self):
return self.stock_sizes[-1]
# ... rest of the code ... |
bad65df528da18293d38b0f50dbbb16390af465e | sphinx/source/docs/user_guide/source_examples/plotting_label.py | sphinx/source/docs/user_guide/source_examples/plotting_label.py | from bokeh.plotting import figure, show, output_file
from bokeh.models import ColumnDataSource, Range1d, Label
output_file("label.html", title="label.py example")
source = ColumnDataSource(data=dict(height=[66, 71, 72, 68, 58, 62],
weight=[165, 189, 220, 141, 260, 174],
names=['Mark', 'Amir', 'Matt', 'Greg',
'Owen', 'Juan']))
p = figure(title='Dist. of 10th Grade Students at Lee High',
x_range=Range1d(140, 275))
p.scatter(x='weight', y='height', size=8, source=source)
p.xaxis[0].axis_label = 'Weight (lbs)'
p.yaxis[0].axis_label = 'Height (in)'
label = Label(x='weight', y='height', text='names', level='glyph',
x_offset=5, y_offset=-5, source=source)
p.add_annotation(label)
show(p)
| from bokeh.plotting import figure, show, output_file
from bokeh.models import ColumnDataSource, Range1d, Label
output_file("label.html", title="label.py example")
source = ColumnDataSource(data=dict(height=[66, 71, 72, 68, 58, 62],
weight=[165, 189, 220, 141, 260, 174],
names=['Mark', 'Amir', 'Matt', 'Greg',
'Owen', 'Juan']))
p = figure(title='Dist. of 10th Grade Students at Lee High',
x_range=Range1d(140, 275))
p.scatter(x='weight', y='height', size=8, source=source)
p.xaxis[0].axis_label = 'Weight (lbs)'
p.yaxis[0].axis_label = 'Height (in)'
labels = Label(x='weight', y='height', text='names', level='glyph',
x_offset=5, y_offset=-5, source=source, render_mode='canvas')
citation = Label(x=70, y=70, x_units='screen', y_units='screen',
text=['Collected by Luke C. 2016-04-01'], render_mode='css',
border_line_color='black', border_line_alpha=1.0,
background_fill_color='white', background_fill_alpha=1.0)
p.add_annotation(labels)
p.add_annotation(citation)
show(p)
| Include example of css render_mode | Include example of css render_mode
| Python | bsd-3-clause | clairetang6/bokeh,Karel-van-de-Plassche/bokeh,mindriot101/bokeh,aiguofer/bokeh,rs2/bokeh,Karel-van-de-Plassche/bokeh,KasperPRasmussen/bokeh,dennisobrien/bokeh,draperjames/bokeh,bokeh/bokeh,quasiben/bokeh,KasperPRasmussen/bokeh,philippjfr/bokeh,stonebig/bokeh,justacec/bokeh,KasperPRasmussen/bokeh,phobson/bokeh,phobson/bokeh,jakirkham/bokeh,rs2/bokeh,ericmjl/bokeh,jakirkham/bokeh,bokeh/bokeh,phobson/bokeh,bokeh/bokeh,aavanian/bokeh,dennisobrien/bokeh,rs2/bokeh,timsnyder/bokeh,ptitjano/bokeh,schoolie/bokeh,DuCorey/bokeh,dennisobrien/bokeh,quasiben/bokeh,mindriot101/bokeh,draperjames/bokeh,stonebig/bokeh,dennisobrien/bokeh,philippjfr/bokeh,rs2/bokeh,Karel-van-de-Plassche/bokeh,rs2/bokeh,azjps/bokeh,ptitjano/bokeh,jakirkham/bokeh,aavanian/bokeh,mindriot101/bokeh,KasperPRasmussen/bokeh,percyfal/bokeh,clairetang6/bokeh,ericmjl/bokeh,philippjfr/bokeh,clairetang6/bokeh,ericmjl/bokeh,mindriot101/bokeh,aiguofer/bokeh,draperjames/bokeh,bokeh/bokeh,bokeh/bokeh,Karel-van-de-Plassche/bokeh,philippjfr/bokeh,ericmjl/bokeh,phobson/bokeh,aavanian/bokeh,jakirkham/bokeh,timsnyder/bokeh,azjps/bokeh,schoolie/bokeh,DuCorey/bokeh,azjps/bokeh,quasiben/bokeh,DuCorey/bokeh,justacec/bokeh,draperjames/bokeh,justacec/bokeh,jakirkham/bokeh,schoolie/bokeh,justacec/bokeh,stonebig/bokeh,philippjfr/bokeh,Karel-van-de-Plassche/bokeh,aiguofer/bokeh,aavanian/bokeh,ptitjano/bokeh,ptitjano/bokeh,DuCorey/bokeh,azjps/bokeh,percyfal/bokeh,timsnyder/bokeh,aiguofer/bokeh,KasperPRasmussen/bokeh,timsnyder/bokeh,schoolie/bokeh,ptitjano/bokeh,stonebig/bokeh,phobson/bokeh,timsnyder/bokeh,dennisobrien/bokeh,draperjames/bokeh,schoolie/bokeh,DuCorey/bokeh,azjps/bokeh,percyfal/bokeh,percyfal/bokeh,clairetang6/bokeh,percyfal/bokeh,ericmjl/bokeh,aiguofer/bokeh,aavanian/bokeh | from bokeh.plotting import figure, show, output_file
from bokeh.models import ColumnDataSource, Range1d, Label
output_file("label.html", title="label.py example")
source = ColumnDataSource(data=dict(height=[66, 71, 72, 68, 58, 62],
weight=[165, 189, 220, 141, 260, 174],
names=['Mark', 'Amir', 'Matt', 'Greg',
'Owen', 'Juan']))
p = figure(title='Dist. of 10th Grade Students at Lee High',
x_range=Range1d(140, 275))
p.scatter(x='weight', y='height', size=8, source=source)
p.xaxis[0].axis_label = 'Weight (lbs)'
p.yaxis[0].axis_label = 'Height (in)'
- label = Label(x='weight', y='height', text='names', level='glyph',
+ labels = Label(x='weight', y='height', text='names', level='glyph',
- x_offset=5, y_offset=-5, source=source)
+ x_offset=5, y_offset=-5, source=source, render_mode='canvas')
+
+ citation = Label(x=70, y=70, x_units='screen', y_units='screen',
+ text=['Collected by Luke C. 2016-04-01'], render_mode='css',
+ border_line_color='black', border_line_alpha=1.0,
+ background_fill_color='white', background_fill_alpha=1.0)
+
- p.add_annotation(label)
+ p.add_annotation(labels)
+ p.add_annotation(citation)
show(p)
| Include example of css render_mode | ## Code Before:
from bokeh.plotting import figure, show, output_file
from bokeh.models import ColumnDataSource, Range1d, Label
output_file("label.html", title="label.py example")
source = ColumnDataSource(data=dict(height=[66, 71, 72, 68, 58, 62],
weight=[165, 189, 220, 141, 260, 174],
names=['Mark', 'Amir', 'Matt', 'Greg',
'Owen', 'Juan']))
p = figure(title='Dist. of 10th Grade Students at Lee High',
x_range=Range1d(140, 275))
p.scatter(x='weight', y='height', size=8, source=source)
p.xaxis[0].axis_label = 'Weight (lbs)'
p.yaxis[0].axis_label = 'Height (in)'
label = Label(x='weight', y='height', text='names', level='glyph',
x_offset=5, y_offset=-5, source=source)
p.add_annotation(label)
show(p)
## Instruction:
Include example of css render_mode
## Code After:
from bokeh.plotting import figure, show, output_file
from bokeh.models import ColumnDataSource, Range1d, Label
output_file("label.html", title="label.py example")
source = ColumnDataSource(data=dict(height=[66, 71, 72, 68, 58, 62],
weight=[165, 189, 220, 141, 260, 174],
names=['Mark', 'Amir', 'Matt', 'Greg',
'Owen', 'Juan']))
p = figure(title='Dist. of 10th Grade Students at Lee High',
x_range=Range1d(140, 275))
p.scatter(x='weight', y='height', size=8, source=source)
p.xaxis[0].axis_label = 'Weight (lbs)'
p.yaxis[0].axis_label = 'Height (in)'
labels = Label(x='weight', y='height', text='names', level='glyph',
x_offset=5, y_offset=-5, source=source, render_mode='canvas')
citation = Label(x=70, y=70, x_units='screen', y_units='screen',
text=['Collected by Luke C. 2016-04-01'], render_mode='css',
border_line_color='black', border_line_alpha=1.0,
background_fill_color='white', background_fill_alpha=1.0)
p.add_annotation(labels)
p.add_annotation(citation)
show(p)
| // ... existing code ...
labels = Label(x='weight', y='height', text='names', level='glyph',
x_offset=5, y_offset=-5, source=source, render_mode='canvas')
citation = Label(x=70, y=70, x_units='screen', y_units='screen',
text=['Collected by Luke C. 2016-04-01'], render_mode='css',
border_line_color='black', border_line_alpha=1.0,
background_fill_color='white', background_fill_alpha=1.0)
p.add_annotation(labels)
p.add_annotation(citation)
// ... rest of the code ... |
c5239c6bbb40ede4279b33b965c5ded26a78b2ae | app/tests/manual/test_twitter_api.py | app/tests/manual/test_twitter_api.py | from __future__ import absolute_import
from unittest import TestCase
from lib.twitter_api import authentication
class TestAuth(TestCase):
def test_generateAppAccessToken(self):
auth = authentication._generateAppAccessToken()
def test_getTweepyConnection(self):
auth = authentication._generateAppAccessToken()
api = authentication._getTweepyConnection(auth)
def test_getAPIConnection(self):
"""
Test that App Access token can be used to connect to Twitter API.
"""
api = authentication.getAPIConnection(userFlow=False)
def test_getAppOnlyConnection(self):
"""
Test App-only token.
"""
api = authentication.getAppOnlyConnection()
| from __future__ import absolute_import
import os
import sys
import unittest
from unittest import TestCase
# Allow imports to be done when executing this file directly.
sys.path.insert(0, os.path.abspath(os.path.join(
os.path.dirname(__file__), os.path.pardir, os.path.pardir)
))
from lib.twitter_api import authentication
class TestAuth(TestCase):
def test_generateAppAccessToken(self):
auth = authentication._generateAppAccessToken()
def test_getTweepyConnection(self):
auth = authentication._generateAppAccessToken()
api = authentication._getTweepyConnection(auth)
def test_getAPIConnection(self):
"""
Test that App Access token can be used to connect to Twitter API.
"""
api = authentication.getAPIConnection(userFlow=False)
def test_getAppOnlyConnection(self):
"""
Test App-only token.
"""
api = authentication.getAppOnlyConnection()
if __name__ == '__main__':
unittest.main()
| Update Twitter auth test to run directly | test: Update Twitter auth test to run directly
| Python | mit | MichaelCurrin/twitterverse,MichaelCurrin/twitterverse | from __future__ import absolute_import
+ import os
+ import sys
+ import unittest
from unittest import TestCase
+
+ # Allow imports to be done when executing this file directly.
+ sys.path.insert(0, os.path.abspath(os.path.join(
+ os.path.dirname(__file__), os.path.pardir, os.path.pardir)
+ ))
+
from lib.twitter_api import authentication
class TestAuth(TestCase):
def test_generateAppAccessToken(self):
auth = authentication._generateAppAccessToken()
def test_getTweepyConnection(self):
auth = authentication._generateAppAccessToken()
api = authentication._getTweepyConnection(auth)
def test_getAPIConnection(self):
"""
Test that App Access token can be used to connect to Twitter API.
"""
api = authentication.getAPIConnection(userFlow=False)
def test_getAppOnlyConnection(self):
"""
Test App-only token.
"""
api = authentication.getAppOnlyConnection()
+
+ if __name__ == '__main__':
+ unittest.main()
+ | Update Twitter auth test to run directly | ## Code Before:
from __future__ import absolute_import
from unittest import TestCase
from lib.twitter_api import authentication
class TestAuth(TestCase):
def test_generateAppAccessToken(self):
auth = authentication._generateAppAccessToken()
def test_getTweepyConnection(self):
auth = authentication._generateAppAccessToken()
api = authentication._getTweepyConnection(auth)
def test_getAPIConnection(self):
"""
Test that App Access token can be used to connect to Twitter API.
"""
api = authentication.getAPIConnection(userFlow=False)
def test_getAppOnlyConnection(self):
"""
Test App-only token.
"""
api = authentication.getAppOnlyConnection()
## Instruction:
Update Twitter auth test to run directly
## Code After:
from __future__ import absolute_import
import os
import sys
import unittest
from unittest import TestCase
# Allow imports to be done when executing this file directly.
sys.path.insert(0, os.path.abspath(os.path.join(
os.path.dirname(__file__), os.path.pardir, os.path.pardir)
))
from lib.twitter_api import authentication
class TestAuth(TestCase):
def test_generateAppAccessToken(self):
auth = authentication._generateAppAccessToken()
def test_getTweepyConnection(self):
auth = authentication._generateAppAccessToken()
api = authentication._getTweepyConnection(auth)
def test_getAPIConnection(self):
"""
Test that App Access token can be used to connect to Twitter API.
"""
api = authentication.getAPIConnection(userFlow=False)
def test_getAppOnlyConnection(self):
"""
Test App-only token.
"""
api = authentication.getAppOnlyConnection()
if __name__ == '__main__':
unittest.main()
| ...
from __future__ import absolute_import
import os
import sys
import unittest
from unittest import TestCase
# Allow imports to be done when executing this file directly.
sys.path.insert(0, os.path.abspath(os.path.join(
os.path.dirname(__file__), os.path.pardir, os.path.pardir)
))
...
api = authentication.getAppOnlyConnection()
if __name__ == '__main__':
unittest.main()
... |
e43596395507c4606909087c0e77e84c1a232811 | damn/__init__.py | damn/__init__.py |
__version__ = '0.0.0'
|
__author__ = 'Romain Clement'
__copyright__ = 'Copyright 2014, Romain Clement'
__credits__ = []
__license__ = 'MIT'
__version__ = "0.0.0"
__maintainer__ = 'Romain Clement'
__email__ = 'contact@romainclement.com'
__status__ = 'Development'
| Add meta information for damn package | [DEV] Add meta information for damn package
| Python | mit | rclement/yodel,rclement/yodel |
+ __author__ = 'Romain Clement'
+ __copyright__ = 'Copyright 2014, Romain Clement'
+ __credits__ = []
+ __license__ = 'MIT'
- __version__ = '0.0.0'
+ __version__ = "0.0.0"
+ __maintainer__ = 'Romain Clement'
+ __email__ = 'contact@romainclement.com'
+ __status__ = 'Development'
| Add meta information for damn package | ## Code Before:
__version__ = '0.0.0'
## Instruction:
Add meta information for damn package
## Code After:
__author__ = 'Romain Clement'
__copyright__ = 'Copyright 2014, Romain Clement'
__credits__ = []
__license__ = 'MIT'
__version__ = "0.0.0"
__maintainer__ = 'Romain Clement'
__email__ = 'contact@romainclement.com'
__status__ = 'Development'
| // ... existing code ...
__author__ = 'Romain Clement'
__copyright__ = 'Copyright 2014, Romain Clement'
__credits__ = []
__license__ = 'MIT'
__version__ = "0.0.0"
__maintainer__ = 'Romain Clement'
__email__ = 'contact@romainclement.com'
__status__ = 'Development'
// ... rest of the code ... |
179c13d3fe2589d43e260da86e0465901d149a80 | rsk_mind/datasource/datasource_csv.py | rsk_mind/datasource/datasource_csv.py | import csv
from datasource import Datasource
from ..dataset import Dataset
class CSVDatasource(Datasource):
def read(self):
with open(self.path, 'rb') as infile:
reader = csv.reader(infile)
header = reader.next()
rows = []
for row in reader:
rows.append(row)
return Dataset(header, rows)
def write(self, dataset):
with open(self.path, 'w') as outfile:
writer = csv.writer(outfile)
writer.writerow(dataset.transformed_header)
for row in dataset.transformed_rows:
writer.writerow(row)
| import csv
from datasource import Datasource
from ..dataset import Dataset
class CSVDatasource(Datasource):
def __init__(self, path, target=None):
super(CSVDatasource, self).__init__(path)
self.target = target
def read(self):
with open(self.path, 'rb') as infile:
reader = csv.reader(infile)
header = reader.next()
rows = []
for row in reader:
if self.target is not None:
index = header.index(self.target)
target = row[index]
del row[index]
row += [target]
rows.append(row)
return Dataset(header, rows)
def write(self, dataset):
with open(self.path, 'w') as outfile:
writer = csv.writer(outfile)
writer.writerow(dataset.transformed_header)
for row in dataset.transformed_rows:
writer.writerow(row)
| Set targe class on csv document | Set targe class on csv document
| Python | mit | rsk-mind/rsk-mind-framework | import csv
from datasource import Datasource
from ..dataset import Dataset
class CSVDatasource(Datasource):
+
+ def __init__(self, path, target=None):
+ super(CSVDatasource, self).__init__(path)
+ self.target = target
def read(self):
with open(self.path, 'rb') as infile:
reader = csv.reader(infile)
header = reader.next()
rows = []
for row in reader:
+ if self.target is not None:
+ index = header.index(self.target)
+ target = row[index]
+ del row[index]
+ row += [target]
rows.append(row)
return Dataset(header, rows)
def write(self, dataset):
with open(self.path, 'w') as outfile:
writer = csv.writer(outfile)
writer.writerow(dataset.transformed_header)
-
+
for row in dataset.transformed_rows:
writer.writerow(row)
| Set targe class on csv document | ## Code Before:
import csv
from datasource import Datasource
from ..dataset import Dataset
class CSVDatasource(Datasource):
def read(self):
with open(self.path, 'rb') as infile:
reader = csv.reader(infile)
header = reader.next()
rows = []
for row in reader:
rows.append(row)
return Dataset(header, rows)
def write(self, dataset):
with open(self.path, 'w') as outfile:
writer = csv.writer(outfile)
writer.writerow(dataset.transformed_header)
for row in dataset.transformed_rows:
writer.writerow(row)
## Instruction:
Set targe class on csv document
## Code After:
import csv
from datasource import Datasource
from ..dataset import Dataset
class CSVDatasource(Datasource):
def __init__(self, path, target=None):
super(CSVDatasource, self).__init__(path)
self.target = target
def read(self):
with open(self.path, 'rb') as infile:
reader = csv.reader(infile)
header = reader.next()
rows = []
for row in reader:
if self.target is not None:
index = header.index(self.target)
target = row[index]
del row[index]
row += [target]
rows.append(row)
return Dataset(header, rows)
def write(self, dataset):
with open(self.path, 'w') as outfile:
writer = csv.writer(outfile)
writer.writerow(dataset.transformed_header)
for row in dataset.transformed_rows:
writer.writerow(row)
| # ... existing code ...
class CSVDatasource(Datasource):
def __init__(self, path, target=None):
super(CSVDatasource, self).__init__(path)
self.target = target
# ... modified code ...
for row in reader:
if self.target is not None:
index = header.index(self.target)
target = row[index]
del row[index]
row += [target]
rows.append(row)
...
writer.writerow(dataset.transformed_header)
for row in dataset.transformed_rows:
# ... rest of the code ... |
a8f4f7a3d3ecc88a8517221437f1e7b14b3f0a1d | seimas/prototype/helpers.py | seimas/prototype/helpers.py | import yaml
import os.path
from django.http import Http404
from django.conf.urls import url
from django.conf import settings
def get_page(path):
url = ('/%s/' % path) if path else '/'
with (settings.PROJECT_DIR / 'prototype.yml').open() as f:
data = yaml.load(f)
try:
page = data['urls'][url] or {
'context': {},
}
except KeyError:
raise Http404("Requested %s page not found." % url)
if 'globals' in data and page.get('type', 'html') == 'html':
page['context'] = dict(data['globals'], **page.get('context', {}))
return page
def get_template(path):
base = os.path.join('seimas', 'website')
candidates = [
os.path.join(path, 'index.html'),
'%s.html' % path,
]
for template in candidates:
if os.path.exists(os.path.join(base, 'templates', template)):
return template
def get_urls(view):
with (settings.PROJECT_DIR / 'prototype.yml').open() as f:
data = yaml.load(f)
urls = []
for path, page in data['urls'].items():
if page and 'name' in page:
pattern = r'^%s$' % path.lstrip('/')
kwargs = {'path': path.strip('/')}
urls.append(url(pattern, view, kwargs, name=page['name']))
return urls
| import yaml
import os.path
from django.http import Http404
from django.conf.urls import url
from django.conf import settings
def get_page(path):
url = ('/%s/' % path) if path else '/'
with (settings.PROJECT_DIR / 'prototype.yml').open(encoding='utf-8') as f:
data = yaml.load(f)
try:
page = data['urls'][url] or {
'context': {},
}
except KeyError:
raise Http404("Requested %s page not found." % url)
if 'globals' in data and page.get('type', 'html') == 'html':
page['context'] = dict(data['globals'], **page.get('context', {}))
return page
def get_template(path):
base = settings.PROJECT_DIR / 'seimas/website'
candidates = [
os.path.join(path, 'index.html'),
'%s.html' % path,
]
for template in candidates:
if (base / 'templates' / template).exists():
return template
def get_urls(view):
with (settings.PROJECT_DIR / 'prototype.yml').open(encoding='utf-8') as f:
data = yaml.load(f)
urls = []
for path, page in data['urls'].items():
if page and 'name' in page:
pattern = r'^%s$' % path.lstrip('/')
kwargs = {'path': path.strip('/')}
urls.append(url(pattern, view, kwargs, name=page['name']))
return urls
| Fix prototype template loading error | Fix prototype template loading error
| Python | agpl-3.0 | sirex/manopozicija.lt,sirex/nuomones,sirex/manopozicija.lt,sirex/nuomones,sirex/manopozicija.lt | import yaml
import os.path
from django.http import Http404
from django.conf.urls import url
from django.conf import settings
def get_page(path):
url = ('/%s/' % path) if path else '/'
- with (settings.PROJECT_DIR / 'prototype.yml').open() as f:
+ with (settings.PROJECT_DIR / 'prototype.yml').open(encoding='utf-8') as f:
data = yaml.load(f)
try:
page = data['urls'][url] or {
'context': {},
}
except KeyError:
raise Http404("Requested %s page not found." % url)
if 'globals' in data and page.get('type', 'html') == 'html':
page['context'] = dict(data['globals'], **page.get('context', {}))
return page
def get_template(path):
- base = os.path.join('seimas', 'website')
+ base = settings.PROJECT_DIR / 'seimas/website'
candidates = [
os.path.join(path, 'index.html'),
'%s.html' % path,
]
for template in candidates:
- if os.path.exists(os.path.join(base, 'templates', template)):
+ if (base / 'templates' / template).exists():
return template
def get_urls(view):
- with (settings.PROJECT_DIR / 'prototype.yml').open() as f:
+ with (settings.PROJECT_DIR / 'prototype.yml').open(encoding='utf-8') as f:
data = yaml.load(f)
urls = []
for path, page in data['urls'].items():
if page and 'name' in page:
pattern = r'^%s$' % path.lstrip('/')
kwargs = {'path': path.strip('/')}
urls.append(url(pattern, view, kwargs, name=page['name']))
return urls
| Fix prototype template loading error | ## Code Before:
import yaml
import os.path
from django.http import Http404
from django.conf.urls import url
from django.conf import settings
def get_page(path):
url = ('/%s/' % path) if path else '/'
with (settings.PROJECT_DIR / 'prototype.yml').open() as f:
data = yaml.load(f)
try:
page = data['urls'][url] or {
'context': {},
}
except KeyError:
raise Http404("Requested %s page not found." % url)
if 'globals' in data and page.get('type', 'html') == 'html':
page['context'] = dict(data['globals'], **page.get('context', {}))
return page
def get_template(path):
base = os.path.join('seimas', 'website')
candidates = [
os.path.join(path, 'index.html'),
'%s.html' % path,
]
for template in candidates:
if os.path.exists(os.path.join(base, 'templates', template)):
return template
def get_urls(view):
with (settings.PROJECT_DIR / 'prototype.yml').open() as f:
data = yaml.load(f)
urls = []
for path, page in data['urls'].items():
if page and 'name' in page:
pattern = r'^%s$' % path.lstrip('/')
kwargs = {'path': path.strip('/')}
urls.append(url(pattern, view, kwargs, name=page['name']))
return urls
## Instruction:
Fix prototype template loading error
## Code After:
import yaml
import os.path
from django.http import Http404
from django.conf.urls import url
from django.conf import settings
def get_page(path):
url = ('/%s/' % path) if path else '/'
with (settings.PROJECT_DIR / 'prototype.yml').open(encoding='utf-8') as f:
data = yaml.load(f)
try:
page = data['urls'][url] or {
'context': {},
}
except KeyError:
raise Http404("Requested %s page not found." % url)
if 'globals' in data and page.get('type', 'html') == 'html':
page['context'] = dict(data['globals'], **page.get('context', {}))
return page
def get_template(path):
base = settings.PROJECT_DIR / 'seimas/website'
candidates = [
os.path.join(path, 'index.html'),
'%s.html' % path,
]
for template in candidates:
if (base / 'templates' / template).exists():
return template
def get_urls(view):
with (settings.PROJECT_DIR / 'prototype.yml').open(encoding='utf-8') as f:
data = yaml.load(f)
urls = []
for path, page in data['urls'].items():
if page and 'name' in page:
pattern = r'^%s$' % path.lstrip('/')
kwargs = {'path': path.strip('/')}
urls.append(url(pattern, view, kwargs, name=page['name']))
return urls
| ...
url = ('/%s/' % path) if path else '/'
with (settings.PROJECT_DIR / 'prototype.yml').open(encoding='utf-8') as f:
data = yaml.load(f)
...
def get_template(path):
base = settings.PROJECT_DIR / 'seimas/website'
candidates = [
...
for template in candidates:
if (base / 'templates' / template).exists():
return template
...
def get_urls(view):
with (settings.PROJECT_DIR / 'prototype.yml').open(encoding='utf-8') as f:
data = yaml.load(f)
... |
45116fc996b097176bcfa2dcd7fb8c9710f6d66e | tests/test_basics.py | tests/test_basics.py |
import os
from xml.etree import ElementTree
from utils import with_app, pretty_print_xml
#=============================================================================
# Tests
@with_app(buildername="xml", srcdir="basics")
def test_basics(app, status, warning):
app.build()
tree = ElementTree.parse(app.outdir / "index.xml")
pretty_print_xml(tree.getroot())
# Verify that 2 traceables are found.
assert len(tree.findall(".//target")) == 2
assert len(tree.findall(".//index")) == 2
assert len(tree.findall(".//admonition")) == 2
assert len(tree.findall(".//admonition")) == 2
# Verify that child-parent relationship are made.
assert len(tree.findall(".//field_list")) == 2
parent_fields, child_fields = tree.findall(".//field_list")
for field in parent_fields:
field_name = field.findall("./field_name")[0]
if field_name.text == "child":
break
else:
assert False, "Parent's child field not found!"
for field in child_fields:
field_name = field.findall("./field_name")[0]
if field_name.text == "parent":
break
else:
assert False, "Child's parent field not found!"
# Verify that a warning is emitted for unknown traceable tag.
assert (warning.getvalue().find(
"WARNING: Traceables: no traceable with tag"
" 'NONEXISTENT' found!") > 0)
|
import os
from xml.etree import ElementTree
from utils import with_app, pretty_print_xml
#=============================================================================
# Tests
@with_app(buildername="xml", srcdir="basics")
def test_basics(app, status, warning):
app.build()
tree = ElementTree.parse(app.outdir / "index.xml")
# Verify that 2 traceables are found.
assert len(tree.findall(".//target")) == 2
assert len(tree.findall(".//index")) == 2
assert len(tree.findall(".//admonition")) == 2
assert len(tree.findall(".//admonition")) == 2
# Verify that child-parent relationship are made.
assert len(tree.findall(".//field_list")) == 2
parent_fields, child_fields = tree.findall(".//field_list")
for field in parent_fields:
field_name = field.findall("./field_name")[0]
if field_name.text == "child":
break
else:
assert False, "Parent's child field not found!"
for field in child_fields:
field_name = field.findall("./field_name")[0]
if field_name.text == "parent":
break
else:
assert False, "Child's parent field not found!"
# Verify that a warning is emitted for unknown traceable tag.
assert (warning.getvalue().find(
"WARNING: Traceables: no traceable with tag"
" 'NONEXISTENT' found!") > 0)
| Remove debug printing from test case | Remove debug printing from test case
| Python | apache-2.0 | t4ngo/sphinxcontrib-traceables |
import os
from xml.etree import ElementTree
from utils import with_app, pretty_print_xml
#=============================================================================
# Tests
@with_app(buildername="xml", srcdir="basics")
def test_basics(app, status, warning):
app.build()
tree = ElementTree.parse(app.outdir / "index.xml")
- pretty_print_xml(tree.getroot())
# Verify that 2 traceables are found.
assert len(tree.findall(".//target")) == 2
assert len(tree.findall(".//index")) == 2
assert len(tree.findall(".//admonition")) == 2
assert len(tree.findall(".//admonition")) == 2
# Verify that child-parent relationship are made.
assert len(tree.findall(".//field_list")) == 2
parent_fields, child_fields = tree.findall(".//field_list")
for field in parent_fields:
field_name = field.findall("./field_name")[0]
if field_name.text == "child":
break
else:
assert False, "Parent's child field not found!"
for field in child_fields:
field_name = field.findall("./field_name")[0]
if field_name.text == "parent":
break
else:
assert False, "Child's parent field not found!"
# Verify that a warning is emitted for unknown traceable tag.
assert (warning.getvalue().find(
"WARNING: Traceables: no traceable with tag"
" 'NONEXISTENT' found!") > 0)
| Remove debug printing from test case | ## Code Before:
import os
from xml.etree import ElementTree
from utils import with_app, pretty_print_xml
#=============================================================================
# Tests
@with_app(buildername="xml", srcdir="basics")
def test_basics(app, status, warning):
app.build()
tree = ElementTree.parse(app.outdir / "index.xml")
pretty_print_xml(tree.getroot())
# Verify that 2 traceables are found.
assert len(tree.findall(".//target")) == 2
assert len(tree.findall(".//index")) == 2
assert len(tree.findall(".//admonition")) == 2
assert len(tree.findall(".//admonition")) == 2
# Verify that child-parent relationship are made.
assert len(tree.findall(".//field_list")) == 2
parent_fields, child_fields = tree.findall(".//field_list")
for field in parent_fields:
field_name = field.findall("./field_name")[0]
if field_name.text == "child":
break
else:
assert False, "Parent's child field not found!"
for field in child_fields:
field_name = field.findall("./field_name")[0]
if field_name.text == "parent":
break
else:
assert False, "Child's parent field not found!"
# Verify that a warning is emitted for unknown traceable tag.
assert (warning.getvalue().find(
"WARNING: Traceables: no traceable with tag"
" 'NONEXISTENT' found!") > 0)
## Instruction:
Remove debug printing from test case
## Code After:
import os
from xml.etree import ElementTree
from utils import with_app, pretty_print_xml
#=============================================================================
# Tests
@with_app(buildername="xml", srcdir="basics")
def test_basics(app, status, warning):
app.build()
tree = ElementTree.parse(app.outdir / "index.xml")
# Verify that 2 traceables are found.
assert len(tree.findall(".//target")) == 2
assert len(tree.findall(".//index")) == 2
assert len(tree.findall(".//admonition")) == 2
assert len(tree.findall(".//admonition")) == 2
# Verify that child-parent relationship are made.
assert len(tree.findall(".//field_list")) == 2
parent_fields, child_fields = tree.findall(".//field_list")
for field in parent_fields:
field_name = field.findall("./field_name")[0]
if field_name.text == "child":
break
else:
assert False, "Parent's child field not found!"
for field in child_fields:
field_name = field.findall("./field_name")[0]
if field_name.text == "parent":
break
else:
assert False, "Child's parent field not found!"
# Verify that a warning is emitted for unknown traceable tag.
assert (warning.getvalue().find(
"WARNING: Traceables: no traceable with tag"
" 'NONEXISTENT' found!") > 0)
| # ... existing code ...
tree = ElementTree.parse(app.outdir / "index.xml")
# ... rest of the code ... |
5fdd28a4707c8dcc9fe9ef3607742e6856725288 | examples/connect4/connect4.py | examples/connect4/connect4.py | class Connect4(object):
def __init__(self):
self.pieces = [[] for i in xrange(7)]
self.turn = 0
def move(self, column):
for i in xrange(column, column + 7):
if len(self.pieces[i % 7]) < 6:
self.pieces[i % 7].append(self.turn)
self.turn = 1 - self.turn
return
def __str__(self):
output = ''
for i in xrange(6):
output += i and '\n ' or ' '
for piece_column in self.pieces:
try:
output += str(piece_column[5 - i]) + ' '
except IndexError:
output += ' '
return output
def start():
pass
| class Connect4(object):
def __init__(self):
self.pieces = [[] for i in xrange(7)]
self.turn = 0
def move(self, column):
for i in xrange(column, column + 7):
if len(self.pieces[i % 7]) < 6:
self.pieces[i % 7].append(self.turn)
self.turn = 1 - self.turn
return
def __str__(self):
output = ''
for i in xrange(6):
output += i and '\n|' or '|'
for piece_column in self.pieces:
try:
output += piece_column[5 - i] and 'X|' or 'O|'
except IndexError:
output += ' |'
output += '\n 0 1 2 3 4 5 6 '
return output
def start():
pass
| Make Connect4's __str__ more readable | Make Connect4's __str__ more readable
| Python | mit | tysonzero/py-ann | class Connect4(object):
def __init__(self):
self.pieces = [[] for i in xrange(7)]
self.turn = 0
def move(self, column):
for i in xrange(column, column + 7):
if len(self.pieces[i % 7]) < 6:
self.pieces[i % 7].append(self.turn)
self.turn = 1 - self.turn
return
def __str__(self):
output = ''
for i in xrange(6):
- output += i and '\n ' or ' '
+ output += i and '\n|' or '|'
for piece_column in self.pieces:
try:
- output += str(piece_column[5 - i]) + ' '
+ output += piece_column[5 - i] and 'X|' or 'O|'
except IndexError:
- output += ' '
+ output += ' |'
+ output += '\n 0 1 2 3 4 5 6 '
return output
def start():
pass
| Make Connect4's __str__ more readable | ## Code Before:
class Connect4(object):
def __init__(self):
self.pieces = [[] for i in xrange(7)]
self.turn = 0
def move(self, column):
for i in xrange(column, column + 7):
if len(self.pieces[i % 7]) < 6:
self.pieces[i % 7].append(self.turn)
self.turn = 1 - self.turn
return
def __str__(self):
output = ''
for i in xrange(6):
output += i and '\n ' or ' '
for piece_column in self.pieces:
try:
output += str(piece_column[5 - i]) + ' '
except IndexError:
output += ' '
return output
def start():
pass
## Instruction:
Make Connect4's __str__ more readable
## Code After:
class Connect4(object):
def __init__(self):
self.pieces = [[] for i in xrange(7)]
self.turn = 0
def move(self, column):
for i in xrange(column, column + 7):
if len(self.pieces[i % 7]) < 6:
self.pieces[i % 7].append(self.turn)
self.turn = 1 - self.turn
return
def __str__(self):
output = ''
for i in xrange(6):
output += i and '\n|' or '|'
for piece_column in self.pieces:
try:
output += piece_column[5 - i] and 'X|' or 'O|'
except IndexError:
output += ' |'
output += '\n 0 1 2 3 4 5 6 '
return output
def start():
pass
| ...
for i in xrange(6):
output += i and '\n|' or '|'
for piece_column in self.pieces:
...
try:
output += piece_column[5 - i] and 'X|' or 'O|'
except IndexError:
output += ' |'
output += '\n 0 1 2 3 4 5 6 '
return output
... |
342d3791aa80084309ffc00a9e5e936fa8277401 | AFQ/viz.py | AFQ/viz.py | import tempfile
import os.path as op
import numpy as np
import IPython.display as display
import nibabel as nib
from dipy.viz import fvtk
from palettable.tableau import Tableau_20
def visualize_bundles(trk, ren=None, inline=True, interact=False):
"""
Visualize bundles in 3D using fvtk
"""
if isinstance(trk, str):
trk = nib.streamlines.load(trk)
if ren is None:
ren = fvtk.ren()
for b in np.unique(trk.tractogram.data_per_streamline['bundle']):
idx = np.where(trk.tractogram.data_per_streamline['bundle'] == b)[0]
this_sl = list(trk.streamlines[idx])
sl_actor = fvtk.line(this_sl, Tableau_20.colors[np.mod(20, int(b))])
fvtk.add(ren, sl_actor)
if inline:
tdir = tempfile.gettempdir()
fname = op.join(tdir, "fig.png")
fvtk.record(ren, out_path=fname)
display.display_png(display.Image(fname))
if interact:
fvtk.show(ren)
return ren
| import tempfile
import os.path as op
import numpy as np
import IPython.display as display
import nibabel as nib
from dipy.viz import fvtk
from dipy.viz.colormap import line_colors
from palettable.tableau import Tableau_20
def visualize_bundles(trk, ren=None, inline=True, interact=False):
"""
Visualize bundles in 3D using fvtk
"""
if isinstance(trk, str):
trk = nib.streamlines.load(trk)
if ren is None:
ren = fvtk.ren()
# There are no bundles in here:
if list(trk.tractogram.data_per_streamline.keys()) == []:
streamlines = list(trk.streamlines)
sl_actor = fvtk.line(streamlines, line_colors(streamlines))
fvtk.add(ren, sl_actor)
for b in np.unique(trk.tractogram.data_per_streamline['bundle']):
idx = np.where(trk.tractogram.data_per_streamline['bundle'] == b)[0]
this_sl = list(trk.streamlines[idx])
sl_actor = fvtk.line(this_sl, Tableau_20.colors[np.mod(20, int(b))])
fvtk.add(ren, sl_actor)
if inline:
tdir = tempfile.gettempdir()
fname = op.join(tdir, "fig.png")
fvtk.record(ren, out_path=fname)
display.display_png(display.Image(fname))
if interact:
fvtk.show(ren)
return ren
| Enable visualizing trk files without bundle designations. | Enable visualizing trk files without bundle designations.
| Python | bsd-2-clause | yeatmanlab/pyAFQ,arokem/pyAFQ,yeatmanlab/pyAFQ,arokem/pyAFQ | import tempfile
import os.path as op
import numpy as np
import IPython.display as display
import nibabel as nib
from dipy.viz import fvtk
+ from dipy.viz.colormap import line_colors
+
from palettable.tableau import Tableau_20
def visualize_bundles(trk, ren=None, inline=True, interact=False):
"""
Visualize bundles in 3D using fvtk
"""
if isinstance(trk, str):
trk = nib.streamlines.load(trk)
if ren is None:
ren = fvtk.ren()
+
+ # There are no bundles in here:
+ if list(trk.tractogram.data_per_streamline.keys()) == []:
+ streamlines = list(trk.streamlines)
+ sl_actor = fvtk.line(streamlines, line_colors(streamlines))
+ fvtk.add(ren, sl_actor)
for b in np.unique(trk.tractogram.data_per_streamline['bundle']):
idx = np.where(trk.tractogram.data_per_streamline['bundle'] == b)[0]
this_sl = list(trk.streamlines[idx])
sl_actor = fvtk.line(this_sl, Tableau_20.colors[np.mod(20, int(b))])
fvtk.add(ren, sl_actor)
if inline:
tdir = tempfile.gettempdir()
fname = op.join(tdir, "fig.png")
fvtk.record(ren, out_path=fname)
display.display_png(display.Image(fname))
if interact:
fvtk.show(ren)
return ren
| Enable visualizing trk files without bundle designations. | ## Code Before:
import tempfile
import os.path as op
import numpy as np
import IPython.display as display
import nibabel as nib
from dipy.viz import fvtk
from palettable.tableau import Tableau_20
def visualize_bundles(trk, ren=None, inline=True, interact=False):
"""
Visualize bundles in 3D using fvtk
"""
if isinstance(trk, str):
trk = nib.streamlines.load(trk)
if ren is None:
ren = fvtk.ren()
for b in np.unique(trk.tractogram.data_per_streamline['bundle']):
idx = np.where(trk.tractogram.data_per_streamline['bundle'] == b)[0]
this_sl = list(trk.streamlines[idx])
sl_actor = fvtk.line(this_sl, Tableau_20.colors[np.mod(20, int(b))])
fvtk.add(ren, sl_actor)
if inline:
tdir = tempfile.gettempdir()
fname = op.join(tdir, "fig.png")
fvtk.record(ren, out_path=fname)
display.display_png(display.Image(fname))
if interact:
fvtk.show(ren)
return ren
## Instruction:
Enable visualizing trk files without bundle designations.
## Code After:
import tempfile
import os.path as op
import numpy as np
import IPython.display as display
import nibabel as nib
from dipy.viz import fvtk
from dipy.viz.colormap import line_colors
from palettable.tableau import Tableau_20
def visualize_bundles(trk, ren=None, inline=True, interact=False):
"""
Visualize bundles in 3D using fvtk
"""
if isinstance(trk, str):
trk = nib.streamlines.load(trk)
if ren is None:
ren = fvtk.ren()
# There are no bundles in here:
if list(trk.tractogram.data_per_streamline.keys()) == []:
streamlines = list(trk.streamlines)
sl_actor = fvtk.line(streamlines, line_colors(streamlines))
fvtk.add(ren, sl_actor)
for b in np.unique(trk.tractogram.data_per_streamline['bundle']):
idx = np.where(trk.tractogram.data_per_streamline['bundle'] == b)[0]
this_sl = list(trk.streamlines[idx])
sl_actor = fvtk.line(this_sl, Tableau_20.colors[np.mod(20, int(b))])
fvtk.add(ren, sl_actor)
if inline:
tdir = tempfile.gettempdir()
fname = op.join(tdir, "fig.png")
fvtk.record(ren, out_path=fname)
display.display_png(display.Image(fname))
if interact:
fvtk.show(ren)
return ren
| // ... existing code ...
from dipy.viz import fvtk
from dipy.viz.colormap import line_colors
from palettable.tableau import Tableau_20
// ... modified code ...
ren = fvtk.ren()
# There are no bundles in here:
if list(trk.tractogram.data_per_streamline.keys()) == []:
streamlines = list(trk.streamlines)
sl_actor = fvtk.line(streamlines, line_colors(streamlines))
fvtk.add(ren, sl_actor)
// ... rest of the code ... |
ba8509a34104ff6aab5e97a6bed842b245ec4b64 | examples/pi-montecarlo/pi_distarray.py | examples/pi-montecarlo/pi_distarray.py |
from __future__ import division
import sys
from util import timer
from distarray.dist import Context, Distribution, hypot
from distarray.dist.random import Random
context = Context()
random = Random(context)
def local_sum(mask):
return mask.ndarray.sum()
@timer
def calc_pi(n):
"""Estimate pi using distributed NumPy arrays."""
distribution = Distribution.from_shape(context=context, shape=(n,))
x = random.rand(distribution)
y = random.rand(distribution)
r = hypot(x, y)
mask = (r < 1)
lsum = context.apply(local_sum, (mask.key,))
return 4 * sum(lsum) / n
if __name__ == '__main__':
N = int(sys.argv[1])
result, time = calc_pi(N)
print('time : %3.4g\nresult: %.7f' % (time, result))
|
from __future__ import division, print_function
import sys
from util import timer
from distarray.dist import Context, Distribution, hypot
from distarray.dist.random import Random
context = Context()
random = Random(context)
@timer
def calc_pi(n):
"""Estimate pi using distributed NumPy arrays."""
distribution = Distribution.from_shape(context=context, shape=(n,))
x = random.rand(distribution)
y = random.rand(distribution)
r = hypot(x, y)
mask = (r < 1)
return 4 * mask.sum().toarray() / n
if __name__ == '__main__':
N = int(sys.argv[1])
result, time = calc_pi(N)
print('time : %3.4g\nresult: %.7f' % (time, result))
| Update pi-montecarlo example to use `sum` again. | Update pi-montecarlo example to use `sum` again.
| Python | bsd-3-clause | RaoUmer/distarray,enthought/distarray,enthought/distarray,RaoUmer/distarray |
- from __future__ import division
+ from __future__ import division, print_function
import sys
from util import timer
from distarray.dist import Context, Distribution, hypot
from distarray.dist.random import Random
context = Context()
random = Random(context)
- def local_sum(mask):
- return mask.ndarray.sum()
-
-
@timer
def calc_pi(n):
"""Estimate pi using distributed NumPy arrays."""
distribution = Distribution.from_shape(context=context, shape=(n,))
x = random.rand(distribution)
y = random.rand(distribution)
r = hypot(x, y)
mask = (r < 1)
+ return 4 * mask.sum().toarray() / n
- lsum = context.apply(local_sum, (mask.key,))
- return 4 * sum(lsum) / n
if __name__ == '__main__':
N = int(sys.argv[1])
result, time = calc_pi(N)
print('time : %3.4g\nresult: %.7f' % (time, result))
| Update pi-montecarlo example to use `sum` again. | ## Code Before:
from __future__ import division
import sys
from util import timer
from distarray.dist import Context, Distribution, hypot
from distarray.dist.random import Random
context = Context()
random = Random(context)
def local_sum(mask):
return mask.ndarray.sum()
@timer
def calc_pi(n):
"""Estimate pi using distributed NumPy arrays."""
distribution = Distribution.from_shape(context=context, shape=(n,))
x = random.rand(distribution)
y = random.rand(distribution)
r = hypot(x, y)
mask = (r < 1)
lsum = context.apply(local_sum, (mask.key,))
return 4 * sum(lsum) / n
if __name__ == '__main__':
N = int(sys.argv[1])
result, time = calc_pi(N)
print('time : %3.4g\nresult: %.7f' % (time, result))
## Instruction:
Update pi-montecarlo example to use `sum` again.
## Code After:
from __future__ import division, print_function
import sys
from util import timer
from distarray.dist import Context, Distribution, hypot
from distarray.dist.random import Random
context = Context()
random = Random(context)
@timer
def calc_pi(n):
"""Estimate pi using distributed NumPy arrays."""
distribution = Distribution.from_shape(context=context, shape=(n,))
x = random.rand(distribution)
y = random.rand(distribution)
r = hypot(x, y)
mask = (r < 1)
return 4 * mask.sum().toarray() / n
if __name__ == '__main__':
N = int(sys.argv[1])
result, time = calc_pi(N)
print('time : %3.4g\nresult: %.7f' % (time, result))
| ...
from __future__ import division, print_function
...
@timer
...
mask = (r < 1)
return 4 * mask.sum().toarray() / n
... |
6032fb8eb10a2f6be28142c7473e03b4bc349c7c | partitions/registry.py | partitions/registry.py | from django.conf import settings
class Registry(object):
def __init__(self):
self._partitions = {}
def register(self, key, app_model, expression):
if not isinstance(app_model, basestring):
app_model = "%s.%s" % (
app_model._meta.app_label,
app_model._meta.object_name
)
if key in self._partitions and app_model in self._partitions[key]:
raise Exception("'%s' is already registered." % key)
if app_model.split(".")[0] not in settings.INSTALLED_APPS:
raise Exception("'%s' is not in INSTALLED_APPS" % app_model.split(".")[0])
self._partitions[key].update({app_model: expression})
def expression_for(self, key, app_model):
return self._partitions.get(key, {}).get(app_model)
registry = Registry()
def register(key, app_model, expression):
registry.register(key, app_model, expression)
| from django.conf import settings
class Registry(object):
def __init__(self):
self._partitions = {}
def register(self, key, app_model, expression):
if not isinstance(app_model, basestring):
app_model = "%s.%s" % (
app_model._meta.app_label,
app_model._meta.object_name
)
if key in self._partitions and app_model in self._partitions[key]:
raise Exception("'%s' is already registered." % key)
if app_model.split(".")[0] not in settings.INSTALLED_APPS:
raise Exception("'%s' is not in INSTALLED_APPS" % app_model.split(".")[0])
self._partitions.update({
key: {
app_model: expression
}
})
def expression_for(self, key, app_model):
return self._partitions.get(key, {}).get(app_model)
registry = Registry()
def register(key, app_model, expression):
registry.register(key, app_model, expression)
| Use update instead of setting key directly | Use update instead of setting key directly
| Python | bsd-3-clause | eldarion/django-partitions | from django.conf import settings
class Registry(object):
def __init__(self):
self._partitions = {}
def register(self, key, app_model, expression):
if not isinstance(app_model, basestring):
app_model = "%s.%s" % (
app_model._meta.app_label,
app_model._meta.object_name
)
if key in self._partitions and app_model in self._partitions[key]:
raise Exception("'%s' is already registered." % key)
if app_model.split(".")[0] not in settings.INSTALLED_APPS:
raise Exception("'%s' is not in INSTALLED_APPS" % app_model.split(".")[0])
- self._partitions[key].update({app_model: expression})
+ self._partitions.update({
+ key: {
+ app_model: expression
+ }
+ })
def expression_for(self, key, app_model):
return self._partitions.get(key, {}).get(app_model)
registry = Registry()
def register(key, app_model, expression):
registry.register(key, app_model, expression)
| Use update instead of setting key directly | ## Code Before:
from django.conf import settings
class Registry(object):
def __init__(self):
self._partitions = {}
def register(self, key, app_model, expression):
if not isinstance(app_model, basestring):
app_model = "%s.%s" % (
app_model._meta.app_label,
app_model._meta.object_name
)
if key in self._partitions and app_model in self._partitions[key]:
raise Exception("'%s' is already registered." % key)
if app_model.split(".")[0] not in settings.INSTALLED_APPS:
raise Exception("'%s' is not in INSTALLED_APPS" % app_model.split(".")[0])
self._partitions[key].update({app_model: expression})
def expression_for(self, key, app_model):
return self._partitions.get(key, {}).get(app_model)
registry = Registry()
def register(key, app_model, expression):
registry.register(key, app_model, expression)
## Instruction:
Use update instead of setting key directly
## Code After:
from django.conf import settings
class Registry(object):
def __init__(self):
self._partitions = {}
def register(self, key, app_model, expression):
if not isinstance(app_model, basestring):
app_model = "%s.%s" % (
app_model._meta.app_label,
app_model._meta.object_name
)
if key in self._partitions and app_model in self._partitions[key]:
raise Exception("'%s' is already registered." % key)
if app_model.split(".")[0] not in settings.INSTALLED_APPS:
raise Exception("'%s' is not in INSTALLED_APPS" % app_model.split(".")[0])
self._partitions.update({
key: {
app_model: expression
}
})
def expression_for(self, key, app_model):
return self._partitions.get(key, {}).get(app_model)
registry = Registry()
def register(key, app_model, expression):
registry.register(key, app_model, expression)
| # ... existing code ...
self._partitions.update({
key: {
app_model: expression
}
})
# ... rest of the code ... |
f00cb6c748e2eda022a7f9f739b60b98a0308eb7 | github3/search/repository.py | github3/search/repository.py | from github3.models import GitHubCore
from github3.repos import Repository
class RepositorySearchResult(GitHubCore):
def __init__(self, data, session=None):
result = data.copy()
#: Score of the result
self.score = result.pop('score')
#: Text matches
self.text_matches = result.pop('text_matches', [])
#: Repository object
self.repository = Repository(result, self)
| from github3.models import GitHubCore
from github3.repos import Repository
class RepositorySearchResult(GitHubCore):
def __init__(self, data, session=None):
result = data.copy()
#: Score of the result
self.score = result.pop('score')
#: Text matches
self.text_matches = result.pop('text_matches', [])
#: Repository object
self.repository = Repository(result, self)
def __repr__(self):
return '<RepositorySearchResult [{0}]>'.format(self.repository)
| Add a __repr__ for RepositorySearchResult | Add a __repr__ for RepositorySearchResult
| Python | bsd-3-clause | ueg1990/github3.py,icio/github3.py,christophelec/github3.py,jim-minter/github3.py,agamdua/github3.py,krxsky/github3.py,itsmemattchung/github3.py,sigmavirus24/github3.py,h4ck3rm1k3/github3.py,balloob/github3.py,wbrefvem/github3.py,degustaf/github3.py | from github3.models import GitHubCore
from github3.repos import Repository
class RepositorySearchResult(GitHubCore):
def __init__(self, data, session=None):
result = data.copy()
#: Score of the result
self.score = result.pop('score')
#: Text matches
self.text_matches = result.pop('text_matches', [])
#: Repository object
self.repository = Repository(result, self)
+ def __repr__(self):
+ return '<RepositorySearchResult [{0}]>'.format(self.repository)
+ | Add a __repr__ for RepositorySearchResult | ## Code Before:
from github3.models import GitHubCore
from github3.repos import Repository
class RepositorySearchResult(GitHubCore):
def __init__(self, data, session=None):
result = data.copy()
#: Score of the result
self.score = result.pop('score')
#: Text matches
self.text_matches = result.pop('text_matches', [])
#: Repository object
self.repository = Repository(result, self)
## Instruction:
Add a __repr__ for RepositorySearchResult
## Code After:
from github3.models import GitHubCore
from github3.repos import Repository
class RepositorySearchResult(GitHubCore):
def __init__(self, data, session=None):
result = data.copy()
#: Score of the result
self.score = result.pop('score')
#: Text matches
self.text_matches = result.pop('text_matches', [])
#: Repository object
self.repository = Repository(result, self)
def __repr__(self):
return '<RepositorySearchResult [{0}]>'.format(self.repository)
| ...
self.repository = Repository(result, self)
def __repr__(self):
return '<RepositorySearchResult [{0}]>'.format(self.repository)
... |
d47d56525f85c5fa8b1f6b817a85479b9eb07582 | sqlalchemy_utils/functions/__init__.py | sqlalchemy_utils/functions/__init__.py | from .defer_except import defer_except
from .mock import create_mock_engine, mock_engine
from .render import render_expression, render_statement
from .sort_query import sort_query, QuerySorterException
from .database import (
database_exists,
create_database,
drop_database,
escape_like,
is_auto_assigned_date_column,
is_indexed_foreign_key,
non_indexed_foreign_keys,
)
from .orm import (
declarative_base,
getdotattr,
has_changes,
identity,
naturally_equivalent,
primary_keys,
table_name,
)
__all__ = (
create_database,
create_mock_engine,
database_exists,
declarative_base,
defer_except,
drop_database,
escape_like,
getdotattr,
has_changes,
identity,
is_auto_assigned_date_column,
is_indexed_foreign_key,
mock_engine,
naturally_equivalent,
non_indexed_foreign_keys,
primary_keys,
QuerySorterException,
render_expression,
render_statement,
sort_query,
table_name,
)
| from .defer_except import defer_except
from .mock import create_mock_engine, mock_engine
from .render import render_expression, render_statement
from .sort_query import sort_query, QuerySorterException
from .database import (
database_exists,
create_database,
drop_database,
escape_like,
is_auto_assigned_date_column,
is_indexed_foreign_key,
non_indexed_foreign_keys,
)
from .orm import (
declarative_base,
getdotattr,
has_changes,
identity,
naturally_equivalent,
query_entities,
primary_keys,
table_name,
)
__all__ = (
create_database,
create_mock_engine,
database_exists,
declarative_base,
defer_except,
drop_database,
escape_like,
getdotattr,
has_changes,
identity,
is_auto_assigned_date_column,
is_indexed_foreign_key,
mock_engine,
naturally_equivalent,
non_indexed_foreign_keys,
primary_keys,
QuerySorterException,
render_expression,
render_statement,
sort_query,
table_name,
)
| Add query_entities to functions module import | Add query_entities to functions module import
| Python | bsd-3-clause | joshfriend/sqlalchemy-utils,joshfriend/sqlalchemy-utils,cheungpat/sqlalchemy-utils,marrybird/sqlalchemy-utils,rmoorman/sqlalchemy-utils,spoqa/sqlalchemy-utils,tonyseek/sqlalchemy-utils,tonyseek/sqlalchemy-utils,JackWink/sqlalchemy-utils,konstantinoskostis/sqlalchemy-utils | from .defer_except import defer_except
from .mock import create_mock_engine, mock_engine
from .render import render_expression, render_statement
from .sort_query import sort_query, QuerySorterException
from .database import (
database_exists,
create_database,
drop_database,
escape_like,
is_auto_assigned_date_column,
is_indexed_foreign_key,
non_indexed_foreign_keys,
)
from .orm import (
declarative_base,
getdotattr,
has_changes,
identity,
naturally_equivalent,
+ query_entities,
primary_keys,
table_name,
)
__all__ = (
create_database,
create_mock_engine,
database_exists,
declarative_base,
defer_except,
drop_database,
escape_like,
getdotattr,
has_changes,
identity,
is_auto_assigned_date_column,
is_indexed_foreign_key,
mock_engine,
naturally_equivalent,
non_indexed_foreign_keys,
primary_keys,
QuerySorterException,
render_expression,
render_statement,
sort_query,
table_name,
)
| Add query_entities to functions module import | ## Code Before:
from .defer_except import defer_except
from .mock import create_mock_engine, mock_engine
from .render import render_expression, render_statement
from .sort_query import sort_query, QuerySorterException
from .database import (
database_exists,
create_database,
drop_database,
escape_like,
is_auto_assigned_date_column,
is_indexed_foreign_key,
non_indexed_foreign_keys,
)
from .orm import (
declarative_base,
getdotattr,
has_changes,
identity,
naturally_equivalent,
primary_keys,
table_name,
)
__all__ = (
create_database,
create_mock_engine,
database_exists,
declarative_base,
defer_except,
drop_database,
escape_like,
getdotattr,
has_changes,
identity,
is_auto_assigned_date_column,
is_indexed_foreign_key,
mock_engine,
naturally_equivalent,
non_indexed_foreign_keys,
primary_keys,
QuerySorterException,
render_expression,
render_statement,
sort_query,
table_name,
)
## Instruction:
Add query_entities to functions module import
## Code After:
from .defer_except import defer_except
from .mock import create_mock_engine, mock_engine
from .render import render_expression, render_statement
from .sort_query import sort_query, QuerySorterException
from .database import (
database_exists,
create_database,
drop_database,
escape_like,
is_auto_assigned_date_column,
is_indexed_foreign_key,
non_indexed_foreign_keys,
)
from .orm import (
declarative_base,
getdotattr,
has_changes,
identity,
naturally_equivalent,
query_entities,
primary_keys,
table_name,
)
__all__ = (
create_database,
create_mock_engine,
database_exists,
declarative_base,
defer_except,
drop_database,
escape_like,
getdotattr,
has_changes,
identity,
is_auto_assigned_date_column,
is_indexed_foreign_key,
mock_engine,
naturally_equivalent,
non_indexed_foreign_keys,
primary_keys,
QuerySorterException,
render_expression,
render_statement,
sort_query,
table_name,
)
| // ... existing code ...
naturally_equivalent,
query_entities,
primary_keys,
// ... rest of the code ... |
7dbbef88fedc07ee8cddf690b8c42785ee7241bd | astropy_helpers/sphinx/setup_package.py | astropy_helpers/sphinx/setup_package.py |
def get_package_data():
# Install the theme files
return {
'astropy_helpers.sphinx': [
'ext/templates/*/*',
'themes/bootstrap-astropy/*.*',
'themes/bootstrap-astropy/static/*.*']}
|
def get_package_data():
# Install the theme files
return {
'astropy_helpers.sphinx': [
'ext/templates/*/*',
'local/*.inv',
'themes/bootstrap-astropy/*.*',
'themes/bootstrap-astropy/static/*.*']}
| Make sure .inv file gets installed | Make sure .inv file gets installed | Python | bsd-3-clause | Cadair/astropy-helpers,bsipocz/astropy-helpers,embray/astropy_helpers,Cadair/astropy-helpers,embray/astropy_helpers,dpshelio/astropy-helpers,larrybradley/astropy-helpers,astropy/astropy-helpers,embray/astropy_helpers,astropy/astropy-helpers,bsipocz/astropy-helpers,larrybradley/astropy-helpers,embray/astropy_helpers,bsipocz/astropy-helpers,larrybradley/astropy-helpers,dpshelio/astropy-helpers |
def get_package_data():
# Install the theme files
return {
'astropy_helpers.sphinx': [
'ext/templates/*/*',
+ 'local/*.inv',
'themes/bootstrap-astropy/*.*',
'themes/bootstrap-astropy/static/*.*']}
| Make sure .inv file gets installed | ## Code Before:
def get_package_data():
# Install the theme files
return {
'astropy_helpers.sphinx': [
'ext/templates/*/*',
'themes/bootstrap-astropy/*.*',
'themes/bootstrap-astropy/static/*.*']}
## Instruction:
Make sure .inv file gets installed
## Code After:
def get_package_data():
# Install the theme files
return {
'astropy_helpers.sphinx': [
'ext/templates/*/*',
'local/*.inv',
'themes/bootstrap-astropy/*.*',
'themes/bootstrap-astropy/static/*.*']}
| ...
'ext/templates/*/*',
'local/*.inv',
'themes/bootstrap-astropy/*.*',
... |
980b7f55968d76b6f9222b7c381e1c98e144ddeb | tests/database_tests.py | tests/database_tests.py | from .query_tests import QueryTestCase
from .sql_builder_tests import SqlBuilderTestCase
from .transaction_tests import TransactionTestCase
from rebel.database import Database
from rebel.exceptions import NotInsideTransaction, MixedPositionalAndNamedArguments
class DatabaseTestCase(QueryTestCase, SqlBuilderTestCase, TransactionTestCase):
def setUp(self):
driver = self.get_driver()
self.db = Database(driver)
self.create_tables()
self.clear_tables()
self.fill_cities()
def fill_cities(self):
self.db.execute("""
INSERT INTO cities (name)
VALUES (?), (?), (?)
""", 'New York', 'Washington', 'Los Angeles')
| from .query_tests import QueryTestCase
from .sql_builder_tests import SqlBuilderTestCase
from .transaction_tests import TransactionTestCase
from rebel.database import Database
class DatabaseTestCase(QueryTestCase, SqlBuilderTestCase, TransactionTestCase):
def setUp(self):
driver = self.get_driver()
self.db = Database(driver)
self.create_tables()
self.clear_tables()
self.fill_cities()
def fill_cities(self):
self.db.execute("""
INSERT INTO cities (name)
VALUES (?), (?), (?)
""", 'New York', 'Washington', 'Los Angeles')
| Remove unused imports from database tests | Remove unused imports from database tests
| Python | mit | hugollm/rebel,hugollm/rebel | from .query_tests import QueryTestCase
from .sql_builder_tests import SqlBuilderTestCase
from .transaction_tests import TransactionTestCase
-
from rebel.database import Database
- from rebel.exceptions import NotInsideTransaction, MixedPositionalAndNamedArguments
class DatabaseTestCase(QueryTestCase, SqlBuilderTestCase, TransactionTestCase):
def setUp(self):
driver = self.get_driver()
self.db = Database(driver)
self.create_tables()
self.clear_tables()
self.fill_cities()
def fill_cities(self):
self.db.execute("""
INSERT INTO cities (name)
VALUES (?), (?), (?)
""", 'New York', 'Washington', 'Los Angeles')
| Remove unused imports from database tests | ## Code Before:
from .query_tests import QueryTestCase
from .sql_builder_tests import SqlBuilderTestCase
from .transaction_tests import TransactionTestCase
from rebel.database import Database
from rebel.exceptions import NotInsideTransaction, MixedPositionalAndNamedArguments
class DatabaseTestCase(QueryTestCase, SqlBuilderTestCase, TransactionTestCase):
def setUp(self):
driver = self.get_driver()
self.db = Database(driver)
self.create_tables()
self.clear_tables()
self.fill_cities()
def fill_cities(self):
self.db.execute("""
INSERT INTO cities (name)
VALUES (?), (?), (?)
""", 'New York', 'Washington', 'Los Angeles')
## Instruction:
Remove unused imports from database tests
## Code After:
from .query_tests import QueryTestCase
from .sql_builder_tests import SqlBuilderTestCase
from .transaction_tests import TransactionTestCase
from rebel.database import Database
class DatabaseTestCase(QueryTestCase, SqlBuilderTestCase, TransactionTestCase):
def setUp(self):
driver = self.get_driver()
self.db = Database(driver)
self.create_tables()
self.clear_tables()
self.fill_cities()
def fill_cities(self):
self.db.execute("""
INSERT INTO cities (name)
VALUES (?), (?), (?)
""", 'New York', 'Washington', 'Los Angeles')
| # ... existing code ...
from .transaction_tests import TransactionTestCase
from rebel.database import Database
# ... rest of the code ... |
5950f14ab025999b8161204595a7c35554fe46a0 | celery/decorators.py | celery/decorators.py | from celery.task.base import Task
from celery.registry import tasks
from inspect import getargspec
def task(**options):
"""Make a task out of any callable.
Examples:
>>> @task()
... def refresh_feed(url):
... return Feed.objects.get(url=url).refresh()
>>> refresh_feed("http://example.com/rss") # Regular
<Feed: http://example.com/rss>
>>> refresh_feed.delay("http://example.com/rss") # Async
<AsyncResult: 8998d0f4-da0b-4669-ba03-d5ab5ac6ad5d>
# With setting extra options and using retry.
>>> @task(exchange="feeds")
... def refresh_feed(url, **kwargs):
... try:
... return Feed.objects.get(url=url).refresh()
... except socket.error, exc:
... refresh_feed.retry(args=[url], kwargs=kwargs,
... exc=exc)
"""
def _create_task_cls(fun):
name = options.pop("name", None)
cls_name = fun.__name__
def run(self, *args, **kwargs):
return fun(*args, **kwargs)
run.__name__ = fun.__name__
run.argspec = getargspec(fun)
cls_dict = dict(options)
cls_dict["run"] = run
cls_dict["__module__"] = fun.__module__
task = type(cls_name, (Task, ), cls_dict)()
return task
return _create_task_cls
| from celery.task.base import Task
from inspect import getargspec
def task(**options):
"""Make a task out of any callable.
Examples:
>>> @task()
... def refresh_feed(url):
... return Feed.objects.get(url=url).refresh()
>>> refresh_feed("http://example.com/rss") # Regular
<Feed: http://example.com/rss>
>>> refresh_feed.delay("http://example.com/rss") # Async
<AsyncResult: 8998d0f4-da0b-4669-ba03-d5ab5ac6ad5d>
# With setting extra options and using retry.
>>> @task(exchange="feeds")
... def refresh_feed(url, **kwargs):
... try:
... return Feed.objects.get(url=url).refresh()
... except socket.error, exc:
... refresh_feed.retry(args=[url], kwargs=kwargs,
... exc=exc)
"""
def _create_task_cls(fun):
base = options.pop("base", Task)
cls_name = fun.__name__
def run(self, *args, **kwargs):
return fun(*args, **kwargs)
run.__name__ = fun.__name__
run.argspec = getargspec(fun)
cls_dict = dict(options)
cls_dict["run"] = run
cls_dict["__module__"] = fun.__module__
task = type(cls_name, (base, ), cls_dict)()
return task
return _create_task_cls
| Allow base=PeriodicTask argument to task decorator | Allow base=PeriodicTask argument to task decorator
| Python | bsd-3-clause | WoLpH/celery,cbrepo/celery,ask/celery,cbrepo/celery,frac/celery,mitsuhiko/celery,WoLpH/celery,ask/celery,frac/celery,mitsuhiko/celery | from celery.task.base import Task
- from celery.registry import tasks
from inspect import getargspec
def task(**options):
"""Make a task out of any callable.
Examples:
>>> @task()
... def refresh_feed(url):
... return Feed.objects.get(url=url).refresh()
>>> refresh_feed("http://example.com/rss") # Regular
<Feed: http://example.com/rss>
>>> refresh_feed.delay("http://example.com/rss") # Async
<AsyncResult: 8998d0f4-da0b-4669-ba03-d5ab5ac6ad5d>
# With setting extra options and using retry.
>>> @task(exchange="feeds")
... def refresh_feed(url, **kwargs):
... try:
... return Feed.objects.get(url=url).refresh()
... except socket.error, exc:
... refresh_feed.retry(args=[url], kwargs=kwargs,
... exc=exc)
"""
def _create_task_cls(fun):
- name = options.pop("name", None)
+ base = options.pop("base", Task)
cls_name = fun.__name__
def run(self, *args, **kwargs):
return fun(*args, **kwargs)
run.__name__ = fun.__name__
run.argspec = getargspec(fun)
cls_dict = dict(options)
cls_dict["run"] = run
cls_dict["__module__"] = fun.__module__
- task = type(cls_name, (Task, ), cls_dict)()
+ task = type(cls_name, (base, ), cls_dict)()
return task
return _create_task_cls
| Allow base=PeriodicTask argument to task decorator | ## Code Before:
from celery.task.base import Task
from celery.registry import tasks
from inspect import getargspec
def task(**options):
"""Make a task out of any callable.
Examples:
>>> @task()
... def refresh_feed(url):
... return Feed.objects.get(url=url).refresh()
>>> refresh_feed("http://example.com/rss") # Regular
<Feed: http://example.com/rss>
>>> refresh_feed.delay("http://example.com/rss") # Async
<AsyncResult: 8998d0f4-da0b-4669-ba03-d5ab5ac6ad5d>
# With setting extra options and using retry.
>>> @task(exchange="feeds")
... def refresh_feed(url, **kwargs):
... try:
... return Feed.objects.get(url=url).refresh()
... except socket.error, exc:
... refresh_feed.retry(args=[url], kwargs=kwargs,
... exc=exc)
"""
def _create_task_cls(fun):
name = options.pop("name", None)
cls_name = fun.__name__
def run(self, *args, **kwargs):
return fun(*args, **kwargs)
run.__name__ = fun.__name__
run.argspec = getargspec(fun)
cls_dict = dict(options)
cls_dict["run"] = run
cls_dict["__module__"] = fun.__module__
task = type(cls_name, (Task, ), cls_dict)()
return task
return _create_task_cls
## Instruction:
Allow base=PeriodicTask argument to task decorator
## Code After:
from celery.task.base import Task
from inspect import getargspec
def task(**options):
"""Make a task out of any callable.
Examples:
>>> @task()
... def refresh_feed(url):
... return Feed.objects.get(url=url).refresh()
>>> refresh_feed("http://example.com/rss") # Regular
<Feed: http://example.com/rss>
>>> refresh_feed.delay("http://example.com/rss") # Async
<AsyncResult: 8998d0f4-da0b-4669-ba03-d5ab5ac6ad5d>
# With setting extra options and using retry.
>>> @task(exchange="feeds")
... def refresh_feed(url, **kwargs):
... try:
... return Feed.objects.get(url=url).refresh()
... except socket.error, exc:
... refresh_feed.retry(args=[url], kwargs=kwargs,
... exc=exc)
"""
def _create_task_cls(fun):
base = options.pop("base", Task)
cls_name = fun.__name__
def run(self, *args, **kwargs):
return fun(*args, **kwargs)
run.__name__ = fun.__name__
run.argspec = getargspec(fun)
cls_dict = dict(options)
cls_dict["run"] = run
cls_dict["__module__"] = fun.__module__
task = type(cls_name, (base, ), cls_dict)()
return task
return _create_task_cls
| # ... existing code ...
from celery.task.base import Task
from inspect import getargspec
# ... modified code ...
def _create_task_cls(fun):
base = options.pop("base", Task)
...
task = type(cls_name, (base, ), cls_dict)()
# ... rest of the code ... |
5d6049be925330803f8c782d884cd318ad23ba28 | repo-log.py | repo-log.py |
import argparse
import csv
import git
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Extract git history information.')
parser.add_argument('-f', '--from', dest='from_', help='from revno')
parser.add_argument('-t', '--to', help='to revno')
parser.add_argument('-l', '--limit', help='max number of commits')
parser.add_argument('-p', '--project', help='project directory')
parser.add_argument('-c', '--csv', help='csv file name')
args = parser.parse_args()
if not args.csv or not args.project:
parser.print_help()
exit(1)
with open(args.csv, 'w') as csvfile:
csvwriter = csv.writer(csvfile, delimiter='\t', quotechar='|')
repo = git.Repo(args.project)
if args.limit:
iter_ = repo.iter_commits(args.from_, max_count=args.limit)
else:
iter_ = repo.iter_commits(args.from_)
for commit in iter_:
if commit.hexsha == args.to:
break
summary = commit.summary.encode('utf-8')
message = commit.message.encode('utf-8')
stats = commit.stats.total
csvwriter.writerow((summary, message, stats['files'],
stats['lines'], stats['insertions'],
stats['deletions']))
|
import argparse
import csv
import git
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Extract git history information.')
parser.add_argument('-f', '--from', dest='from_', help='from revno')
parser.add_argument('-t', '--to', help='to revno')
parser.add_argument('-l', '--limit', help='max number of commits')
parser.add_argument('-p', '--project', help='project directory')
parser.add_argument('-c', '--csv', help='csv file name')
args = parser.parse_args()
if not args.csv or not args.project:
parser.print_help()
exit(1)
with open(args.csv, 'w') as csvfile:
csvwriter = csv.writer(csvfile, delimiter=',', quotechar='"', doublequote=True)
repo = git.Repo(args.project)
if args.limit:
iter_ = repo.iter_commits(args.from_, max_count=args.limit, no_merges=True)
else:
iter_ = repo.iter_commits(args.from_, no_merges=True)
for commit in iter_:
if commit.hexsha == args.to:
break
summary = commit.summary.encode('utf-8')
message = commit.message.encode('utf-8')
stats = commit.stats.total
csvwriter.writerow((summary, message, commit.hexsha,
stats['files'], stats['lines'],
stats['insertions'],
stats['deletions']))
| Remove merges from the log. | Remove merges from the log.
| Python | mit | aplanas/hackweek11,aplanas/hackweek11 |
import argparse
import csv
import git
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Extract git history information.')
parser.add_argument('-f', '--from', dest='from_', help='from revno')
parser.add_argument('-t', '--to', help='to revno')
parser.add_argument('-l', '--limit', help='max number of commits')
parser.add_argument('-p', '--project', help='project directory')
parser.add_argument('-c', '--csv', help='csv file name')
args = parser.parse_args()
if not args.csv or not args.project:
parser.print_help()
exit(1)
with open(args.csv, 'w') as csvfile:
- csvwriter = csv.writer(csvfile, delimiter='\t', quotechar='|')
+ csvwriter = csv.writer(csvfile, delimiter=',', quotechar='"', doublequote=True)
repo = git.Repo(args.project)
if args.limit:
- iter_ = repo.iter_commits(args.from_, max_count=args.limit)
+ iter_ = repo.iter_commits(args.from_, max_count=args.limit, no_merges=True)
else:
- iter_ = repo.iter_commits(args.from_)
+ iter_ = repo.iter_commits(args.from_, no_merges=True)
for commit in iter_:
if commit.hexsha == args.to:
break
summary = commit.summary.encode('utf-8')
message = commit.message.encode('utf-8')
stats = commit.stats.total
- csvwriter.writerow((summary, message, stats['files'],
+ csvwriter.writerow((summary, message, commit.hexsha,
+ stats['files'], stats['lines'],
- stats['lines'], stats['insertions'],
+ stats['insertions'],
stats['deletions']))
| Remove merges from the log. | ## Code Before:
import argparse
import csv
import git
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Extract git history information.')
parser.add_argument('-f', '--from', dest='from_', help='from revno')
parser.add_argument('-t', '--to', help='to revno')
parser.add_argument('-l', '--limit', help='max number of commits')
parser.add_argument('-p', '--project', help='project directory')
parser.add_argument('-c', '--csv', help='csv file name')
args = parser.parse_args()
if not args.csv or not args.project:
parser.print_help()
exit(1)
with open(args.csv, 'w') as csvfile:
csvwriter = csv.writer(csvfile, delimiter='\t', quotechar='|')
repo = git.Repo(args.project)
if args.limit:
iter_ = repo.iter_commits(args.from_, max_count=args.limit)
else:
iter_ = repo.iter_commits(args.from_)
for commit in iter_:
if commit.hexsha == args.to:
break
summary = commit.summary.encode('utf-8')
message = commit.message.encode('utf-8')
stats = commit.stats.total
csvwriter.writerow((summary, message, stats['files'],
stats['lines'], stats['insertions'],
stats['deletions']))
## Instruction:
Remove merges from the log.
## Code After:
import argparse
import csv
import git
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Extract git history information.')
parser.add_argument('-f', '--from', dest='from_', help='from revno')
parser.add_argument('-t', '--to', help='to revno')
parser.add_argument('-l', '--limit', help='max number of commits')
parser.add_argument('-p', '--project', help='project directory')
parser.add_argument('-c', '--csv', help='csv file name')
args = parser.parse_args()
if not args.csv or not args.project:
parser.print_help()
exit(1)
with open(args.csv, 'w') as csvfile:
csvwriter = csv.writer(csvfile, delimiter=',', quotechar='"', doublequote=True)
repo = git.Repo(args.project)
if args.limit:
iter_ = repo.iter_commits(args.from_, max_count=args.limit, no_merges=True)
else:
iter_ = repo.iter_commits(args.from_, no_merges=True)
for commit in iter_:
if commit.hexsha == args.to:
break
summary = commit.summary.encode('utf-8')
message = commit.message.encode('utf-8')
stats = commit.stats.total
csvwriter.writerow((summary, message, commit.hexsha,
stats['files'], stats['lines'],
stats['insertions'],
stats['deletions']))
| # ... existing code ...
with open(args.csv, 'w') as csvfile:
csvwriter = csv.writer(csvfile, delimiter=',', quotechar='"', doublequote=True)
repo = git.Repo(args.project)
# ... modified code ...
if args.limit:
iter_ = repo.iter_commits(args.from_, max_count=args.limit, no_merges=True)
else:
iter_ = repo.iter_commits(args.from_, no_merges=True)
for commit in iter_:
...
stats = commit.stats.total
csvwriter.writerow((summary, message, commit.hexsha,
stats['files'], stats['lines'],
stats['insertions'],
stats['deletions']))
# ... rest of the code ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.