commit stringlengths 40 40 | old_file stringlengths 4 106 | new_file stringlengths 4 106 | old_contents stringlengths 10 2.94k | new_contents stringlengths 21 2.95k | subject stringlengths 16 444 | message stringlengths 17 2.63k | lang stringclasses 1 value | license stringclasses 13 values | repos stringlengths 7 43k | ndiff stringlengths 52 3.31k | instruction stringlengths 16 444 | content stringlengths 133 4.32k | diff stringlengths 49 3.61k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bc05c56c60fa61f045079a4b3ef2dea185b213b4 | fortuitus/fcore/tests.py | fortuitus/fcore/tests.py | from django.core.urlresolvers import reverse
from django.test import TestCase
from fortuitus.fcore.factories import UserF
from fortuitus.fcore.models import FortuitusProfile
class HomeViewTestCase(TestCase):
def test_renders_template(self):
""" Tests is home page is rendered properly. """
response = self.client.get(reverse('home'))
self.assertEqual(200, response.status_code)
self.assertTemplateUsed('fortuitus/fcore/home.html')
class ProfileTestCase(TestCase):
def test_profile_created(self):
""" Tests that profile is automatically created along with User. """
u = UserF.create()
p = FortuitusProfile.objects.all()[0]
self.assertEqual(u.fortuitusprofile, p)
def test_profiles_not_conflicted(self):
"""
Tests that second profile is created and not conflicted with the first
user nor his profile.
"""
u1 = UserF.create()
p1 = FortuitusProfile.objects.get(user_id=u1.pk)
u2 = UserF.create()
p2 = FortuitusProfile.objects.get(user_id=u2.pk)
self.assertNotEqual(p1, p2)
| from django.core.urlresolvers import reverse
from django.test import TestCase
from fortuitus.fcore.factories import UserF
from fortuitus.fcore.models import FortuitusProfile
class HomeViewTestCase(TestCase):
def test_renders_template(self):
""" Tests is home page is rendered properly. """
response = self.client.get(reverse('home'))
self.assertEqual(200, response.status_code)
self.assertTemplateUsed('fortuitus/fcore/home.html')
class ProfileTestCase(TestCase):
def test_profile_created(self):
""" Tests that profile is automatically created along with User. """
u = UserF.create()
p = FortuitusProfile.objects.all()[0]
self.assertEqual(u.fortuitusprofile, p)
def test_profiles_not_conflicted(self):
"""
Tests that second profile is created and not conflicted with the first
user nor his profile.
"""
u1 = UserF.create(username='u1')
p1 = FortuitusProfile.objects.get(user_id=u1.pk)
u2 = UserF.create(username='u2')
p2 = FortuitusProfile.objects.get(user_id=u2.pk)
self.assertNotEqual(p1, p2)
| Fix failing user profile test | Fix failing user profile test
| Python | mit | elegion/djangodash2012,elegion/djangodash2012 | from django.core.urlresolvers import reverse
from django.test import TestCase
from fortuitus.fcore.factories import UserF
from fortuitus.fcore.models import FortuitusProfile
class HomeViewTestCase(TestCase):
def test_renders_template(self):
""" Tests is home page is rendered properly. """
response = self.client.get(reverse('home'))
self.assertEqual(200, response.status_code)
self.assertTemplateUsed('fortuitus/fcore/home.html')
class ProfileTestCase(TestCase):
def test_profile_created(self):
""" Tests that profile is automatically created along with User. """
u = UserF.create()
p = FortuitusProfile.objects.all()[0]
self.assertEqual(u.fortuitusprofile, p)
def test_profiles_not_conflicted(self):
"""
Tests that second profile is created and not conflicted with the first
user nor his profile.
"""
- u1 = UserF.create()
+ u1 = UserF.create(username='u1')
p1 = FortuitusProfile.objects.get(user_id=u1.pk)
- u2 = UserF.create()
+ u2 = UserF.create(username='u2')
p2 = FortuitusProfile.objects.get(user_id=u2.pk)
self.assertNotEqual(p1, p2)
| Fix failing user profile test | ## Code Before:
from django.core.urlresolvers import reverse
from django.test import TestCase
from fortuitus.fcore.factories import UserF
from fortuitus.fcore.models import FortuitusProfile
class HomeViewTestCase(TestCase):
def test_renders_template(self):
""" Tests is home page is rendered properly. """
response = self.client.get(reverse('home'))
self.assertEqual(200, response.status_code)
self.assertTemplateUsed('fortuitus/fcore/home.html')
class ProfileTestCase(TestCase):
def test_profile_created(self):
""" Tests that profile is automatically created along with User. """
u = UserF.create()
p = FortuitusProfile.objects.all()[0]
self.assertEqual(u.fortuitusprofile, p)
def test_profiles_not_conflicted(self):
"""
Tests that second profile is created and not conflicted with the first
user nor his profile.
"""
u1 = UserF.create()
p1 = FortuitusProfile.objects.get(user_id=u1.pk)
u2 = UserF.create()
p2 = FortuitusProfile.objects.get(user_id=u2.pk)
self.assertNotEqual(p1, p2)
## Instruction:
Fix failing user profile test
## Code After:
from django.core.urlresolvers import reverse
from django.test import TestCase
from fortuitus.fcore.factories import UserF
from fortuitus.fcore.models import FortuitusProfile
class HomeViewTestCase(TestCase):
def test_renders_template(self):
""" Tests is home page is rendered properly. """
response = self.client.get(reverse('home'))
self.assertEqual(200, response.status_code)
self.assertTemplateUsed('fortuitus/fcore/home.html')
class ProfileTestCase(TestCase):
def test_profile_created(self):
""" Tests that profile is automatically created along with User. """
u = UserF.create()
p = FortuitusProfile.objects.all()[0]
self.assertEqual(u.fortuitusprofile, p)
def test_profiles_not_conflicted(self):
"""
Tests that second profile is created and not conflicted with the first
user nor his profile.
"""
u1 = UserF.create(username='u1')
p1 = FortuitusProfile.objects.get(user_id=u1.pk)
u2 = UserF.create(username='u2')
p2 = FortuitusProfile.objects.get(user_id=u2.pk)
self.assertNotEqual(p1, p2)
| from django.core.urlresolvers import reverse
from django.test import TestCase
from fortuitus.fcore.factories import UserF
from fortuitus.fcore.models import FortuitusProfile
class HomeViewTestCase(TestCase):
def test_renders_template(self):
""" Tests is home page is rendered properly. """
response = self.client.get(reverse('home'))
self.assertEqual(200, response.status_code)
self.assertTemplateUsed('fortuitus/fcore/home.html')
class ProfileTestCase(TestCase):
def test_profile_created(self):
""" Tests that profile is automatically created along with User. """
u = UserF.create()
p = FortuitusProfile.objects.all()[0]
self.assertEqual(u.fortuitusprofile, p)
def test_profiles_not_conflicted(self):
"""
Tests that second profile is created and not conflicted with the first
user nor his profile.
"""
- u1 = UserF.create()
+ u1 = UserF.create(username='u1')
? +++++++++++++
p1 = FortuitusProfile.objects.get(user_id=u1.pk)
- u2 = UserF.create()
+ u2 = UserF.create(username='u2')
? +++++++++++++
p2 = FortuitusProfile.objects.get(user_id=u2.pk)
self.assertNotEqual(p1, p2) |
6defa096b3dae109bf50ab32cdee7062c8b4327b | _python/config/settings/settings_pytest.py | _python/config/settings/settings_pytest.py |
from .settings_dev import *
# Don't use whitenoise for tests. Including whitenoise causes it to rescan static during each test, which greatly
# increases test time.
MIDDLEWARE.remove('whitenoise.middleware.WhiteNoiseMiddleware')
|
from .settings_dev import *
# Don't use whitenoise for tests. Including whitenoise causes it to rescan static during each test, which greatly
# increases test time.
MIDDLEWARE.remove('whitenoise.middleware.WhiteNoiseMiddleware')
CAPAPI_API_KEY = '12345'
| Add placeholder CAPAPI key for tests. | Add placeholder CAPAPI key for tests.
| Python | agpl-3.0 | harvard-lil/h2o,harvard-lil/h2o,harvard-lil/h2o,harvard-lil/h2o |
from .settings_dev import *
# Don't use whitenoise for tests. Including whitenoise causes it to rescan static during each test, which greatly
# increases test time.
MIDDLEWARE.remove('whitenoise.middleware.WhiteNoiseMiddleware')
+ CAPAPI_API_KEY = '12345'
| Add placeholder CAPAPI key for tests. | ## Code Before:
from .settings_dev import *
# Don't use whitenoise for tests. Including whitenoise causes it to rescan static during each test, which greatly
# increases test time.
MIDDLEWARE.remove('whitenoise.middleware.WhiteNoiseMiddleware')
## Instruction:
Add placeholder CAPAPI key for tests.
## Code After:
from .settings_dev import *
# Don't use whitenoise for tests. Including whitenoise causes it to rescan static during each test, which greatly
# increases test time.
MIDDLEWARE.remove('whitenoise.middleware.WhiteNoiseMiddleware')
CAPAPI_API_KEY = '12345'
|
from .settings_dev import *
# Don't use whitenoise for tests. Including whitenoise causes it to rescan static during each test, which greatly
# increases test time.
MIDDLEWARE.remove('whitenoise.middleware.WhiteNoiseMiddleware')
+ CAPAPI_API_KEY = '12345' |
920e2fbb7e99c17dbe8d5b71e9c9b26a718ca444 | ideascube/search/apps.py | ideascube/search/apps.py | from django.apps import AppConfig
from django.db.models.signals import pre_migrate, post_migrate
from .utils import create_index_table, reindex_content
def create_index(sender, **kwargs):
if isinstance(sender, SearchConfig):
create_index_table(force=True)
def reindex(sender, **kwargs):
if isinstance(sender, SearchConfig):
reindex_content(force=False)
class SearchConfig(AppConfig):
name = 'ideascube.search'
verbose_name = 'Search'
def ready(self):
pre_migrate.connect(create_index, sender=self)
post_migrate.connect(reindex, sender=self)
| from django.apps import AppConfig
from django.db.models.signals import pre_migrate, post_migrate
from .utils import create_index_table, reindex_content
def create_index(sender, **kwargs):
if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)):
create_index_table(force=True)
def reindex(sender, **kwargs):
if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)):
reindex_content(force=False)
class SearchConfig(AppConfig):
name = 'ideascube.search'
verbose_name = 'Search'
def ready(self):
pre_migrate.connect(create_index, sender=self)
post_migrate.connect(reindex, sender=self)
| Make (pre|post)_migrate scripts for the index table only if working on 'transient'. | Make (pre|post)_migrate scripts for the index table only if working on 'transient'.
Django run (pre|post)_migrate script once per database.
As we have two databases, the create_index is launch twice with different
kwargs['using'] ('default' and 'transient'). We should try to create
the index table only when we are working on the transient database.
Most of the time, this is not important and create a new index table
twice is not important.
However, if we run tests, the database are configured and migrate
one after the other and the 'transient' database may be miss-configured
at a time. By creating the table only at the right time, we ensure that
everything is properly configured.
| Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube | from django.apps import AppConfig
from django.db.models.signals import pre_migrate, post_migrate
from .utils import create_index_table, reindex_content
def create_index(sender, **kwargs):
- if isinstance(sender, SearchConfig):
+ if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)):
create_index_table(force=True)
def reindex(sender, **kwargs):
- if isinstance(sender, SearchConfig):
+ if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)):
reindex_content(force=False)
class SearchConfig(AppConfig):
name = 'ideascube.search'
verbose_name = 'Search'
def ready(self):
pre_migrate.connect(create_index, sender=self)
post_migrate.connect(reindex, sender=self)
| Make (pre|post)_migrate scripts for the index table only if working on 'transient'. | ## Code Before:
from django.apps import AppConfig
from django.db.models.signals import pre_migrate, post_migrate
from .utils import create_index_table, reindex_content
def create_index(sender, **kwargs):
if isinstance(sender, SearchConfig):
create_index_table(force=True)
def reindex(sender, **kwargs):
if isinstance(sender, SearchConfig):
reindex_content(force=False)
class SearchConfig(AppConfig):
name = 'ideascube.search'
verbose_name = 'Search'
def ready(self):
pre_migrate.connect(create_index, sender=self)
post_migrate.connect(reindex, sender=self)
## Instruction:
Make (pre|post)_migrate scripts for the index table only if working on 'transient'.
## Code After:
from django.apps import AppConfig
from django.db.models.signals import pre_migrate, post_migrate
from .utils import create_index_table, reindex_content
def create_index(sender, **kwargs):
if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)):
create_index_table(force=True)
def reindex(sender, **kwargs):
if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)):
reindex_content(force=False)
class SearchConfig(AppConfig):
name = 'ideascube.search'
verbose_name = 'Search'
def ready(self):
pre_migrate.connect(create_index, sender=self)
post_migrate.connect(reindex, sender=self)
| from django.apps import AppConfig
from django.db.models.signals import pre_migrate, post_migrate
from .utils import create_index_table, reindex_content
def create_index(sender, **kwargs):
- if isinstance(sender, SearchConfig):
+ if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)):
create_index_table(force=True)
def reindex(sender, **kwargs):
- if isinstance(sender, SearchConfig):
+ if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)):
reindex_content(force=False)
class SearchConfig(AppConfig):
name = 'ideascube.search'
verbose_name = 'Search'
def ready(self):
pre_migrate.connect(create_index, sender=self)
post_migrate.connect(reindex, sender=self) |
8e2596db204d2f6779280309aaa06d90872e9fb2 | tests/test_bot_support.py | tests/test_bot_support.py | from __future__ import unicode_literals
import pytest
from .test_bot import TestBot
class TestBotSupport(TestBot):
@pytest.mark.parametrize('url,result', [
('https://google.com', ['https://google.com']),
('google.com', ['google.com']),
('google.com/search?q=instabot', ['google.com/search?q=instabot']),
('https://google.com/search?q=instabot', ['https://google.com/search?q=instabot']),
('мвд.рф', ['мвд.рф']),
('https://мвд.рф', ['https://мвд.рф']),
('http://мвд.рф/news/', ['http://мвд.рф/news/']),
('hello, google.com/search?q=test and bing.com', ['google.com/search?q=test', 'bing.com']),
])
def test_extract_urls(self, url, result):
assert self.BOT.extract_urls(url) == result
| from __future__ import unicode_literals
import os
import pytest
from .test_bot import TestBot
class TestBotSupport(TestBot):
@pytest.mark.parametrize('url,result', [
('https://google.com', ['https://google.com']),
('google.com', ['google.com']),
('google.com/search?q=instabot', ['google.com/search?q=instabot']),
('https://google.com/search?q=instabot', ['https://google.com/search?q=instabot']),
('мвд.рф', ['мвд.рф']),
('https://мвд.рф', ['https://мвд.рф']),
('http://мвд.рф/news/', ['http://мвд.рф/news/']),
('hello, google.com/search?q=test and bing.com', ['google.com/search?q=test', 'bing.com']),
])
def test_extract_urls(self, url, result):
assert self.BOT.extract_urls(url) == result
def test_check_if_file_exist(self):
test_file = open('test', 'w')
assert self.BOT.check_if_file_exists('test')
test_file.close()
os.remove('test')
def test_check_if_file_exist_fail(self):
assert not self.BOT.check_if_file_exists('test')
| Add test on check file if exist | Add test on check file if exist
| Python | apache-2.0 | instagrambot/instabot,ohld/instabot,instagrambot/instabot | from __future__ import unicode_literals
+
+ import os
import pytest
from .test_bot import TestBot
class TestBotSupport(TestBot):
@pytest.mark.parametrize('url,result', [
('https://google.com', ['https://google.com']),
('google.com', ['google.com']),
('google.com/search?q=instabot', ['google.com/search?q=instabot']),
('https://google.com/search?q=instabot', ['https://google.com/search?q=instabot']),
('мвд.рф', ['мвд.рф']),
('https://мвд.рф', ['https://мвд.рф']),
('http://мвд.рф/news/', ['http://мвд.рф/news/']),
('hello, google.com/search?q=test and bing.com', ['google.com/search?q=test', 'bing.com']),
])
def test_extract_urls(self, url, result):
assert self.BOT.extract_urls(url) == result
+ def test_check_if_file_exist(self):
+ test_file = open('test', 'w')
+
+ assert self.BOT.check_if_file_exists('test')
+
+ test_file.close()
+ os.remove('test')
+
+ def test_check_if_file_exist_fail(self):
+ assert not self.BOT.check_if_file_exists('test')
+ | Add test on check file if exist | ## Code Before:
from __future__ import unicode_literals
import pytest
from .test_bot import TestBot
class TestBotSupport(TestBot):
@pytest.mark.parametrize('url,result', [
('https://google.com', ['https://google.com']),
('google.com', ['google.com']),
('google.com/search?q=instabot', ['google.com/search?q=instabot']),
('https://google.com/search?q=instabot', ['https://google.com/search?q=instabot']),
('мвд.рф', ['мвд.рф']),
('https://мвд.рф', ['https://мвд.рф']),
('http://мвд.рф/news/', ['http://мвд.рф/news/']),
('hello, google.com/search?q=test and bing.com', ['google.com/search?q=test', 'bing.com']),
])
def test_extract_urls(self, url, result):
assert self.BOT.extract_urls(url) == result
## Instruction:
Add test on check file if exist
## Code After:
from __future__ import unicode_literals
import os
import pytest
from .test_bot import TestBot
class TestBotSupport(TestBot):
@pytest.mark.parametrize('url,result', [
('https://google.com', ['https://google.com']),
('google.com', ['google.com']),
('google.com/search?q=instabot', ['google.com/search?q=instabot']),
('https://google.com/search?q=instabot', ['https://google.com/search?q=instabot']),
('мвд.рф', ['мвд.рф']),
('https://мвд.рф', ['https://мвд.рф']),
('http://мвд.рф/news/', ['http://мвд.рф/news/']),
('hello, google.com/search?q=test and bing.com', ['google.com/search?q=test', 'bing.com']),
])
def test_extract_urls(self, url, result):
assert self.BOT.extract_urls(url) == result
def test_check_if_file_exist(self):
test_file = open('test', 'w')
assert self.BOT.check_if_file_exists('test')
test_file.close()
os.remove('test')
def test_check_if_file_exist_fail(self):
assert not self.BOT.check_if_file_exists('test')
| from __future__ import unicode_literals
+
+ import os
import pytest
from .test_bot import TestBot
class TestBotSupport(TestBot):
@pytest.mark.parametrize('url,result', [
('https://google.com', ['https://google.com']),
('google.com', ['google.com']),
('google.com/search?q=instabot', ['google.com/search?q=instabot']),
('https://google.com/search?q=instabot', ['https://google.com/search?q=instabot']),
('мвд.рф', ['мвд.рф']),
('https://мвд.рф', ['https://мвд.рф']),
('http://мвд.рф/news/', ['http://мвд.рф/news/']),
('hello, google.com/search?q=test and bing.com', ['google.com/search?q=test', 'bing.com']),
])
def test_extract_urls(self, url, result):
assert self.BOT.extract_urls(url) == result
+
+ def test_check_if_file_exist(self):
+ test_file = open('test', 'w')
+
+ assert self.BOT.check_if_file_exists('test')
+
+ test_file.close()
+ os.remove('test')
+
+ def test_check_if_file_exist_fail(self):
+ assert not self.BOT.check_if_file_exists('test') |
b6ccc6b6ae6c5fab45f7a27dbecbda88cc8775b8 | SplitNavigation.py | SplitNavigation.py | import sublime, sublime_plugin
class SplitNavigationCommand(sublime_plugin.TextCommand):
def run(self, edit, direction):
win = self.view.window()
num = win.num_groups()
act = win.active_group()
if direction == "up":
act = act + 1
else:
act = act - 1
win.focus_group(act % num)
| import sublime, sublime_plugin
def focusNext(win):
act = win.active_group()
num = win.num_groups()
act += 1
if act >= num:
act = 0
win.focus_group(act)
if len(win.views_in_group(act)) == 0:
focusNext(win)
def focusPrev(win):
act = win.active_group()
num = win.num_groups()
act -= 1
if act < 0:
act = num - 1
win.focus_group(act)
if len(win.views_in_group(act)) == 0:
focusPrev(win)
class SplitNavigationCommand(sublime_plugin.TextCommand):
def run(self, edit, direction):
win = self.view.window()
if direction == "up":
focusNext(win)
else:
focusPrev(win)
| Fix some weird action when user navigates between blank groups. | Fix some weird action when user navigates between blank groups.
| Python | mit | oleander/sublime-split-navigation,oleander/sublime-split-navigation | import sublime, sublime_plugin
+ def focusNext(win):
+ act = win.active_group()
+ num = win.num_groups()
+ act += 1
+
+ if act >= num:
+ act = 0
+
+ win.focus_group(act)
+
+ if len(win.views_in_group(act)) == 0:
+ focusNext(win)
+
+ def focusPrev(win):
+ act = win.active_group()
+ num = win.num_groups()
+ act -= 1
+
+ if act < 0:
+ act = num - 1
+
+ win.focus_group(act)
+
+ if len(win.views_in_group(act)) == 0:
+ focusPrev(win)
+
+
class SplitNavigationCommand(sublime_plugin.TextCommand):
+
def run(self, edit, direction):
win = self.view.window()
- num = win.num_groups()
- act = win.active_group()
if direction == "up":
- act = act + 1
+ focusNext(win)
else:
+ focusPrev(win)
+
- act = act - 1
- win.focus_group(act % num)
- | Fix some weird action when user navigates between blank groups. | ## Code Before:
import sublime, sublime_plugin
class SplitNavigationCommand(sublime_plugin.TextCommand):
def run(self, edit, direction):
win = self.view.window()
num = win.num_groups()
act = win.active_group()
if direction == "up":
act = act + 1
else:
act = act - 1
win.focus_group(act % num)
## Instruction:
Fix some weird action when user navigates between blank groups.
## Code After:
import sublime, sublime_plugin
def focusNext(win):
act = win.active_group()
num = win.num_groups()
act += 1
if act >= num:
act = 0
win.focus_group(act)
if len(win.views_in_group(act)) == 0:
focusNext(win)
def focusPrev(win):
act = win.active_group()
num = win.num_groups()
act -= 1
if act < 0:
act = num - 1
win.focus_group(act)
if len(win.views_in_group(act)) == 0:
focusPrev(win)
class SplitNavigationCommand(sublime_plugin.TextCommand):
def run(self, edit, direction):
win = self.view.window()
if direction == "up":
focusNext(win)
else:
focusPrev(win)
| import sublime, sublime_plugin
+ def focusNext(win):
+ act = win.active_group()
+ num = win.num_groups()
+ act += 1
+
+ if act >= num:
+ act = 0
+
+ win.focus_group(act)
+
+ if len(win.views_in_group(act)) == 0:
+ focusNext(win)
+
+ def focusPrev(win):
+ act = win.active_group()
+ num = win.num_groups()
+ act -= 1
+
+ if act < 0:
+ act = num - 1
+
+ win.focus_group(act)
+
+ if len(win.views_in_group(act)) == 0:
+ focusPrev(win)
+
+
class SplitNavigationCommand(sublime_plugin.TextCommand):
+
def run(self, edit, direction):
win = self.view.window()
- num = win.num_groups()
- act = win.active_group()
if direction == "up":
- act = act + 1
+ focusNext(win)
else:
+ focusPrev(win)
- act = act - 1
- win.focus_group(act % num)
- |
6654c3741f314e6617d53de6468f739b4304c5eb | tequila/deploy.py | tequila/deploy.py | import argparse
import os
from subprocess import check_call
import tequila
def main():
tequila_dir = os.path.dirname(tequila.__file__)
tequila_roles_dir = os.path.join(tequila_dir, 'roles')
if not os.path.exists(tequila_roles_dir):
raise Exception("Something is wrong, tequila roles were expected to be at "
"%s but they're not" % tequila_roles_dir)
os.environ['ANSIBLE_ROLES_PATH'] = 'roles:%s' % tequila_roles_dir
parser = argparse.ArgumentParser()
parser.add_argument("envname")
args = parser.parse_args()
envname = args.envname
check_call(
['ansible-playbook',
'-i', 'inventory/%s' % envname,
'-e', '@inventory/group_vars/%s' % envname,
'-e', 'tequila_dir=%s' % tequila_dir,
'-e', 'env_name=%s' % envname,
'%s/deploy.yml' % tequila_dir,
]
)
| import argparse
import os
from subprocess import check_call
import tequila
def main():
tequila_dir = os.path.dirname(tequila.__file__)
tequila_roles_dir = os.path.join(tequila_dir, 'roles')
if not os.path.exists(tequila_roles_dir):
raise Exception("Something is wrong, tequila roles were expected to be at "
"%s but they're not" % tequila_roles_dir)
os.environ['ANSIBLE_ROLES_PATH'] = 'roles:%s' % tequila_roles_dir
parser = argparse.ArgumentParser()
parser.add_argument("envname")
args = parser.parse_args()
envname = args.envname
options = [
'-i', 'inventory/%s' % envname,
'-e', '@inventory/group_vars/%s' % envname,
'-e', 'tequila_dir=%s' % tequila_dir,
'-e', 'env_name=%s' % envname,
]
if os.path.exists('.vaultpassword'):
options.extend(
['--vault-password-file', '.vaultpassword',
'-e', '@inventory/secrets/%s' % envname,
]
)
else:
print("WARNING: No .vaultpassword file found, will not use any secrets.")
command = ['ansible-playbook'] + options + ['%s/deploy.yml' % tequila_dir]
check_call(command)
| Add support for encrypted secrets | Add support for encrypted secrets
| Python | bsd-3-clause | caktus/tequila-django | import argparse
import os
from subprocess import check_call
import tequila
def main():
tequila_dir = os.path.dirname(tequila.__file__)
tequila_roles_dir = os.path.join(tequila_dir, 'roles')
if not os.path.exists(tequila_roles_dir):
raise Exception("Something is wrong, tequila roles were expected to be at "
"%s but they're not" % tequila_roles_dir)
os.environ['ANSIBLE_ROLES_PATH'] = 'roles:%s' % tequila_roles_dir
parser = argparse.ArgumentParser()
parser.add_argument("envname")
args = parser.parse_args()
envname = args.envname
+ options = [
- check_call(
- ['ansible-playbook',
- '-i', 'inventory/%s' % envname,
+ '-i', 'inventory/%s' % envname,
- '-e', '@inventory/group_vars/%s' % envname,
+ '-e', '@inventory/group_vars/%s' % envname,
- '-e', 'tequila_dir=%s' % tequila_dir,
+ '-e', 'tequila_dir=%s' % tequila_dir,
- '-e', 'env_name=%s' % envname,
+ '-e', 'env_name=%s' % envname,
- '%s/deploy.yml' % tequila_dir,
- ]
- )
+ ]
+ if os.path.exists('.vaultpassword'):
+ options.extend(
+ ['--vault-password-file', '.vaultpassword',
+ '-e', '@inventory/secrets/%s' % envname,
+ ]
+ )
+ else:
+ print("WARNING: No .vaultpassword file found, will not use any secrets.")
+
+ command = ['ansible-playbook'] + options + ['%s/deploy.yml' % tequila_dir]
+
+ check_call(command)
+ | Add support for encrypted secrets | ## Code Before:
import argparse
import os
from subprocess import check_call
import tequila
def main():
tequila_dir = os.path.dirname(tequila.__file__)
tequila_roles_dir = os.path.join(tequila_dir, 'roles')
if not os.path.exists(tequila_roles_dir):
raise Exception("Something is wrong, tequila roles were expected to be at "
"%s but they're not" % tequila_roles_dir)
os.environ['ANSIBLE_ROLES_PATH'] = 'roles:%s' % tequila_roles_dir
parser = argparse.ArgumentParser()
parser.add_argument("envname")
args = parser.parse_args()
envname = args.envname
check_call(
['ansible-playbook',
'-i', 'inventory/%s' % envname,
'-e', '@inventory/group_vars/%s' % envname,
'-e', 'tequila_dir=%s' % tequila_dir,
'-e', 'env_name=%s' % envname,
'%s/deploy.yml' % tequila_dir,
]
)
## Instruction:
Add support for encrypted secrets
## Code After:
import argparse
import os
from subprocess import check_call
import tequila
def main():
tequila_dir = os.path.dirname(tequila.__file__)
tequila_roles_dir = os.path.join(tequila_dir, 'roles')
if not os.path.exists(tequila_roles_dir):
raise Exception("Something is wrong, tequila roles were expected to be at "
"%s but they're not" % tequila_roles_dir)
os.environ['ANSIBLE_ROLES_PATH'] = 'roles:%s' % tequila_roles_dir
parser = argparse.ArgumentParser()
parser.add_argument("envname")
args = parser.parse_args()
envname = args.envname
options = [
'-i', 'inventory/%s' % envname,
'-e', '@inventory/group_vars/%s' % envname,
'-e', 'tequila_dir=%s' % tequila_dir,
'-e', 'env_name=%s' % envname,
]
if os.path.exists('.vaultpassword'):
options.extend(
['--vault-password-file', '.vaultpassword',
'-e', '@inventory/secrets/%s' % envname,
]
)
else:
print("WARNING: No .vaultpassword file found, will not use any secrets.")
command = ['ansible-playbook'] + options + ['%s/deploy.yml' % tequila_dir]
check_call(command)
| import argparse
import os
from subprocess import check_call
import tequila
def main():
tequila_dir = os.path.dirname(tequila.__file__)
tequila_roles_dir = os.path.join(tequila_dir, 'roles')
if not os.path.exists(tequila_roles_dir):
raise Exception("Something is wrong, tequila roles were expected to be at "
"%s but they're not" % tequila_roles_dir)
os.environ['ANSIBLE_ROLES_PATH'] = 'roles:%s' % tequila_roles_dir
parser = argparse.ArgumentParser()
parser.add_argument("envname")
args = parser.parse_args()
envname = args.envname
+ options = [
- check_call(
- ['ansible-playbook',
- '-i', 'inventory/%s' % envname,
? -
+ '-i', 'inventory/%s' % envname,
- '-e', '@inventory/group_vars/%s' % envname,
? -
+ '-e', '@inventory/group_vars/%s' % envname,
- '-e', 'tequila_dir=%s' % tequila_dir,
? -
+ '-e', 'tequila_dir=%s' % tequila_dir,
- '-e', 'env_name=%s' % envname,
? -
+ '-e', 'env_name=%s' % envname,
- '%s/deploy.yml' % tequila_dir,
+ ]
+
+ if os.path.exists('.vaultpassword'):
+ options.extend(
+ ['--vault-password-file', '.vaultpassword',
+ '-e', '@inventory/secrets/%s' % envname,
+ ]
- ]
? ^^
+ )
? ^
- )
+ else:
+ print("WARNING: No .vaultpassword file found, will not use any secrets.")
+
+ command = ['ansible-playbook'] + options + ['%s/deploy.yml' % tequila_dir]
+
+ check_call(command) |
ba5bfeb652804e57203b1794c6293b8227590ac1 | pyinstalive/logger.py | pyinstalive/logger.py | def colors(state):
color = ''
if (state == 'BLUE'):
color = '\033[94m'
if (state == 'GREEN'):
color = '\033[92m'
if (state == 'YELLOW'):
color = '\033[93m'
if (state == 'RED'):
color = '\033[91m'
if (state == 'ENDC'):
color = '\033[0m'
if (state == 'WHITE'):
color = '\033[0m'
return color
def log(string, color):
print('\033[1m' + colors(color) + string + colors("ENDC"))
def seperator(color):
print('\033[1m' + colors(color) + ("-" * 50) + colors("ENDC")) | import sys
import os
def colors(state):
color = ''
if (state == 'BLUE'):
color = '\033[94m'
if (state == 'GREEN'):
color = '\033[92m'
if (state == 'YELLOW'):
color = '\033[93m'
if (state == 'RED'):
color = '\033[91m'
if (state == 'ENDC'):
color = '\033[0m'
if (state == 'WHITE'):
color = '\033[0m'
return color
def supports_color():
"""
from https://github.com/django/django/blob/master/django/core/management/color.py
Return True if the running system's terminal supports color,
and False otherwise.
"""
plat = sys.platform
supported_platform = plat != 'Pocket PC' and (plat != 'win32' or 'ANSICON' in os.environ)
# isatty is not always implemented, #6223.
is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
if not supported_platform or not is_a_tty:
return False
return True
def log(string, color):
if not supports_color():
print(string)
else:
print('\033[1m' + colors(color) + string + colors("ENDC"))
def seperator(color):
if not supports_color():
print("-" * 50)
else:
print('\033[1m' + colors(color) + ("-" * 50) + colors("ENDC")) | Add proper logging support for consoles that don't accept ANSI | Add proper logging support for consoles that don't accept ANSI
| Python | mit | notcammy/PyInstaLive | + import sys
+ import os
+
def colors(state):
color = ''
if (state == 'BLUE'):
color = '\033[94m'
if (state == 'GREEN'):
color = '\033[92m'
if (state == 'YELLOW'):
color = '\033[93m'
if (state == 'RED'):
color = '\033[91m'
if (state == 'ENDC'):
color = '\033[0m'
if (state == 'WHITE'):
color = '\033[0m'
return color
+ def supports_color():
+ """
+ from https://github.com/django/django/blob/master/django/core/management/color.py
+ Return True if the running system's terminal supports color,
+ and False otherwise.
+ """
+
+ plat = sys.platform
+ supported_platform = plat != 'Pocket PC' and (plat != 'win32' or 'ANSICON' in os.environ)
+
+ # isatty is not always implemented, #6223.
+ is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
+ if not supported_platform or not is_a_tty:
+ return False
+ return True
+
def log(string, color):
+ if not supports_color():
+ print(string)
+ else:
- print('\033[1m' + colors(color) + string + colors("ENDC"))
+ print('\033[1m' + colors(color) + string + colors("ENDC"))
def seperator(color):
+ if not supports_color():
+ print("-" * 50)
+ else:
- print('\033[1m' + colors(color) + ("-" * 50) + colors("ENDC"))
+ print('\033[1m' + colors(color) + ("-" * 50) + colors("ENDC")) | Add proper logging support for consoles that don't accept ANSI | ## Code Before:
def colors(state):
color = ''
if (state == 'BLUE'):
color = '\033[94m'
if (state == 'GREEN'):
color = '\033[92m'
if (state == 'YELLOW'):
color = '\033[93m'
if (state == 'RED'):
color = '\033[91m'
if (state == 'ENDC'):
color = '\033[0m'
if (state == 'WHITE'):
color = '\033[0m'
return color
def log(string, color):
print('\033[1m' + colors(color) + string + colors("ENDC"))
def seperator(color):
print('\033[1m' + colors(color) + ("-" * 50) + colors("ENDC"))
## Instruction:
Add proper logging support for consoles that don't accept ANSI
## Code After:
import sys
import os
def colors(state):
color = ''
if (state == 'BLUE'):
color = '\033[94m'
if (state == 'GREEN'):
color = '\033[92m'
if (state == 'YELLOW'):
color = '\033[93m'
if (state == 'RED'):
color = '\033[91m'
if (state == 'ENDC'):
color = '\033[0m'
if (state == 'WHITE'):
color = '\033[0m'
return color
def supports_color():
"""
from https://github.com/django/django/blob/master/django/core/management/color.py
Return True if the running system's terminal supports color,
and False otherwise.
"""
plat = sys.platform
supported_platform = plat != 'Pocket PC' and (plat != 'win32' or 'ANSICON' in os.environ)
# isatty is not always implemented, #6223.
is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
if not supported_platform or not is_a_tty:
return False
return True
def log(string, color):
if not supports_color():
print(string)
else:
print('\033[1m' + colors(color) + string + colors("ENDC"))
def seperator(color):
if not supports_color():
print("-" * 50)
else:
print('\033[1m' + colors(color) + ("-" * 50) + colors("ENDC")) | + import sys
+ import os
+
def colors(state):
color = ''
if (state == 'BLUE'):
color = '\033[94m'
if (state == 'GREEN'):
color = '\033[92m'
if (state == 'YELLOW'):
color = '\033[93m'
if (state == 'RED'):
color = '\033[91m'
if (state == 'ENDC'):
color = '\033[0m'
if (state == 'WHITE'):
color = '\033[0m'
return color
+ def supports_color():
+ """
+ from https://github.com/django/django/blob/master/django/core/management/color.py
+ Return True if the running system's terminal supports color,
+ and False otherwise.
+ """
+
+ plat = sys.platform
+ supported_platform = plat != 'Pocket PC' and (plat != 'win32' or 'ANSICON' in os.environ)
+
+ # isatty is not always implemented, #6223.
+ is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
+ if not supported_platform or not is_a_tty:
+ return False
+ return True
+
def log(string, color):
+ if not supports_color():
+ print(string)
+ else:
- print('\033[1m' + colors(color) + string + colors("ENDC"))
+ print('\033[1m' + colors(color) + string + colors("ENDC"))
? +
def seperator(color):
+ if not supports_color():
+ print("-" * 50)
+ else:
- print('\033[1m' + colors(color) + ("-" * 50) + colors("ENDC"))
+ print('\033[1m' + colors(color) + ("-" * 50) + colors("ENDC"))
? +
|
412dc6e29e47148758382646dd65e0a9c5ff4505 | pymanopt/tools/autodiff/__init__.py | pymanopt/tools/autodiff/__init__.py | class Function(object):
def __init__(self, function, arg, backend):
self._function = function
self._arg = arg
self._backend = backend
self._verify_backend()
self._compile()
def _verify_backend(self):
if not self._backend.is_available():
raise ValueError("Backend `{:s}' is not available".format(
str(self._backend)))
if not self._backend.is_compatible(self._function, self._arg):
raise ValueError("Backend `{:s}' is not compatible with cost "
"function of type `{:s}'".format(
str(self._backend),
self._function.__class__.__name__))
def _compile(self):
assert self._backend is not None
self._compiled_function = self._backend.compile_function(
self._function, self._arg)
def _perform_differentiation(self, attr):
assert self._backend is not None
method = getattr(self._backend, attr)
return method(self._function, self._arg)
def compute_gradient(self):
return self._perform_differentiation("compute_gradient")
def compute_hessian(self):
return self._perform_differentiation("compute_hessian")
def __call__(self, *args, **kwargs):
assert self._compiled_function is not None
return self._compiled_function(*args, **kwargs)
| from ._callable import CallableBackend
from ._autograd import AutogradBackend
from ._pytorch import PyTorchBackend
from ._theano import TheanoBackend
from ._tensorflow import TensorflowBackend
class Function(object):
def __init__(self, function, arg, backend):
self._function = function
self._arg = arg
self._backend = backend
self._verify_backend()
self._compile()
def _verify_backend(self):
if not self._backend.is_available():
raise ValueError("Backend `{:s}' is not available".format(
str(self._backend)))
if not self._backend.is_compatible(self._function, self._arg):
raise ValueError("Backend `{:s}' is not compatible with cost "
"function of type `{:s}'".format(
str(self._backend),
self._function.__class__.__name__))
def _compile(self):
assert self._backend is not None
self._compiled_function = self._backend.compile_function(
self._function, self._arg)
def _perform_differentiation(self, attr):
assert self._backend is not None
method = getattr(self._backend, attr)
return method(self._function, self._arg)
def compute_gradient(self):
return self._perform_differentiation("compute_gradient")
def compute_hessian(self):
return self._perform_differentiation("compute_hessian")
def __call__(self, *args, **kwargs):
assert self._compiled_function is not None
return self._compiled_function(*args, **kwargs)
| Revert "autodiff: remove unused imports" | Revert "autodiff: remove unused imports"
This reverts commit d0ad4944671d94673d0051bd8faf4f3cf5d93ca9.
| Python | bsd-3-clause | pymanopt/pymanopt,pymanopt/pymanopt,nkoep/pymanopt,nkoep/pymanopt,nkoep/pymanopt | + from ._callable import CallableBackend
+ from ._autograd import AutogradBackend
+ from ._pytorch import PyTorchBackend
+ from ._theano import TheanoBackend
+ from ._tensorflow import TensorflowBackend
+
+
class Function(object):
def __init__(self, function, arg, backend):
self._function = function
self._arg = arg
self._backend = backend
self._verify_backend()
self._compile()
def _verify_backend(self):
if not self._backend.is_available():
raise ValueError("Backend `{:s}' is not available".format(
str(self._backend)))
if not self._backend.is_compatible(self._function, self._arg):
raise ValueError("Backend `{:s}' is not compatible with cost "
"function of type `{:s}'".format(
str(self._backend),
self._function.__class__.__name__))
def _compile(self):
assert self._backend is not None
self._compiled_function = self._backend.compile_function(
self._function, self._arg)
def _perform_differentiation(self, attr):
assert self._backend is not None
method = getattr(self._backend, attr)
return method(self._function, self._arg)
def compute_gradient(self):
return self._perform_differentiation("compute_gradient")
def compute_hessian(self):
return self._perform_differentiation("compute_hessian")
def __call__(self, *args, **kwargs):
assert self._compiled_function is not None
return self._compiled_function(*args, **kwargs)
| Revert "autodiff: remove unused imports" | ## Code Before:
class Function(object):
def __init__(self, function, arg, backend):
self._function = function
self._arg = arg
self._backend = backend
self._verify_backend()
self._compile()
def _verify_backend(self):
if not self._backend.is_available():
raise ValueError("Backend `{:s}' is not available".format(
str(self._backend)))
if not self._backend.is_compatible(self._function, self._arg):
raise ValueError("Backend `{:s}' is not compatible with cost "
"function of type `{:s}'".format(
str(self._backend),
self._function.__class__.__name__))
def _compile(self):
assert self._backend is not None
self._compiled_function = self._backend.compile_function(
self._function, self._arg)
def _perform_differentiation(self, attr):
assert self._backend is not None
method = getattr(self._backend, attr)
return method(self._function, self._arg)
def compute_gradient(self):
return self._perform_differentiation("compute_gradient")
def compute_hessian(self):
return self._perform_differentiation("compute_hessian")
def __call__(self, *args, **kwargs):
assert self._compiled_function is not None
return self._compiled_function(*args, **kwargs)
## Instruction:
Revert "autodiff: remove unused imports"
## Code After:
from ._callable import CallableBackend
from ._autograd import AutogradBackend
from ._pytorch import PyTorchBackend
from ._theano import TheanoBackend
from ._tensorflow import TensorflowBackend
class Function(object):
def __init__(self, function, arg, backend):
self._function = function
self._arg = arg
self._backend = backend
self._verify_backend()
self._compile()
def _verify_backend(self):
if not self._backend.is_available():
raise ValueError("Backend `{:s}' is not available".format(
str(self._backend)))
if not self._backend.is_compatible(self._function, self._arg):
raise ValueError("Backend `{:s}' is not compatible with cost "
"function of type `{:s}'".format(
str(self._backend),
self._function.__class__.__name__))
def _compile(self):
assert self._backend is not None
self._compiled_function = self._backend.compile_function(
self._function, self._arg)
def _perform_differentiation(self, attr):
assert self._backend is not None
method = getattr(self._backend, attr)
return method(self._function, self._arg)
def compute_gradient(self):
return self._perform_differentiation("compute_gradient")
def compute_hessian(self):
return self._perform_differentiation("compute_hessian")
def __call__(self, *args, **kwargs):
assert self._compiled_function is not None
return self._compiled_function(*args, **kwargs)
| + from ._callable import CallableBackend
+ from ._autograd import AutogradBackend
+ from ._pytorch import PyTorchBackend
+ from ._theano import TheanoBackend
+ from ._tensorflow import TensorflowBackend
+
+
class Function(object):
def __init__(self, function, arg, backend):
self._function = function
self._arg = arg
self._backend = backend
self._verify_backend()
self._compile()
def _verify_backend(self):
if not self._backend.is_available():
raise ValueError("Backend `{:s}' is not available".format(
str(self._backend)))
if not self._backend.is_compatible(self._function, self._arg):
raise ValueError("Backend `{:s}' is not compatible with cost "
"function of type `{:s}'".format(
str(self._backend),
self._function.__class__.__name__))
def _compile(self):
assert self._backend is not None
self._compiled_function = self._backend.compile_function(
self._function, self._arg)
def _perform_differentiation(self, attr):
assert self._backend is not None
method = getattr(self._backend, attr)
return method(self._function, self._arg)
def compute_gradient(self):
return self._perform_differentiation("compute_gradient")
def compute_hessian(self):
return self._perform_differentiation("compute_hessian")
def __call__(self, *args, **kwargs):
assert self._compiled_function is not None
return self._compiled_function(*args, **kwargs) |
c8360831ab2fa4d5af2929a85beca4a1f33ef9d1 | travis_settings.py | travis_settings.py | from settings import *
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'alexia_test', # Of pad naar sqlite3 database
# Hieronder negeren voor sqlite3
'USER': '',
'PASSWORD': '',
'HOST': '', # Leeg voor localhost
'PORT': '', # Leeg is default
}
}
SECRET_KEY = 'zBCMvM1BwLtlkoXf1mbgCo3W60j2UgIPhevmEJ9cMPft2JtUk5'
| from settings import *
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'alexia_test', # Of pad naar sqlite3 database
# Hieronder negeren voor sqlite3
'USER': 'travis',
'PASSWORD': '',
'HOST': '', # Leeg voor localhost
'PORT': '', # Leeg is default
}
}
SECRET_KEY = 'zBCMvM1BwLtlkoXf1mbgCo3W60j2UgIPhevmEJ9cMPft2JtUk5'
| Use MySQL database backend in Travis CI. | Use MySQL database backend in Travis CI.
| Python | bsd-3-clause | Inter-Actief/alexia,Inter-Actief/alexia,Inter-Actief/alexia,Inter-Actief/alexia | from settings import *
# Database
DATABASES = {
'default': {
- 'ENGINE': 'django.db.backends.sqlite3', # 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
+ 'ENGINE': 'django.db.backends.mysql', # 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'alexia_test', # Of pad naar sqlite3 database
# Hieronder negeren voor sqlite3
- 'USER': '',
+ 'USER': 'travis',
'PASSWORD': '',
'HOST': '', # Leeg voor localhost
'PORT': '', # Leeg is default
}
}
SECRET_KEY = 'zBCMvM1BwLtlkoXf1mbgCo3W60j2UgIPhevmEJ9cMPft2JtUk5'
| Use MySQL database backend in Travis CI. | ## Code Before:
from settings import *
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'alexia_test', # Of pad naar sqlite3 database
# Hieronder negeren voor sqlite3
'USER': '',
'PASSWORD': '',
'HOST': '', # Leeg voor localhost
'PORT': '', # Leeg is default
}
}
SECRET_KEY = 'zBCMvM1BwLtlkoXf1mbgCo3W60j2UgIPhevmEJ9cMPft2JtUk5'
## Instruction:
Use MySQL database backend in Travis CI.
## Code After:
from settings import *
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'alexia_test', # Of pad naar sqlite3 database
# Hieronder negeren voor sqlite3
'USER': 'travis',
'PASSWORD': '',
'HOST': '', # Leeg voor localhost
'PORT': '', # Leeg is default
}
}
SECRET_KEY = 'zBCMvM1BwLtlkoXf1mbgCo3W60j2UgIPhevmEJ9cMPft2JtUk5'
| from settings import *
# Database
DATABASES = {
'default': {
- 'ENGINE': 'django.db.backends.sqlite3', # 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
? ----
+ 'ENGINE': 'django.db.backends.mysql', # 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
? ++
'NAME': 'alexia_test', # Of pad naar sqlite3 database
# Hieronder negeren voor sqlite3
- 'USER': '',
+ 'USER': 'travis',
? ++++++
'PASSWORD': '',
'HOST': '', # Leeg voor localhost
'PORT': '', # Leeg is default
}
}
SECRET_KEY = 'zBCMvM1BwLtlkoXf1mbgCo3W60j2UgIPhevmEJ9cMPft2JtUk5' |
d7fa7d2bacd45a50f14e4e1aeae57cfc56a315db | __init__.py | __init__.py | from openedoo_project import db
from openedoo.core.libs import Blueprint
from .controllers.employee import EmployeeLogin, EmployeeLogout, AddEmployee, \
AssignEmployeeAsTeacher, EmployeeDashboard, EditEmployee, DeleteEmployee, \
SearchEmployee, AddSubject
module_employee = Blueprint('module_employee', __name__,
template_folder='templates',
static_folder='static')
module_employee.add_url_rule('/admin/dashboard',
view_func=EmployeeDashboard.as_view('dashboard'))
module_employee.add_url_rule('/admin/login',
view_func=EmployeeLogin.as_view('login'))
module_employee.add_url_rule('/admin/logout',
view_func=EmployeeLogout.as_view('logout'))
module_employee.add_url_rule('/admin/add',
view_func=AddEmployee.as_view('add'))
module_employee.add_url_rule('/admin/edit',
view_func=EditEmployee.as_view('edit'))
assignEmployeeAsTeacherView = AssignEmployeeAsTeacher.as_view('assign')
module_employee.add_url_rule('/admin/assign',
view_func=assignEmployeeAsTeacherView)
module_employee.add_url_rule('/admin/delete',
view_func=DeleteEmployee.as_view('delete'))
module_employee.add_url_rule('/search',
view_func=SearchEmployee.as_view('search'))
module_employee.add_url_rule('/admin/subject/add',
view_func=AddSubject.as_view('add_subject'))
| from openedoo_project import db
from openedoo.core.libs import Blueprint
from .controllers.employee import EmployeeLogin, EmployeeLogout, AddEmployee, \
AssignEmployeeAsTeacher, EmployeeDashboard, EditEmployee, DeleteEmployee, \
SearchEmployee, AddSubject
module_employee = Blueprint('module_employee', __name__,
template_folder='templates',
static_folder='static')
module_employee.add_url_rule('/admin',
view_func=EmployeeDashboard.as_view('dashboard'))
module_employee.add_url_rule('/admin/login',
view_func=EmployeeLogin.as_view('login'))
module_employee.add_url_rule('/admin/logout',
view_func=EmployeeLogout.as_view('logout'))
module_employee.add_url_rule('/admin/add',
view_func=AddEmployee.as_view('add'))
module_employee.add_url_rule('/admin/edit',
view_func=EditEmployee.as_view('edit'))
assignEmployeeAsTeacherView = AssignEmployeeAsTeacher.as_view('assign')
module_employee.add_url_rule('/admin/assign',
view_func=assignEmployeeAsTeacherView)
module_employee.add_url_rule('/admin/delete',
view_func=DeleteEmployee.as_view('delete'))
module_employee.add_url_rule('/search',
view_func=SearchEmployee.as_view('search'))
module_employee.add_url_rule('/admin/subject/add',
view_func=AddSubject.as_view('add_subject'))
| Make dashboard route become admin's default | Make dashboard route become admin's default
| Python | mit | openedoo/module_employee,openedoo/module_employee,openedoo/module_employee | from openedoo_project import db
from openedoo.core.libs import Blueprint
from .controllers.employee import EmployeeLogin, EmployeeLogout, AddEmployee, \
AssignEmployeeAsTeacher, EmployeeDashboard, EditEmployee, DeleteEmployee, \
SearchEmployee, AddSubject
module_employee = Blueprint('module_employee', __name__,
template_folder='templates',
static_folder='static')
- module_employee.add_url_rule('/admin/dashboard',
+ module_employee.add_url_rule('/admin',
view_func=EmployeeDashboard.as_view('dashboard'))
module_employee.add_url_rule('/admin/login',
view_func=EmployeeLogin.as_view('login'))
module_employee.add_url_rule('/admin/logout',
view_func=EmployeeLogout.as_view('logout'))
module_employee.add_url_rule('/admin/add',
view_func=AddEmployee.as_view('add'))
module_employee.add_url_rule('/admin/edit',
view_func=EditEmployee.as_view('edit'))
assignEmployeeAsTeacherView = AssignEmployeeAsTeacher.as_view('assign')
module_employee.add_url_rule('/admin/assign',
view_func=assignEmployeeAsTeacherView)
module_employee.add_url_rule('/admin/delete',
view_func=DeleteEmployee.as_view('delete'))
module_employee.add_url_rule('/search',
view_func=SearchEmployee.as_view('search'))
module_employee.add_url_rule('/admin/subject/add',
view_func=AddSubject.as_view('add_subject'))
| Make dashboard route become admin's default | ## Code Before:
from openedoo_project import db
from openedoo.core.libs import Blueprint
from .controllers.employee import EmployeeLogin, EmployeeLogout, AddEmployee, \
AssignEmployeeAsTeacher, EmployeeDashboard, EditEmployee, DeleteEmployee, \
SearchEmployee, AddSubject
module_employee = Blueprint('module_employee', __name__,
template_folder='templates',
static_folder='static')
module_employee.add_url_rule('/admin/dashboard',
view_func=EmployeeDashboard.as_view('dashboard'))
module_employee.add_url_rule('/admin/login',
view_func=EmployeeLogin.as_view('login'))
module_employee.add_url_rule('/admin/logout',
view_func=EmployeeLogout.as_view('logout'))
module_employee.add_url_rule('/admin/add',
view_func=AddEmployee.as_view('add'))
module_employee.add_url_rule('/admin/edit',
view_func=EditEmployee.as_view('edit'))
assignEmployeeAsTeacherView = AssignEmployeeAsTeacher.as_view('assign')
module_employee.add_url_rule('/admin/assign',
view_func=assignEmployeeAsTeacherView)
module_employee.add_url_rule('/admin/delete',
view_func=DeleteEmployee.as_view('delete'))
module_employee.add_url_rule('/search',
view_func=SearchEmployee.as_view('search'))
module_employee.add_url_rule('/admin/subject/add',
view_func=AddSubject.as_view('add_subject'))
## Instruction:
Make dashboard route become admin's default
## Code After:
from openedoo_project import db
from openedoo.core.libs import Blueprint
from .controllers.employee import EmployeeLogin, EmployeeLogout, AddEmployee, \
AssignEmployeeAsTeacher, EmployeeDashboard, EditEmployee, DeleteEmployee, \
SearchEmployee, AddSubject
module_employee = Blueprint('module_employee', __name__,
template_folder='templates',
static_folder='static')
module_employee.add_url_rule('/admin',
view_func=EmployeeDashboard.as_view('dashboard'))
module_employee.add_url_rule('/admin/login',
view_func=EmployeeLogin.as_view('login'))
module_employee.add_url_rule('/admin/logout',
view_func=EmployeeLogout.as_view('logout'))
module_employee.add_url_rule('/admin/add',
view_func=AddEmployee.as_view('add'))
module_employee.add_url_rule('/admin/edit',
view_func=EditEmployee.as_view('edit'))
assignEmployeeAsTeacherView = AssignEmployeeAsTeacher.as_view('assign')
module_employee.add_url_rule('/admin/assign',
view_func=assignEmployeeAsTeacherView)
module_employee.add_url_rule('/admin/delete',
view_func=DeleteEmployee.as_view('delete'))
module_employee.add_url_rule('/search',
view_func=SearchEmployee.as_view('search'))
module_employee.add_url_rule('/admin/subject/add',
view_func=AddSubject.as_view('add_subject'))
| from openedoo_project import db
from openedoo.core.libs import Blueprint
from .controllers.employee import EmployeeLogin, EmployeeLogout, AddEmployee, \
AssignEmployeeAsTeacher, EmployeeDashboard, EditEmployee, DeleteEmployee, \
SearchEmployee, AddSubject
module_employee = Blueprint('module_employee', __name__,
template_folder='templates',
static_folder='static')
- module_employee.add_url_rule('/admin/dashboard',
? ----------
+ module_employee.add_url_rule('/admin',
view_func=EmployeeDashboard.as_view('dashboard'))
module_employee.add_url_rule('/admin/login',
view_func=EmployeeLogin.as_view('login'))
module_employee.add_url_rule('/admin/logout',
view_func=EmployeeLogout.as_view('logout'))
module_employee.add_url_rule('/admin/add',
view_func=AddEmployee.as_view('add'))
module_employee.add_url_rule('/admin/edit',
view_func=EditEmployee.as_view('edit'))
assignEmployeeAsTeacherView = AssignEmployeeAsTeacher.as_view('assign')
module_employee.add_url_rule('/admin/assign',
view_func=assignEmployeeAsTeacherView)
module_employee.add_url_rule('/admin/delete',
view_func=DeleteEmployee.as_view('delete'))
module_employee.add_url_rule('/search',
view_func=SearchEmployee.as_view('search'))
module_employee.add_url_rule('/admin/subject/add',
view_func=AddSubject.as_view('add_subject')) |
684ac5e6e6011581d5abcb42a7c0e54742f20606 | Arduino/IMUstream_WifiUDP_iot33/read_UDP_JSON_IMU.py | Arduino/IMUstream_WifiUDP_iot33/read_UDP_JSON_IMU.py | import socket, traceback
import time
import json
host = ''
port = 2390
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.bind((host, port))
filein = open('saveUDP.txt', 'w')
t0 = time.time()
while time.time()-t0 < 200:
try:
message, address = s.recvfrom(4096)
print(message)
json.loads(message.decode("utf-8"))
filein.write('%s\n' % (message))
except (KeyboardInterrupt, SystemExit):
raise
except:
traceback.print_exc()
filein.close()
# -------------------------------------------------------
| import socket, traceback
import time
import json
import numpy as np
from scipy.spatial.transform import Rotation as R
host = ''
port = 2390
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.bind((host, port))
filein = open('saveUDP.txt', 'w')
t0 = time.time()
# Place IMU x-axis into wind going direction when launching script
is_init_done = False
wind_yaw = 0
while time.time()-t0 < 200:
try:
message, address = s.recvfrom(4096)
#print(message)
msg = json.loads(message.decode("utf-8"))
if is_init_done==False:
wind_yaw = msg["Yaw"]
is_init_done = True
msg['Yaw'] = msg['Yaw']-wind_yaw
print(msg)
ypr = [msg['Yaw'], msg['Pitch'], msg['Roll']]
seq = 'ZYX' # small letters from intrinsic rotations
r = R.from_euler(seq, ypr, degrees=True)
# Compute coordinates in NED (could be useful to compare position with GPS position for example)
line_length = 10
base_to_kite = [0, 0, line_length]
base_to_kite_in_NED = r.apply(base_to_kite)
# Express kite coordinates as great roll, great pitch and small yaw angles
grpy=r.as_euler(seq="XYZ")
print(grpy*180/np.pi)
filein.write('%s\n' % (message))
except (KeyboardInterrupt, SystemExit):
raise
except:
traceback.print_exc()
filein.close()
# -------------------------------------------------------
| Add computations of great roll, pitch and small yaw angle (kite angles) | Add computations of great roll, pitch and small yaw angle (kite angles)
| Python | mit | baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite | import socket, traceback
import time
import json
+
+ import numpy as np
+ from scipy.spatial.transform import Rotation as R
host = ''
port = 2390
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.bind((host, port))
filein = open('saveUDP.txt', 'w')
t0 = time.time()
+
+ # Place IMU x-axis into wind going direction when launching script
+ is_init_done = False
+ wind_yaw = 0
while time.time()-t0 < 200:
try:
message, address = s.recvfrom(4096)
- print(message)
+ #print(message)
- json.loads(message.decode("utf-8"))
+ msg = json.loads(message.decode("utf-8"))
+ if is_init_done==False:
+ wind_yaw = msg["Yaw"]
+ is_init_done = True
+ msg['Yaw'] = msg['Yaw']-wind_yaw
+ print(msg)
+
+ ypr = [msg['Yaw'], msg['Pitch'], msg['Roll']]
+ seq = 'ZYX' # small letters from intrinsic rotations
+
+ r = R.from_euler(seq, ypr, degrees=True)
+
+ # Compute coordinates in NED (could be useful to compare position with GPS position for example)
+ line_length = 10
+ base_to_kite = [0, 0, line_length]
+ base_to_kite_in_NED = r.apply(base_to_kite)
+
+ # Express kite coordinates as great roll, great pitch and small yaw angles
+ grpy=r.as_euler(seq="XYZ")
+ print(grpy*180/np.pi)
+
filein.write('%s\n' % (message))
except (KeyboardInterrupt, SystemExit):
raise
except:
traceback.print_exc()
filein.close()
# -------------------------------------------------------
| Add computations of great roll, pitch and small yaw angle (kite angles) | ## Code Before:
import socket, traceback
import time
import json
host = ''
port = 2390
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.bind((host, port))
filein = open('saveUDP.txt', 'w')
t0 = time.time()
while time.time()-t0 < 200:
try:
message, address = s.recvfrom(4096)
print(message)
json.loads(message.decode("utf-8"))
filein.write('%s\n' % (message))
except (KeyboardInterrupt, SystemExit):
raise
except:
traceback.print_exc()
filein.close()
# -------------------------------------------------------
## Instruction:
Add computations of great roll, pitch and small yaw angle (kite angles)
## Code After:
import socket, traceback
import time
import json
import numpy as np
from scipy.spatial.transform import Rotation as R
host = ''
port = 2390
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.bind((host, port))
filein = open('saveUDP.txt', 'w')
t0 = time.time()
# Place IMU x-axis into wind going direction when launching script
is_init_done = False
wind_yaw = 0
while time.time()-t0 < 200:
try:
message, address = s.recvfrom(4096)
#print(message)
msg = json.loads(message.decode("utf-8"))
if is_init_done==False:
wind_yaw = msg["Yaw"]
is_init_done = True
msg['Yaw'] = msg['Yaw']-wind_yaw
print(msg)
ypr = [msg['Yaw'], msg['Pitch'], msg['Roll']]
seq = 'ZYX' # small letters from intrinsic rotations
r = R.from_euler(seq, ypr, degrees=True)
# Compute coordinates in NED (could be useful to compare position with GPS position for example)
line_length = 10
base_to_kite = [0, 0, line_length]
base_to_kite_in_NED = r.apply(base_to_kite)
# Express kite coordinates as great roll, great pitch and small yaw angles
grpy=r.as_euler(seq="XYZ")
print(grpy*180/np.pi)
filein.write('%s\n' % (message))
except (KeyboardInterrupt, SystemExit):
raise
except:
traceback.print_exc()
filein.close()
# -------------------------------------------------------
| import socket, traceback
import time
import json
+
+ import numpy as np
+ from scipy.spatial.transform import Rotation as R
host = ''
port = 2390
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.bind((host, port))
filein = open('saveUDP.txt', 'w')
t0 = time.time()
+
+ # Place IMU x-axis into wind going direction when launching script
+ is_init_done = False
+ wind_yaw = 0
while time.time()-t0 < 200:
try:
message, address = s.recvfrom(4096)
- print(message)
+ #print(message)
? +
- json.loads(message.decode("utf-8"))
+ msg = json.loads(message.decode("utf-8"))
? ++++++
+ if is_init_done==False:
+ wind_yaw = msg["Yaw"]
+ is_init_done = True
+ msg['Yaw'] = msg['Yaw']-wind_yaw
+ print(msg)
+
+ ypr = [msg['Yaw'], msg['Pitch'], msg['Roll']]
+ seq = 'ZYX' # small letters from intrinsic rotations
+
+ r = R.from_euler(seq, ypr, degrees=True)
+
+ # Compute coordinates in NED (could be useful to compare position with GPS position for example)
+ line_length = 10
+ base_to_kite = [0, 0, line_length]
+ base_to_kite_in_NED = r.apply(base_to_kite)
+
+ # Express kite coordinates as great roll, great pitch and small yaw angles
+ grpy=r.as_euler(seq="XYZ")
+ print(grpy*180/np.pi)
+
filein.write('%s\n' % (message))
except (KeyboardInterrupt, SystemExit):
raise
except:
traceback.print_exc()
filein.close()
# ------------------------------------------------------- |
90a265c9c673856a6f119ab04bbd5d57ab375dc6 | django_fsm_log/models.py | django_fsm_log/models.py | from __future__ import unicode_literals
from django.conf import settings
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django_fsm.signals import post_transition
from .managers import StateLogManager
class StateLog(models.Model):
timestamp = models.DateTimeField(auto_now_add=True)
by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True)
state = models.CharField(max_length=255, db_index=True)
transition = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = GenericForeignKey('content_type', 'object_id')
objects = StateLogManager()
def transition_callback(sender, instance, name, source, target, **kwargs):
state_log = StateLog(
by=getattr(instance, 'by', None),
state=target,
transition=name,
content_object=instance,
)
state_log.save()
post_transition.connect(transition_callback)
| from __future__ import unicode_literals
from django.conf import settings
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.timezone import now
from django_fsm.signals import post_transition
from .managers import StateLogManager
class StateLog(models.Model):
timestamp = models.DateTimeField(default=now)
by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True)
state = models.CharField(max_length=255, db_index=True)
transition = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = GenericForeignKey('content_type', 'object_id')
objects = StateLogManager()
def transition_callback(sender, instance, name, source, target, **kwargs):
state_log = StateLog(
by=getattr(instance, 'by', None),
state=target,
transition=name,
content_object=instance,
)
state_log.save()
post_transition.connect(transition_callback)
| Switch from auto_now_add=True to default=now | Switch from auto_now_add=True to default=now
This allows for optional direct setting of the timestamp, eg when loading fixtures. | Python | mit | ticosax/django-fsm-log,blueyed/django-fsm-log,Andrey86/django-fsm-log,gizmag/django-fsm-log,fjcapdevila/django-fsm-log,mord4z/django-fsm-log,pombredanne/django-fsm-log | from __future__ import unicode_literals
from django.conf import settings
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
+ from django.utils.timezone import now
from django_fsm.signals import post_transition
from .managers import StateLogManager
class StateLog(models.Model):
- timestamp = models.DateTimeField(auto_now_add=True)
+ timestamp = models.DateTimeField(default=now)
by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True)
state = models.CharField(max_length=255, db_index=True)
transition = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = GenericForeignKey('content_type', 'object_id')
objects = StateLogManager()
def transition_callback(sender, instance, name, source, target, **kwargs):
state_log = StateLog(
by=getattr(instance, 'by', None),
state=target,
transition=name,
content_object=instance,
)
state_log.save()
post_transition.connect(transition_callback)
| Switch from auto_now_add=True to default=now | ## Code Before:
from __future__ import unicode_literals
from django.conf import settings
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django_fsm.signals import post_transition
from .managers import StateLogManager
class StateLog(models.Model):
timestamp = models.DateTimeField(auto_now_add=True)
by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True)
state = models.CharField(max_length=255, db_index=True)
transition = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = GenericForeignKey('content_type', 'object_id')
objects = StateLogManager()
def transition_callback(sender, instance, name, source, target, **kwargs):
state_log = StateLog(
by=getattr(instance, 'by', None),
state=target,
transition=name,
content_object=instance,
)
state_log.save()
post_transition.connect(transition_callback)
## Instruction:
Switch from auto_now_add=True to default=now
## Code After:
from __future__ import unicode_literals
from django.conf import settings
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.timezone import now
from django_fsm.signals import post_transition
from .managers import StateLogManager
class StateLog(models.Model):
timestamp = models.DateTimeField(default=now)
by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True)
state = models.CharField(max_length=255, db_index=True)
transition = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = GenericForeignKey('content_type', 'object_id')
objects = StateLogManager()
def transition_callback(sender, instance, name, source, target, **kwargs):
state_log = StateLog(
by=getattr(instance, 'by', None),
state=target,
transition=name,
content_object=instance,
)
state_log.save()
post_transition.connect(transition_callback)
| from __future__ import unicode_literals
from django.conf import settings
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
+ from django.utils.timezone import now
from django_fsm.signals import post_transition
from .managers import StateLogManager
class StateLog(models.Model):
- timestamp = models.DateTimeField(auto_now_add=True)
? ^^ ---------
+ timestamp = models.DateTimeField(default=now)
? +++ + ^
by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True)
state = models.CharField(max_length=255, db_index=True)
transition = models.CharField(max_length=255)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = GenericForeignKey('content_type', 'object_id')
objects = StateLogManager()
def transition_callback(sender, instance, name, source, target, **kwargs):
state_log = StateLog(
by=getattr(instance, 'by', None),
state=target,
transition=name,
content_object=instance,
)
state_log.save()
post_transition.connect(transition_callback) |
3ec5c0a742054177be525182f42b69d48f837aff | rache/utils.py | rache/utils.py | import os
try:
from urllib import parse
except ImportError:
import urlparse as parse
def parse_redis_url():
config = {
'host': 'localhost',
'port': 6379,
'password': None,
'db': 0,
}
parsed_redis = parse.urlparse(
os.environ.get('REDIS_URL', 'redis://localhost:6379/0'))
if '?' in parsed_redis.path and not parsed_redis.query:
# Bug in python 2.7.3, fixed in 2.7.4
path, q, querystring = parsed_redis.path.partition('?')
else:
path, q, querystring = parsed_redis.path, None, parsed_redis.query
if path[1:]:
config['db'] = int(path[1:])
querystring = parse.parse_qs(querystring)
for key in querystring.keys():
querystring[key] = querystring[key][0]
for key in config.keys():
querystring.pop(key, None)
host, colon, port = parsed_redis.netloc.partition(':')
if '@' in host:
password, at, host = host.partition('@')
config['password'] = password
config['host'] = host
config['port'] = int(port)
return config
| import os
try:
from urllib import parse
except ImportError:
import urlparse as parse
def parse_redis_url():
config = {
'host': 'localhost',
'port': 6379,
'password': None,
'db': 0,
}
parsed_redis = parse.urlparse(
os.environ.get('REDIS_URL', 'redis://localhost:6379/0'))
if '?' in parsed_redis.path and not parsed_redis.query:
# Bug in python 2.7.3, fixed in 2.7.4
path, q, querystring = parsed_redis.path.partition('?')
else:
path, q, querystring = parsed_redis.path, None, parsed_redis.query
if parsed_redis.netloc.endswith('unix'):
del config['port']
del config['host']
# the last item of the path could also be just part of the socket path
try:
config['db'] = int(os.path.split(path)[-1])
except ValueError:
pass
else:
path = os.path.join(*os.path.split(path)[:-1])
config['unix_socket_path'] = path
if parsed_redis.password:
config['password'] = parsed_redis.password
else:
if path[1:]:
config['db'] = int(path[1:])
if parsed_redis.password:
config['password'] = parsed_redis.password
if parsed_redis.port:
config['port'] = int(parsed_redis.port)
if parsed_redis.hostname:
config['host'] = parsed_redis.hostname
return config
| Support unix sockets in the Redis URL parser. | Support unix sockets in the Redis URL parser.
| Python | bsd-3-clause | brutasse/rache | import os
try:
from urllib import parse
except ImportError:
import urlparse as parse
def parse_redis_url():
config = {
'host': 'localhost',
'port': 6379,
'password': None,
'db': 0,
}
parsed_redis = parse.urlparse(
os.environ.get('REDIS_URL', 'redis://localhost:6379/0'))
if '?' in parsed_redis.path and not parsed_redis.query:
# Bug in python 2.7.3, fixed in 2.7.4
path, q, querystring = parsed_redis.path.partition('?')
else:
path, q, querystring = parsed_redis.path, None, parsed_redis.query
+
+ if parsed_redis.netloc.endswith('unix'):
+ del config['port']
+ del config['host']
+ # the last item of the path could also be just part of the socket path
+ try:
+ config['db'] = int(os.path.split(path)[-1])
+ except ValueError:
+ pass
+ else:
+ path = os.path.join(*os.path.split(path)[:-1])
+ config['unix_socket_path'] = path
+ if parsed_redis.password:
+ config['password'] = parsed_redis.password
+ else:
- if path[1:]:
+ if path[1:]:
- config['db'] = int(path[1:])
+ config['db'] = int(path[1:])
+ if parsed_redis.password:
- querystring = parse.parse_qs(querystring)
- for key in querystring.keys():
- querystring[key] = querystring[key][0]
- for key in config.keys():
- querystring.pop(key, None)
- host, colon, port = parsed_redis.netloc.partition(':')
- if '@' in host:
- password, at, host = host.partition('@')
- config['password'] = password
+ config['password'] = parsed_redis.password
- config['host'] = host
- config['port'] = int(port)
+ if parsed_redis.port:
+ config['port'] = int(parsed_redis.port)
+ if parsed_redis.hostname:
+ config['host'] = parsed_redis.hostname
+
return config
| Support unix sockets in the Redis URL parser. | ## Code Before:
import os
try:
from urllib import parse
except ImportError:
import urlparse as parse
def parse_redis_url():
config = {
'host': 'localhost',
'port': 6379,
'password': None,
'db': 0,
}
parsed_redis = parse.urlparse(
os.environ.get('REDIS_URL', 'redis://localhost:6379/0'))
if '?' in parsed_redis.path and not parsed_redis.query:
# Bug in python 2.7.3, fixed in 2.7.4
path, q, querystring = parsed_redis.path.partition('?')
else:
path, q, querystring = parsed_redis.path, None, parsed_redis.query
if path[1:]:
config['db'] = int(path[1:])
querystring = parse.parse_qs(querystring)
for key in querystring.keys():
querystring[key] = querystring[key][0]
for key in config.keys():
querystring.pop(key, None)
host, colon, port = parsed_redis.netloc.partition(':')
if '@' in host:
password, at, host = host.partition('@')
config['password'] = password
config['host'] = host
config['port'] = int(port)
return config
## Instruction:
Support unix sockets in the Redis URL parser.
## Code After:
import os
try:
from urllib import parse
except ImportError:
import urlparse as parse
def parse_redis_url():
config = {
'host': 'localhost',
'port': 6379,
'password': None,
'db': 0,
}
parsed_redis = parse.urlparse(
os.environ.get('REDIS_URL', 'redis://localhost:6379/0'))
if '?' in parsed_redis.path and not parsed_redis.query:
# Bug in python 2.7.3, fixed in 2.7.4
path, q, querystring = parsed_redis.path.partition('?')
else:
path, q, querystring = parsed_redis.path, None, parsed_redis.query
if parsed_redis.netloc.endswith('unix'):
del config['port']
del config['host']
# the last item of the path could also be just part of the socket path
try:
config['db'] = int(os.path.split(path)[-1])
except ValueError:
pass
else:
path = os.path.join(*os.path.split(path)[:-1])
config['unix_socket_path'] = path
if parsed_redis.password:
config['password'] = parsed_redis.password
else:
if path[1:]:
config['db'] = int(path[1:])
if parsed_redis.password:
config['password'] = parsed_redis.password
if parsed_redis.port:
config['port'] = int(parsed_redis.port)
if parsed_redis.hostname:
config['host'] = parsed_redis.hostname
return config
| import os
try:
from urllib import parse
except ImportError:
import urlparse as parse
def parse_redis_url():
config = {
'host': 'localhost',
'port': 6379,
'password': None,
'db': 0,
}
parsed_redis = parse.urlparse(
os.environ.get('REDIS_URL', 'redis://localhost:6379/0'))
if '?' in parsed_redis.path and not parsed_redis.query:
# Bug in python 2.7.3, fixed in 2.7.4
path, q, querystring = parsed_redis.path.partition('?')
else:
path, q, querystring = parsed_redis.path, None, parsed_redis.query
+
+ if parsed_redis.netloc.endswith('unix'):
+ del config['port']
+ del config['host']
+ # the last item of the path could also be just part of the socket path
+ try:
+ config['db'] = int(os.path.split(path)[-1])
+ except ValueError:
+ pass
+ else:
+ path = os.path.join(*os.path.split(path)[:-1])
+ config['unix_socket_path'] = path
+ if parsed_redis.password:
+ config['password'] = parsed_redis.password
+ else:
- if path[1:]:
+ if path[1:]:
? ++++
- config['db'] = int(path[1:])
+ config['db'] = int(path[1:])
? ++++
+ if parsed_redis.password:
- querystring = parse.parse_qs(querystring)
- for key in querystring.keys():
- querystring[key] = querystring[key][0]
- for key in config.keys():
- querystring.pop(key, None)
- host, colon, port = parsed_redis.netloc.partition(':')
- if '@' in host:
- password, at, host = host.partition('@')
- config['password'] = password
+ config['password'] = parsed_redis.password
? ++++ +++++++++++++
- config['host'] = host
- config['port'] = int(port)
+ if parsed_redis.port:
+ config['port'] = int(parsed_redis.port)
+ if parsed_redis.hostname:
+ config['host'] = parsed_redis.hostname
+
return config |
8378b474fca360696adc8a7c11439ac78912fab4 | tools/test_filter.py | tools/test_filter.py | {
'bslstl_iteratorutil': [ {'OS': 'SunOS'} ],
'bslstl_unorderedmultiset': [ {'OS': 'SunOS'} ],
'bsls_atomic' : [
{'case': 7, 'HOST': 'VM', 'policy': 'skip' },
{'case': 8, 'HOST': 'VM', 'policy': 'skip' },
],
'bsls_stopwatch' : [ {'case': 6, 'HOST': 'VM', 'policy': 'skip' } ],
}
| {
'bsls_atomic' : [
{'case': 7, 'HOST': 'VM', 'policy': 'skip' },
{'case': 8, 'HOST': 'VM', 'policy': 'skip' },
],
'bsls_stopwatch' : [ {'case': 6, 'HOST': 'VM', 'policy': 'skip' } ],
}
| Remove test driver exceptions for bslstl_iteratorutil and bslstl_unorderedmultiset on Sun | Remove test driver exceptions for bslstl_iteratorutil and bslstl_unorderedmultiset on Sun
| Python | apache-2.0 | mversche/bde,gbleaney/Allocator-Benchmarks,abeels/bde,RMGiroux/bde-allocator-benchmarks,bowlofstew/bde,abeels/bde,che2/bde,saxena84/bde,minhlongdo/bde,jmptrader/bde,che2/bde,dharesign/bde,bloomberg/bde-allocator-benchmarks,bloomberg/bde-allocator-benchmarks,apaprocki/bde,jmptrader/bde,osubboo/bde,bloomberg/bde-allocator-benchmarks,mversche/bde,dharesign/bde,bloomberg/bde,osubboo/bde,che2/bde,bloomberg/bde,frutiger/bde,RMGiroux/bde-allocator-benchmarks,bowlofstew/bde,frutiger/bde,minhlongdo/bde,abeels/bde,dbremner/bde,apaprocki/bde,mversche/bde,bowlofstew/bde,bloomberg/bde,jmptrader/bde,osubboo/bde,idispatch/bde,apaprocki/bde,dbremner/bde,idispatch/bde,dharesign/bde,apaprocki/bde,apaprocki/bde,RMGiroux/bde-allocator-benchmarks,gbleaney/Allocator-Benchmarks,frutiger/bde,RMGiroux/bde-allocator-benchmarks,frutiger/bde,bloomberg/bde,gbleaney/Allocator-Benchmarks,dbremner/bde,mversche/bde,bowlofstew/bde,osubboo/bde,bloomberg/bde-allocator-benchmarks,saxena84/bde,jmptrader/bde,bloomberg/bde-allocator-benchmarks,abeels/bde,che2/bde,bloomberg/bde,saxena84/bde,dharesign/bde,idispatch/bde,abeels/bde,idispatch/bde,gbleaney/Allocator-Benchmarks,abeels/bde,minhlongdo/bde,dbremner/bde,RMGiroux/bde-allocator-benchmarks,saxena84/bde,minhlongdo/bde | {
- 'bslstl_iteratorutil': [ {'OS': 'SunOS'} ],
- 'bslstl_unorderedmultiset': [ {'OS': 'SunOS'} ],
'bsls_atomic' : [
{'case': 7, 'HOST': 'VM', 'policy': 'skip' },
{'case': 8, 'HOST': 'VM', 'policy': 'skip' },
],
'bsls_stopwatch' : [ {'case': 6, 'HOST': 'VM', 'policy': 'skip' } ],
}
| Remove test driver exceptions for bslstl_iteratorutil and bslstl_unorderedmultiset on Sun | ## Code Before:
{
'bslstl_iteratorutil': [ {'OS': 'SunOS'} ],
'bslstl_unorderedmultiset': [ {'OS': 'SunOS'} ],
'bsls_atomic' : [
{'case': 7, 'HOST': 'VM', 'policy': 'skip' },
{'case': 8, 'HOST': 'VM', 'policy': 'skip' },
],
'bsls_stopwatch' : [ {'case': 6, 'HOST': 'VM', 'policy': 'skip' } ],
}
## Instruction:
Remove test driver exceptions for bslstl_iteratorutil and bslstl_unorderedmultiset on Sun
## Code After:
{
'bsls_atomic' : [
{'case': 7, 'HOST': 'VM', 'policy': 'skip' },
{'case': 8, 'HOST': 'VM', 'policy': 'skip' },
],
'bsls_stopwatch' : [ {'case': 6, 'HOST': 'VM', 'policy': 'skip' } ],
}
| {
- 'bslstl_iteratorutil': [ {'OS': 'SunOS'} ],
- 'bslstl_unorderedmultiset': [ {'OS': 'SunOS'} ],
'bsls_atomic' : [
{'case': 7, 'HOST': 'VM', 'policy': 'skip' },
{'case': 8, 'HOST': 'VM', 'policy': 'skip' },
],
'bsls_stopwatch' : [ {'case': 6, 'HOST': 'VM', 'policy': 'skip' } ],
} |
6589df70baad1b57c604736d75e424465cf8775e | djangoautoconf/auto_conf_admin_tools/reversion_feature.py | djangoautoconf/auto_conf_admin_tools/reversion_feature.py | from djangoautoconf.auto_conf_admin_tools.admin_feature_base import AdminFeatureBase
from django.conf import settings
__author__ = 'weijia'
class ReversionFeature(AdminFeatureBase):
def __init__(self):
super(ReversionFeature, self).__init__()
self.related_search_fields = {}
def process_parent_class_list(self, parent_list, class_inst):
if "reversion" in settings.INSTALLED_APPS:
from reversion import VersionAdmin
parent_list.append(VersionAdmin)
| from djangoautoconf.auto_conf_admin_tools.admin_feature_base import AdminFeatureBase
from django.conf import settings
__author__ = 'weijia'
class ReversionFeature(AdminFeatureBase):
def __init__(self):
super(ReversionFeature, self).__init__()
self.related_search_fields = {}
def process_parent_class_list(self, parent_list, class_inst):
if "reversion" in settings.INSTALLED_APPS:
try:
from reversion import VersionAdmin # for Django 1.5
except:
from reversion.admin import VersionAdmin # for Django 1.8
parent_list.append(VersionAdmin)
| Fix import issue for Django 1.5 above | Fix import issue for Django 1.5 above
| Python | bsd-3-clause | weijia/djangoautoconf,weijia/djangoautoconf | from djangoautoconf.auto_conf_admin_tools.admin_feature_base import AdminFeatureBase
from django.conf import settings
__author__ = 'weijia'
class ReversionFeature(AdminFeatureBase):
def __init__(self):
super(ReversionFeature, self).__init__()
self.related_search_fields = {}
def process_parent_class_list(self, parent_list, class_inst):
if "reversion" in settings.INSTALLED_APPS:
+ try:
- from reversion import VersionAdmin
+ from reversion import VersionAdmin # for Django 1.5
+ except:
+ from reversion.admin import VersionAdmin # for Django 1.8
parent_list.append(VersionAdmin)
| Fix import issue for Django 1.5 above | ## Code Before:
from djangoautoconf.auto_conf_admin_tools.admin_feature_base import AdminFeatureBase
from django.conf import settings
__author__ = 'weijia'
class ReversionFeature(AdminFeatureBase):
def __init__(self):
super(ReversionFeature, self).__init__()
self.related_search_fields = {}
def process_parent_class_list(self, parent_list, class_inst):
if "reversion" in settings.INSTALLED_APPS:
from reversion import VersionAdmin
parent_list.append(VersionAdmin)
## Instruction:
Fix import issue for Django 1.5 above
## Code After:
from djangoautoconf.auto_conf_admin_tools.admin_feature_base import AdminFeatureBase
from django.conf import settings
__author__ = 'weijia'
class ReversionFeature(AdminFeatureBase):
def __init__(self):
super(ReversionFeature, self).__init__()
self.related_search_fields = {}
def process_parent_class_list(self, parent_list, class_inst):
if "reversion" in settings.INSTALLED_APPS:
try:
from reversion import VersionAdmin # for Django 1.5
except:
from reversion.admin import VersionAdmin # for Django 1.8
parent_list.append(VersionAdmin)
| from djangoautoconf.auto_conf_admin_tools.admin_feature_base import AdminFeatureBase
from django.conf import settings
__author__ = 'weijia'
class ReversionFeature(AdminFeatureBase):
def __init__(self):
super(ReversionFeature, self).__init__()
self.related_search_fields = {}
def process_parent_class_list(self, parent_list, class_inst):
if "reversion" in settings.INSTALLED_APPS:
+ try:
- from reversion import VersionAdmin
+ from reversion import VersionAdmin # for Django 1.5
? ++++ ++++++++++++++++++
+ except:
+ from reversion.admin import VersionAdmin # for Django 1.8
parent_list.append(VersionAdmin) |
9901044b2b3218714a3c807e982db518aa97a446 | djangoautoconf/features/bae_settings.py | djangoautoconf/features/bae_settings.py |
try:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': const.CACHE_ADDR,
'TIMEOUT': 60,
}
}
except:
pass
try:
from bae.core import const
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': bae_secrets.database_name,
'USER': const.MYSQL_USER,
'PASSWORD': const.MYSQL_PASS,
'HOST': const.MYSQL_HOST,
'PORT': const.MYSQL_PORT,
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
###Or
#SESSION_ENGINE = 'django.contrib.sessions.backends.db'
##################################
except:
pass
EMAIL_BACKEND = 'django.core.mail.backends.bcms.EmailBackend'
try:
from objsys.baidu_mail import EmailBackend
EMAIL_BACKEND = 'objsys.baidu_mail.EmailBackend'
except:
EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
|
try:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': const.CACHE_ADDR,
'TIMEOUT': 60,
}
}
except:
pass
try:
from bae.core import const
import bae_secrets
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': bae_secrets.database_name,
'USER': const.MYSQL_USER,
'PASSWORD': const.MYSQL_PASS,
'HOST': const.MYSQL_HOST,
'PORT': const.MYSQL_PORT,
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
###Or
#SESSION_ENGINE = 'django.contrib.sessions.backends.db'
##################################
except:
pass
EMAIL_BACKEND = 'django.core.mail.backends.bcms.EmailBackend'
try:
from objsys.baidu_mail import EmailBackend
EMAIL_BACKEND = 'objsys.baidu_mail.EmailBackend'
except:
EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
| Move BAE secret into try catch block | Move BAE secret into try catch block
| Python | bsd-3-clause | weijia/djangoautoconf,weijia/djangoautoconf | +
try:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': const.CACHE_ADDR,
'TIMEOUT': 60,
}
}
except:
pass
try:
from bae.core import const
+ import bae_secrets
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': bae_secrets.database_name,
'USER': const.MYSQL_USER,
'PASSWORD': const.MYSQL_PASS,
'HOST': const.MYSQL_HOST,
'PORT': const.MYSQL_PORT,
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
###Or
#SESSION_ENGINE = 'django.contrib.sessions.backends.db'
##################################
except:
pass
EMAIL_BACKEND = 'django.core.mail.backends.bcms.EmailBackend'
try:
from objsys.baidu_mail import EmailBackend
EMAIL_BACKEND = 'objsys.baidu_mail.EmailBackend'
except:
EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
| Move BAE secret into try catch block | ## Code Before:
try:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': const.CACHE_ADDR,
'TIMEOUT': 60,
}
}
except:
pass
try:
from bae.core import const
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': bae_secrets.database_name,
'USER': const.MYSQL_USER,
'PASSWORD': const.MYSQL_PASS,
'HOST': const.MYSQL_HOST,
'PORT': const.MYSQL_PORT,
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
###Or
#SESSION_ENGINE = 'django.contrib.sessions.backends.db'
##################################
except:
pass
EMAIL_BACKEND = 'django.core.mail.backends.bcms.EmailBackend'
try:
from objsys.baidu_mail import EmailBackend
EMAIL_BACKEND = 'objsys.baidu_mail.EmailBackend'
except:
EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
## Instruction:
Move BAE secret into try catch block
## Code After:
try:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': const.CACHE_ADDR,
'TIMEOUT': 60,
}
}
except:
pass
try:
from bae.core import const
import bae_secrets
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': bae_secrets.database_name,
'USER': const.MYSQL_USER,
'PASSWORD': const.MYSQL_PASS,
'HOST': const.MYSQL_HOST,
'PORT': const.MYSQL_PORT,
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
###Or
#SESSION_ENGINE = 'django.contrib.sessions.backends.db'
##################################
except:
pass
EMAIL_BACKEND = 'django.core.mail.backends.bcms.EmailBackend'
try:
from objsys.baidu_mail import EmailBackend
EMAIL_BACKEND = 'objsys.baidu_mail.EmailBackend'
except:
EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
| +
try:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': const.CACHE_ADDR,
'TIMEOUT': 60,
}
}
except:
pass
try:
from bae.core import const
+ import bae_secrets
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': bae_secrets.database_name,
'USER': const.MYSQL_USER,
'PASSWORD': const.MYSQL_PASS,
'HOST': const.MYSQL_HOST,
'PORT': const.MYSQL_PORT,
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
###Or
#SESSION_ENGINE = 'django.contrib.sessions.backends.db'
##################################
except:
pass
EMAIL_BACKEND = 'django.core.mail.backends.bcms.EmailBackend'
try:
from objsys.baidu_mail import EmailBackend
EMAIL_BACKEND = 'objsys.baidu_mail.EmailBackend'
except:
EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
|
0c9bf270a7a2d8a4184f644bbe8a50995e155b0a | buddy/error.py | buddy/error.py | from functools import wraps
import botocore.exceptions
from click import ClickException
EXC_TO_ECHO = [
botocore.exceptions.NoRegionError,
]
def handle_exception(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exc:
if exc.__class__ in EXC_TO_ECHO:
msg = '%s: %s' % (exc.__class__, exc)
raise ClickException(msg)
raise
return wrapper
| from functools import wraps
import botocore.exceptions
from click import ClickException
EXC_TO_ECHO = [
botocore.exceptions.NoRegionError,
botocore.exceptions.ParamValidationError,
]
def handle_exception(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exc:
if exc.__class__ in EXC_TO_ECHO:
msg = '%s: %s' % (exc.__class__, exc)
raise ClickException(msg)
raise
return wrapper
| Add boto ParamValidationError to exc list | Add boto ParamValidationError to exc list
| Python | mit | pior/buddy | from functools import wraps
import botocore.exceptions
from click import ClickException
EXC_TO_ECHO = [
botocore.exceptions.NoRegionError,
+ botocore.exceptions.ParamValidationError,
]
def handle_exception(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exc:
if exc.__class__ in EXC_TO_ECHO:
msg = '%s: %s' % (exc.__class__, exc)
raise ClickException(msg)
raise
return wrapper
| Add boto ParamValidationError to exc list | ## Code Before:
from functools import wraps
import botocore.exceptions
from click import ClickException
EXC_TO_ECHO = [
botocore.exceptions.NoRegionError,
]
def handle_exception(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exc:
if exc.__class__ in EXC_TO_ECHO:
msg = '%s: %s' % (exc.__class__, exc)
raise ClickException(msg)
raise
return wrapper
## Instruction:
Add boto ParamValidationError to exc list
## Code After:
from functools import wraps
import botocore.exceptions
from click import ClickException
EXC_TO_ECHO = [
botocore.exceptions.NoRegionError,
botocore.exceptions.ParamValidationError,
]
def handle_exception(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exc:
if exc.__class__ in EXC_TO_ECHO:
msg = '%s: %s' % (exc.__class__, exc)
raise ClickException(msg)
raise
return wrapper
| from functools import wraps
import botocore.exceptions
from click import ClickException
EXC_TO_ECHO = [
botocore.exceptions.NoRegionError,
+ botocore.exceptions.ParamValidationError,
]
def handle_exception(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exc:
if exc.__class__ in EXC_TO_ECHO:
msg = '%s: %s' % (exc.__class__, exc)
raise ClickException(msg)
raise
return wrapper |
ac786779916e39d31582ed538635dc0aa7ee9310 | karspexet/show/admin.py | karspexet/show/admin.py | from django.contrib import admin
from karspexet.show.models import Production, Show
@admin.register(Production)
class ProductionAdmin(admin.ModelAdmin):
list_display = ("name", "alt_name")
@admin.register(Show)
class ShowAdmin(admin.ModelAdmin):
list_display = ("production", "slug", "date_string")
list_filter = ("production",)
exclude = ("slug",)
ordering = ("-pk",)
| from django.contrib import admin
from django.utils import timezone
from karspexet.show.models import Production, Show
@admin.register(Production)
class ProductionAdmin(admin.ModelAdmin):
list_display = ("name", "alt_name")
@admin.register(Show)
class ShowAdmin(admin.ModelAdmin):
list_display = ("date_string", "production", "venue", "visible", "is_upcoming")
list_select_related = ("production", "venue")
list_filter = ("visible", "production")
exclude = ("slug",)
ordering = ("-pk",)
@admin.display(boolean=True)
def is_upcoming(self, obj):
return obj.date > timezone.now()
| Improve ShowAdmin to give better overview | Improve ShowAdmin to give better overview
| Python | mit | Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet | from django.contrib import admin
+ from django.utils import timezone
from karspexet.show.models import Production, Show
@admin.register(Production)
class ProductionAdmin(admin.ModelAdmin):
list_display = ("name", "alt_name")
@admin.register(Show)
class ShowAdmin(admin.ModelAdmin):
- list_display = ("production", "slug", "date_string")
+ list_display = ("date_string", "production", "venue", "visible", "is_upcoming")
+ list_select_related = ("production", "venue")
- list_filter = ("production",)
+ list_filter = ("visible", "production")
exclude = ("slug",)
ordering = ("-pk",)
+ @admin.display(boolean=True)
+ def is_upcoming(self, obj):
+ return obj.date > timezone.now()
+ | Improve ShowAdmin to give better overview | ## Code Before:
from django.contrib import admin
from karspexet.show.models import Production, Show
@admin.register(Production)
class ProductionAdmin(admin.ModelAdmin):
list_display = ("name", "alt_name")
@admin.register(Show)
class ShowAdmin(admin.ModelAdmin):
list_display = ("production", "slug", "date_string")
list_filter = ("production",)
exclude = ("slug",)
ordering = ("-pk",)
## Instruction:
Improve ShowAdmin to give better overview
## Code After:
from django.contrib import admin
from django.utils import timezone
from karspexet.show.models import Production, Show
@admin.register(Production)
class ProductionAdmin(admin.ModelAdmin):
list_display = ("name", "alt_name")
@admin.register(Show)
class ShowAdmin(admin.ModelAdmin):
list_display = ("date_string", "production", "venue", "visible", "is_upcoming")
list_select_related = ("production", "venue")
list_filter = ("visible", "production")
exclude = ("slug",)
ordering = ("-pk",)
@admin.display(boolean=True)
def is_upcoming(self, obj):
return obj.date > timezone.now()
| from django.contrib import admin
+ from django.utils import timezone
from karspexet.show.models import Production, Show
@admin.register(Production)
class ProductionAdmin(admin.ModelAdmin):
list_display = ("name", "alt_name")
@admin.register(Show)
class ShowAdmin(admin.ModelAdmin):
- list_display = ("production", "slug", "date_string")
+ list_display = ("date_string", "production", "venue", "visible", "is_upcoming")
+ list_select_related = ("production", "venue")
- list_filter = ("production",)
? -
+ list_filter = ("visible", "production")
? +++++++++++
exclude = ("slug",)
ordering = ("-pk",)
+
+ @admin.display(boolean=True)
+ def is_upcoming(self, obj):
+ return obj.date > timezone.now() |
13e70f822e3cf96a0604bb4ce6ed46dbe2dcf376 | zsl/application/initializers/__init__.py | zsl/application/initializers/__init__.py |
from .logger_initializer import LoggerInitializer
from .unittest_initializer import UnitTestInitializer
from .library_initializer import LibraryInitializer
from .database_initializer import DatabaseInitializer
from .application_initializer import ApplicationInitializer
from .service_initializer import ServiceInitializer
from .cache_initializer import CacheInitializer
from .context_initializer import ContextInitializer
injection_views = []
injection_modules = []
def injection_view(f):
"""
Adds the view to the list of Injector-enabled views to add to the Flask app.
:param callable f: The decorated view function.
"""
injection_views.append(f)
return f
def injection_module(f):
"""
Adds the module to the list of injection enabled modules. The decorated function is then called in the
initialization phase and can create and initialize the object which will be able to be injected.
:param callable f: The decorated initializing function.
"""
injection_modules.append(f)
return f
|
injection_views = []
injection_modules = []
def injection_view(f):
"""
Adds the view to the list of Injector-enabled views to add to the Flask app.
:param callable f: The decorated view function.
"""
injection_views.append(f)
return f
def injection_module(f):
"""
Adds the module to the list of injection enabled modules. The decorated function is then called in the
initialization phase and can create and initialize the object which will be able to be injected.
:param callable f: The decorated initializing function.
"""
injection_modules.append(f)
return f
from .logger_initializer import LoggerInitializer
from .unittest_initializer import UnitTestInitializer
from .library_initializer import LibraryInitializer
from .database_initializer import DatabaseInitializer
from .application_initializer import ApplicationInitializer
from .service_initializer import ServiceInitializer
from .cache_initializer import CacheInitializer
from .context_initializer import ContextInitializer | FIX import order - cyclic dependencies | FIX import order - cyclic dependencies
| Python | mit | AtteqCom/zsl,AtteqCom/zsl | -
- from .logger_initializer import LoggerInitializer
- from .unittest_initializer import UnitTestInitializer
- from .library_initializer import LibraryInitializer
- from .database_initializer import DatabaseInitializer
- from .application_initializer import ApplicationInitializer
- from .service_initializer import ServiceInitializer
- from .cache_initializer import CacheInitializer
- from .context_initializer import ContextInitializer
injection_views = []
injection_modules = []
def injection_view(f):
"""
Adds the view to the list of Injector-enabled views to add to the Flask app.
:param callable f: The decorated view function.
"""
injection_views.append(f)
return f
def injection_module(f):
"""
Adds the module to the list of injection enabled modules. The decorated function is then called in the
initialization phase and can create and initialize the object which will be able to be injected.
:param callable f: The decorated initializing function.
"""
injection_modules.append(f)
return f
+
+ from .logger_initializer import LoggerInitializer
+ from .unittest_initializer import UnitTestInitializer
+ from .library_initializer import LibraryInitializer
+ from .database_initializer import DatabaseInitializer
+ from .application_initializer import ApplicationInitializer
+ from .service_initializer import ServiceInitializer
+ from .cache_initializer import CacheInitializer
+ from .context_initializer import ContextInitializer | FIX import order - cyclic dependencies | ## Code Before:
from .logger_initializer import LoggerInitializer
from .unittest_initializer import UnitTestInitializer
from .library_initializer import LibraryInitializer
from .database_initializer import DatabaseInitializer
from .application_initializer import ApplicationInitializer
from .service_initializer import ServiceInitializer
from .cache_initializer import CacheInitializer
from .context_initializer import ContextInitializer
injection_views = []
injection_modules = []
def injection_view(f):
"""
Adds the view to the list of Injector-enabled views to add to the Flask app.
:param callable f: The decorated view function.
"""
injection_views.append(f)
return f
def injection_module(f):
"""
Adds the module to the list of injection enabled modules. The decorated function is then called in the
initialization phase and can create and initialize the object which will be able to be injected.
:param callable f: The decorated initializing function.
"""
injection_modules.append(f)
return f
## Instruction:
FIX import order - cyclic dependencies
## Code After:
injection_views = []
injection_modules = []
def injection_view(f):
"""
Adds the view to the list of Injector-enabled views to add to the Flask app.
:param callable f: The decorated view function.
"""
injection_views.append(f)
return f
def injection_module(f):
"""
Adds the module to the list of injection enabled modules. The decorated function is then called in the
initialization phase and can create and initialize the object which will be able to be injected.
:param callable f: The decorated initializing function.
"""
injection_modules.append(f)
return f
from .logger_initializer import LoggerInitializer
from .unittest_initializer import UnitTestInitializer
from .library_initializer import LibraryInitializer
from .database_initializer import DatabaseInitializer
from .application_initializer import ApplicationInitializer
from .service_initializer import ServiceInitializer
from .cache_initializer import CacheInitializer
from .context_initializer import ContextInitializer | -
- from .logger_initializer import LoggerInitializer
- from .unittest_initializer import UnitTestInitializer
- from .library_initializer import LibraryInitializer
- from .database_initializer import DatabaseInitializer
- from .application_initializer import ApplicationInitializer
- from .service_initializer import ServiceInitializer
- from .cache_initializer import CacheInitializer
- from .context_initializer import ContextInitializer
injection_views = []
injection_modules = []
def injection_view(f):
"""
Adds the view to the list of Injector-enabled views to add to the Flask app.
:param callable f: The decorated view function.
"""
injection_views.append(f)
return f
def injection_module(f):
"""
Adds the module to the list of injection enabled modules. The decorated function is then called in the
initialization phase and can create and initialize the object which will be able to be injected.
:param callable f: The decorated initializing function.
"""
injection_modules.append(f)
return f
+
+
+ from .logger_initializer import LoggerInitializer
+ from .unittest_initializer import UnitTestInitializer
+ from .library_initializer import LibraryInitializer
+ from .database_initializer import DatabaseInitializer
+ from .application_initializer import ApplicationInitializer
+ from .service_initializer import ServiceInitializer
+ from .cache_initializer import CacheInitializer
+ from .context_initializer import ContextInitializer |
0cdb7a0baa6e4f00b3b54cb49701175cdb3c8a05 | entities/filters.py | entities/filters.py | from . import forms
import django_filters as filters
class Group(filters.FilterSet):
name = filters.CharFilter(lookup_expr='icontains')
class Meta:
form = forms.GroupFilter
| from . import forms
import django_filters as filters
from features.groups import models
class Group(filters.FilterSet):
name = filters.CharFilter(label='Name', lookup_expr='icontains')
class Meta:
model = models.Group
fields = ['name']
form = forms.GroupFilter
| Fix filter for django-filter 1.0 | Fix filter for django-filter 1.0
| Python | agpl-3.0 | stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten | from . import forms
import django_filters as filters
+ from features.groups import models
class Group(filters.FilterSet):
- name = filters.CharFilter(lookup_expr='icontains')
+ name = filters.CharFilter(label='Name', lookup_expr='icontains')
class Meta:
+ model = models.Group
+ fields = ['name']
form = forms.GroupFilter
| Fix filter for django-filter 1.0 | ## Code Before:
from . import forms
import django_filters as filters
class Group(filters.FilterSet):
name = filters.CharFilter(lookup_expr='icontains')
class Meta:
form = forms.GroupFilter
## Instruction:
Fix filter for django-filter 1.0
## Code After:
from . import forms
import django_filters as filters
from features.groups import models
class Group(filters.FilterSet):
name = filters.CharFilter(label='Name', lookup_expr='icontains')
class Meta:
model = models.Group
fields = ['name']
form = forms.GroupFilter
| from . import forms
import django_filters as filters
+ from features.groups import models
class Group(filters.FilterSet):
- name = filters.CharFilter(lookup_expr='icontains')
+ name = filters.CharFilter(label='Name', lookup_expr='icontains')
? ++++++++++++++
class Meta:
+ model = models.Group
+ fields = ['name']
form = forms.GroupFilter |
c84e22824cd5546406656ecc06a7dcd37a013954 | shopit_app/urls.py | shopit_app/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
import authentication_app.views
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'gettingstarted.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', authentication_app.views.index, name='index'),
url(r'^db', authentication_app.views.db, name='db'),
url(r'^admin/', include(admin.site.urls)),
)
| from rest_frmaework_nested import routers
from authentication_app.views import AccountViewSet
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpatterns = patterns('',
# APIendpoints
url(r'^api/v1/', include(router.urls)),
url('^.*$', IndexView.as_view(), name='index'),
)
| Add the API endpoint url for the account view set. | Add the API endpoint url for the account view set.
| Python | mit | mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app | - from django.conf.urls import patterns, include, url
+ from rest_frmaework_nested import routers
+ from authentication_app.views import AccountViewSet
+ router = routers.SimpleRouter()
+ router.register(r'accounts', AccountViewSet)
- from django.contrib import admin
- admin.autodiscover()
-
- import authentication_app.views
urlpatterns = patterns('',
+ # APIendpoints
- # Examples:
- # url(r'^$', 'gettingstarted.views.home', name='home'),
- # url(r'^blog/', include('blog.urls')),
-
- url(r'^$', authentication_app.views.index, name='index'),
- url(r'^db', authentication_app.views.db, name='db'),
- url(r'^admin/', include(admin.site.urls)),
+ url(r'^api/v1/', include(router.urls)),
-
+ url('^.*$', IndexView.as_view(), name='index'),
)
| Add the API endpoint url for the account view set. | ## Code Before:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
import authentication_app.views
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'gettingstarted.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', authentication_app.views.index, name='index'),
url(r'^db', authentication_app.views.db, name='db'),
url(r'^admin/', include(admin.site.urls)),
)
## Instruction:
Add the API endpoint url for the account view set.
## Code After:
from rest_frmaework_nested import routers
from authentication_app.views import AccountViewSet
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpatterns = patterns('',
# APIendpoints
url(r'^api/v1/', include(router.urls)),
url('^.*$', IndexView.as_view(), name='index'),
)
| - from django.conf.urls import patterns, include, url
+ from rest_frmaework_nested import routers
+ from authentication_app.views import AccountViewSet
+ router = routers.SimpleRouter()
+ router.register(r'accounts', AccountViewSet)
- from django.contrib import admin
- admin.autodiscover()
-
- import authentication_app.views
urlpatterns = patterns('',
+ # APIendpoints
- # Examples:
- # url(r'^$', 'gettingstarted.views.home', name='home'),
- # url(r'^blog/', include('blog.urls')),
-
- url(r'^$', authentication_app.views.index, name='index'),
- url(r'^db', authentication_app.views.db, name='db'),
- url(r'^admin/', include(admin.site.urls)),
? ^^ ^ ^^^^^^^^
+ url(r'^api/v1/', include(router.urls)),
? ^ ^^^ ^^^ +
-
+ url('^.*$', IndexView.as_view(), name='index'),
) |
5da820b85f9e55a54639856bdd698c35b866833c | fireplace/cards/gvg/neutral_epic.py | fireplace/cards/gvg/neutral_epic.py | from ..utils import *
##
# Minions
# Hobgoblin
class GVG_104:
def OWN_MINION_SUMMON(self, minion):
if minion.atk == 1:
return [Buff(minion, "GVG_104a")]
| from ..utils import *
##
# Minions
# Hobgoblin
class GVG_104:
def OWN_CARD_PLAYED(self, card):
if card.type == CardType.MINION and card.atk == 1:
return [Buff(card, "GVG_104a")]
| Fix Hobgoblin to trigger only on cards played | Fix Hobgoblin to trigger only on cards played
| Python | agpl-3.0 | smallnamespace/fireplace,jleclanche/fireplace,liujimj/fireplace,Meerkov/fireplace,amw2104/fireplace,butozerca/fireplace,oftc-ftw/fireplace,Ragowit/fireplace,NightKev/fireplace,smallnamespace/fireplace,Meerkov/fireplace,liujimj/fireplace,butozerca/fireplace,Ragowit/fireplace,beheh/fireplace,oftc-ftw/fireplace,amw2104/fireplace | from ..utils import *
##
# Minions
# Hobgoblin
class GVG_104:
- def OWN_MINION_SUMMON(self, minion):
- if minion.atk == 1:
+ def OWN_CARD_PLAYED(self, card):
+ if card.type == CardType.MINION and card.atk == 1:
- return [Buff(minion, "GVG_104a")]
+ return [Buff(card, "GVG_104a")]
| Fix Hobgoblin to trigger only on cards played | ## Code Before:
from ..utils import *
##
# Minions
# Hobgoblin
class GVG_104:
def OWN_MINION_SUMMON(self, minion):
if minion.atk == 1:
return [Buff(minion, "GVG_104a")]
## Instruction:
Fix Hobgoblin to trigger only on cards played
## Code After:
from ..utils import *
##
# Minions
# Hobgoblin
class GVG_104:
def OWN_CARD_PLAYED(self, card):
if card.type == CardType.MINION and card.atk == 1:
return [Buff(card, "GVG_104a")]
| from ..utils import *
##
# Minions
# Hobgoblin
class GVG_104:
- def OWN_MINION_SUMMON(self, minion):
- if minion.atk == 1:
+ def OWN_CARD_PLAYED(self, card):
+ if card.type == CardType.MINION and card.atk == 1:
- return [Buff(minion, "GVG_104a")]
? ^^^^^^
+ return [Buff(card, "GVG_104a")]
? ^^^^
|
8ac142af2afc577a47197fe9bc821cb796883f38 | virtual_machine.py | virtual_machine.py | class VirtualMachine:
def __init__(self, bytecodes, ram_size=256, executing=True):
self.bytecodes = bytecodes
self.data = [None]*ram_size
self.stack = []
self.executing = executing
self.pc = 0
def push(self, value):
"""Push something onto the stack."""
self.stack += [value]
def pop(self):
"""Pop something from the stack. Crash if empty."""
return self.stack.pop()
def read_memory(self, index):
"""Read from memory, crashing if index is out of bounds."""
return self.data[index]
def write_memory(self, index, value):
"""Write to memory. Crash if index is out of bounds."""
self.data[index] = value
def run(self):
while self.executing:
self.bytecodes[self.pc].execute(self)
if self.bytecodes[self.pc].autoincrement:
self.pc += 1
| class VirtualMachine:
def __init__(self, bytecodes, ram_size=256, executing=True):
self.bytecodes = bytecodes
self.data = [None]*ram_size
self.stack = []
self.executing = executing
self.pc = 0
def push(self, value):
"""Push something onto the stack."""
self.stack += [value]
def pop(self):
"""Pop something from the stack. Crash if empty."""
return self.stack.pop()
def read_memory(self, index):
"""Read from memory, crashing if index is out of bounds."""
return self.data[index]
def write_memory(self, index, value):
"""Write to memory. Crash if index is out of bounds."""
self.data[index] = value
def run(self):
while self.executing:
increment = self.bytecodes[self.pc].autoincrement
self.bytecodes[self.pc].execute(self)
if increment:
self.pc += 1
| Check for autoincrement before executing the instruction | Check for autoincrement before executing the instruction
| Python | bsd-3-clause | darbaga/simple_compiler | class VirtualMachine:
def __init__(self, bytecodes, ram_size=256, executing=True):
self.bytecodes = bytecodes
self.data = [None]*ram_size
self.stack = []
self.executing = executing
self.pc = 0
def push(self, value):
"""Push something onto the stack."""
self.stack += [value]
def pop(self):
"""Pop something from the stack. Crash if empty."""
return self.stack.pop()
def read_memory(self, index):
"""Read from memory, crashing if index is out of bounds."""
return self.data[index]
def write_memory(self, index, value):
"""Write to memory. Crash if index is out of bounds."""
self.data[index] = value
def run(self):
while self.executing:
+ increment = self.bytecodes[self.pc].autoincrement
self.bytecodes[self.pc].execute(self)
- if self.bytecodes[self.pc].autoincrement:
+ if increment:
self.pc += 1
| Check for autoincrement before executing the instruction | ## Code Before:
class VirtualMachine:
def __init__(self, bytecodes, ram_size=256, executing=True):
self.bytecodes = bytecodes
self.data = [None]*ram_size
self.stack = []
self.executing = executing
self.pc = 0
def push(self, value):
"""Push something onto the stack."""
self.stack += [value]
def pop(self):
"""Pop something from the stack. Crash if empty."""
return self.stack.pop()
def read_memory(self, index):
"""Read from memory, crashing if index is out of bounds."""
return self.data[index]
def write_memory(self, index, value):
"""Write to memory. Crash if index is out of bounds."""
self.data[index] = value
def run(self):
while self.executing:
self.bytecodes[self.pc].execute(self)
if self.bytecodes[self.pc].autoincrement:
self.pc += 1
## Instruction:
Check for autoincrement before executing the instruction
## Code After:
class VirtualMachine:
def __init__(self, bytecodes, ram_size=256, executing=True):
self.bytecodes = bytecodes
self.data = [None]*ram_size
self.stack = []
self.executing = executing
self.pc = 0
def push(self, value):
"""Push something onto the stack."""
self.stack += [value]
def pop(self):
"""Pop something from the stack. Crash if empty."""
return self.stack.pop()
def read_memory(self, index):
"""Read from memory, crashing if index is out of bounds."""
return self.data[index]
def write_memory(self, index, value):
"""Write to memory. Crash if index is out of bounds."""
self.data[index] = value
def run(self):
while self.executing:
increment = self.bytecodes[self.pc].autoincrement
self.bytecodes[self.pc].execute(self)
if increment:
self.pc += 1
| class VirtualMachine:
def __init__(self, bytecodes, ram_size=256, executing=True):
self.bytecodes = bytecodes
self.data = [None]*ram_size
self.stack = []
self.executing = executing
self.pc = 0
def push(self, value):
"""Push something onto the stack."""
self.stack += [value]
def pop(self):
"""Pop something from the stack. Crash if empty."""
return self.stack.pop()
def read_memory(self, index):
"""Read from memory, crashing if index is out of bounds."""
return self.data[index]
def write_memory(self, index, value):
"""Write to memory. Crash if index is out of bounds."""
self.data[index] = value
def run(self):
while self.executing:
+ increment = self.bytecodes[self.pc].autoincrement
self.bytecodes[self.pc].execute(self)
- if self.bytecodes[self.pc].autoincrement:
+ if increment:
self.pc += 1
|
a292f2978f07839af07a8963a51fd48b046f0c73 | website/addons/mendeley/settings/__init__.py | website/addons/mendeley/settings/__init__.py | import logging
from .defaults import * # noqa
try:
from .local import * # noqa
except ImportError as error:
logging.warn('No local.py settings file found')
| import logging
from .defaults import * # noqa
logger = logging.getLogger(__name__)
try:
from .local import * # noqa
except ImportError as error:
logger.warn('No local.py settings file found')
| Use namespaces logger in mendeley settings | Use namespaces logger in mendeley settings
h/t Arpita for catching this
[skip ci]
| Python | apache-2.0 | brianjgeiger/osf.io,Johnetordoff/osf.io,samchrisinger/osf.io,KAsante95/osf.io,crcresearch/osf.io,arpitar/osf.io,danielneis/osf.io,cslzchen/osf.io,baylee-d/osf.io,Johnetordoff/osf.io,asanfilippo7/osf.io,kwierman/osf.io,SSJohns/osf.io,GageGaskins/osf.io,GageGaskins/osf.io,danielneis/osf.io,brandonPurvis/osf.io,emetsger/osf.io,brandonPurvis/osf.io,billyhunt/osf.io,chrisseto/osf.io,zamattiac/osf.io,monikagrabowska/osf.io,njantrania/osf.io,cosenal/osf.io,TomHeatwole/osf.io,DanielSBrown/osf.io,chrisseto/osf.io,mfraezz/osf.io,leb2dg/osf.io,CenterForOpenScience/osf.io,billyhunt/osf.io,SSJohns/osf.io,cwisecarver/osf.io,caneruguz/osf.io,rdhyee/osf.io,caseyrollins/osf.io,caseyrollins/osf.io,Nesiehr/osf.io,KAsante95/osf.io,samanehsan/osf.io,aaxelb/osf.io,petermalcolm/osf.io,adlius/osf.io,amyshi188/osf.io,Johnetordoff/osf.io,sloria/osf.io,erinspace/osf.io,hmoco/osf.io,RomanZWang/osf.io,ZobairAlijan/osf.io,haoyuchen1992/osf.io,danielneis/osf.io,mluke93/osf.io,samanehsan/osf.io,brandonPurvis/osf.io,samanehsan/osf.io,ticklemepierce/osf.io,amyshi188/osf.io,billyhunt/osf.io,samchrisinger/osf.io,kch8qx/osf.io,hmoco/osf.io,baylee-d/osf.io,icereval/osf.io,baylee-d/osf.io,caneruguz/osf.io,rdhyee/osf.io,mluo613/osf.io,CenterForOpenScience/osf.io,caseyrygt/osf.io,ticklemepierce/osf.io,chrisseto/osf.io,adlius/osf.io,ticklemepierce/osf.io,mluo613/osf.io,emetsger/osf.io,Ghalko/osf.io,Ghalko/osf.io,HalcyonChimera/osf.io,CenterForOpenScience/osf.io,abought/osf.io,pattisdr/osf.io,RomanZWang/osf.io,chennan47/osf.io,haoyuchen1992/osf.io,alexschiller/osf.io,TomBaxter/osf.io,doublebits/osf.io,mluke93/osf.io,acshi/osf.io,caseyrygt/osf.io,pattisdr/osf.io,brianjgeiger/osf.io,njantrania/osf.io,monikagrabowska/osf.io,RomanZWang/osf.io,samanehsan/osf.io,Nesiehr/osf.io,alexschiller/osf.io,njantrania/osf.io,sloria/osf.io,saradbowman/osf.io,asanfilippo7/osf.io,jnayak1/osf.io,njantrania/osf.io,brandonPurvis/osf.io,sloria/osf.io,mluo613/osf.io,chrisseto/osf.io,felliott/osf.io,SSJohns/osf.io,caseyrygt/osf.io,zachjanicki/osf.io,rdhyee/osf.io,cosenal/osf.io,laurenrevere/osf.io,felliott/osf.io,chennan47/osf.io,kwierman/osf.io,kch8qx/osf.io,abought/osf.io,Ghalko/osf.io,cslzchen/osf.io,KAsante95/osf.io,doublebits/osf.io,caseyrygt/osf.io,HalcyonChimera/osf.io,chennan47/osf.io,arpitar/osf.io,danielneis/osf.io,aaxelb/osf.io,doublebits/osf.io,erinspace/osf.io,brandonPurvis/osf.io,KAsante95/osf.io,felliott/osf.io,mluke93/osf.io,mattclark/osf.io,Johnetordoff/osf.io,ticklemepierce/osf.io,Ghalko/osf.io,arpitar/osf.io,binoculars/osf.io,samchrisinger/osf.io,brianjgeiger/osf.io,Nesiehr/osf.io,kch8qx/osf.io,asanfilippo7/osf.io,jnayak1/osf.io,arpitar/osf.io,brianjgeiger/osf.io,DanielSBrown/osf.io,jnayak1/osf.io,mluke93/osf.io,HalcyonChimera/osf.io,icereval/osf.io,acshi/osf.io,alexschiller/osf.io,aaxelb/osf.io,emetsger/osf.io,TomHeatwole/osf.io,SSJohns/osf.io,petermalcolm/osf.io,monikagrabowska/osf.io,laurenrevere/osf.io,TomBaxter/osf.io,mattclark/osf.io,cosenal/osf.io,DanielSBrown/osf.io,HalcyonChimera/osf.io,caneruguz/osf.io,mluo613/osf.io,wearpants/osf.io,cwisecarver/osf.io,TomHeatwole/osf.io,kwierman/osf.io,GageGaskins/osf.io,billyhunt/osf.io,DanielSBrown/osf.io,aaxelb/osf.io,Nesiehr/osf.io,GageGaskins/osf.io,adlius/osf.io,doublebits/osf.io,zachjanicki/osf.io,RomanZWang/osf.io,felliott/osf.io,hmoco/osf.io,cwisecarver/osf.io,kch8qx/osf.io,mfraezz/osf.io,caneruguz/osf.io,alexschiller/osf.io,asanfilippo7/osf.io,rdhyee/osf.io,TomHeatwole/osf.io,jnayak1/osf.io,mfraezz/osf.io,CenterForOpenScience/osf.io,saradbowman/osf.io,ZobairAlijan/osf.io,cwisecarver/osf.io,emetsger/osf.io,cslzchen/osf.io,TomBaxter/osf.io,crcresearch/osf.io,caseyrollins/osf.io,amyshi188/osf.io,haoyuchen1992/osf.io,binoculars/osf.io,leb2dg/osf.io,zachjanicki/osf.io,acshi/osf.io,zamattiac/osf.io,ZobairAlijan/osf.io,cosenal/osf.io,alexschiller/osf.io,zachjanicki/osf.io,mluo613/osf.io,wearpants/osf.io,petermalcolm/osf.io,doublebits/osf.io,erinspace/osf.io,cslzchen/osf.io,acshi/osf.io,mattclark/osf.io,leb2dg/osf.io,RomanZWang/osf.io,abought/osf.io,acshi/osf.io,pattisdr/osf.io,samchrisinger/osf.io,zamattiac/osf.io,icereval/osf.io,billyhunt/osf.io,kch8qx/osf.io,laurenrevere/osf.io,adlius/osf.io,kwierman/osf.io,monikagrabowska/osf.io,zamattiac/osf.io,abought/osf.io,monikagrabowska/osf.io,wearpants/osf.io,KAsante95/osf.io,GageGaskins/osf.io,petermalcolm/osf.io,leb2dg/osf.io,crcresearch/osf.io,wearpants/osf.io,haoyuchen1992/osf.io,amyshi188/osf.io,hmoco/osf.io,binoculars/osf.io,ZobairAlijan/osf.io,mfraezz/osf.io | import logging
from .defaults import * # noqa
+
+ logger = logging.getLogger(__name__)
try:
from .local import * # noqa
except ImportError as error:
- logging.warn('No local.py settings file found')
+ logger.warn('No local.py settings file found')
| Use namespaces logger in mendeley settings | ## Code Before:
import logging
from .defaults import * # noqa
try:
from .local import * # noqa
except ImportError as error:
logging.warn('No local.py settings file found')
## Instruction:
Use namespaces logger in mendeley settings
## Code After:
import logging
from .defaults import * # noqa
logger = logging.getLogger(__name__)
try:
from .local import * # noqa
except ImportError as error:
logger.warn('No local.py settings file found')
| import logging
from .defaults import * # noqa
+
+ logger = logging.getLogger(__name__)
try:
from .local import * # noqa
except ImportError as error:
- logging.warn('No local.py settings file found')
? ^^^
+ logger.warn('No local.py settings file found')
? ^^
|
7021aabe068f546adb10b8f741656c423cb7eb5a | sale_order_mass_confirm/wizard/sale_order_confirm.py | sale_order_mass_confirm/wizard/sale_order_confirm.py |
from odoo import api, models
class SaleOrderConfirmWizard(models.TransientModel):
_name = "sale.order.confirm.wizard"
_description = "Wizard - Sale Order Confirm"
@api.multi
def confirm_sale_orders(self):
self.ensure_one()
active_ids = self._context.get('active_ids')
orders = self.env['sale.order'].browse(active_ids)
orders.action_confirm()
|
from odoo import models, api
class SaleOrderConfirmWizard(models.TransientModel):
_name = "sale.order.confirm.wizard"
_description = "Wizard - Sale Order Confirm"
@api.multi
def confirm_sale_orders(self):
self.ensure_one()
active_ids = self._context.get('active_ids')
orders = self.env['sale.order'].browse(active_ids)
for order in orders:
if order.state in ['draft', 'sent']:
order.action_confirm()
| Make sure only Sales Order with state in 'draft' or 'sent' is confirmed (state 'canceled' will not be confirmed) | Make sure only Sales Order with state in 'draft' or 'sent' is confirmed (state 'canceled' will not be confirmed)
| Python | agpl-3.0 | VitalPet/addons-onestein,VitalPet/addons-onestein,VitalPet/addons-onestein |
- from odoo import api, models
+ from odoo import models, api
class SaleOrderConfirmWizard(models.TransientModel):
_name = "sale.order.confirm.wizard"
_description = "Wizard - Sale Order Confirm"
@api.multi
def confirm_sale_orders(self):
self.ensure_one()
active_ids = self._context.get('active_ids')
orders = self.env['sale.order'].browse(active_ids)
+ for order in orders:
+ if order.state in ['draft', 'sent']:
- orders.action_confirm()
+ order.action_confirm()
| Make sure only Sales Order with state in 'draft' or 'sent' is confirmed (state 'canceled' will not be confirmed) | ## Code Before:
from odoo import api, models
class SaleOrderConfirmWizard(models.TransientModel):
_name = "sale.order.confirm.wizard"
_description = "Wizard - Sale Order Confirm"
@api.multi
def confirm_sale_orders(self):
self.ensure_one()
active_ids = self._context.get('active_ids')
orders = self.env['sale.order'].browse(active_ids)
orders.action_confirm()
## Instruction:
Make sure only Sales Order with state in 'draft' or 'sent' is confirmed (state 'canceled' will not be confirmed)
## Code After:
from odoo import models, api
class SaleOrderConfirmWizard(models.TransientModel):
_name = "sale.order.confirm.wizard"
_description = "Wizard - Sale Order Confirm"
@api.multi
def confirm_sale_orders(self):
self.ensure_one()
active_ids = self._context.get('active_ids')
orders = self.env['sale.order'].browse(active_ids)
for order in orders:
if order.state in ['draft', 'sent']:
order.action_confirm()
|
- from odoo import api, models
? -----
+ from odoo import models, api
? +++++
class SaleOrderConfirmWizard(models.TransientModel):
_name = "sale.order.confirm.wizard"
_description = "Wizard - Sale Order Confirm"
@api.multi
def confirm_sale_orders(self):
self.ensure_one()
active_ids = self._context.get('active_ids')
orders = self.env['sale.order'].browse(active_ids)
+ for order in orders:
+ if order.state in ['draft', 'sent']:
- orders.action_confirm()
? -
+ order.action_confirm()
? ++++++++
|
b95e6069a1faa849b1c5b31daf0dfd4dd4b5be23 | electionleaflets/boundaries/models.py | electionleaflets/boundaries/models.py | from django.db import models
from legacy.models import Constituency
class Boundary(models.Model):
id = models.IntegerField(primary_key=True)
constituency_id = models.IntegerField()
boundary = models.TextField()
zoom = models.IntegerField()
north = models.FloatField()
south = models.FloatField()
east = models.FloatField()
west = models.FloatField()
class Meta:
db_table = u'boundaries_boundary'
| from django.db import models
from legacy.models import Constituency
class Boundary(models.Model):
constituency = models.ForeignKey( Constituency )
boundary = models.TextField()
zoom = models.IntegerField()
north = models.FloatField()
south = models.FloatField()
east = models.FloatField()
west = models.FloatField()
class Meta:
db_table = u'boundaries_boundary'
| Put the model back the way it was | Put the model back the way it was
| Python | mit | JustinWingChungHui/electionleaflets,electionleaflets/electionleaflets,electionleaflets/electionleaflets,JustinWingChungHui/electionleaflets,DemocracyClub/electionleaflets,JustinWingChungHui/electionleaflets,DemocracyClub/electionleaflets,DemocracyClub/electionleaflets,JustinWingChungHui/electionleaflets | from django.db import models
from legacy.models import Constituency
class Boundary(models.Model):
+ constituency = models.ForeignKey( Constituency )
- id = models.IntegerField(primary_key=True)
- constituency_id = models.IntegerField()
boundary = models.TextField()
zoom = models.IntegerField()
north = models.FloatField()
south = models.FloatField()
east = models.FloatField()
west = models.FloatField()
class Meta:
db_table = u'boundaries_boundary'
| Put the model back the way it was | ## Code Before:
from django.db import models
from legacy.models import Constituency
class Boundary(models.Model):
id = models.IntegerField(primary_key=True)
constituency_id = models.IntegerField()
boundary = models.TextField()
zoom = models.IntegerField()
north = models.FloatField()
south = models.FloatField()
east = models.FloatField()
west = models.FloatField()
class Meta:
db_table = u'boundaries_boundary'
## Instruction:
Put the model back the way it was
## Code After:
from django.db import models
from legacy.models import Constituency
class Boundary(models.Model):
constituency = models.ForeignKey( Constituency )
boundary = models.TextField()
zoom = models.IntegerField()
north = models.FloatField()
south = models.FloatField()
east = models.FloatField()
west = models.FloatField()
class Meta:
db_table = u'boundaries_boundary'
| from django.db import models
from legacy.models import Constituency
class Boundary(models.Model):
+ constituency = models.ForeignKey( Constituency )
- id = models.IntegerField(primary_key=True)
- constituency_id = models.IntegerField()
boundary = models.TextField()
zoom = models.IntegerField()
north = models.FloatField()
south = models.FloatField()
east = models.FloatField()
west = models.FloatField()
class Meta:
db_table = u'boundaries_boundary' |
d2cbcad65914ccd26b57dcec12c048c3524ecdc4 | src/cclib/__init__.py | src/cclib/__init__.py |
__version__ = "1.5"
from . import parser
from . import progress
from . import method
from . import bridge
from . import io
# The test module can be imported if it was installed with cclib.
try:
from . import test
except ImportError:
pass
|
__version__ = "1.5"
from . import parser
from . import progress
from . import method
from . import bridge
from . import io
# The test module can be imported if it was installed with cclib.
try:
from . import test
except ImportError:
pass
# The objects below constitute our public API. These names will not change
# over time. Names in the sub-modules will typically also be backwards
# compatible, but may sometimes change when code is moved around.
ccopen = io.ccopen
| Add alias cclib.ccopen for easy access | Add alias cclib.ccopen for easy access
| Python | bsd-3-clause | langner/cclib,gaursagar/cclib,ATenderholt/cclib,cclib/cclib,berquist/cclib,berquist/cclib,langner/cclib,berquist/cclib,ATenderholt/cclib,gaursagar/cclib,langner/cclib,cclib/cclib,cclib/cclib |
__version__ = "1.5"
from . import parser
from . import progress
from . import method
from . import bridge
from . import io
# The test module can be imported if it was installed with cclib.
try:
from . import test
except ImportError:
pass
+ # The objects below constitute our public API. These names will not change
+ # over time. Names in the sub-modules will typically also be backwards
+ # compatible, but may sometimes change when code is moved around.
+ ccopen = io.ccopen
+ | Add alias cclib.ccopen for easy access | ## Code Before:
__version__ = "1.5"
from . import parser
from . import progress
from . import method
from . import bridge
from . import io
# The test module can be imported if it was installed with cclib.
try:
from . import test
except ImportError:
pass
## Instruction:
Add alias cclib.ccopen for easy access
## Code After:
__version__ = "1.5"
from . import parser
from . import progress
from . import method
from . import bridge
from . import io
# The test module can be imported if it was installed with cclib.
try:
from . import test
except ImportError:
pass
# The objects below constitute our public API. These names will not change
# over time. Names in the sub-modules will typically also be backwards
# compatible, but may sometimes change when code is moved around.
ccopen = io.ccopen
|
__version__ = "1.5"
from . import parser
from . import progress
from . import method
from . import bridge
from . import io
# The test module can be imported if it was installed with cclib.
try:
from . import test
except ImportError:
pass
+
+ # The objects below constitute our public API. These names will not change
+ # over time. Names in the sub-modules will typically also be backwards
+ # compatible, but may sometimes change when code is moved around.
+ ccopen = io.ccopen |
b855dbde90bfd5842ad292f5f424957df02c2fe0 | myflaskapp/myflaskapp/item/models.py | myflaskapp/myflaskapp/item/models.py | """User models."""
import datetime as dt
from flask_login import UserMixin
from myflaskapp.database import Column, Model, SurrogatePK, db, reference_col, relationship
from myflaskapp.extensions import bcrypt
class Item(SurrogatePK, Model):
__tablename__ = 'items'
pass
| """User models."""
import datetime as dt
from flask_login import UserMixin
from myflaskapp.database import Column, Model, SurrogatePK, db, reference_col, relationship
from myflaskapp.extensions import bcrypt
class Item(SurrogatePK, Model):
__tablename__ = 'items'
text = Column(db.String(80),nullable=True)
| Add text field to Item model | Add text field to Item model
| Python | mit | terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python | """User models."""
import datetime as dt
from flask_login import UserMixin
from myflaskapp.database import Column, Model, SurrogatePK, db, reference_col, relationship
from myflaskapp.extensions import bcrypt
class Item(SurrogatePK, Model):
__tablename__ = 'items'
- pass
+ text = Column(db.String(80),nullable=True)
+ | Add text field to Item model | ## Code Before:
"""User models."""
import datetime as dt
from flask_login import UserMixin
from myflaskapp.database import Column, Model, SurrogatePK, db, reference_col, relationship
from myflaskapp.extensions import bcrypt
class Item(SurrogatePK, Model):
__tablename__ = 'items'
pass
## Instruction:
Add text field to Item model
## Code After:
"""User models."""
import datetime as dt
from flask_login import UserMixin
from myflaskapp.database import Column, Model, SurrogatePK, db, reference_col, relationship
from myflaskapp.extensions import bcrypt
class Item(SurrogatePK, Model):
__tablename__ = 'items'
text = Column(db.String(80),nullable=True)
| """User models."""
import datetime as dt
from flask_login import UserMixin
from myflaskapp.database import Column, Model, SurrogatePK, db, reference_col, relationship
from myflaskapp.extensions import bcrypt
class Item(SurrogatePK, Model):
__tablename__ = 'items'
- pass
+ text = Column(db.String(80),nullable=True)
+ |
c75071ad2dd8c2e5efdef660f1aa33ffa28f0613 | frontends/etiquette_repl.py | frontends/etiquette_repl.py |
import etiquette
import os
import sys
P = etiquette.photodb.PhotoDB()
import traceback
def easytagger():
while True:
i = input('> ')
if i.startswith('?'):
i = i.split('?')[1] or None
try:
etiquette.tag_export.stdout([P.get_tag(i)])
except:
traceback.print_exc()
else:
P.easybake(i)
def photag(photoid):
photo = P.get_photo_by_id(photoid)
print(photo.tags())
while True:
photo.add_tag(input('> '))
get=P.get_tag
|
import argparse
import os
import sys
import traceback
import etiquette
P = etiquette.photodb.PhotoDB()
def easytagger():
while True:
i = input('> ')
if i.startswith('?'):
i = i.split('?')[1] or None
try:
etiquette.tag_export.stdout([P.get_tag(i)])
except:
traceback.print_exc()
else:
P.easybake(i)
def photag(photoid):
photo = P.get_photo_by_id(photoid)
print(photo.tags())
while True:
photo.add_tag(input('> '))
get = P.get_tag
def erepl_argparse(args):
if args.exec_statement:
exec(args.exec_statement)
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument('--exec', dest='exec_statement', default=None)
parser.set_defaults(func=erepl_argparse)
args = parser.parse_args(argv)
args.func(args)
if __name__ == '__main__':
main(sys.argv[1:])
| Clean up the erepl code a little bit. | Clean up the erepl code a little bit.
| Python | bsd-3-clause | voussoir/etiquette,voussoir/etiquette,voussoir/etiquette | +
+ import argparse
+ import os
+ import sys
+ import traceback
import etiquette
- import os
- import sys
P = etiquette.photodb.PhotoDB()
- import traceback
def easytagger():
while True:
i = input('> ')
if i.startswith('?'):
i = i.split('?')[1] or None
try:
etiquette.tag_export.stdout([P.get_tag(i)])
except:
traceback.print_exc()
else:
P.easybake(i)
def photag(photoid):
photo = P.get_photo_by_id(photoid)
print(photo.tags())
while True:
photo.add_tag(input('> '))
- get=P.get_tag
+ get = P.get_tag
+
+ def erepl_argparse(args):
+ if args.exec_statement:
+ exec(args.exec_statement)
+
+ def main(argv):
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument('--exec', dest='exec_statement', default=None)
+ parser.set_defaults(func=erepl_argparse)
+
+ args = parser.parse_args(argv)
+ args.func(args)
+
+ if __name__ == '__main__':
+ main(sys.argv[1:])
+ | Clean up the erepl code a little bit. | ## Code Before:
import etiquette
import os
import sys
P = etiquette.photodb.PhotoDB()
import traceback
def easytagger():
while True:
i = input('> ')
if i.startswith('?'):
i = i.split('?')[1] or None
try:
etiquette.tag_export.stdout([P.get_tag(i)])
except:
traceback.print_exc()
else:
P.easybake(i)
def photag(photoid):
photo = P.get_photo_by_id(photoid)
print(photo.tags())
while True:
photo.add_tag(input('> '))
get=P.get_tag
## Instruction:
Clean up the erepl code a little bit.
## Code After:
import argparse
import os
import sys
import traceback
import etiquette
P = etiquette.photodb.PhotoDB()
def easytagger():
while True:
i = input('> ')
if i.startswith('?'):
i = i.split('?')[1] or None
try:
etiquette.tag_export.stdout([P.get_tag(i)])
except:
traceback.print_exc()
else:
P.easybake(i)
def photag(photoid):
photo = P.get_photo_by_id(photoid)
print(photo.tags())
while True:
photo.add_tag(input('> '))
get = P.get_tag
def erepl_argparse(args):
if args.exec_statement:
exec(args.exec_statement)
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument('--exec', dest='exec_statement', default=None)
parser.set_defaults(func=erepl_argparse)
args = parser.parse_args(argv)
args.func(args)
if __name__ == '__main__':
main(sys.argv[1:])
| +
+ import argparse
+ import os
+ import sys
+ import traceback
import etiquette
- import os
- import sys
P = etiquette.photodb.PhotoDB()
- import traceback
def easytagger():
while True:
i = input('> ')
if i.startswith('?'):
i = i.split('?')[1] or None
try:
etiquette.tag_export.stdout([P.get_tag(i)])
except:
traceback.print_exc()
else:
P.easybake(i)
def photag(photoid):
photo = P.get_photo_by_id(photoid)
print(photo.tags())
while True:
photo.add_tag(input('> '))
- get=P.get_tag
+ get = P.get_tag
? + +
+
+
+ def erepl_argparse(args):
+ if args.exec_statement:
+ exec(args.exec_statement)
+
+ def main(argv):
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument('--exec', dest='exec_statement', default=None)
+ parser.set_defaults(func=erepl_argparse)
+
+ args = parser.parse_args(argv)
+ args.func(args)
+
+ if __name__ == '__main__':
+ main(sys.argv[1:]) |
0f71f39a8634927b532c3f5b258720761f1d9c5c | mentorup/users/models.py | mentorup/users/models.py | from chosen import forms as chosenforms
# Import the AbstractUser model
from django.contrib.auth.models import AbstractUser
# Import the basic Django ORM models and forms library
from django.db import models
from django import forms
# Import tags for searching
from taggit.models import Tag
from taggit.models import TagBase
from taggit.managers import TaggableManager
from django.utils.translation import ugettext_lazy as _
# Create seperate classes for each tag type that will be a foreign key reference from User
class TeachSkills(models.Model):
skills = TaggableManager()
class LearnSkills(models.Model):
skills = TaggableManager()
# Subclass AbstractUser
class User(AbstractUser):
def __unicode__(self):
return self.username
teach = models.ForeignKey(TeachSkills, null=True)
learn = models.ForeignKey(LearnSkills, null=True)
short_bio = models.TextField()
location = models.CharField(max_length=50) | from chosen import forms as chosenforms
# Import the AbstractUser model
from django.contrib.auth.models import AbstractUser
# Import the basic Django ORM models and forms library
from django.db import models
from django import forms
# Import tags for searching
from taggit.models import Tag
from taggit.models import TagBase
from taggit.managers import TaggableManager
from django.utils.translation import ugettext_lazy as _
# Create seperate classes for each tag type that will be a foreign key reference from User
class TeachSkills(models.Model):
skills = TaggableManager()
class LearnSkills(models.Model):
skills = TaggableManager()
class UserManager(models.Manager):
def create(self, name):
new_user = Food()
new_user.name = name
new_user.teach = TeachSkills()
new_user.teach.save()
new_user.learn = LearnSkills()
new_user.learn.save()
new_user.save()
return new_user
# Subclass AbstractUser
class User(AbstractUser):
def __unicode__(self):
return self.username
objects = UserManager()
teach = models.ForeignKey(TeachSkills, null=True)
learn = models.ForeignKey(LearnSkills, null=True)
short_bio = models.TextField()
location = models.CharField(max_length=50) | Create UserManager to ensure ForeignKey relation is saved and associated with User upon creation | Create UserManager to ensure ForeignKey relation is saved and associated with User upon creation
| Python | bsd-3-clause | briandant/mentor_up,briandant/mentor_up,briandant/mentor_up,briandant/mentor_up | from chosen import forms as chosenforms
# Import the AbstractUser model
from django.contrib.auth.models import AbstractUser
# Import the basic Django ORM models and forms library
from django.db import models
from django import forms
# Import tags for searching
from taggit.models import Tag
from taggit.models import TagBase
from taggit.managers import TaggableManager
from django.utils.translation import ugettext_lazy as _
# Create seperate classes for each tag type that will be a foreign key reference from User
class TeachSkills(models.Model):
skills = TaggableManager()
class LearnSkills(models.Model):
skills = TaggableManager()
+ class UserManager(models.Manager):
+ def create(self, name):
+ new_user = Food()
+ new_user.name = name
+ new_user.teach = TeachSkills()
+ new_user.teach.save()
+ new_user.learn = LearnSkills()
+ new_user.learn.save()
+ new_user.save()
+ return new_user
+
# Subclass AbstractUser
class User(AbstractUser):
def __unicode__(self):
return self.username
-
+
+ objects = UserManager()
teach = models.ForeignKey(TeachSkills, null=True)
learn = models.ForeignKey(LearnSkills, null=True)
short_bio = models.TextField()
location = models.CharField(max_length=50) | Create UserManager to ensure ForeignKey relation is saved and associated with User upon creation | ## Code Before:
from chosen import forms as chosenforms
# Import the AbstractUser model
from django.contrib.auth.models import AbstractUser
# Import the basic Django ORM models and forms library
from django.db import models
from django import forms
# Import tags for searching
from taggit.models import Tag
from taggit.models import TagBase
from taggit.managers import TaggableManager
from django.utils.translation import ugettext_lazy as _
# Create seperate classes for each tag type that will be a foreign key reference from User
class TeachSkills(models.Model):
skills = TaggableManager()
class LearnSkills(models.Model):
skills = TaggableManager()
# Subclass AbstractUser
class User(AbstractUser):
def __unicode__(self):
return self.username
teach = models.ForeignKey(TeachSkills, null=True)
learn = models.ForeignKey(LearnSkills, null=True)
short_bio = models.TextField()
location = models.CharField(max_length=50)
## Instruction:
Create UserManager to ensure ForeignKey relation is saved and associated with User upon creation
## Code After:
from chosen import forms as chosenforms
# Import the AbstractUser model
from django.contrib.auth.models import AbstractUser
# Import the basic Django ORM models and forms library
from django.db import models
from django import forms
# Import tags for searching
from taggit.models import Tag
from taggit.models import TagBase
from taggit.managers import TaggableManager
from django.utils.translation import ugettext_lazy as _
# Create seperate classes for each tag type that will be a foreign key reference from User
class TeachSkills(models.Model):
skills = TaggableManager()
class LearnSkills(models.Model):
skills = TaggableManager()
class UserManager(models.Manager):
def create(self, name):
new_user = Food()
new_user.name = name
new_user.teach = TeachSkills()
new_user.teach.save()
new_user.learn = LearnSkills()
new_user.learn.save()
new_user.save()
return new_user
# Subclass AbstractUser
class User(AbstractUser):
def __unicode__(self):
return self.username
objects = UserManager()
teach = models.ForeignKey(TeachSkills, null=True)
learn = models.ForeignKey(LearnSkills, null=True)
short_bio = models.TextField()
location = models.CharField(max_length=50) | from chosen import forms as chosenforms
# Import the AbstractUser model
from django.contrib.auth.models import AbstractUser
# Import the basic Django ORM models and forms library
from django.db import models
from django import forms
# Import tags for searching
from taggit.models import Tag
from taggit.models import TagBase
from taggit.managers import TaggableManager
from django.utils.translation import ugettext_lazy as _
# Create seperate classes for each tag type that will be a foreign key reference from User
class TeachSkills(models.Model):
skills = TaggableManager()
class LearnSkills(models.Model):
skills = TaggableManager()
+ class UserManager(models.Manager):
+ def create(self, name):
+ new_user = Food()
+ new_user.name = name
+ new_user.teach = TeachSkills()
+ new_user.teach.save()
+ new_user.learn = LearnSkills()
+ new_user.learn.save()
+ new_user.save()
+ return new_user
+
# Subclass AbstractUser
class User(AbstractUser):
def __unicode__(self):
return self.username
-
+
+ objects = UserManager()
teach = models.ForeignKey(TeachSkills, null=True)
learn = models.ForeignKey(LearnSkills, null=True)
short_bio = models.TextField()
location = models.CharField(max_length=50) |
9ff59c13f0c1295e9a0acd45913f00d8c9a5c0af | mongoctl/errors.py | mongoctl/errors.py | __author__ = 'abdul'
###############################################################################
# Mongoctl Exception class
###############################################################################
class MongoctlException(Exception):
def __init__(self, message,cause=None):
self.message = message
self.cause = cause
def __str__(self):
return self.message | __author__ = 'abdul'
###############################################################################
# Mongoctl Exception class
###############################################################################
class MongoctlException(Exception):
def __init__(self, message, cause=None):
super(MongoctlException, self).__init__(message)
self._cause = cause | Remove ref to deprecated "message" property of BaseException | Remove ref to deprecated "message" property of BaseException
| Python | mit | mongolab/mongoctl | __author__ = 'abdul'
###############################################################################
# Mongoctl Exception class
###############################################################################
class MongoctlException(Exception):
- def __init__(self, message,cause=None):
+ def __init__(self, message, cause=None):
- self.message = message
+ super(MongoctlException, self).__init__(message)
- self.cause = cause
+ self._cause = cause
-
- def __str__(self):
- return self.message | Remove ref to deprecated "message" property of BaseException | ## Code Before:
__author__ = 'abdul'
###############################################################################
# Mongoctl Exception class
###############################################################################
class MongoctlException(Exception):
def __init__(self, message,cause=None):
self.message = message
self.cause = cause
def __str__(self):
return self.message
## Instruction:
Remove ref to deprecated "message" property of BaseException
## Code After:
__author__ = 'abdul'
###############################################################################
# Mongoctl Exception class
###############################################################################
class MongoctlException(Exception):
def __init__(self, message, cause=None):
super(MongoctlException, self).__init__(message)
self._cause = cause | __author__ = 'abdul'
###############################################################################
# Mongoctl Exception class
###############################################################################
class MongoctlException(Exception):
- def __init__(self, message,cause=None):
+ def __init__(self, message, cause=None):
? +
- self.message = message
+ super(MongoctlException, self).__init__(message)
- self.cause = cause
+ self._cause = cause
? +
-
- def __str__(self):
- return self.message |
71166b445eb5b4aec407b743f8167842e21ed28f | dataedit/templatetags/dataedit/taghandler.py | dataedit/templatetags/dataedit/taghandler.py | from django import template
from dataedit import models
import webcolors
register = template.Library()
@register.assignment_tag
def get_tags():
return models.Tag.objects.all()[:10]
@register.simple_tag()
def readable_text_color(color_hex):
r,g,b = webcolors.hex_to_rgb(color_hex)
L = 0.2126 * r + 0.7152 * g+ 0.0722 * b
print((r,g,b), L, 0.279*255)
if L < 0.279*255:
return "#FFFFFF"
else:
return "#000000" | from django import template
from dataedit import models
import webcolors
register = template.Library()
@register.assignment_tag
def get_tags():
return models.Tag.objects.all()[:10]
@register.simple_tag()
def readable_text_color(color_hex):
r, g, b = webcolors.hex_to_rgb(color_hex)
# Calculate brightness of the background and compare to threshold
if 0.2126 * r + 0.7152 * g+ 0.0722 * b < 0.279*255:
return "#FFFFFF"
else:
return "#000000"
| Remove unnecessary variable assignment and print | Remove unnecessary variable assignment and print
| Python | agpl-3.0 | openego/oeplatform,tom-heimbrodt/oeplatform,tom-heimbrodt/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform,tom-heimbrodt/oeplatform | from django import template
from dataedit import models
import webcolors
register = template.Library()
@register.assignment_tag
def get_tags():
return models.Tag.objects.all()[:10]
+
@register.simple_tag()
def readable_text_color(color_hex):
- r,g,b = webcolors.hex_to_rgb(color_hex)
+ r, g, b = webcolors.hex_to_rgb(color_hex)
+ # Calculate brightness of the background and compare to threshold
- L = 0.2126 * r + 0.7152 * g+ 0.0722 * b
+ if 0.2126 * r + 0.7152 * g+ 0.0722 * b < 0.279*255:
- print((r,g,b), L, 0.279*255)
- if L < 0.279*255:
return "#FFFFFF"
else:
return "#000000"
+ | Remove unnecessary variable assignment and print | ## Code Before:
from django import template
from dataedit import models
import webcolors
register = template.Library()
@register.assignment_tag
def get_tags():
return models.Tag.objects.all()[:10]
@register.simple_tag()
def readable_text_color(color_hex):
r,g,b = webcolors.hex_to_rgb(color_hex)
L = 0.2126 * r + 0.7152 * g+ 0.0722 * b
print((r,g,b), L, 0.279*255)
if L < 0.279*255:
return "#FFFFFF"
else:
return "#000000"
## Instruction:
Remove unnecessary variable assignment and print
## Code After:
from django import template
from dataedit import models
import webcolors
register = template.Library()
@register.assignment_tag
def get_tags():
return models.Tag.objects.all()[:10]
@register.simple_tag()
def readable_text_color(color_hex):
r, g, b = webcolors.hex_to_rgb(color_hex)
# Calculate brightness of the background and compare to threshold
if 0.2126 * r + 0.7152 * g+ 0.0722 * b < 0.279*255:
return "#FFFFFF"
else:
return "#000000"
| from django import template
from dataedit import models
import webcolors
register = template.Library()
@register.assignment_tag
def get_tags():
return models.Tag.objects.all()[:10]
+
@register.simple_tag()
def readable_text_color(color_hex):
- r,g,b = webcolors.hex_to_rgb(color_hex)
+ r, g, b = webcolors.hex_to_rgb(color_hex)
? + +
+ # Calculate brightness of the background and compare to threshold
- L = 0.2126 * r + 0.7152 * g+ 0.0722 * b
? ^^^
+ if 0.2126 * r + 0.7152 * g+ 0.0722 * b < 0.279*255:
? ^^ +++++++++++++
- print((r,g,b), L, 0.279*255)
- if L < 0.279*255:
return "#FFFFFF"
else:
return "#000000" |
375b26fbb6e5ba043a1017e28027241c12374207 | napalm_logs/transport/zeromq.py | napalm_logs/transport/zeromq.py | '''
ZeroMQ transport for napalm-logs.
'''
from __future__ import absolute_import
from __future__ import unicode_literals
# Import stdlib
import json
# Import third party libs
import zmq
# Import napalm-logs pkgs
from napalm_logs.transport.base import TransportBase
class ZMQTransport(TransportBase):
'''
ZMQ transport class.
'''
def __init__(self, addr, port):
self.addr = addr
self.port = port
def start(self):
self.context = zmq.Context()
self.socket = self.context.socket(zmq.PUB)
self.socket.bind('tcp://{addr}:{port}'.format(
addr=self.addr,
port=self.port)
)
def serialise(self, obj):
return json.dumps(obj)
def publish(self, obj):
self.socket.send(
self.serialise(obj)
)
def tear_down(self):
if hasattr(self, 'socket'):
self.socket.close()
if hasattr(self, 'context'):
self.context.term()
| '''
ZeroMQ transport for napalm-logs.
'''
from __future__ import absolute_import
from __future__ import unicode_literals
# Import stdlib
import json
import logging
# Import third party libs
import zmq
# Import napalm-logs pkgs
from napalm_logs.exceptions import BindException
from napalm_logs.transport.base import TransportBase
log = logging.getLogger(__name__)
class ZMQTransport(TransportBase):
'''
ZMQ transport class.
'''
def __init__(self, addr, port):
self.addr = addr
self.port = port
def start(self):
self.context = zmq.Context()
self.socket = self.context.socket(zmq.PUB)
try:
self.socket.bind('tcp://{addr}:{port}'.format(
addr=self.addr,
port=self.port)
)
except zmq.error.ZMQError as err:
log.error(err, exc_info=True)
raise BindException(err)
def serialise(self, obj):
return json.dumps(obj)
def publish(self, obj):
self.socket.send(
self.serialise(obj)
)
def tear_down(self):
if hasattr(self, 'socket'):
self.socket.close()
if hasattr(self, 'context'):
self.context.term()
| Raise bind exception and log | Raise bind exception and log
| Python | apache-2.0 | napalm-automation/napalm-logs,napalm-automation/napalm-logs | '''
ZeroMQ transport for napalm-logs.
'''
from __future__ import absolute_import
from __future__ import unicode_literals
# Import stdlib
import json
+ import logging
# Import third party libs
import zmq
# Import napalm-logs pkgs
+ from napalm_logs.exceptions import BindException
from napalm_logs.transport.base import TransportBase
+
+ log = logging.getLogger(__name__)
class ZMQTransport(TransportBase):
'''
ZMQ transport class.
'''
def __init__(self, addr, port):
self.addr = addr
self.port = port
def start(self):
self.context = zmq.Context()
self.socket = self.context.socket(zmq.PUB)
+ try:
- self.socket.bind('tcp://{addr}:{port}'.format(
+ self.socket.bind('tcp://{addr}:{port}'.format(
- addr=self.addr,
+ addr=self.addr,
- port=self.port)
+ port=self.port)
- )
+ )
+ except zmq.error.ZMQError as err:
+ log.error(err, exc_info=True)
+ raise BindException(err)
def serialise(self, obj):
return json.dumps(obj)
def publish(self, obj):
self.socket.send(
self.serialise(obj)
)
def tear_down(self):
if hasattr(self, 'socket'):
self.socket.close()
if hasattr(self, 'context'):
self.context.term()
| Raise bind exception and log | ## Code Before:
'''
ZeroMQ transport for napalm-logs.
'''
from __future__ import absolute_import
from __future__ import unicode_literals
# Import stdlib
import json
# Import third party libs
import zmq
# Import napalm-logs pkgs
from napalm_logs.transport.base import TransportBase
class ZMQTransport(TransportBase):
'''
ZMQ transport class.
'''
def __init__(self, addr, port):
self.addr = addr
self.port = port
def start(self):
self.context = zmq.Context()
self.socket = self.context.socket(zmq.PUB)
self.socket.bind('tcp://{addr}:{port}'.format(
addr=self.addr,
port=self.port)
)
def serialise(self, obj):
return json.dumps(obj)
def publish(self, obj):
self.socket.send(
self.serialise(obj)
)
def tear_down(self):
if hasattr(self, 'socket'):
self.socket.close()
if hasattr(self, 'context'):
self.context.term()
## Instruction:
Raise bind exception and log
## Code After:
'''
ZeroMQ transport for napalm-logs.
'''
from __future__ import absolute_import
from __future__ import unicode_literals
# Import stdlib
import json
import logging
# Import third party libs
import zmq
# Import napalm-logs pkgs
from napalm_logs.exceptions import BindException
from napalm_logs.transport.base import TransportBase
log = logging.getLogger(__name__)
class ZMQTransport(TransportBase):
'''
ZMQ transport class.
'''
def __init__(self, addr, port):
self.addr = addr
self.port = port
def start(self):
self.context = zmq.Context()
self.socket = self.context.socket(zmq.PUB)
try:
self.socket.bind('tcp://{addr}:{port}'.format(
addr=self.addr,
port=self.port)
)
except zmq.error.ZMQError as err:
log.error(err, exc_info=True)
raise BindException(err)
def serialise(self, obj):
return json.dumps(obj)
def publish(self, obj):
self.socket.send(
self.serialise(obj)
)
def tear_down(self):
if hasattr(self, 'socket'):
self.socket.close()
if hasattr(self, 'context'):
self.context.term()
| '''
ZeroMQ transport for napalm-logs.
'''
from __future__ import absolute_import
from __future__ import unicode_literals
# Import stdlib
import json
+ import logging
# Import third party libs
import zmq
# Import napalm-logs pkgs
+ from napalm_logs.exceptions import BindException
from napalm_logs.transport.base import TransportBase
+
+ log = logging.getLogger(__name__)
class ZMQTransport(TransportBase):
'''
ZMQ transport class.
'''
def __init__(self, addr, port):
self.addr = addr
self.port = port
def start(self):
self.context = zmq.Context()
self.socket = self.context.socket(zmq.PUB)
+ try:
- self.socket.bind('tcp://{addr}:{port}'.format(
+ self.socket.bind('tcp://{addr}:{port}'.format(
? ++++
- addr=self.addr,
+ addr=self.addr,
? ++++
- port=self.port)
+ port=self.port)
? ++++
- )
+ )
? ++++
+ except zmq.error.ZMQError as err:
+ log.error(err, exc_info=True)
+ raise BindException(err)
def serialise(self, obj):
return json.dumps(obj)
def publish(self, obj):
self.socket.send(
self.serialise(obj)
)
def tear_down(self):
if hasattr(self, 'socket'):
self.socket.close()
if hasattr(self, 'context'):
self.context.term() |
b0b4bad0ca68ebd1927229e85e7116fb63126c65 | src/olympia/zadmin/helpers.py | src/olympia/zadmin/helpers.py | from jingo import register
from olympia.amo.urlresolvers import reverse
@register.function
def admin_site_links():
return {
'addons': [
('Search for add-ons by name or id',
reverse('zadmin.addon-search')),
('Featured add-ons', reverse('zadmin.features')),
('Discovery Pane promo modules',
reverse('discovery.module_admin')),
('Monthly Pick', reverse('zadmin.monthly_pick')),
('Bulk add-on validation', reverse('zadmin.validation')),
('Fake mail', reverse('zadmin.mail')),
('ACR Reports', reverse('zadmin.compat')),
('Email Add-on Developers', reverse('zadmin.email_devs')),
],
'users': [
('Configure groups', reverse('admin:access_group_changelist')),
],
'settings': [
('View site settings', reverse('zadmin.settings')),
('Django admin pages', reverse('zadmin.home')),
('Site Events', reverse('zadmin.site_events')),
],
'tools': [
('View request environment', reverse('amo.env')),
('Manage elasticsearch', reverse('zadmin.elastic')),
('Purge data from memcache', reverse('zadmin.memcache')),
('View event log', reverse('admin:editors_eventlog_changelist')),
('View addon log', reverse('admin:devhub_activitylog_changelist')),
('Generate error', reverse('zadmin.generate-error')),
('Site Status', reverse('amo.monitor')),
],
}
| from jingo import register
from olympia.amo.urlresolvers import reverse
@register.function
def admin_site_links():
return {
'addons': [
('Search for add-ons by name or id',
reverse('zadmin.addon-search')),
('Featured add-ons', reverse('zadmin.features')),
('Discovery Pane promo modules',
reverse('discovery.module_admin')),
('Monthly Pick', reverse('zadmin.monthly_pick')),
('Bulk add-on validation', reverse('zadmin.validation')),
('Fake mail', reverse('zadmin.mail')),
('ACR Reports', reverse('zadmin.compat')),
('Email Add-on Developers', reverse('zadmin.email_devs')),
],
'users': [
('Configure groups', reverse('admin:access_group_changelist')),
],
'settings': [
('View site settings', reverse('zadmin.settings')),
('Django admin pages', reverse('zadmin.home')),
('Site Events', reverse('zadmin.site_events')),
],
'tools': [
('View request environment', reverse('amo.env')),
('Manage elasticsearch', reverse('zadmin.elastic')),
('Purge data from memcache', reverse('zadmin.memcache')),
('View event log', reverse('admin:editors_eventlog_changelist')),
('View addon log', reverse('admin:devhub_activitylog_changelist')),
('Site Status', reverse('amo.monitor')),
],
}
| Remove generate error page from admin site | Remove generate error page from admin site
| Python | bsd-3-clause | bqbn/addons-server,wagnerand/olympia,harry-7/addons-server,wagnerand/addons-server,harikishen/addons-server,psiinon/addons-server,lavish205/olympia,mstriemer/addons-server,kumar303/addons-server,Prashant-Surya/addons-server,mstriemer/olympia,mozilla/addons-server,harikishen/addons-server,Revanth47/addons-server,mstriemer/addons-server,mstriemer/olympia,lavish205/olympia,lavish205/olympia,wagnerand/olympia,diox/olympia,eviljeff/olympia,aviarypl/mozilla-l10n-addons-server,mozilla/olympia,tsl143/addons-server,Revanth47/addons-server,wagnerand/addons-server,psiinon/addons-server,eviljeff/olympia,wagnerand/addons-server,harry-7/addons-server,kumar303/addons-server,wagnerand/olympia,eviljeff/olympia,Prashant-Surya/addons-server,bqbn/addons-server,kumar303/addons-server,Revanth47/addons-server,kumar303/olympia,harry-7/addons-server,kumar303/olympia,aviarypl/mozilla-l10n-addons-server,kumar303/addons-server,mstriemer/addons-server,harikishen/addons-server,mstriemer/olympia,Prashant-Surya/addons-server,mozilla/olympia,diox/olympia,psiinon/addons-server,harry-7/addons-server,wagnerand/olympia,aviarypl/mozilla-l10n-addons-server,kumar303/olympia,mstriemer/olympia,mozilla/addons-server,bqbn/addons-server,Revanth47/addons-server,mstriemer/addons-server,diox/olympia,harikishen/addons-server,wagnerand/addons-server,diox/olympia,atiqueahmedziad/addons-server,psiinon/addons-server,eviljeff/olympia,tsl143/addons-server,mozilla/olympia,kumar303/olympia,lavish205/olympia,atiqueahmedziad/addons-server,tsl143/addons-server,tsl143/addons-server,mozilla/addons-server,mozilla/olympia,bqbn/addons-server,aviarypl/mozilla-l10n-addons-server,Prashant-Surya/addons-server,atiqueahmedziad/addons-server,mozilla/addons-server,atiqueahmedziad/addons-server | from jingo import register
from olympia.amo.urlresolvers import reverse
@register.function
def admin_site_links():
return {
'addons': [
('Search for add-ons by name or id',
reverse('zadmin.addon-search')),
('Featured add-ons', reverse('zadmin.features')),
('Discovery Pane promo modules',
reverse('discovery.module_admin')),
('Monthly Pick', reverse('zadmin.monthly_pick')),
('Bulk add-on validation', reverse('zadmin.validation')),
('Fake mail', reverse('zadmin.mail')),
('ACR Reports', reverse('zadmin.compat')),
('Email Add-on Developers', reverse('zadmin.email_devs')),
],
'users': [
('Configure groups', reverse('admin:access_group_changelist')),
],
'settings': [
('View site settings', reverse('zadmin.settings')),
('Django admin pages', reverse('zadmin.home')),
('Site Events', reverse('zadmin.site_events')),
],
'tools': [
('View request environment', reverse('amo.env')),
('Manage elasticsearch', reverse('zadmin.elastic')),
('Purge data from memcache', reverse('zadmin.memcache')),
('View event log', reverse('admin:editors_eventlog_changelist')),
('View addon log', reverse('admin:devhub_activitylog_changelist')),
- ('Generate error', reverse('zadmin.generate-error')),
('Site Status', reverse('amo.monitor')),
],
}
| Remove generate error page from admin site | ## Code Before:
from jingo import register
from olympia.amo.urlresolvers import reverse
@register.function
def admin_site_links():
return {
'addons': [
('Search for add-ons by name or id',
reverse('zadmin.addon-search')),
('Featured add-ons', reverse('zadmin.features')),
('Discovery Pane promo modules',
reverse('discovery.module_admin')),
('Monthly Pick', reverse('zadmin.monthly_pick')),
('Bulk add-on validation', reverse('zadmin.validation')),
('Fake mail', reverse('zadmin.mail')),
('ACR Reports', reverse('zadmin.compat')),
('Email Add-on Developers', reverse('zadmin.email_devs')),
],
'users': [
('Configure groups', reverse('admin:access_group_changelist')),
],
'settings': [
('View site settings', reverse('zadmin.settings')),
('Django admin pages', reverse('zadmin.home')),
('Site Events', reverse('zadmin.site_events')),
],
'tools': [
('View request environment', reverse('amo.env')),
('Manage elasticsearch', reverse('zadmin.elastic')),
('Purge data from memcache', reverse('zadmin.memcache')),
('View event log', reverse('admin:editors_eventlog_changelist')),
('View addon log', reverse('admin:devhub_activitylog_changelist')),
('Generate error', reverse('zadmin.generate-error')),
('Site Status', reverse('amo.monitor')),
],
}
## Instruction:
Remove generate error page from admin site
## Code After:
from jingo import register
from olympia.amo.urlresolvers import reverse
@register.function
def admin_site_links():
return {
'addons': [
('Search for add-ons by name or id',
reverse('zadmin.addon-search')),
('Featured add-ons', reverse('zadmin.features')),
('Discovery Pane promo modules',
reverse('discovery.module_admin')),
('Monthly Pick', reverse('zadmin.monthly_pick')),
('Bulk add-on validation', reverse('zadmin.validation')),
('Fake mail', reverse('zadmin.mail')),
('ACR Reports', reverse('zadmin.compat')),
('Email Add-on Developers', reverse('zadmin.email_devs')),
],
'users': [
('Configure groups', reverse('admin:access_group_changelist')),
],
'settings': [
('View site settings', reverse('zadmin.settings')),
('Django admin pages', reverse('zadmin.home')),
('Site Events', reverse('zadmin.site_events')),
],
'tools': [
('View request environment', reverse('amo.env')),
('Manage elasticsearch', reverse('zadmin.elastic')),
('Purge data from memcache', reverse('zadmin.memcache')),
('View event log', reverse('admin:editors_eventlog_changelist')),
('View addon log', reverse('admin:devhub_activitylog_changelist')),
('Site Status', reverse('amo.monitor')),
],
}
| from jingo import register
from olympia.amo.urlresolvers import reverse
@register.function
def admin_site_links():
return {
'addons': [
('Search for add-ons by name or id',
reverse('zadmin.addon-search')),
('Featured add-ons', reverse('zadmin.features')),
('Discovery Pane promo modules',
reverse('discovery.module_admin')),
('Monthly Pick', reverse('zadmin.monthly_pick')),
('Bulk add-on validation', reverse('zadmin.validation')),
('Fake mail', reverse('zadmin.mail')),
('ACR Reports', reverse('zadmin.compat')),
('Email Add-on Developers', reverse('zadmin.email_devs')),
],
'users': [
('Configure groups', reverse('admin:access_group_changelist')),
],
'settings': [
('View site settings', reverse('zadmin.settings')),
('Django admin pages', reverse('zadmin.home')),
('Site Events', reverse('zadmin.site_events')),
],
'tools': [
('View request environment', reverse('amo.env')),
('Manage elasticsearch', reverse('zadmin.elastic')),
('Purge data from memcache', reverse('zadmin.memcache')),
('View event log', reverse('admin:editors_eventlog_changelist')),
('View addon log', reverse('admin:devhub_activitylog_changelist')),
- ('Generate error', reverse('zadmin.generate-error')),
('Site Status', reverse('amo.monitor')),
],
} |
248fda4f499375b24a2f670569259f0904948b7e | troposphere/detective.py | troposphere/detective.py |
from . import AWSObject
from .validators import boolean
class Graph(AWSObject):
resource_type = "AWS::Detective::Graph"
props = {}
class MemberInvitation(AWSObject):
resource_type = "AWS::Detective::MemberInvitation"
props = {
"DisableEmailNotification": (boolean, False),
"GraphArn": (str, True),
"MemberEmailAddress": (str, True),
"MemberId": (str, True),
"Message": (str, False),
}
|
from . import AWSObject, Tags
from .validators import boolean
class Graph(AWSObject):
resource_type = "AWS::Detective::Graph"
props = {
"Tags": (Tags, False),
}
class MemberInvitation(AWSObject):
resource_type = "AWS::Detective::MemberInvitation"
props = {
"DisableEmailNotification": (boolean, False),
"GraphArn": (str, True),
"MemberEmailAddress": (str, True),
"MemberId": (str, True),
"Message": (str, False),
}
| Update Detective per 2021-04-29 changes | Update Detective per 2021-04-29 changes
| Python | bsd-2-clause | cloudtools/troposphere,cloudtools/troposphere |
- from . import AWSObject
+ from . import AWSObject, Tags
from .validators import boolean
class Graph(AWSObject):
resource_type = "AWS::Detective::Graph"
- props = {}
+ props = {
+ "Tags": (Tags, False),
+ }
class MemberInvitation(AWSObject):
resource_type = "AWS::Detective::MemberInvitation"
props = {
"DisableEmailNotification": (boolean, False),
"GraphArn": (str, True),
"MemberEmailAddress": (str, True),
"MemberId": (str, True),
"Message": (str, False),
}
| Update Detective per 2021-04-29 changes | ## Code Before:
from . import AWSObject
from .validators import boolean
class Graph(AWSObject):
resource_type = "AWS::Detective::Graph"
props = {}
class MemberInvitation(AWSObject):
resource_type = "AWS::Detective::MemberInvitation"
props = {
"DisableEmailNotification": (boolean, False),
"GraphArn": (str, True),
"MemberEmailAddress": (str, True),
"MemberId": (str, True),
"Message": (str, False),
}
## Instruction:
Update Detective per 2021-04-29 changes
## Code After:
from . import AWSObject, Tags
from .validators import boolean
class Graph(AWSObject):
resource_type = "AWS::Detective::Graph"
props = {
"Tags": (Tags, False),
}
class MemberInvitation(AWSObject):
resource_type = "AWS::Detective::MemberInvitation"
props = {
"DisableEmailNotification": (boolean, False),
"GraphArn": (str, True),
"MemberEmailAddress": (str, True),
"MemberId": (str, True),
"Message": (str, False),
}
|
- from . import AWSObject
+ from . import AWSObject, Tags
? ++++++
from .validators import boolean
class Graph(AWSObject):
resource_type = "AWS::Detective::Graph"
- props = {}
? -
+ props = {
+ "Tags": (Tags, False),
+ }
class MemberInvitation(AWSObject):
resource_type = "AWS::Detective::MemberInvitation"
props = {
"DisableEmailNotification": (boolean, False),
"GraphArn": (str, True),
"MemberEmailAddress": (str, True),
"MemberId": (str, True),
"Message": (str, False),
} |
e4ef3df9401bde3c2087a7659a54246de8ec95c6 | src/api/urls.py | src/api/urls.py | from rest_framework.routers import SimpleRouter
#
from bingo_server.api import views as bingo_server_views
router = SimpleRouter()
router.register('games', bingo_server_views.GameViewSet)
urlpatterns = router.urls
| from rest_framework.routers import DefaultRouter
#
from bingo_server.api import views as bingo_server_views
router = DefaultRouter()
router.register('games', bingo_server_views.GameViewSet)
urlpatterns = router.urls
| Add root view to API | Add root view to API
| Python | mit | steakholders-tm/bingo-server | - from rest_framework.routers import SimpleRouter
+ from rest_framework.routers import DefaultRouter
#
from bingo_server.api import views as bingo_server_views
- router = SimpleRouter()
+ router = DefaultRouter()
router.register('games', bingo_server_views.GameViewSet)
urlpatterns = router.urls
| Add root view to API | ## Code Before:
from rest_framework.routers import SimpleRouter
#
from bingo_server.api import views as bingo_server_views
router = SimpleRouter()
router.register('games', bingo_server_views.GameViewSet)
urlpatterns = router.urls
## Instruction:
Add root view to API
## Code After:
from rest_framework.routers import DefaultRouter
#
from bingo_server.api import views as bingo_server_views
router = DefaultRouter()
router.register('games', bingo_server_views.GameViewSet)
urlpatterns = router.urls
| - from rest_framework.routers import SimpleRouter
? ^^^^ ^
+ from rest_framework.routers import DefaultRouter
? ^^^^^ ^
#
from bingo_server.api import views as bingo_server_views
- router = SimpleRouter()
? ^^^^ ^
+ router = DefaultRouter()
? ^^^^^ ^
router.register('games', bingo_server_views.GameViewSet)
urlpatterns = router.urls |
43f4d3394e184f9984f10cbeec51ca561a8d548c | shellish/logging.py | shellish/logging.py |
import logging
from . import rendering
class VTMLHandler(logging.StreamHandler):
""" Parse VTML messages to colorize and embolden logs. """
log_format = '[<blue>%(asctime)s</blue>] [%(levelname)s] %(message)s'
level_fmt = {
10: '<dim>%s</dim>',
20: '%s',
30: '<b>%s</b>',
40: '<red>%s</red>',
50: '<red><b>%s</b></red>',
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setFormatter(VTMLFormatter(self.log_format))
def format(self, record):
record.levelname = self.level_fmt[record.levelno] % record.levelname
return str(rendering.vtmlrender(super().format(record)))
class VTMLFormatter(logging.Formatter):
def formatException(self, ei):
return '\n'.join(rendering.format_exception(ei[1]))
|
import logging
from . import rendering
class VTMLHandler(logging.StreamHandler):
""" Parse VTML messages to colorize and embolden logs. """
log_format = '[<blue>%(asctime)s</blue>] [<cyan>%(name)s</cyan>] ' \
'[%(levelname)s] %(message)s'
level_fmt = {
10: '<dim>%s</dim>',
20: '%s',
30: '<b>%s</b>',
40: '<red>%s</red>',
50: '<red><b>%s</b></red>',
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setFormatter(VTMLFormatter(self.log_format))
def format(self, record):
record.levelname = self.level_fmt[record.levelno] % record.levelname
return str(rendering.vtmlrender(super().format(record)))
class VTMLFormatter(logging.Formatter):
def formatException(self, ei):
return '\n'.join(rendering.format_exception(ei[1]))
| Add logger name to default log format. | Add logger name to default log format.
| Python | mit | mayfield/shellish |
import logging
from . import rendering
class VTMLHandler(logging.StreamHandler):
""" Parse VTML messages to colorize and embolden logs. """
- log_format = '[<blue>%(asctime)s</blue>] [%(levelname)s] %(message)s'
+ log_format = '[<blue>%(asctime)s</blue>] [<cyan>%(name)s</cyan>] ' \
+ '[%(levelname)s] %(message)s'
level_fmt = {
10: '<dim>%s</dim>',
20: '%s',
30: '<b>%s</b>',
40: '<red>%s</red>',
50: '<red><b>%s</b></red>',
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setFormatter(VTMLFormatter(self.log_format))
def format(self, record):
record.levelname = self.level_fmt[record.levelno] % record.levelname
return str(rendering.vtmlrender(super().format(record)))
class VTMLFormatter(logging.Formatter):
def formatException(self, ei):
return '\n'.join(rendering.format_exception(ei[1]))
| Add logger name to default log format. | ## Code Before:
import logging
from . import rendering
class VTMLHandler(logging.StreamHandler):
""" Parse VTML messages to colorize and embolden logs. """
log_format = '[<blue>%(asctime)s</blue>] [%(levelname)s] %(message)s'
level_fmt = {
10: '<dim>%s</dim>',
20: '%s',
30: '<b>%s</b>',
40: '<red>%s</red>',
50: '<red><b>%s</b></red>',
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setFormatter(VTMLFormatter(self.log_format))
def format(self, record):
record.levelname = self.level_fmt[record.levelno] % record.levelname
return str(rendering.vtmlrender(super().format(record)))
class VTMLFormatter(logging.Formatter):
def formatException(self, ei):
return '\n'.join(rendering.format_exception(ei[1]))
## Instruction:
Add logger name to default log format.
## Code After:
import logging
from . import rendering
class VTMLHandler(logging.StreamHandler):
""" Parse VTML messages to colorize and embolden logs. """
log_format = '[<blue>%(asctime)s</blue>] [<cyan>%(name)s</cyan>] ' \
'[%(levelname)s] %(message)s'
level_fmt = {
10: '<dim>%s</dim>',
20: '%s',
30: '<b>%s</b>',
40: '<red>%s</red>',
50: '<red><b>%s</b></red>',
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setFormatter(VTMLFormatter(self.log_format))
def format(self, record):
record.levelname = self.level_fmt[record.levelno] % record.levelname
return str(rendering.vtmlrender(super().format(record)))
class VTMLFormatter(logging.Formatter):
def formatException(self, ei):
return '\n'.join(rendering.format_exception(ei[1]))
|
import logging
from . import rendering
class VTMLHandler(logging.StreamHandler):
""" Parse VTML messages to colorize and embolden logs. """
- log_format = '[<blue>%(asctime)s</blue>] [%(levelname)s] %(message)s'
? ----- -----------
+ log_format = '[<blue>%(asctime)s</blue>] [<cyan>%(name)s</cyan>] ' \
? ++++++ +++++++ ++
+ '[%(levelname)s] %(message)s'
level_fmt = {
10: '<dim>%s</dim>',
20: '%s',
30: '<b>%s</b>',
40: '<red>%s</red>',
50: '<red><b>%s</b></red>',
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setFormatter(VTMLFormatter(self.log_format))
def format(self, record):
record.levelname = self.level_fmt[record.levelno] % record.levelname
return str(rendering.vtmlrender(super().format(record)))
class VTMLFormatter(logging.Formatter):
def formatException(self, ei):
return '\n'.join(rendering.format_exception(ei[1])) |
9be37b96450780b41f5a5443568ca41a18e06d22 | lcapy/sequence.py | lcapy/sequence.py |
from .expr import ExprList
class Sequence(ExprList):
def __init__(self, seq, n=None):
super (Sequence, self).__init__(seq)
# Save the indexes. Ideally, should annotate which item
# in sequence corresponds to n = 0.
self.n = n
def latex(self):
items = []
for v1, n1 in zip(self.n, self):
s = v.latex()
if n1 == 0:
s = r'\underline{%s}' % v1
items.append(s)
return '\left{%s\right\}' % ', '.join(items)
|
from .expr import ExprList
class Sequence(ExprList):
def __init__(self, seq, n=None):
super (Sequence, self).__init__(seq)
# Save the indexes. Ideally, should annotate which item
# in sequence corresponds to n = 0.
self.n = n
def latex(self):
items = []
for v1, n1 in zip(self, self.n):
try:
s = v1.latex()
except:
s = str(v1)
if n1 == 0:
s = r'\underline{%s}' % v1
items.append(s)
return r'\left\{%s\right\}' % ', '.join(items)
def pretty(self):
items = []
for v1, n1 in zip(self, self.n):
try:
s = v1.pretty()
except:
s = str(v1)
if n1 == 0:
s = '_%s_' % v1
items.append(s)
return r'{%s}' % ', '.join(items)
| Add pretty and latex for Sequence | Add pretty and latex for Sequence
| Python | lgpl-2.1 | mph-/lcapy |
from .expr import ExprList
class Sequence(ExprList):
def __init__(self, seq, n=None):
super (Sequence, self).__init__(seq)
# Save the indexes. Ideally, should annotate which item
# in sequence corresponds to n = 0.
self.n = n
def latex(self):
items = []
- for v1, n1 in zip(self.n, self):
+ for v1, n1 in zip(self, self.n):
+ try:
- s = v.latex()
+ s = v1.latex()
+ except:
+ s = str(v1)
+
if n1 == 0:
s = r'\underline{%s}' % v1
items.append(s)
- return '\left{%s\right\}' % ', '.join(items)
+ return r'\left\{%s\right\}' % ', '.join(items)
+
+ def pretty(self):
+
+ items = []
+ for v1, n1 in zip(self, self.n):
+ try:
+ s = v1.pretty()
+ except:
+ s = str(v1)
+ if n1 == 0:
+ s = '_%s_' % v1
+ items.append(s)
+ return r'{%s}' % ', '.join(items)
+
+
+ | Add pretty and latex for Sequence | ## Code Before:
from .expr import ExprList
class Sequence(ExprList):
def __init__(self, seq, n=None):
super (Sequence, self).__init__(seq)
# Save the indexes. Ideally, should annotate which item
# in sequence corresponds to n = 0.
self.n = n
def latex(self):
items = []
for v1, n1 in zip(self.n, self):
s = v.latex()
if n1 == 0:
s = r'\underline{%s}' % v1
items.append(s)
return '\left{%s\right\}' % ', '.join(items)
## Instruction:
Add pretty and latex for Sequence
## Code After:
from .expr import ExprList
class Sequence(ExprList):
def __init__(self, seq, n=None):
super (Sequence, self).__init__(seq)
# Save the indexes. Ideally, should annotate which item
# in sequence corresponds to n = 0.
self.n = n
def latex(self):
items = []
for v1, n1 in zip(self, self.n):
try:
s = v1.latex()
except:
s = str(v1)
if n1 == 0:
s = r'\underline{%s}' % v1
items.append(s)
return r'\left\{%s\right\}' % ', '.join(items)
def pretty(self):
items = []
for v1, n1 in zip(self, self.n):
try:
s = v1.pretty()
except:
s = str(v1)
if n1 == 0:
s = '_%s_' % v1
items.append(s)
return r'{%s}' % ', '.join(items)
|
from .expr import ExprList
class Sequence(ExprList):
def __init__(self, seq, n=None):
super (Sequence, self).__init__(seq)
# Save the indexes. Ideally, should annotate which item
# in sequence corresponds to n = 0.
self.n = n
def latex(self):
items = []
- for v1, n1 in zip(self.n, self):
? --
+ for v1, n1 in zip(self, self.n):
? ++
+ try:
- s = v.latex()
+ s = v1.latex()
? ++++ +
+ except:
+ s = str(v1)
+
if n1 == 0:
s = r'\underline{%s}' % v1
items.append(s)
- return '\left{%s\right\}' % ', '.join(items)
+ return r'\left\{%s\right\}' % ', '.join(items)
? + +
+
+ def pretty(self):
+
+ items = []
+ for v1, n1 in zip(self, self.n):
+ try:
+ s = v1.pretty()
+ except:
+ s = str(v1)
+ if n1 == 0:
+ s = '_%s_' % v1
+ items.append(s)
+
+ return r'{%s}' % ', '.join(items)
+
+ |
0fbc02b40f4414d96686d879aa9f7611e8fbb85d | singlet/config.py | singlet/config.py | import os
import yaml
# Globals
config_filename = os.getenv(
'SINGLET_CONFIG_FILENAME',
os.getenv('HOME') + '/.singlet/config.yml')
with open(config_filename) as stream:
config = yaml.load(stream)
# Warnings that should be seen only once
config['_once_warnings'] = []
config.reset_once_warings = lambda: config['_once_warnings'] = []
| import os
import yaml
# Globals
config_filename = os.getenv(
'SINGLET_CONFIG_FILENAME',
os.getenv('HOME') + '/.singlet/config.yml')
with open(config_filename) as stream:
config = yaml.load(stream)
# Warnings that should be seen only once
config['_once_warnings'] = []
| Remove function to reset _once_warnings (messy) | Remove function to reset _once_warnings (messy)
| Python | mit | iosonofabio/singlet,iosonofabio/singlet | import os
import yaml
# Globals
config_filename = os.getenv(
'SINGLET_CONFIG_FILENAME',
os.getenv('HOME') + '/.singlet/config.yml')
with open(config_filename) as stream:
config = yaml.load(stream)
# Warnings that should be seen only once
config['_once_warnings'] = []
- config.reset_once_warings = lambda: config['_once_warnings'] = []
| Remove function to reset _once_warnings (messy) | ## Code Before:
import os
import yaml
# Globals
config_filename = os.getenv(
'SINGLET_CONFIG_FILENAME',
os.getenv('HOME') + '/.singlet/config.yml')
with open(config_filename) as stream:
config = yaml.load(stream)
# Warnings that should be seen only once
config['_once_warnings'] = []
config.reset_once_warings = lambda: config['_once_warnings'] = []
## Instruction:
Remove function to reset _once_warnings (messy)
## Code After:
import os
import yaml
# Globals
config_filename = os.getenv(
'SINGLET_CONFIG_FILENAME',
os.getenv('HOME') + '/.singlet/config.yml')
with open(config_filename) as stream:
config = yaml.load(stream)
# Warnings that should be seen only once
config['_once_warnings'] = []
| import os
import yaml
# Globals
config_filename = os.getenv(
'SINGLET_CONFIG_FILENAME',
os.getenv('HOME') + '/.singlet/config.yml')
with open(config_filename) as stream:
config = yaml.load(stream)
# Warnings that should be seen only once
config['_once_warnings'] = []
- config.reset_once_warings = lambda: config['_once_warnings'] = [] |
baf08cb5aedd7a75dad8f79601ce31244544a3dd | elections/uk_general_election_2015/views/parties.py | elections/uk_general_election_2015/views/parties.py | from candidates.views import PartyDetailView
class UKPartyDetailView(PartyDetailView):
def get_context_data(self, **kwargs):
context = super(UKPartyDetailView, self).get_context_data(**kwargs)
party_ec_id = context['party'].identifiers.get(scheme='electoral-commission')
context['ec_url'] = None
if party_ec_id:
ec_tmpl = 'http://search.electoralcommission.org.uk/English/Registrations/{0}'
context['ec_url'] = ec_tmpl.format(party_ec_id)
context['register'] = context['party'].extra.register
return context
| from candidates.views import PartyDetailView
from popolo.models import Identifier
class UKPartyDetailView(PartyDetailView):
def get_context_data(self, **kwargs):
context = super(UKPartyDetailView, self).get_context_data(**kwargs)
context['ec_url'] = ''
context['register'] = ''
try:
party_ec_id = context['party'].identifiers.get(scheme='electoral-commission')
if party_ec_id:
ec_tmpl = 'http://search.electoralcommission.org.uk/English/Registrations/{0}'
context['ec_url'] = ec_tmpl.format(party_ec_id)
context['register'] = context['party'].extra.register
except Identifier.DoesNotExist:
pass
return context
| Fix the 'Independent' party pages for UK elections | Fix the 'Independent' party pages for UK elections
There's no Electoral Commission identifier for the 'Independent'
pseudo-party, so the party page for independents was failing.
| Python | agpl-3.0 | mysociety/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,datamade/yournextmp-popit,neavouli/yournextrepresentative,neavouli/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextmp-popit,neavouli/yournextrepresentative,datamade/yournextmp-popit,datamade/yournextmp-popit,mysociety/yournextmp-popit,datamade/yournextmp-popit | from candidates.views import PartyDetailView
+ from popolo.models import Identifier
class UKPartyDetailView(PartyDetailView):
def get_context_data(self, **kwargs):
context = super(UKPartyDetailView, self).get_context_data(**kwargs)
+ context['ec_url'] = ''
+ context['register'] = ''
+ try:
- party_ec_id = context['party'].identifiers.get(scheme='electoral-commission')
+ party_ec_id = context['party'].identifiers.get(scheme='electoral-commission')
- context['ec_url'] = None
- if party_ec_id:
+ if party_ec_id:
- ec_tmpl = 'http://search.electoralcommission.org.uk/English/Registrations/{0}'
+ ec_tmpl = 'http://search.electoralcommission.org.uk/English/Registrations/{0}'
- context['ec_url'] = ec_tmpl.format(party_ec_id)
+ context['ec_url'] = ec_tmpl.format(party_ec_id)
- context['register'] = context['party'].extra.register
+ context['register'] = context['party'].extra.register
+ except Identifier.DoesNotExist:
+ pass
return context
| Fix the 'Independent' party pages for UK elections | ## Code Before:
from candidates.views import PartyDetailView
class UKPartyDetailView(PartyDetailView):
def get_context_data(self, **kwargs):
context = super(UKPartyDetailView, self).get_context_data(**kwargs)
party_ec_id = context['party'].identifiers.get(scheme='electoral-commission')
context['ec_url'] = None
if party_ec_id:
ec_tmpl = 'http://search.electoralcommission.org.uk/English/Registrations/{0}'
context['ec_url'] = ec_tmpl.format(party_ec_id)
context['register'] = context['party'].extra.register
return context
## Instruction:
Fix the 'Independent' party pages for UK elections
## Code After:
from candidates.views import PartyDetailView
from popolo.models import Identifier
class UKPartyDetailView(PartyDetailView):
def get_context_data(self, **kwargs):
context = super(UKPartyDetailView, self).get_context_data(**kwargs)
context['ec_url'] = ''
context['register'] = ''
try:
party_ec_id = context['party'].identifiers.get(scheme='electoral-commission')
if party_ec_id:
ec_tmpl = 'http://search.electoralcommission.org.uk/English/Registrations/{0}'
context['ec_url'] = ec_tmpl.format(party_ec_id)
context['register'] = context['party'].extra.register
except Identifier.DoesNotExist:
pass
return context
| from candidates.views import PartyDetailView
+ from popolo.models import Identifier
class UKPartyDetailView(PartyDetailView):
def get_context_data(self, **kwargs):
context = super(UKPartyDetailView, self).get_context_data(**kwargs)
+ context['ec_url'] = ''
+ context['register'] = ''
+ try:
- party_ec_id = context['party'].identifiers.get(scheme='electoral-commission')
+ party_ec_id = context['party'].identifiers.get(scheme='electoral-commission')
? ++++
- context['ec_url'] = None
- if party_ec_id:
+ if party_ec_id:
? ++++
- ec_tmpl = 'http://search.electoralcommission.org.uk/English/Registrations/{0}'
+ ec_tmpl = 'http://search.electoralcommission.org.uk/English/Registrations/{0}'
? ++++
- context['ec_url'] = ec_tmpl.format(party_ec_id)
+ context['ec_url'] = ec_tmpl.format(party_ec_id)
? ++++
- context['register'] = context['party'].extra.register
+ context['register'] = context['party'].extra.register
? ++++
+ except Identifier.DoesNotExist:
+ pass
return context |
0da65e9051ec6bf0c72f8dcc856a76547a1a125d | drf_multiple_model/views.py | drf_multiple_model/views.py | from drf_multiple_model.mixins import FlatMultipleModelMixin, ObjectMultipleModelMixin
from rest_framework.generics import GenericAPIView
class FlatMultipleModelAPIView(FlatMultipleModelMixin, GenericAPIView):
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def initial(self, request, *args, **kwargs):
super().initial(request, *args, **kwargs)
if self.sorting_parameter_name in request.query_params:
self.sorting_field = request.query_params.get(self.sorting_parameter_name)
self.sort_descending = self.sorting_field[0] == '-'
if self.sort_descending:
self.sorting_field = self.sorting_field[1:]
self.sorting_field = self.sorting_fields_map.get(self.sorting_field, self.sorting_field)
def get_queryset(self):
return None
class ObjectMultipleModelAPIView(ObjectMultipleModelMixin, GenericAPIView):
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def get_queryset(self):
return None
| from drf_multiple_model.mixins import FlatMultipleModelMixin, ObjectMultipleModelMixin
from rest_framework.generics import GenericAPIView
class FlatMultipleModelAPIView(FlatMultipleModelMixin, GenericAPIView):
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def initial(self, request, *args, **kwargs):
super(GenericAPIView, self).initial(request, *args, **kwargs)
if self.sorting_parameter_name in request.query_params:
# Extract sorting parameter from query string
self.sorting_field = request.query_params.get(self.sorting_parameter_name)
if self.sorting_field:
# Handle sorting direction and sorting field mapping
self.sort_descending = self.sorting_field[0] == '-'
if self.sort_descending:
self.sorting_field = self.sorting_field[1:]
self.sorting_field = self.sorting_fields_map.get(self.sorting_field, self.sorting_field)
def get_queryset(self):
return None
class ObjectMultipleModelAPIView(ObjectMultipleModelMixin, GenericAPIView):
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def get_queryset(self):
return None
| Fix initialization ofr sorting parameters | Fix initialization ofr sorting parameters
| Python | mit | Axiologue/DjangoRestMultipleModels | from drf_multiple_model.mixins import FlatMultipleModelMixin, ObjectMultipleModelMixin
from rest_framework.generics import GenericAPIView
class FlatMultipleModelAPIView(FlatMultipleModelMixin, GenericAPIView):
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def initial(self, request, *args, **kwargs):
- super().initial(request, *args, **kwargs)
+ super(GenericAPIView, self).initial(request, *args, **kwargs)
if self.sorting_parameter_name in request.query_params:
+ # Extract sorting parameter from query string
self.sorting_field = request.query_params.get(self.sorting_parameter_name)
+
+ if self.sorting_field:
+ # Handle sorting direction and sorting field mapping
self.sort_descending = self.sorting_field[0] == '-'
if self.sort_descending:
self.sorting_field = self.sorting_field[1:]
self.sorting_field = self.sorting_fields_map.get(self.sorting_field, self.sorting_field)
def get_queryset(self):
return None
class ObjectMultipleModelAPIView(ObjectMultipleModelMixin, GenericAPIView):
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def get_queryset(self):
return None
| Fix initialization ofr sorting parameters | ## Code Before:
from drf_multiple_model.mixins import FlatMultipleModelMixin, ObjectMultipleModelMixin
from rest_framework.generics import GenericAPIView
class FlatMultipleModelAPIView(FlatMultipleModelMixin, GenericAPIView):
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def initial(self, request, *args, **kwargs):
super().initial(request, *args, **kwargs)
if self.sorting_parameter_name in request.query_params:
self.sorting_field = request.query_params.get(self.sorting_parameter_name)
self.sort_descending = self.sorting_field[0] == '-'
if self.sort_descending:
self.sorting_field = self.sorting_field[1:]
self.sorting_field = self.sorting_fields_map.get(self.sorting_field, self.sorting_field)
def get_queryset(self):
return None
class ObjectMultipleModelAPIView(ObjectMultipleModelMixin, GenericAPIView):
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def get_queryset(self):
return None
## Instruction:
Fix initialization ofr sorting parameters
## Code After:
from drf_multiple_model.mixins import FlatMultipleModelMixin, ObjectMultipleModelMixin
from rest_framework.generics import GenericAPIView
class FlatMultipleModelAPIView(FlatMultipleModelMixin, GenericAPIView):
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def initial(self, request, *args, **kwargs):
super(GenericAPIView, self).initial(request, *args, **kwargs)
if self.sorting_parameter_name in request.query_params:
# Extract sorting parameter from query string
self.sorting_field = request.query_params.get(self.sorting_parameter_name)
if self.sorting_field:
# Handle sorting direction and sorting field mapping
self.sort_descending = self.sorting_field[0] == '-'
if self.sort_descending:
self.sorting_field = self.sorting_field[1:]
self.sorting_field = self.sorting_fields_map.get(self.sorting_field, self.sorting_field)
def get_queryset(self):
return None
class ObjectMultipleModelAPIView(ObjectMultipleModelMixin, GenericAPIView):
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def get_queryset(self):
return None
| from drf_multiple_model.mixins import FlatMultipleModelMixin, ObjectMultipleModelMixin
from rest_framework.generics import GenericAPIView
class FlatMultipleModelAPIView(FlatMultipleModelMixin, GenericAPIView):
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def initial(self, request, *args, **kwargs):
- super().initial(request, *args, **kwargs)
+ super(GenericAPIView, self).initial(request, *args, **kwargs)
? ++++++++++++++++++++
if self.sorting_parameter_name in request.query_params:
+ # Extract sorting parameter from query string
self.sorting_field = request.query_params.get(self.sorting_parameter_name)
+
+ if self.sorting_field:
+ # Handle sorting direction and sorting field mapping
self.sort_descending = self.sorting_field[0] == '-'
if self.sort_descending:
self.sorting_field = self.sorting_field[1:]
self.sorting_field = self.sorting_fields_map.get(self.sorting_field, self.sorting_field)
def get_queryset(self):
return None
class ObjectMultipleModelAPIView(ObjectMultipleModelMixin, GenericAPIView):
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def get_queryset(self):
return None |
c75c1764e276d1cbda61e1258eb6e09298bce3ce | tests/test_bulk.py | tests/test_bulk.py | import json
from django.db import models
from django.conf import settings
from django.test import TestCase
from localized_fields.fields import LocalizedField, LocalizedUniqueSlugField
from .data import get_init_values
from .fake_model import get_fake_model
class LocalizedBulkTestCase(TestCase):
"""Tests bulk operations with data structures provided
by the django-localized-fields library."""
@staticmethod
def test_localized_bulk_insert():
"""Tests whether bulk inserts work properly when using
a :see:LocalizedUniqueSlugField in the model."""
model = get_fake_model(
'BulkSlugInsertModel',
{
'name': LocalizedField(),
'slug': LocalizedUniqueSlugField(populate_from='name', include_time=True),
'score': models.IntegerField()
}
)
objects = model.objects.bulk_create([
model(name={'en': 'english name 1', 'ro': 'romanian name 1'}, score=1),
model(name={'en': 'english name 2', 'ro': 'romanian name 2'}, score=2),
model(name={'en': 'english name 3', 'ro': 'romanian name 3'}, score=3)
])
assert model.objects.all().count() == 3
| from django.db import models
from django.test import TestCase
from localized_fields.fields import LocalizedField, LocalizedUniqueSlugField
from .fake_model import get_fake_model
class LocalizedBulkTestCase(TestCase):
"""Tests bulk operations with data structures provided
by the django-localized-fields library."""
@staticmethod
def test_localized_bulk_insert():
"""Tests whether bulk inserts work properly when using
a :see:LocalizedUniqueSlugField in the model."""
model = get_fake_model(
'BulkSlugInsertModel',
{
'name': LocalizedField(),
'slug': LocalizedUniqueSlugField(populate_from='name', include_time=True),
'score': models.IntegerField()
}
)
to_create = [
model(name={'en': 'english name 1', 'ro': 'romanian name 1'}, score=1),
model(name={'en': 'english name 2', 'ro': 'romanian name 2'}, score=2),
model(name={'en': 'english name 3', 'ro': 'romanian name 3'}, score=3)
]
model.objects.bulk_create(to_create)
assert model.objects.all().count() == 3
for obj in to_create:
obj_db = model.objects.filter(
name__en=obj.name.en,
name__ro=obj.name.ro,
score=obj.score
).first()
assert obj_db
assert len(obj_db.slug.en) >= len(obj_db.name.en)
assert len(obj_db.slug.ro) >= len(obj_db.name.ro)
| Improve test case for bulk_create | Improve test case for bulk_create
| Python | mit | SectorLabs/django-localized-fields,SectorLabs/django-localized-fields,SectorLabs/django-localized-fields | - import json
-
from django.db import models
- from django.conf import settings
from django.test import TestCase
from localized_fields.fields import LocalizedField, LocalizedUniqueSlugField
- from .data import get_init_values
from .fake_model import get_fake_model
class LocalizedBulkTestCase(TestCase):
"""Tests bulk operations with data structures provided
by the django-localized-fields library."""
@staticmethod
def test_localized_bulk_insert():
"""Tests whether bulk inserts work properly when using
a :see:LocalizedUniqueSlugField in the model."""
model = get_fake_model(
'BulkSlugInsertModel',
{
'name': LocalizedField(),
'slug': LocalizedUniqueSlugField(populate_from='name', include_time=True),
'score': models.IntegerField()
}
)
- objects = model.objects.bulk_create([
+ to_create = [
model(name={'en': 'english name 1', 'ro': 'romanian name 1'}, score=1),
model(name={'en': 'english name 2', 'ro': 'romanian name 2'}, score=2),
model(name={'en': 'english name 3', 'ro': 'romanian name 3'}, score=3)
- ])
+ ]
+ model.objects.bulk_create(to_create)
assert model.objects.all().count() == 3
+ for obj in to_create:
+ obj_db = model.objects.filter(
+ name__en=obj.name.en,
+ name__ro=obj.name.ro,
+ score=obj.score
+ ).first()
+
+ assert obj_db
+ assert len(obj_db.slug.en) >= len(obj_db.name.en)
+ assert len(obj_db.slug.ro) >= len(obj_db.name.ro)
+ | Improve test case for bulk_create | ## Code Before:
import json
from django.db import models
from django.conf import settings
from django.test import TestCase
from localized_fields.fields import LocalizedField, LocalizedUniqueSlugField
from .data import get_init_values
from .fake_model import get_fake_model
class LocalizedBulkTestCase(TestCase):
"""Tests bulk operations with data structures provided
by the django-localized-fields library."""
@staticmethod
def test_localized_bulk_insert():
"""Tests whether bulk inserts work properly when using
a :see:LocalizedUniqueSlugField in the model."""
model = get_fake_model(
'BulkSlugInsertModel',
{
'name': LocalizedField(),
'slug': LocalizedUniqueSlugField(populate_from='name', include_time=True),
'score': models.IntegerField()
}
)
objects = model.objects.bulk_create([
model(name={'en': 'english name 1', 'ro': 'romanian name 1'}, score=1),
model(name={'en': 'english name 2', 'ro': 'romanian name 2'}, score=2),
model(name={'en': 'english name 3', 'ro': 'romanian name 3'}, score=3)
])
assert model.objects.all().count() == 3
## Instruction:
Improve test case for bulk_create
## Code After:
from django.db import models
from django.test import TestCase
from localized_fields.fields import LocalizedField, LocalizedUniqueSlugField
from .fake_model import get_fake_model
class LocalizedBulkTestCase(TestCase):
"""Tests bulk operations with data structures provided
by the django-localized-fields library."""
@staticmethod
def test_localized_bulk_insert():
"""Tests whether bulk inserts work properly when using
a :see:LocalizedUniqueSlugField in the model."""
model = get_fake_model(
'BulkSlugInsertModel',
{
'name': LocalizedField(),
'slug': LocalizedUniqueSlugField(populate_from='name', include_time=True),
'score': models.IntegerField()
}
)
to_create = [
model(name={'en': 'english name 1', 'ro': 'romanian name 1'}, score=1),
model(name={'en': 'english name 2', 'ro': 'romanian name 2'}, score=2),
model(name={'en': 'english name 3', 'ro': 'romanian name 3'}, score=3)
]
model.objects.bulk_create(to_create)
assert model.objects.all().count() == 3
for obj in to_create:
obj_db = model.objects.filter(
name__en=obj.name.en,
name__ro=obj.name.ro,
score=obj.score
).first()
assert obj_db
assert len(obj_db.slug.en) >= len(obj_db.name.en)
assert len(obj_db.slug.ro) >= len(obj_db.name.ro)
| - import json
-
from django.db import models
- from django.conf import settings
from django.test import TestCase
from localized_fields.fields import LocalizedField, LocalizedUniqueSlugField
- from .data import get_init_values
from .fake_model import get_fake_model
class LocalizedBulkTestCase(TestCase):
"""Tests bulk operations with data structures provided
by the django-localized-fields library."""
@staticmethod
def test_localized_bulk_insert():
"""Tests whether bulk inserts work properly when using
a :see:LocalizedUniqueSlugField in the model."""
model = get_fake_model(
'BulkSlugInsertModel',
{
'name': LocalizedField(),
'slug': LocalizedUniqueSlugField(populate_from='name', include_time=True),
'score': models.IntegerField()
}
)
- objects = model.objects.bulk_create([
+ to_create = [
model(name={'en': 'english name 1', 'ro': 'romanian name 1'}, score=1),
model(name={'en': 'english name 2', 'ro': 'romanian name 2'}, score=2),
model(name={'en': 'english name 3', 'ro': 'romanian name 3'}, score=3)
- ])
? -
+ ]
+ model.objects.bulk_create(to_create)
assert model.objects.all().count() == 3
+
+ for obj in to_create:
+ obj_db = model.objects.filter(
+ name__en=obj.name.en,
+ name__ro=obj.name.ro,
+ score=obj.score
+ ).first()
+
+ assert obj_db
+ assert len(obj_db.slug.en) >= len(obj_db.name.en)
+ assert len(obj_db.slug.ro) >= len(obj_db.name.ro) |
9dc90727df23e655e5c921ca84cb98b7d5ae5eb2 | example_game.py | example_game.py | from pygametemplate import Game
class ExampleGame(Game):
def logic(self):
pass
def draw(self):
pass
def quit(self):
pass
| from pygametemplate import Game
class ExampleGame(Game):
def logic(self):
pass
def draw(self):
pass
| Remove now unnecessary quit() method from ExampleGame | Remove now unnecessary quit() method from ExampleGame
| Python | mit | AndyDeany/pygame-template | from pygametemplate import Game
class ExampleGame(Game):
def logic(self):
pass
def draw(self):
pass
- def quit(self):
- pass
- | Remove now unnecessary quit() method from ExampleGame | ## Code Before:
from pygametemplate import Game
class ExampleGame(Game):
def logic(self):
pass
def draw(self):
pass
def quit(self):
pass
## Instruction:
Remove now unnecessary quit() method from ExampleGame
## Code After:
from pygametemplate import Game
class ExampleGame(Game):
def logic(self):
pass
def draw(self):
pass
| from pygametemplate import Game
class ExampleGame(Game):
def logic(self):
pass
def draw(self):
pass
-
- def quit(self):
- pass |
0388ab2bb8ad50aa40716a1c5f83f5e1f400bb32 | scripts/start_baxter.py | scripts/start_baxter.py |
from baxter_myo.arm_controller import ArmController
from baxter_myo.config_reader import ConfigReader
def main():
c = ConfigReader("demo_config")
c.parse_all()
s = ArmController('right', c.right_angles, c.push_thresh)
s.move_loop()
if __name__ == "__main__":
main()
| import time
import rospy
from baxter_myo.arm_controller import ArmController
from baxter_myo.config_reader import ConfigReader
def main():
c = ConfigReader("demo_config")
c.parse_all()
s = ArmController('right', c.right_angles, c.push_thresh)
while not rospy.is_shutdown():
s.step()
if __name__ == "__main__":
main()
| Enable ctrl-c control with rospy | Enable ctrl-c control with rospy
| Python | mit | ipab-rad/baxter_myo,ipab-rad/myo_baxter_pc,ipab-rad/myo_baxter_pc,ipab-rad/baxter_myo | + import time
+ import rospy
from baxter_myo.arm_controller import ArmController
from baxter_myo.config_reader import ConfigReader
def main():
c = ConfigReader("demo_config")
c.parse_all()
s = ArmController('right', c.right_angles, c.push_thresh)
- s.move_loop()
+ while not rospy.is_shutdown():
+ s.step()
if __name__ == "__main__":
main()
| Enable ctrl-c control with rospy | ## Code Before:
from baxter_myo.arm_controller import ArmController
from baxter_myo.config_reader import ConfigReader
def main():
c = ConfigReader("demo_config")
c.parse_all()
s = ArmController('right', c.right_angles, c.push_thresh)
s.move_loop()
if __name__ == "__main__":
main()
## Instruction:
Enable ctrl-c control with rospy
## Code After:
import time
import rospy
from baxter_myo.arm_controller import ArmController
from baxter_myo.config_reader import ConfigReader
def main():
c = ConfigReader("demo_config")
c.parse_all()
s = ArmController('right', c.right_angles, c.push_thresh)
while not rospy.is_shutdown():
s.step()
if __name__ == "__main__":
main()
| + import time
+ import rospy
from baxter_myo.arm_controller import ArmController
from baxter_myo.config_reader import ConfigReader
def main():
c = ConfigReader("demo_config")
c.parse_all()
s = ArmController('right', c.right_angles, c.push_thresh)
- s.move_loop()
+ while not rospy.is_shutdown():
+ s.step()
if __name__ == "__main__":
main() |
6b971de14fbd987286b02bf6e469a1fbb7ad8695 | graph.py | graph.py | from __future__ import unicode_literals
class Graph(object):
"""A class for a simple graph data structure."""
def __init__(self):
self.nodes = {}
def __repr__(self):
pass
def nodes(self):
"""Return a list of all nodes in the graph."""
return [node for node in self.nodes]
def edges(self):
"""Return a list of all edges in the graph."""
return "edge list"
def add_node(self, n):
"""Add a new node to the graph."""
self.nodes[n] = set()
def add_edge(self, n1, n2):
"""Add a new edge connecting n1 to n2."""
self.nodes[n1].add(n2)
def del_node(self, n):
"""Delete a node from the graph."""
del self.nodes[n]
for edgeset in self.nodes.values:
edgeset.discard(n)
def del_edge(self, n1, n2):
"""Delete the edge connecting two nodes from graph."""
self.nodes[n1].remove(n2)
def has_node(self, n):
"""Check if a given node is in the graph."""
return n in self.nodes
def neighbors(self, n):
"""Return a list of all nodes connected to 'n' by edges."""
neighbors = []
for node in self.nodes:
if n in self.node:
neighbors.append(node)
return neighbors
| from __future__ import unicode_literals
class Graph(object):
"""A class for a simple graph data structure."""
def __init__(self):
self.graph = {}
def __repr__(self):
return repr(self.graph)
def nodes(self):
"""Return a list of all nodes in the graph."""
return [node for node in self.graph]
def edges(self):
"""Return a list of all edges in the graph."""
return "edge list"
def add_node(self, n):
"""Add a new node to the graph."""
self.graph[n] = set()
def add_edge(self, n1, n2):
"""Add a new edge connecting n1 to n2."""
self.graph[n1].add(n2)
def del_node(self, n):
"""Delete a node from the graph."""
del self.graph[n]
for edgeset in self.graph.values():
edgeset.discard(n)
def del_edge(self, n1, n2):
"""Delete the edge connecting two nodes from graph."""
self.graph[n1].remove(n2)
def has_node(self, n):
"""Check if a given node is in the graph."""
return n in self.graph
def neighbors(self, n):
"""Return a list of all nodes connected to 'n' by edges."""
neighbors = []
for node in self.graph:
if n in self.node:
neighbors.append(node)
return neighbors
| Change dictionary name to avoid collision; fix dict.values() call | Change dictionary name to avoid collision; fix dict.values() call
| Python | mit | jay-tyler/data-structures,jonathanstallings/data-structures | from __future__ import unicode_literals
class Graph(object):
"""A class for a simple graph data structure."""
def __init__(self):
- self.nodes = {}
+ self.graph = {}
def __repr__(self):
- pass
+ return repr(self.graph)
def nodes(self):
"""Return a list of all nodes in the graph."""
- return [node for node in self.nodes]
+ return [node for node in self.graph]
def edges(self):
"""Return a list of all edges in the graph."""
return "edge list"
def add_node(self, n):
"""Add a new node to the graph."""
- self.nodes[n] = set()
+ self.graph[n] = set()
def add_edge(self, n1, n2):
"""Add a new edge connecting n1 to n2."""
- self.nodes[n1].add(n2)
+ self.graph[n1].add(n2)
def del_node(self, n):
"""Delete a node from the graph."""
- del self.nodes[n]
+ del self.graph[n]
- for edgeset in self.nodes.values:
+ for edgeset in self.graph.values():
edgeset.discard(n)
def del_edge(self, n1, n2):
"""Delete the edge connecting two nodes from graph."""
- self.nodes[n1].remove(n2)
+ self.graph[n1].remove(n2)
def has_node(self, n):
"""Check if a given node is in the graph."""
- return n in self.nodes
+ return n in self.graph
def neighbors(self, n):
"""Return a list of all nodes connected to 'n' by edges."""
neighbors = []
- for node in self.nodes:
+ for node in self.graph:
if n in self.node:
neighbors.append(node)
return neighbors
| Change dictionary name to avoid collision; fix dict.values() call | ## Code Before:
from __future__ import unicode_literals
class Graph(object):
"""A class for a simple graph data structure."""
def __init__(self):
self.nodes = {}
def __repr__(self):
pass
def nodes(self):
"""Return a list of all nodes in the graph."""
return [node for node in self.nodes]
def edges(self):
"""Return a list of all edges in the graph."""
return "edge list"
def add_node(self, n):
"""Add a new node to the graph."""
self.nodes[n] = set()
def add_edge(self, n1, n2):
"""Add a new edge connecting n1 to n2."""
self.nodes[n1].add(n2)
def del_node(self, n):
"""Delete a node from the graph."""
del self.nodes[n]
for edgeset in self.nodes.values:
edgeset.discard(n)
def del_edge(self, n1, n2):
"""Delete the edge connecting two nodes from graph."""
self.nodes[n1].remove(n2)
def has_node(self, n):
"""Check if a given node is in the graph."""
return n in self.nodes
def neighbors(self, n):
"""Return a list of all nodes connected to 'n' by edges."""
neighbors = []
for node in self.nodes:
if n in self.node:
neighbors.append(node)
return neighbors
## Instruction:
Change dictionary name to avoid collision; fix dict.values() call
## Code After:
from __future__ import unicode_literals
class Graph(object):
"""A class for a simple graph data structure."""
def __init__(self):
self.graph = {}
def __repr__(self):
return repr(self.graph)
def nodes(self):
"""Return a list of all nodes in the graph."""
return [node for node in self.graph]
def edges(self):
"""Return a list of all edges in the graph."""
return "edge list"
def add_node(self, n):
"""Add a new node to the graph."""
self.graph[n] = set()
def add_edge(self, n1, n2):
"""Add a new edge connecting n1 to n2."""
self.graph[n1].add(n2)
def del_node(self, n):
"""Delete a node from the graph."""
del self.graph[n]
for edgeset in self.graph.values():
edgeset.discard(n)
def del_edge(self, n1, n2):
"""Delete the edge connecting two nodes from graph."""
self.graph[n1].remove(n2)
def has_node(self, n):
"""Check if a given node is in the graph."""
return n in self.graph
def neighbors(self, n):
"""Return a list of all nodes connected to 'n' by edges."""
neighbors = []
for node in self.graph:
if n in self.node:
neighbors.append(node)
return neighbors
| from __future__ import unicode_literals
class Graph(object):
"""A class for a simple graph data structure."""
def __init__(self):
- self.nodes = {}
? ^^^^^
+ self.graph = {}
? ^^^^^
def __repr__(self):
- pass
+ return repr(self.graph)
def nodes(self):
"""Return a list of all nodes in the graph."""
- return [node for node in self.nodes]
? ^^^^^
+ return [node for node in self.graph]
? ^^^^^
def edges(self):
"""Return a list of all edges in the graph."""
return "edge list"
def add_node(self, n):
"""Add a new node to the graph."""
- self.nodes[n] = set()
? ^^^^^
+ self.graph[n] = set()
? ^^^^^
def add_edge(self, n1, n2):
"""Add a new edge connecting n1 to n2."""
- self.nodes[n1].add(n2)
? ^^^^^
+ self.graph[n1].add(n2)
? ^^^^^
def del_node(self, n):
"""Delete a node from the graph."""
- del self.nodes[n]
? ^^^^^
+ del self.graph[n]
? ^^^^^
- for edgeset in self.nodes.values:
? ^^^^^
+ for edgeset in self.graph.values():
? ^^^^^ ++
edgeset.discard(n)
def del_edge(self, n1, n2):
"""Delete the edge connecting two nodes from graph."""
- self.nodes[n1].remove(n2)
? ^^^^^
+ self.graph[n1].remove(n2)
? ^^^^^
def has_node(self, n):
"""Check if a given node is in the graph."""
- return n in self.nodes
? ^^^^^
+ return n in self.graph
? ^^^^^
def neighbors(self, n):
"""Return a list of all nodes connected to 'n' by edges."""
neighbors = []
- for node in self.nodes:
? ^^^^^
+ for node in self.graph:
? ^^^^^
if n in self.node:
neighbors.append(node)
return neighbors |
b14e605c83f95e6e1a3c70f148c32bbdc0ca12b1 | zeus/api/resources/build_index.py | zeus/api/resources/build_index.py | from sqlalchemy.orm import joinedload, subqueryload_all
from zeus import auth
from zeus.models import Build
from .base import Resource
from ..schemas import BuildSchema
builds_schema = BuildSchema(many=True, strict=True)
class BuildIndexResource(Resource):
def get(self):
"""
Return a list of builds.
"""
# tenants automatically restrict this query but we dont want
# to include public repos
tenant = auth.get_current_tenant()
if not tenant.repository_ids:
return self.respond([])
query = Build.query.options(
joinedload('repository'),
joinedload('source'),
joinedload('source').joinedload('author'),
joinedload('source').joinedload('revision'),
joinedload('source').joinedload('patch'),
subqueryload_all('stats'),
).filter(
Build.repository_id.in_(tenant.repository_ids),
).order_by(Build.date_created.desc()).limit(100)
return self.respond_with_schema(builds_schema, query)
| from sqlalchemy.orm import joinedload, subqueryload_all
from zeus import auth
from zeus.models import Build
from .base import Resource
from ..schemas import BuildSchema
builds_schema = BuildSchema(many=True, strict=True)
class BuildIndexResource(Resource):
def get(self):
"""
Return a list of builds.
"""
# tenants automatically restrict this query but we dont want
# to include public repos
tenant = auth.get_current_tenant()
if not tenant.repository_ids:
return self.respond([])
query = Build.query.options(
joinedload('repository'),
joinedload('source'),
joinedload('source').joinedload('author'),
joinedload('source').joinedload('revision'),
joinedload('source').joinedload('patch'),
subqueryload_all('stats'),
).filter(
Build.repository_id.in_(tenant.repository_ids),
).order_by(Build.date_created.desc())
return self.paginate_with_schema(builds_schema, query)
| Add pagination to build index | feat: Add pagination to build index
| Python | apache-2.0 | getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus | from sqlalchemy.orm import joinedload, subqueryload_all
from zeus import auth
from zeus.models import Build
from .base import Resource
from ..schemas import BuildSchema
builds_schema = BuildSchema(many=True, strict=True)
class BuildIndexResource(Resource):
def get(self):
"""
Return a list of builds.
"""
# tenants automatically restrict this query but we dont want
# to include public repos
tenant = auth.get_current_tenant()
if not tenant.repository_ids:
return self.respond([])
query = Build.query.options(
joinedload('repository'),
joinedload('source'),
joinedload('source').joinedload('author'),
joinedload('source').joinedload('revision'),
joinedload('source').joinedload('patch'),
subqueryload_all('stats'),
).filter(
Build.repository_id.in_(tenant.repository_ids),
- ).order_by(Build.date_created.desc()).limit(100)
+ ).order_by(Build.date_created.desc())
- return self.respond_with_schema(builds_schema, query)
+ return self.paginate_with_schema(builds_schema, query)
| Add pagination to build index | ## Code Before:
from sqlalchemy.orm import joinedload, subqueryload_all
from zeus import auth
from zeus.models import Build
from .base import Resource
from ..schemas import BuildSchema
builds_schema = BuildSchema(many=True, strict=True)
class BuildIndexResource(Resource):
def get(self):
"""
Return a list of builds.
"""
# tenants automatically restrict this query but we dont want
# to include public repos
tenant = auth.get_current_tenant()
if not tenant.repository_ids:
return self.respond([])
query = Build.query.options(
joinedload('repository'),
joinedload('source'),
joinedload('source').joinedload('author'),
joinedload('source').joinedload('revision'),
joinedload('source').joinedload('patch'),
subqueryload_all('stats'),
).filter(
Build.repository_id.in_(tenant.repository_ids),
).order_by(Build.date_created.desc()).limit(100)
return self.respond_with_schema(builds_schema, query)
## Instruction:
Add pagination to build index
## Code After:
from sqlalchemy.orm import joinedload, subqueryload_all
from zeus import auth
from zeus.models import Build
from .base import Resource
from ..schemas import BuildSchema
builds_schema = BuildSchema(many=True, strict=True)
class BuildIndexResource(Resource):
def get(self):
"""
Return a list of builds.
"""
# tenants automatically restrict this query but we dont want
# to include public repos
tenant = auth.get_current_tenant()
if not tenant.repository_ids:
return self.respond([])
query = Build.query.options(
joinedload('repository'),
joinedload('source'),
joinedload('source').joinedload('author'),
joinedload('source').joinedload('revision'),
joinedload('source').joinedload('patch'),
subqueryload_all('stats'),
).filter(
Build.repository_id.in_(tenant.repository_ids),
).order_by(Build.date_created.desc())
return self.paginate_with_schema(builds_schema, query)
| from sqlalchemy.orm import joinedload, subqueryload_all
from zeus import auth
from zeus.models import Build
from .base import Resource
from ..schemas import BuildSchema
builds_schema = BuildSchema(many=True, strict=True)
class BuildIndexResource(Resource):
def get(self):
"""
Return a list of builds.
"""
# tenants automatically restrict this query but we dont want
# to include public repos
tenant = auth.get_current_tenant()
if not tenant.repository_ids:
return self.respond([])
query = Build.query.options(
joinedload('repository'),
joinedload('source'),
joinedload('source').joinedload('author'),
joinedload('source').joinedload('revision'),
joinedload('source').joinedload('patch'),
subqueryload_all('stats'),
).filter(
Build.repository_id.in_(tenant.repository_ids),
- ).order_by(Build.date_created.desc()).limit(100)
? -----------
+ ).order_by(Build.date_created.desc())
- return self.respond_with_schema(builds_schema, query)
? ^ -----
+ return self.paginate_with_schema(builds_schema, query)
? ^^^^^^^
|
42f74f304d0ac404f17d6489033b6140816cb194 | fireplace/cards/gvg/neutral_common.py | fireplace/cards/gvg/neutral_common.py | from ..utils import *
##
# Minions
# Explosive Sheep
class GVG_076:
def deathrattle(self):
for target in self.game.board:
self.hit(target, 2)
# Clockwork Gnome
class GVG_082:
deathrattle = giveSparePart
# Micro Machine
class GVG_103:
def TURN_BEGIN(self, player):
# That card ID is not a mistake
self.buff(self, "GVG_076a")
# Pistons
class GVG_076a:
Atk = 1
| from ..utils import *
##
# Minions
# Stonesplinter Trogg
class GVG_067:
def CARD_PLAYED(self, player, card):
if player is not self.controller and card.type == CardType.SPELL:
self.buff("GVG_067a")
class GVG_067a:
Atk = 1
# Burly Rockjaw Trogg
class GVG_068:
def CARD_PLAYED(self, player, card):
if player is not self.controller and card.type == CardType.SPELL:
self.buff("GVG_068a")
class GVG_068a:
Atk = 2
# Ship's Cannon
class GVG_075:
def OWN_MINION_SUMMONED(self, minion):
if minion.race == Race.PIRATE:
targets = self.controller.getTargets(TARGET_ENEMY_CHARACTERS)
self.hit(random.choice(targets), 2)
# Explosive Sheep
class GVG_076:
def deathrattle(self):
for target in self.game.board:
self.hit(target, 2)
# Clockwork Gnome
class GVG_082:
deathrattle = giveSparePart
# Micro Machine
class GVG_103:
def TURN_BEGIN(self, player):
# That card ID is not a mistake
self.buff(self, "GVG_076a")
# Pistons
class GVG_076a:
Atk = 1
| Implement Stonesplinter Trogg, Burly Rockjaw Trogg, Ship's Cannon | Implement Stonesplinter Trogg, Burly Rockjaw Trogg, Ship's Cannon
| Python | agpl-3.0 | Ragowit/fireplace,NightKev/fireplace,jleclanche/fireplace,smallnamespace/fireplace,smallnamespace/fireplace,amw2104/fireplace,beheh/fireplace,Meerkov/fireplace,amw2104/fireplace,oftc-ftw/fireplace,butozerca/fireplace,liujimj/fireplace,oftc-ftw/fireplace,Meerkov/fireplace,butozerca/fireplace,Ragowit/fireplace,liujimj/fireplace | from ..utils import *
##
# Minions
+
+ # Stonesplinter Trogg
+ class GVG_067:
+ def CARD_PLAYED(self, player, card):
+ if player is not self.controller and card.type == CardType.SPELL:
+ self.buff("GVG_067a")
+
+ class GVG_067a:
+ Atk = 1
+
+
+ # Burly Rockjaw Trogg
+ class GVG_068:
+ def CARD_PLAYED(self, player, card):
+ if player is not self.controller and card.type == CardType.SPELL:
+ self.buff("GVG_068a")
+
+ class GVG_068a:
+ Atk = 2
+
+
+ # Ship's Cannon
+ class GVG_075:
+ def OWN_MINION_SUMMONED(self, minion):
+ if minion.race == Race.PIRATE:
+ targets = self.controller.getTargets(TARGET_ENEMY_CHARACTERS)
+ self.hit(random.choice(targets), 2)
+
# Explosive Sheep
class GVG_076:
def deathrattle(self):
for target in self.game.board:
self.hit(target, 2)
# Clockwork Gnome
class GVG_082:
deathrattle = giveSparePart
# Micro Machine
class GVG_103:
def TURN_BEGIN(self, player):
# That card ID is not a mistake
self.buff(self, "GVG_076a")
# Pistons
class GVG_076a:
Atk = 1
| Implement Stonesplinter Trogg, Burly Rockjaw Trogg, Ship's Cannon | ## Code Before:
from ..utils import *
##
# Minions
# Explosive Sheep
class GVG_076:
def deathrattle(self):
for target in self.game.board:
self.hit(target, 2)
# Clockwork Gnome
class GVG_082:
deathrattle = giveSparePart
# Micro Machine
class GVG_103:
def TURN_BEGIN(self, player):
# That card ID is not a mistake
self.buff(self, "GVG_076a")
# Pistons
class GVG_076a:
Atk = 1
## Instruction:
Implement Stonesplinter Trogg, Burly Rockjaw Trogg, Ship's Cannon
## Code After:
from ..utils import *
##
# Minions
# Stonesplinter Trogg
class GVG_067:
def CARD_PLAYED(self, player, card):
if player is not self.controller and card.type == CardType.SPELL:
self.buff("GVG_067a")
class GVG_067a:
Atk = 1
# Burly Rockjaw Trogg
class GVG_068:
def CARD_PLAYED(self, player, card):
if player is not self.controller and card.type == CardType.SPELL:
self.buff("GVG_068a")
class GVG_068a:
Atk = 2
# Ship's Cannon
class GVG_075:
def OWN_MINION_SUMMONED(self, minion):
if minion.race == Race.PIRATE:
targets = self.controller.getTargets(TARGET_ENEMY_CHARACTERS)
self.hit(random.choice(targets), 2)
# Explosive Sheep
class GVG_076:
def deathrattle(self):
for target in self.game.board:
self.hit(target, 2)
# Clockwork Gnome
class GVG_082:
deathrattle = giveSparePart
# Micro Machine
class GVG_103:
def TURN_BEGIN(self, player):
# That card ID is not a mistake
self.buff(self, "GVG_076a")
# Pistons
class GVG_076a:
Atk = 1
| from ..utils import *
##
# Minions
+
+ # Stonesplinter Trogg
+ class GVG_067:
+ def CARD_PLAYED(self, player, card):
+ if player is not self.controller and card.type == CardType.SPELL:
+ self.buff("GVG_067a")
+
+ class GVG_067a:
+ Atk = 1
+
+
+ # Burly Rockjaw Trogg
+ class GVG_068:
+ def CARD_PLAYED(self, player, card):
+ if player is not self.controller and card.type == CardType.SPELL:
+ self.buff("GVG_068a")
+
+ class GVG_068a:
+ Atk = 2
+
+
+ # Ship's Cannon
+ class GVG_075:
+ def OWN_MINION_SUMMONED(self, minion):
+ if minion.race == Race.PIRATE:
+ targets = self.controller.getTargets(TARGET_ENEMY_CHARACTERS)
+ self.hit(random.choice(targets), 2)
+
# Explosive Sheep
class GVG_076:
def deathrattle(self):
for target in self.game.board:
self.hit(target, 2)
# Clockwork Gnome
class GVG_082:
deathrattle = giveSparePart
# Micro Machine
class GVG_103:
def TURN_BEGIN(self, player):
# That card ID is not a mistake
self.buff(self, "GVG_076a")
# Pistons
class GVG_076a:
Atk = 1 |
5e25577d067f891474c722000327026744068e88 | src/unittest/python/permission_lambda_tests.py | src/unittest/python/permission_lambda_tests.py | from unittest2 import TestCase
import simplejson as json
import boto3
from moto import mock_s3
import permission_lambda
class PermissionLambdaTests(TestCase):
def _get_permission_statements(self, client, queue_url):
""" Return a list of policy statements for given queue"""
policy_response = client.get_queue_attributes(
QueueUrl=queue_url, AttributeNames=['Policy'])
policy = policy_response['Attributes']['Policy']
return json.loads(policy)['Statement']
@mock_s3
def test_get_usofa_accountlist_from_bucket(self):
bucketname = "testbucket"
usofa_data = {
"account1": {
"id": "123456789",
"email": "user1@domain.invalid"
},
"account2": {
"id": "987654321",
"email": "user2@domain.invalid"
}
}
client = boto3.client('s3')
client.create_bucket(
Bucket=bucketname,
CreateBucketConfiguration={
'LocationConstraint': 'eu-west-1'
})
client.put_object(
Bucket=bucketname,
Key="accounts.json",
Body=json.dumps(usofa_data)
)
accountlist = permission_lambda.get_usofa_accountlist(bucketname)
accountlist.sort()
self.assertEqual(accountlist, ["123456789", "987654321"])
| from unittest2 import TestCase
import simplejson as json
import boto3
from moto import mock_s3
import permission_lambda
class PermissionLambdaTests(TestCase):
@mock_s3
def test_get_usofa_accountlist_from_bucket(self):
bucketname = "testbucket"
usofa_data = {
"account1": {
"id": "123456789",
"email": "user1@domain.invalid"
},
"account2": {
"id": "987654321",
"email": "user2@domain.invalid"
}
}
client = boto3.client('s3')
client.create_bucket(
Bucket=bucketname,
CreateBucketConfiguration={
'LocationConstraint': 'eu-west-1'
})
client.put_object(
Bucket=bucketname,
Key="accounts.json",
Body=json.dumps(usofa_data)
)
accountlist = permission_lambda.get_usofa_accountlist(bucketname)
accountlist.sort()
self.assertEqual(accountlist, ["123456789", "987654321"])
| Remove Unittests done as integrationtests, due to NotImplementedErrors from moto | PIO-129: Remove Unittests done as integrationtests, due to NotImplementedErrors from moto
| Python | apache-2.0 | ImmobilienScout24/aws-set-sqs-permission-lambda | from unittest2 import TestCase
import simplejson as json
import boto3
from moto import mock_s3
import permission_lambda
class PermissionLambdaTests(TestCase):
- def _get_permission_statements(self, client, queue_url):
- """ Return a list of policy statements for given queue"""
- policy_response = client.get_queue_attributes(
- QueueUrl=queue_url, AttributeNames=['Policy'])
- policy = policy_response['Attributes']['Policy']
- return json.loads(policy)['Statement']
-
@mock_s3
def test_get_usofa_accountlist_from_bucket(self):
bucketname = "testbucket"
usofa_data = {
"account1": {
"id": "123456789",
"email": "user1@domain.invalid"
},
"account2": {
"id": "987654321",
"email": "user2@domain.invalid"
}
}
client = boto3.client('s3')
client.create_bucket(
Bucket=bucketname,
CreateBucketConfiguration={
'LocationConstraint': 'eu-west-1'
})
client.put_object(
Bucket=bucketname,
Key="accounts.json",
Body=json.dumps(usofa_data)
)
accountlist = permission_lambda.get_usofa_accountlist(bucketname)
accountlist.sort()
self.assertEqual(accountlist, ["123456789", "987654321"])
| Remove Unittests done as integrationtests, due to NotImplementedErrors from moto | ## Code Before:
from unittest2 import TestCase
import simplejson as json
import boto3
from moto import mock_s3
import permission_lambda
class PermissionLambdaTests(TestCase):
def _get_permission_statements(self, client, queue_url):
""" Return a list of policy statements for given queue"""
policy_response = client.get_queue_attributes(
QueueUrl=queue_url, AttributeNames=['Policy'])
policy = policy_response['Attributes']['Policy']
return json.loads(policy)['Statement']
@mock_s3
def test_get_usofa_accountlist_from_bucket(self):
bucketname = "testbucket"
usofa_data = {
"account1": {
"id": "123456789",
"email": "user1@domain.invalid"
},
"account2": {
"id": "987654321",
"email": "user2@domain.invalid"
}
}
client = boto3.client('s3')
client.create_bucket(
Bucket=bucketname,
CreateBucketConfiguration={
'LocationConstraint': 'eu-west-1'
})
client.put_object(
Bucket=bucketname,
Key="accounts.json",
Body=json.dumps(usofa_data)
)
accountlist = permission_lambda.get_usofa_accountlist(bucketname)
accountlist.sort()
self.assertEqual(accountlist, ["123456789", "987654321"])
## Instruction:
Remove Unittests done as integrationtests, due to NotImplementedErrors from moto
## Code After:
from unittest2 import TestCase
import simplejson as json
import boto3
from moto import mock_s3
import permission_lambda
class PermissionLambdaTests(TestCase):
@mock_s3
def test_get_usofa_accountlist_from_bucket(self):
bucketname = "testbucket"
usofa_data = {
"account1": {
"id": "123456789",
"email": "user1@domain.invalid"
},
"account2": {
"id": "987654321",
"email": "user2@domain.invalid"
}
}
client = boto3.client('s3')
client.create_bucket(
Bucket=bucketname,
CreateBucketConfiguration={
'LocationConstraint': 'eu-west-1'
})
client.put_object(
Bucket=bucketname,
Key="accounts.json",
Body=json.dumps(usofa_data)
)
accountlist = permission_lambda.get_usofa_accountlist(bucketname)
accountlist.sort()
self.assertEqual(accountlist, ["123456789", "987654321"])
| from unittest2 import TestCase
import simplejson as json
import boto3
from moto import mock_s3
import permission_lambda
class PermissionLambdaTests(TestCase):
- def _get_permission_statements(self, client, queue_url):
- """ Return a list of policy statements for given queue"""
- policy_response = client.get_queue_attributes(
- QueueUrl=queue_url, AttributeNames=['Policy'])
- policy = policy_response['Attributes']['Policy']
- return json.loads(policy)['Statement']
-
@mock_s3
def test_get_usofa_accountlist_from_bucket(self):
bucketname = "testbucket"
usofa_data = {
"account1": {
"id": "123456789",
"email": "user1@domain.invalid"
},
"account2": {
"id": "987654321",
"email": "user2@domain.invalid"
}
}
client = boto3.client('s3')
client.create_bucket(
Bucket=bucketname,
CreateBucketConfiguration={
'LocationConstraint': 'eu-west-1'
})
client.put_object(
Bucket=bucketname,
Key="accounts.json",
Body=json.dumps(usofa_data)
)
accountlist = permission_lambda.get_usofa_accountlist(bucketname)
accountlist.sort()
self.assertEqual(accountlist, ["123456789", "987654321"]) |
6a8f5bcc6dd42e125f7219d7d692c3af610c38c3 | masters/master.client.polymer/polymer_repos.py | masters/master.client.polymer/polymer_repos.py |
REPOS = (
'polymer',
'platform',
'CustomElements',
'mdv',
'PointerGestures',
'ShadowDOM',
'HTMLImports',
)
|
REPOS = (
'polymer',
'platform',
'CustomElements',
'mdv',
'PointerGestures',
'PointerEvents',
'ShadowDOM',
'HTMLImports',
)
| Add PointerEvents repo to master.client.polymer. | Add PointerEvents repo to master.client.polymer.
R=hinoka@google.com
BUG=chromium:237914
Review URL: https://codereview.chromium.org/15783003
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@201643 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build |
REPOS = (
'polymer',
'platform',
'CustomElements',
'mdv',
'PointerGestures',
+ 'PointerEvents',
'ShadowDOM',
'HTMLImports',
)
| Add PointerEvents repo to master.client.polymer. | ## Code Before:
REPOS = (
'polymer',
'platform',
'CustomElements',
'mdv',
'PointerGestures',
'ShadowDOM',
'HTMLImports',
)
## Instruction:
Add PointerEvents repo to master.client.polymer.
## Code After:
REPOS = (
'polymer',
'platform',
'CustomElements',
'mdv',
'PointerGestures',
'PointerEvents',
'ShadowDOM',
'HTMLImports',
)
|
REPOS = (
'polymer',
'platform',
'CustomElements',
'mdv',
'PointerGestures',
+ 'PointerEvents',
'ShadowDOM',
'HTMLImports',
) |
e97fabb025e66671edbe4446efa966d853f1d6df | tools/utils.py | tools/utils.py |
''' This script provides utils for python scripts in cameo.
'''
import os
import sys
import subprocess
def TryAddDepotToolsToPythonPath():
depot_tools = FindDepotToolsInPath()
if depot_tools:
sys.path.append(depot_tools)
def FindDepotToolsInPath():
paths = os.getenv('PATH').split(os.path.pathsep)
for path in paths:
if os.path.basename(path) == '':
# path is end with os.path.pathsep
path = os.path.dirname(path)
if os.path.basename(path) == 'depot_tools':
return path
return None
def IsWindows():
return sys.platform == 'cygwin' or sys.platform.startswith('win')
def IsLinux():
return sys.platform.startswith('linux')
def IsMac():
return sys.platform.startswith('darwin')
def GitExe():
if IsWindows():
return 'git.bat'
else:
return 'git'
def GetCommandOutput(command, cwd=None):
proc = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, bufsize=1,
cwd=cwd)
output = proc.communicate()[0]
result = proc.returncode
if result:
raise Exception('%s: %s' % (subprocess.list2cmdline(command), output))
return output
|
''' This script provides utils for python scripts in cameo.
'''
import os
import sys
import subprocess
def TryAddDepotToolsToPythonPath():
depot_tools = FindDepotToolsInPath()
if depot_tools:
sys.path.append(depot_tools)
python_path = os.environ.get('PYTHONPATH')
if python_path:
os.environ['PYTHONPATH'] = os.path.pathsep.join(
python_path.split(os.path.pathsep)+[depot_tools])
else:
os.environ['PYTHONPATH'] = depot_tools
def FindDepotToolsInPath():
paths = os.getenv('PATH').split(os.path.pathsep)
for path in paths:
if os.path.basename(path) == '':
# path is end with os.path.pathsep
path = os.path.dirname(path)
if os.path.basename(path) == 'depot_tools':
return path
return None
def IsWindows():
return sys.platform == 'cygwin' or sys.platform.startswith('win')
def IsLinux():
return sys.platform.startswith('linux')
def IsMac():
return sys.platform.startswith('darwin')
def GitExe():
if IsWindows():
return 'git.bat'
else:
return 'git'
def GetCommandOutput(command, cwd=None):
proc = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, bufsize=1,
cwd=cwd)
output = proc.communicate()[0]
result = proc.returncode
if result:
raise Exception('%s: %s' % (subprocess.list2cmdline(command), output))
return output
| Add depot_tools to PYTHONPATH for pylint | Add depot_tools to PYTHONPATH for pylint
Otherwise, pylint will fail on trybot.
| Python | bsd-3-clause | weiyirong/crosswalk-1,qjia7/crosswalk,baleboy/crosswalk,pozdnyakov/crosswalk,rakuco/crosswalk,jpike88/crosswalk,baleboy/crosswalk,baleboy/crosswalk,huningxin/crosswalk,jpike88/crosswalk,myroot/crosswalk,Pluto-tv/crosswalk,Pluto-tv/crosswalk,jondong/crosswalk,DonnaWuDongxia/crosswalk,ZhengXinCN/crosswalk,tomatell/crosswalk,seanlong/crosswalk,ZhengXinCN/crosswalk,Bysmyyr/crosswalk,rakuco/crosswalk,lincsoon/crosswalk,minggangw/crosswalk,XiaosongWei/crosswalk,baleboy/crosswalk,alex-zhang/crosswalk,myroot/crosswalk,jpike88/crosswalk,zliang7/crosswalk,XiaosongWei/crosswalk,hgl888/crosswalk,fujunwei/crosswalk,marcuspridham/crosswalk,fujunwei/crosswalk,heke123/crosswalk,kurli/crosswalk,amaniak/crosswalk,leonhsl/crosswalk,lincsoon/crosswalk,rakuco/crosswalk,xzhan96/crosswalk,crosswalk-project/crosswalk-efl,RafuCater/crosswalk,kurli/crosswalk,crosswalk-project/crosswalk-efl,bestwpw/crosswalk,tomatell/crosswalk,huningxin/crosswalk,axinging/crosswalk,jondwillis/crosswalk,DonnaWuDongxia/crosswalk,alex-zhang/crosswalk,lincsoon/crosswalk,seanlong/crosswalk,hgl888/crosswalk-efl,XiaosongWei/crosswalk,jondong/crosswalk,heke123/crosswalk,pozdnyakov/crosswalk,chuan9/crosswalk,qjia7/crosswalk,crosswalk-project/crosswalk-efl,RafuCater/crosswalk,qjia7/crosswalk,tomatell/crosswalk,Shouqun/crosswalk,hgl888/crosswalk,stonegithubs/crosswalk,axinging/crosswalk,tomatell/crosswalk,pk-sam/crosswalk,bestwpw/crosswalk,alex-zhang/crosswalk,siovene/crosswalk,leonhsl/crosswalk,xzhan96/crosswalk,tedshroyer/crosswalk,alex-zhang/crosswalk,dreamsxin/crosswalk,tomatell/crosswalk,RafuCater/crosswalk,siovene/crosswalk,chuan9/crosswalk,hgl888/crosswalk-efl,crosswalk-project/crosswalk,pk-sam/crosswalk,zliang7/crosswalk,wuhengzhi/crosswalk,Pluto-tv/crosswalk,crosswalk-project/crosswalk,rakuco/crosswalk,zliang7/crosswalk,qjia7/crosswalk,siovene/crosswalk,TheDirtyCalvinist/spacewalk,tedshroyer/crosswalk,kurli/crosswalk,wuhengzhi/crosswalk,hgl888/crosswalk,chinakids/crosswalk,myroot/crosswalk,qjia7/crosswalk,minggangw/crosswalk,huningxin/crosswalk,seanlong/crosswalk,ZhengXinCN/crosswalk,tedshroyer/crosswalk,Shouqun/crosswalk,tedshroyer/crosswalk,xzhan96/crosswalk,crosswalk-project/crosswalk-efl,baleboy/crosswalk,Bysmyyr/crosswalk,tomatell/crosswalk,chinakids/crosswalk,RafuCater/crosswalk,huningxin/crosswalk,jondong/crosswalk,leonhsl/crosswalk,darktears/crosswalk,hgl888/crosswalk,amaniak/crosswalk,darktears/crosswalk,zliang7/crosswalk,mrunalk/crosswalk,dreamsxin/crosswalk,Pluto-tv/crosswalk,chuan9/crosswalk,shaochangbin/crosswalk,bestwpw/crosswalk,shaochangbin/crosswalk,hgl888/crosswalk-efl,tomatell/crosswalk,axinging/crosswalk,hgl888/crosswalk,myroot/crosswalk,XiaosongWei/crosswalk,minggangw/crosswalk,weiyirong/crosswalk-1,pk-sam/crosswalk,zeropool/crosswalk,darktears/crosswalk,hgl888/crosswalk-efl,dreamsxin/crosswalk,Bysmyyr/crosswalk,jpike88/crosswalk,mrunalk/crosswalk,Bysmyyr/crosswalk,ZhengXinCN/crosswalk,bestwpw/crosswalk,zliang7/crosswalk,amaniak/crosswalk,DonnaWuDongxia/crosswalk,Pluto-tv/crosswalk,huningxin/crosswalk,jondwillis/crosswalk,PeterWangIntel/crosswalk,darktears/crosswalk,leonhsl/crosswalk,chuan9/crosswalk,lincsoon/crosswalk,leonhsl/crosswalk,Pluto-tv/crosswalk,Shouqun/crosswalk,fujunwei/crosswalk,dreamsxin/crosswalk,lincsoon/crosswalk,RafuCater/crosswalk,Shouqun/crosswalk,PeterWangIntel/crosswalk,lincsoon/crosswalk,fujunwei/crosswalk,minggangw/crosswalk,fujunwei/crosswalk,zeropool/crosswalk,darktears/crosswalk,stonegithubs/crosswalk,weiyirong/crosswalk-1,amaniak/crosswalk,TheDirtyCalvinist/spacewalk,crosswalk-project/crosswalk,heke123/crosswalk,jondong/crosswalk,xzhan96/crosswalk,myroot/crosswalk,lincsoon/crosswalk,marcuspridham/crosswalk,pozdnyakov/crosswalk,marcuspridham/crosswalk,jpike88/crosswalk,TheDirtyCalvinist/spacewalk,mrunalk/crosswalk,minggangw/crosswalk,Shouqun/crosswalk,bestwpw/crosswalk,hgl888/crosswalk,tedshroyer/crosswalk,DonnaWuDongxia/crosswalk,Shouqun/crosswalk,heke123/crosswalk,heke123/crosswalk,amaniak/crosswalk,weiyirong/crosswalk-1,shaochangbin/crosswalk,crosswalk-project/crosswalk,stonegithubs/crosswalk,siovene/crosswalk,chinakids/crosswalk,pk-sam/crosswalk,jpike88/crosswalk,rakuco/crosswalk,kurli/crosswalk,wuhengzhi/crosswalk,zeropool/crosswalk,Pluto-tv/crosswalk,Bysmyyr/crosswalk,TheDirtyCalvinist/spacewalk,rakuco/crosswalk,kurli/crosswalk,amaniak/crosswalk,crosswalk-project/crosswalk-efl,zeropool/crosswalk,myroot/crosswalk,kurli/crosswalk,zliang7/crosswalk,chinakids/crosswalk,jondwillis/crosswalk,hgl888/crosswalk-efl,leonhsl/crosswalk,darktears/crosswalk,jondong/crosswalk,jondwillis/crosswalk,alex-zhang/crosswalk,ZhengXinCN/crosswalk,minggangw/crosswalk,xzhan96/crosswalk,Bysmyyr/crosswalk,chinakids/crosswalk,bestwpw/crosswalk,hgl888/crosswalk,baleboy/crosswalk,shaochangbin/crosswalk,minggangw/crosswalk,chinakids/crosswalk,zeropool/crosswalk,mrunalk/crosswalk,leonhsl/crosswalk,shaochangbin/crosswalk,heke123/crosswalk,pk-sam/crosswalk,stonegithubs/crosswalk,hgl888/crosswalk,hgl888/crosswalk-efl,jondong/crosswalk,marcuspridham/crosswalk,wuhengzhi/crosswalk,zliang7/crosswalk,qjia7/crosswalk,pozdnyakov/crosswalk,fujunwei/crosswalk,wuhengzhi/crosswalk,zeropool/crosswalk,pozdnyakov/crosswalk,crosswalk-project/crosswalk,hgl888/crosswalk-efl,XiaosongWei/crosswalk,seanlong/crosswalk,rakuco/crosswalk,marcuspridham/crosswalk,heke123/crosswalk,PeterWangIntel/crosswalk,xzhan96/crosswalk,tedshroyer/crosswalk,seanlong/crosswalk,tedshroyer/crosswalk,chuan9/crosswalk,crosswalk-project/crosswalk-efl,PeterWangIntel/crosswalk,PeterWangIntel/crosswalk,siovene/crosswalk,stonegithubs/crosswalk,jondwillis/crosswalk,jondwillis/crosswalk,baleboy/crosswalk,wuhengzhi/crosswalk,Bysmyyr/crosswalk,chuan9/crosswalk,weiyirong/crosswalk-1,ZhengXinCN/crosswalk,amaniak/crosswalk,axinging/crosswalk,siovene/crosswalk,stonegithubs/crosswalk,xzhan96/crosswalk,marcuspridham/crosswalk,mrunalk/crosswalk,stonegithubs/crosswalk,pk-sam/crosswalk,dreamsxin/crosswalk,XiaosongWei/crosswalk,axinging/crosswalk,xzhan96/crosswalk,jpike88/crosswalk,axinging/crosswalk,DonnaWuDongxia/crosswalk,crosswalk-project/crosswalk,bestwpw/crosswalk,darktears/crosswalk,chuan9/crosswalk,alex-zhang/crosswalk,Bysmyyr/crosswalk,marcuspridham/crosswalk,alex-zhang/crosswalk,DonnaWuDongxia/crosswalk,crosswalk-project/crosswalk,zeropool/crosswalk,huningxin/crosswalk,pk-sam/crosswalk,crosswalk-project/crosswalk,zliang7/crosswalk,marcuspridham/crosswalk,heke123/crosswalk,XiaosongWei/crosswalk,PeterWangIntel/crosswalk,mrunalk/crosswalk,axinging/crosswalk,jondong/crosswalk,lincsoon/crosswalk,weiyirong/crosswalk-1,RafuCater/crosswalk,jondong/crosswalk,shaochangbin/crosswalk,crosswalk-project/crosswalk-efl,pozdnyakov/crosswalk,fujunwei/crosswalk,jondwillis/crosswalk,seanlong/crosswalk,ZhengXinCN/crosswalk,rakuco/crosswalk,baleboy/crosswalk,darktears/crosswalk,weiyirong/crosswalk-1,TheDirtyCalvinist/spacewalk,minggangw/crosswalk,dreamsxin/crosswalk,dreamsxin/crosswalk,siovene/crosswalk,DonnaWuDongxia/crosswalk,TheDirtyCalvinist/spacewalk,RafuCater/crosswalk,PeterWangIntel/crosswalk |
''' This script provides utils for python scripts in cameo.
'''
import os
import sys
import subprocess
def TryAddDepotToolsToPythonPath():
depot_tools = FindDepotToolsInPath()
if depot_tools:
sys.path.append(depot_tools)
+ python_path = os.environ.get('PYTHONPATH')
+ if python_path:
+ os.environ['PYTHONPATH'] = os.path.pathsep.join(
+ python_path.split(os.path.pathsep)+[depot_tools])
+ else:
+ os.environ['PYTHONPATH'] = depot_tools
def FindDepotToolsInPath():
paths = os.getenv('PATH').split(os.path.pathsep)
for path in paths:
if os.path.basename(path) == '':
# path is end with os.path.pathsep
path = os.path.dirname(path)
if os.path.basename(path) == 'depot_tools':
return path
return None
def IsWindows():
return sys.platform == 'cygwin' or sys.platform.startswith('win')
def IsLinux():
return sys.platform.startswith('linux')
def IsMac():
return sys.platform.startswith('darwin')
def GitExe():
if IsWindows():
return 'git.bat'
else:
return 'git'
def GetCommandOutput(command, cwd=None):
proc = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, bufsize=1,
cwd=cwd)
output = proc.communicate()[0]
result = proc.returncode
if result:
raise Exception('%s: %s' % (subprocess.list2cmdline(command), output))
return output
| Add depot_tools to PYTHONPATH for pylint | ## Code Before:
''' This script provides utils for python scripts in cameo.
'''
import os
import sys
import subprocess
def TryAddDepotToolsToPythonPath():
depot_tools = FindDepotToolsInPath()
if depot_tools:
sys.path.append(depot_tools)
def FindDepotToolsInPath():
paths = os.getenv('PATH').split(os.path.pathsep)
for path in paths:
if os.path.basename(path) == '':
# path is end with os.path.pathsep
path = os.path.dirname(path)
if os.path.basename(path) == 'depot_tools':
return path
return None
def IsWindows():
return sys.platform == 'cygwin' or sys.platform.startswith('win')
def IsLinux():
return sys.platform.startswith('linux')
def IsMac():
return sys.platform.startswith('darwin')
def GitExe():
if IsWindows():
return 'git.bat'
else:
return 'git'
def GetCommandOutput(command, cwd=None):
proc = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, bufsize=1,
cwd=cwd)
output = proc.communicate()[0]
result = proc.returncode
if result:
raise Exception('%s: %s' % (subprocess.list2cmdline(command), output))
return output
## Instruction:
Add depot_tools to PYTHONPATH for pylint
## Code After:
''' This script provides utils for python scripts in cameo.
'''
import os
import sys
import subprocess
def TryAddDepotToolsToPythonPath():
depot_tools = FindDepotToolsInPath()
if depot_tools:
sys.path.append(depot_tools)
python_path = os.environ.get('PYTHONPATH')
if python_path:
os.environ['PYTHONPATH'] = os.path.pathsep.join(
python_path.split(os.path.pathsep)+[depot_tools])
else:
os.environ['PYTHONPATH'] = depot_tools
def FindDepotToolsInPath():
paths = os.getenv('PATH').split(os.path.pathsep)
for path in paths:
if os.path.basename(path) == '':
# path is end with os.path.pathsep
path = os.path.dirname(path)
if os.path.basename(path) == 'depot_tools':
return path
return None
def IsWindows():
return sys.platform == 'cygwin' or sys.platform.startswith('win')
def IsLinux():
return sys.platform.startswith('linux')
def IsMac():
return sys.platform.startswith('darwin')
def GitExe():
if IsWindows():
return 'git.bat'
else:
return 'git'
def GetCommandOutput(command, cwd=None):
proc = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, bufsize=1,
cwd=cwd)
output = proc.communicate()[0]
result = proc.returncode
if result:
raise Exception('%s: %s' % (subprocess.list2cmdline(command), output))
return output
|
''' This script provides utils for python scripts in cameo.
'''
import os
import sys
import subprocess
def TryAddDepotToolsToPythonPath():
depot_tools = FindDepotToolsInPath()
if depot_tools:
sys.path.append(depot_tools)
+ python_path = os.environ.get('PYTHONPATH')
+ if python_path:
+ os.environ['PYTHONPATH'] = os.path.pathsep.join(
+ python_path.split(os.path.pathsep)+[depot_tools])
+ else:
+ os.environ['PYTHONPATH'] = depot_tools
def FindDepotToolsInPath():
paths = os.getenv('PATH').split(os.path.pathsep)
for path in paths:
if os.path.basename(path) == '':
# path is end with os.path.pathsep
path = os.path.dirname(path)
if os.path.basename(path) == 'depot_tools':
return path
return None
def IsWindows():
return sys.platform == 'cygwin' or sys.platform.startswith('win')
def IsLinux():
return sys.platform.startswith('linux')
def IsMac():
return sys.platform.startswith('darwin')
def GitExe():
if IsWindows():
return 'git.bat'
else:
return 'git'
def GetCommandOutput(command, cwd=None):
proc = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, bufsize=1,
cwd=cwd)
output = proc.communicate()[0]
result = proc.returncode
if result:
raise Exception('%s: %s' % (subprocess.list2cmdline(command), output))
return output |
7b72dbb331c120eb5657ce9a81e725c550779485 | dataportal/broker/__init__.py | dataportal/broker/__init__.py | from .simple_broker import _DataBrokerClass, EventQueue, Header
from .handler_registration import register_builtin_handlers
DataBroker = _DataBrokerClass() # singleton
register_builtin_handlers()
| from .simple_broker import (_DataBrokerClass, EventQueue, Header,
LocationError, IntegrityError)
from .handler_registration import register_builtin_handlers
DataBroker = _DataBrokerClass() # singleton
register_builtin_handlers()
| Add Errors to the public API. | DOC: Add Errors to the public API.
| Python | bsd-3-clause | danielballan/dataportal,ericdill/datamuxer,tacaswell/dataportal,ericdill/datamuxer,tacaswell/dataportal,NSLS-II/dataportal,danielballan/datamuxer,danielballan/datamuxer,ericdill/databroker,NSLS-II/datamuxer,danielballan/dataportal,NSLS-II/dataportal,ericdill/databroker | - from .simple_broker import _DataBrokerClass, EventQueue, Header
+ from .simple_broker import (_DataBrokerClass, EventQueue, Header,
+ LocationError, IntegrityError)
from .handler_registration import register_builtin_handlers
DataBroker = _DataBrokerClass() # singleton
register_builtin_handlers()
| Add Errors to the public API. | ## Code Before:
from .simple_broker import _DataBrokerClass, EventQueue, Header
from .handler_registration import register_builtin_handlers
DataBroker = _DataBrokerClass() # singleton
register_builtin_handlers()
## Instruction:
Add Errors to the public API.
## Code After:
from .simple_broker import (_DataBrokerClass, EventQueue, Header,
LocationError, IntegrityError)
from .handler_registration import register_builtin_handlers
DataBroker = _DataBrokerClass() # singleton
register_builtin_handlers()
| - from .simple_broker import _DataBrokerClass, EventQueue, Header
+ from .simple_broker import (_DataBrokerClass, EventQueue, Header,
? + +
+ LocationError, IntegrityError)
from .handler_registration import register_builtin_handlers
DataBroker = _DataBrokerClass() # singleton
register_builtin_handlers() |
5dd78f614e5882bc2a3fcae24117a26ee34371ac | register-result.py | register-result.py |
import json
import socket
import sys
if len(sys.argv) < 4:
print("Error: Usage <register-result> <client> <name> <output> <status> <ttl>")
sys.exit(128)
check_client = sys.argv[1]
check_name = sys.argv[2]
check_output = sys.argv[3]
check_status = int(sys.argv[4])
check_ttl = int(sys.argv[5]) if len(sys.argv) > 5 else 90000
# Our result dict
result = dict()
result['source'] = check_client
result['name'] = check_name
result['output'] = check_output
result['status'] = check_status
result['ttl'] = check_ttl
# TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 3030)
sock.connect(server_address)
print (json.dumps(result))
socket.sendall(json.dumps(result))
|
import json
import socket
import sys
if len(sys.argv) < 4:
print("Error: Usage <register-result> <client> <name> <output> <status> <ttl>")
sys.exit(128)
check_client = sys.argv[1]
check_name = sys.argv[2]
check_output = sys.argv[3]
check_status = int(sys.argv[4])
check_ttl = int(sys.argv[5]) if len(sys.argv) > 5 else 90000
# Our result dict
result = dict()
result['source'] = check_client
result['name'] = check_name
result['output'] = check_output
result['status'] = check_status
result['ttl'] = check_ttl
# TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 3030)
sock.connect(server_address)
sock.sendall(json.dumps(result))
print (json.dumps(result))
| Fix mistake with socket constructor | Fix mistake with socket constructor
| Python | mit | panubo/docker-monitor,panubo/docker-monitor,panubo/docker-monitor |
import json
import socket
import sys
if len(sys.argv) < 4:
print("Error: Usage <register-result> <client> <name> <output> <status> <ttl>")
sys.exit(128)
check_client = sys.argv[1]
check_name = sys.argv[2]
check_output = sys.argv[3]
check_status = int(sys.argv[4])
check_ttl = int(sys.argv[5]) if len(sys.argv) > 5 else 90000
# Our result dict
result = dict()
result['source'] = check_client
result['name'] = check_name
result['output'] = check_output
result['status'] = check_status
result['ttl'] = check_ttl
# TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 3030)
sock.connect(server_address)
+ sock.sendall(json.dumps(result))
print (json.dumps(result))
- socket.sendall(json.dumps(result))
| Fix mistake with socket constructor | ## Code Before:
import json
import socket
import sys
if len(sys.argv) < 4:
print("Error: Usage <register-result> <client> <name> <output> <status> <ttl>")
sys.exit(128)
check_client = sys.argv[1]
check_name = sys.argv[2]
check_output = sys.argv[3]
check_status = int(sys.argv[4])
check_ttl = int(sys.argv[5]) if len(sys.argv) > 5 else 90000
# Our result dict
result = dict()
result['source'] = check_client
result['name'] = check_name
result['output'] = check_output
result['status'] = check_status
result['ttl'] = check_ttl
# TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 3030)
sock.connect(server_address)
print (json.dumps(result))
socket.sendall(json.dumps(result))
## Instruction:
Fix mistake with socket constructor
## Code After:
import json
import socket
import sys
if len(sys.argv) < 4:
print("Error: Usage <register-result> <client> <name> <output> <status> <ttl>")
sys.exit(128)
check_client = sys.argv[1]
check_name = sys.argv[2]
check_output = sys.argv[3]
check_status = int(sys.argv[4])
check_ttl = int(sys.argv[5]) if len(sys.argv) > 5 else 90000
# Our result dict
result = dict()
result['source'] = check_client
result['name'] = check_name
result['output'] = check_output
result['status'] = check_status
result['ttl'] = check_ttl
# TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 3030)
sock.connect(server_address)
sock.sendall(json.dumps(result))
print (json.dumps(result))
|
import json
import socket
import sys
if len(sys.argv) < 4:
print("Error: Usage <register-result> <client> <name> <output> <status> <ttl>")
sys.exit(128)
check_client = sys.argv[1]
check_name = sys.argv[2]
check_output = sys.argv[3]
check_status = int(sys.argv[4])
check_ttl = int(sys.argv[5]) if len(sys.argv) > 5 else 90000
# Our result dict
result = dict()
result['source'] = check_client
result['name'] = check_name
result['output'] = check_output
result['status'] = check_status
result['ttl'] = check_ttl
# TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 3030)
sock.connect(server_address)
+ sock.sendall(json.dumps(result))
print (json.dumps(result))
- socket.sendall(json.dumps(result)) |
44110a305b5a23609c5f6366da9d746244807dbb | power/__init__.py | power/__init__.py | from sys import platform
from power.common import *
from power.version import VERSION
__version__ = VERSION
try:
if platform.startswith('darwin'):
from power.darwin import PowerManagement
elif platform.startswith('freebsd'):
from power.freebsd import PowerManagement
elif platform.startswith('win32'):
from power.win32 import PowerManagement
elif platform.startswith('linux'):
from power.linux import PowerManagement
else:
raise RuntimeError("{platform} is not supported.".format(platform=platform))
except RuntimeError as e:
import warnings
warnings.warn("Unable to load PowerManagement for {platform}. No-op PowerManagement class is used: {error}".format(error=str(e), platform=platform))
from power.common import PowerManagementNoop as PowerManagement
| from sys import platform
from power.common import *
from power.version import VERSION
__version__ = VERSION
try:
if platform.startswith('darwin'):
from power.darwin import PowerManagement
elif platform.startswith('freebsd'):
from power.freebsd import PowerManagement
elif platform.startswith('win32'):
from power.win32 import PowerManagement
elif platform.startswith('linux'):
from power.linux import PowerManagement
else:
raise RuntimeError("{platform} is not supported.".format(platform=platform))
except (RuntimeError, ImportError) as e:
import warnings
warnings.warn("Unable to load PowerManagement for {platform}. No-op PowerManagement class is used: {error}".format(error=str(e), platform=platform))
from power.common import PowerManagementNoop as PowerManagement
| Use PowerManagementNoop on import errors | Use PowerManagementNoop on import errors
Platform implementation can fail to import its dependencies.
| Python | mit | Kentzo/Power | from sys import platform
from power.common import *
from power.version import VERSION
__version__ = VERSION
try:
if platform.startswith('darwin'):
from power.darwin import PowerManagement
elif platform.startswith('freebsd'):
from power.freebsd import PowerManagement
elif platform.startswith('win32'):
from power.win32 import PowerManagement
elif platform.startswith('linux'):
from power.linux import PowerManagement
else:
raise RuntimeError("{platform} is not supported.".format(platform=platform))
- except RuntimeError as e:
+ except (RuntimeError, ImportError) as e:
import warnings
warnings.warn("Unable to load PowerManagement for {platform}. No-op PowerManagement class is used: {error}".format(error=str(e), platform=platform))
from power.common import PowerManagementNoop as PowerManagement
| Use PowerManagementNoop on import errors | ## Code Before:
from sys import platform
from power.common import *
from power.version import VERSION
__version__ = VERSION
try:
if platform.startswith('darwin'):
from power.darwin import PowerManagement
elif platform.startswith('freebsd'):
from power.freebsd import PowerManagement
elif platform.startswith('win32'):
from power.win32 import PowerManagement
elif platform.startswith('linux'):
from power.linux import PowerManagement
else:
raise RuntimeError("{platform} is not supported.".format(platform=platform))
except RuntimeError as e:
import warnings
warnings.warn("Unable to load PowerManagement for {platform}. No-op PowerManagement class is used: {error}".format(error=str(e), platform=platform))
from power.common import PowerManagementNoop as PowerManagement
## Instruction:
Use PowerManagementNoop on import errors
## Code After:
from sys import platform
from power.common import *
from power.version import VERSION
__version__ = VERSION
try:
if platform.startswith('darwin'):
from power.darwin import PowerManagement
elif platform.startswith('freebsd'):
from power.freebsd import PowerManagement
elif platform.startswith('win32'):
from power.win32 import PowerManagement
elif platform.startswith('linux'):
from power.linux import PowerManagement
else:
raise RuntimeError("{platform} is not supported.".format(platform=platform))
except (RuntimeError, ImportError) as e:
import warnings
warnings.warn("Unable to load PowerManagement for {platform}. No-op PowerManagement class is used: {error}".format(error=str(e), platform=platform))
from power.common import PowerManagementNoop as PowerManagement
| from sys import platform
from power.common import *
from power.version import VERSION
__version__ = VERSION
try:
if platform.startswith('darwin'):
from power.darwin import PowerManagement
elif platform.startswith('freebsd'):
from power.freebsd import PowerManagement
elif platform.startswith('win32'):
from power.win32 import PowerManagement
elif platform.startswith('linux'):
from power.linux import PowerManagement
else:
raise RuntimeError("{platform} is not supported.".format(platform=platform))
- except RuntimeError as e:
+ except (RuntimeError, ImportError) as e:
? + ++++++++++++++
import warnings
warnings.warn("Unable to load PowerManagement for {platform}. No-op PowerManagement class is used: {error}".format(error=str(e), platform=platform))
from power.common import PowerManagementNoop as PowerManagement |
3800c095f58e9bc2ca8c580537ea576049bbfe2d | sell/urls.py | sell/urls.py | from django.conf.urls import url
from sell import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^personal/$', views.personal_data),
url(r'^books/$', views.books),
url(r'^summary/$', views.summary),
] | from django.conf.urls import url
from sell import views
urlpatterns = [
url(r'^$', views.index),
url(r'^personal/$', views.personal_data),
url(r'^books/$', views.books),
url(r'^summary/$', views.summary),
] | Remove unnecessary URL name in Sell app | Remove unnecessary URL name in Sell app
| Python | agpl-3.0 | m4tx/egielda,m4tx/egielda,m4tx/egielda | from django.conf.urls import url
from sell import views
urlpatterns = [
- url(r'^$', views.index, name='index'),
+ url(r'^$', views.index),
url(r'^personal/$', views.personal_data),
url(r'^books/$', views.books),
url(r'^summary/$', views.summary),
] | Remove unnecessary URL name in Sell app | ## Code Before:
from django.conf.urls import url
from sell import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^personal/$', views.personal_data),
url(r'^books/$', views.books),
url(r'^summary/$', views.summary),
]
## Instruction:
Remove unnecessary URL name in Sell app
## Code After:
from django.conf.urls import url
from sell import views
urlpatterns = [
url(r'^$', views.index),
url(r'^personal/$', views.personal_data),
url(r'^books/$', views.books),
url(r'^summary/$', views.summary),
] | from django.conf.urls import url
from sell import views
urlpatterns = [
- url(r'^$', views.index, name='index'),
? --------------
+ url(r'^$', views.index),
url(r'^personal/$', views.personal_data),
url(r'^books/$', views.books),
url(r'^summary/$', views.summary),
] |
220953f4f8136e9c5eff21426421e6ac7f6f502d | tssim/functions/wrapper.py | tssim/functions/wrapper.py | """This module contains the main wrapper class."""
class BaseWrapper:
"""Define base template for function wrapper classes. """
def __init__(self, func):
self.func = func
self.__doc__ = func.__doc__
def __call__(self, *args, **kwargs):
raise NotImplementedError
class NumpyWrapper(BaseWrapper):
"""Function wrapper for numpy's random functions. Allows easy usage
avoiding the creation anonymous lambda functions. In addition, the `size`
attribute is adjusted automatically.
For instance, instead of writing
'lambda x: np.random.randint(low=1, high=10, size=x.shape[0])'
you may simply write
'ts.random.randint(low=1, high=10)'.
"""
def __init__(self, func, size="arg"):
super(NumpyWrapper, self).__init__(func)
self.size = size
def __call__(self, *args, **kwargs):
if self.size == "arg":
def wrapped(x):
return self.func(*args, x.shape[0], **kwargs)
elif self.size == "kwarg":
def wrapped(x):
return self.func(*args, size=x.shape[0], **kwargs)
else:
raise ValueError("Size argument must be 'arg' or 'kwarg'.")
wrapped.__doc__ = self.func.__doc__
return wrapped
| """This module contains the main wrapper class."""
class BaseWrapper:
"""Define base template for function wrapper classes. """
def __init__(self, func):
self.func = func
self.__doc__ = func.__doc__
def __call__(self, *args, **kwargs):
raise NotImplementedError
class NumpyWrapper(BaseWrapper):
"""Function wrapper for numpy's random functions. Allows easy usage
avoiding the creation anonymous lambda functions. In addition, the `size`
attribute is adjusted automatically.
For instance, instead of writing
'lambda x: np.random.randint(low=1, high=10, size=x.shape[0])'
you may simply write
'ts.random.randint(low=1, high=10)'.
"""
def __init__(self, func, size="arg"):
super(NumpyWrapper, self).__init__(func)
self.size = size
def __call__(self, *args, **kwargs):
if self.size == "arg":
def wrapped(x):
return self.func(x.shape[0], *args, **kwargs)
elif self.size == "kwarg":
def wrapped(x):
return self.func(*args, size=x.shape[0], **kwargs)
else:
raise ValueError("Size argument must be 'arg' or 'kwarg'.")
wrapped.__doc__ = self.func.__doc__
return wrapped
| Fix bug due to wrong arguments order. | Fix bug due to wrong arguments order.
| Python | mit | mansenfranzen/tssim | """This module contains the main wrapper class."""
class BaseWrapper:
"""Define base template for function wrapper classes. """
def __init__(self, func):
self.func = func
self.__doc__ = func.__doc__
def __call__(self, *args, **kwargs):
raise NotImplementedError
class NumpyWrapper(BaseWrapper):
"""Function wrapper for numpy's random functions. Allows easy usage
avoiding the creation anonymous lambda functions. In addition, the `size`
attribute is adjusted automatically.
For instance, instead of writing
'lambda x: np.random.randint(low=1, high=10, size=x.shape[0])'
you may simply write
'ts.random.randint(low=1, high=10)'.
"""
def __init__(self, func, size="arg"):
super(NumpyWrapper, self).__init__(func)
self.size = size
def __call__(self, *args, **kwargs):
if self.size == "arg":
def wrapped(x):
- return self.func(*args, x.shape[0], **kwargs)
+ return self.func(x.shape[0], *args, **kwargs)
elif self.size == "kwarg":
def wrapped(x):
return self.func(*args, size=x.shape[0], **kwargs)
else:
raise ValueError("Size argument must be 'arg' or 'kwarg'.")
wrapped.__doc__ = self.func.__doc__
return wrapped
| Fix bug due to wrong arguments order. | ## Code Before:
"""This module contains the main wrapper class."""
class BaseWrapper:
"""Define base template for function wrapper classes. """
def __init__(self, func):
self.func = func
self.__doc__ = func.__doc__
def __call__(self, *args, **kwargs):
raise NotImplementedError
class NumpyWrapper(BaseWrapper):
"""Function wrapper for numpy's random functions. Allows easy usage
avoiding the creation anonymous lambda functions. In addition, the `size`
attribute is adjusted automatically.
For instance, instead of writing
'lambda x: np.random.randint(low=1, high=10, size=x.shape[0])'
you may simply write
'ts.random.randint(low=1, high=10)'.
"""
def __init__(self, func, size="arg"):
super(NumpyWrapper, self).__init__(func)
self.size = size
def __call__(self, *args, **kwargs):
if self.size == "arg":
def wrapped(x):
return self.func(*args, x.shape[0], **kwargs)
elif self.size == "kwarg":
def wrapped(x):
return self.func(*args, size=x.shape[0], **kwargs)
else:
raise ValueError("Size argument must be 'arg' or 'kwarg'.")
wrapped.__doc__ = self.func.__doc__
return wrapped
## Instruction:
Fix bug due to wrong arguments order.
## Code After:
"""This module contains the main wrapper class."""
class BaseWrapper:
"""Define base template for function wrapper classes. """
def __init__(self, func):
self.func = func
self.__doc__ = func.__doc__
def __call__(self, *args, **kwargs):
raise NotImplementedError
class NumpyWrapper(BaseWrapper):
"""Function wrapper for numpy's random functions. Allows easy usage
avoiding the creation anonymous lambda functions. In addition, the `size`
attribute is adjusted automatically.
For instance, instead of writing
'lambda x: np.random.randint(low=1, high=10, size=x.shape[0])'
you may simply write
'ts.random.randint(low=1, high=10)'.
"""
def __init__(self, func, size="arg"):
super(NumpyWrapper, self).__init__(func)
self.size = size
def __call__(self, *args, **kwargs):
if self.size == "arg":
def wrapped(x):
return self.func(x.shape[0], *args, **kwargs)
elif self.size == "kwarg":
def wrapped(x):
return self.func(*args, size=x.shape[0], **kwargs)
else:
raise ValueError("Size argument must be 'arg' or 'kwarg'.")
wrapped.__doc__ = self.func.__doc__
return wrapped
| """This module contains the main wrapper class."""
class BaseWrapper:
"""Define base template for function wrapper classes. """
def __init__(self, func):
self.func = func
self.__doc__ = func.__doc__
def __call__(self, *args, **kwargs):
raise NotImplementedError
class NumpyWrapper(BaseWrapper):
"""Function wrapper for numpy's random functions. Allows easy usage
avoiding the creation anonymous lambda functions. In addition, the `size`
attribute is adjusted automatically.
For instance, instead of writing
'lambda x: np.random.randint(low=1, high=10, size=x.shape[0])'
you may simply write
'ts.random.randint(low=1, high=10)'.
"""
def __init__(self, func, size="arg"):
super(NumpyWrapper, self).__init__(func)
self.size = size
def __call__(self, *args, **kwargs):
if self.size == "arg":
def wrapped(x):
- return self.func(*args, x.shape[0], **kwargs)
? -------
+ return self.func(x.shape[0], *args, **kwargs)
? +++++++
elif self.size == "kwarg":
def wrapped(x):
return self.func(*args, size=x.shape[0], **kwargs)
else:
raise ValueError("Size argument must be 'arg' or 'kwarg'.")
wrapped.__doc__ = self.func.__doc__
return wrapped |
fb0b956563efbcd22af8300fd4341e3cb277b80a | app/models/user.py | app/models/user.py | from app import db
from flask import Flask
from datetime import datetime
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
name = db.Column(db.String(80))
bio = db.Column(db.String(180))
github_id = db.Column(db.Integer, unique=True)
github_username = db.Column(db.String(64), unique=True)
github_token = db.Column(db.String(300), unique=True)
password = db.Column(db.String(300))
created_at = db.Column(db.DateTime)
def __init__(self, username, email, password, name=None):
self.email = email
self.username = username
self.password = password
if name is None:
self.name = username
else:
self.name = name
self.created_at = datetime.now()
is_authenticated = True
is_anonymous = False
is_active = True
def get_id(self):
return unicode(self.id)
def __repr__(self):
return '<User %r>' % self.username
| from app import db
from flask import Flask
from datetime import datetime
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
name = db.Column(db.String(80))
bio = db.Column(db.String(180))
avatar_url = db.Column(db.String(256))
owner = db.Column(db.String(32), nullable=False, default='user')
github_id = db.Column(db.Integer, unique=True)
github_username = db.Column(db.String(64), unique=True)
github_token = db.Column(db.String(300), unique=True)
password = db.Column(db.String(300))
created_at = db.Column(db.DateTime)
def __init__(self, username, email, password, name=None):
self.email = email
self.username = username
self.password = password
if name is None:
self.name = username
else:
self.name = name
self.created_at = datetime.now()
is_authenticated = True
is_anonymous = False
is_active = True
def get_id(self):
return unicode(self.id)
def __repr__(self):
return '<User %r>' % self.username
| Add avatar_url and owner field for User | Add avatar_url and owner field for User
| Python | agpl-3.0 | lc-soft/GitDigger,lc-soft/GitDigger,lc-soft/GitDigger,lc-soft/GitDigger | from app import db
from flask import Flask
from datetime import datetime
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
name = db.Column(db.String(80))
bio = db.Column(db.String(180))
+ avatar_url = db.Column(db.String(256))
+ owner = db.Column(db.String(32), nullable=False, default='user')
github_id = db.Column(db.Integer, unique=True)
github_username = db.Column(db.String(64), unique=True)
github_token = db.Column(db.String(300), unique=True)
password = db.Column(db.String(300))
created_at = db.Column(db.DateTime)
def __init__(self, username, email, password, name=None):
self.email = email
self.username = username
self.password = password
if name is None:
self.name = username
else:
self.name = name
self.created_at = datetime.now()
is_authenticated = True
is_anonymous = False
is_active = True
def get_id(self):
return unicode(self.id)
def __repr__(self):
return '<User %r>' % self.username
| Add avatar_url and owner field for User | ## Code Before:
from app import db
from flask import Flask
from datetime import datetime
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
name = db.Column(db.String(80))
bio = db.Column(db.String(180))
github_id = db.Column(db.Integer, unique=True)
github_username = db.Column(db.String(64), unique=True)
github_token = db.Column(db.String(300), unique=True)
password = db.Column(db.String(300))
created_at = db.Column(db.DateTime)
def __init__(self, username, email, password, name=None):
self.email = email
self.username = username
self.password = password
if name is None:
self.name = username
else:
self.name = name
self.created_at = datetime.now()
is_authenticated = True
is_anonymous = False
is_active = True
def get_id(self):
return unicode(self.id)
def __repr__(self):
return '<User %r>' % self.username
## Instruction:
Add avatar_url and owner field for User
## Code After:
from app import db
from flask import Flask
from datetime import datetime
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
name = db.Column(db.String(80))
bio = db.Column(db.String(180))
avatar_url = db.Column(db.String(256))
owner = db.Column(db.String(32), nullable=False, default='user')
github_id = db.Column(db.Integer, unique=True)
github_username = db.Column(db.String(64), unique=True)
github_token = db.Column(db.String(300), unique=True)
password = db.Column(db.String(300))
created_at = db.Column(db.DateTime)
def __init__(self, username, email, password, name=None):
self.email = email
self.username = username
self.password = password
if name is None:
self.name = username
else:
self.name = name
self.created_at = datetime.now()
is_authenticated = True
is_anonymous = False
is_active = True
def get_id(self):
return unicode(self.id)
def __repr__(self):
return '<User %r>' % self.username
| from app import db
from flask import Flask
from datetime import datetime
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
name = db.Column(db.String(80))
bio = db.Column(db.String(180))
+ avatar_url = db.Column(db.String(256))
+ owner = db.Column(db.String(32), nullable=False, default='user')
github_id = db.Column(db.Integer, unique=True)
github_username = db.Column(db.String(64), unique=True)
github_token = db.Column(db.String(300), unique=True)
password = db.Column(db.String(300))
created_at = db.Column(db.DateTime)
def __init__(self, username, email, password, name=None):
self.email = email
self.username = username
self.password = password
if name is None:
self.name = username
else:
self.name = name
self.created_at = datetime.now()
is_authenticated = True
is_anonymous = False
is_active = True
def get_id(self):
return unicode(self.id)
def __repr__(self):
return '<User %r>' % self.username |
12c2c7f20e46dce54990d5cf4c0e51ab02d549c4 | adder/__init__.py | adder/__init__.py | """adder is an amazing module which adds things"""
def add(first, second):
"""The power of add is that it adds its arguments"""
return first + second
| """A mighty module to add things to each other"""
def add(first, second):
"""The power of add is that it adds its arguments"""
return first + second
| Make the docstring match the github description | Make the docstring match the github description | Python | mit | jamesmcdonald/adder | - """adder is an amazing module which adds things"""
+ """A mighty module to add things to each other"""
def add(first, second):
"""The power of add is that it adds its arguments"""
return first + second
| Make the docstring match the github description | ## Code Before:
"""adder is an amazing module which adds things"""
def add(first, second):
"""The power of add is that it adds its arguments"""
return first + second
## Instruction:
Make the docstring match the github description
## Code After:
"""A mighty module to add things to each other"""
def add(first, second):
"""The power of add is that it adds its arguments"""
return first + second
| - """adder is an amazing module which adds things"""
+ """A mighty module to add things to each other"""
def add(first, second):
"""The power of add is that it adds its arguments"""
return first + second |
1975d5391f058f85272def4435b243440b72bff6 | weather/admin.py | weather/admin.py | from django.contrib.admin import ModelAdmin, register
from django.contrib.gis.admin import GeoModelAdmin
from weather.models import WeatherStation, Location
@register(Location)
class LocationAdmin(GeoModelAdmin):
openlayers_url = '//static.dpaw.wa.gov.au/static/libs/openlayers/2.13.1/OpenLayers.js'
list_display = ('pk', 'title', 'point', 'height')
@register(WeatherStation)
class WeatherStationAdmin(ModelAdmin):
list_display = (
'name', 'manufacturer', 'abbreviation', 'bom_abbreviation',
'ip_address', 'last_reading', 'connect_every', 'active', 'upload_data')
list_filter = ('manufacturer', 'active', 'upload_data')
| from django.contrib.admin import ModelAdmin, register
from django.contrib.gis.admin import GeoModelAdmin
from weather.models import WeatherStation, Location
@register(Location)
class LocationAdmin(GeoModelAdmin):
list_display = ('pk', 'title', 'point', 'height')
@register(WeatherStation)
class WeatherStationAdmin(ModelAdmin):
list_display = (
'name', 'manufacturer', 'abbreviation', 'bom_abbreviation',
'ip_address', 'last_reading', 'connect_every', 'active', 'upload_data')
list_filter = ('manufacturer', 'active', 'upload_data')
| Remove custom OpenLayers.js from LocationAdmin. | Remove custom OpenLayers.js from LocationAdmin.
| Python | bsd-3-clause | parksandwildlife/resource_tracking,parksandwildlife/resource_tracking,parksandwildlife/resource_tracking,ropable/resource_tracking,ropable/resource_tracking,ropable/resource_tracking | from django.contrib.admin import ModelAdmin, register
from django.contrib.gis.admin import GeoModelAdmin
from weather.models import WeatherStation, Location
@register(Location)
class LocationAdmin(GeoModelAdmin):
- openlayers_url = '//static.dpaw.wa.gov.au/static/libs/openlayers/2.13.1/OpenLayers.js'
list_display = ('pk', 'title', 'point', 'height')
@register(WeatherStation)
class WeatherStationAdmin(ModelAdmin):
list_display = (
'name', 'manufacturer', 'abbreviation', 'bom_abbreviation',
'ip_address', 'last_reading', 'connect_every', 'active', 'upload_data')
list_filter = ('manufacturer', 'active', 'upload_data')
| Remove custom OpenLayers.js from LocationAdmin. | ## Code Before:
from django.contrib.admin import ModelAdmin, register
from django.contrib.gis.admin import GeoModelAdmin
from weather.models import WeatherStation, Location
@register(Location)
class LocationAdmin(GeoModelAdmin):
openlayers_url = '//static.dpaw.wa.gov.au/static/libs/openlayers/2.13.1/OpenLayers.js'
list_display = ('pk', 'title', 'point', 'height')
@register(WeatherStation)
class WeatherStationAdmin(ModelAdmin):
list_display = (
'name', 'manufacturer', 'abbreviation', 'bom_abbreviation',
'ip_address', 'last_reading', 'connect_every', 'active', 'upload_data')
list_filter = ('manufacturer', 'active', 'upload_data')
## Instruction:
Remove custom OpenLayers.js from LocationAdmin.
## Code After:
from django.contrib.admin import ModelAdmin, register
from django.contrib.gis.admin import GeoModelAdmin
from weather.models import WeatherStation, Location
@register(Location)
class LocationAdmin(GeoModelAdmin):
list_display = ('pk', 'title', 'point', 'height')
@register(WeatherStation)
class WeatherStationAdmin(ModelAdmin):
list_display = (
'name', 'manufacturer', 'abbreviation', 'bom_abbreviation',
'ip_address', 'last_reading', 'connect_every', 'active', 'upload_data')
list_filter = ('manufacturer', 'active', 'upload_data')
| from django.contrib.admin import ModelAdmin, register
from django.contrib.gis.admin import GeoModelAdmin
from weather.models import WeatherStation, Location
@register(Location)
class LocationAdmin(GeoModelAdmin):
- openlayers_url = '//static.dpaw.wa.gov.au/static/libs/openlayers/2.13.1/OpenLayers.js'
list_display = ('pk', 'title', 'point', 'height')
@register(WeatherStation)
class WeatherStationAdmin(ModelAdmin):
list_display = (
'name', 'manufacturer', 'abbreviation', 'bom_abbreviation',
'ip_address', 'last_reading', 'connect_every', 'active', 'upload_data')
list_filter = ('manufacturer', 'active', 'upload_data') |
21368fc9354e3c55132a0d42a734802c00466cb6 | blimpy/__init__.py | blimpy/__init__.py | from __future__ import absolute_import
try:
from . import waterfall
from .waterfall import Waterfall
from .guppi import GuppiRaw
from . import utils
from . import fil2h5
from . import h52fil
from . import h5diag
from . import bl_scrunch
from . import calcload
from . import rawhdr
from . import stax
from . import stix
from . import match_fils
from blimpy.io import file_wrapper
except:
print("Warning: At least one utility could not be imported!")
from pkg_resources import get_distribution, DistributionNotFound
try:
__version__ = get_distribution('blimpy').version
except DistributionNotFound:
__version__ = '0.0.0 - please install via pip/setup.py'
| from __future__ import absolute_import
try:
from . import waterfall
from .waterfall import Waterfall
from .guppi import GuppiRaw
from . import utils
from . import fil2h5
from . import h52fil
from . import h5diag
from . import bl_scrunch
from . import calcload
from . import rawhdr
from . import stax
from . import stix
from . import match_fils
from . import dsamp
from blimpy.io import file_wrapper
except:
print("Warning: At least one utility could not be imported!")
from pkg_resources import get_distribution, DistributionNotFound
try:
__version__ = get_distribution('blimpy').version
except DistributionNotFound:
__version__ = '0.0.0 - please install via pip/setup.py'
| Make dsamp a visible component of blimpy | Make dsamp a visible component of blimpy | Python | bsd-3-clause | UCBerkeleySETI/blimpy,UCBerkeleySETI/blimpy | from __future__ import absolute_import
try:
from . import waterfall
from .waterfall import Waterfall
from .guppi import GuppiRaw
from . import utils
from . import fil2h5
from . import h52fil
from . import h5diag
from . import bl_scrunch
from . import calcload
from . import rawhdr
from . import stax
from . import stix
from . import match_fils
+ from . import dsamp
from blimpy.io import file_wrapper
except:
print("Warning: At least one utility could not be imported!")
from pkg_resources import get_distribution, DistributionNotFound
try:
__version__ = get_distribution('blimpy').version
except DistributionNotFound:
__version__ = '0.0.0 - please install via pip/setup.py'
| Make dsamp a visible component of blimpy | ## Code Before:
from __future__ import absolute_import
try:
from . import waterfall
from .waterfall import Waterfall
from .guppi import GuppiRaw
from . import utils
from . import fil2h5
from . import h52fil
from . import h5diag
from . import bl_scrunch
from . import calcload
from . import rawhdr
from . import stax
from . import stix
from . import match_fils
from blimpy.io import file_wrapper
except:
print("Warning: At least one utility could not be imported!")
from pkg_resources import get_distribution, DistributionNotFound
try:
__version__ = get_distribution('blimpy').version
except DistributionNotFound:
__version__ = '0.0.0 - please install via pip/setup.py'
## Instruction:
Make dsamp a visible component of blimpy
## Code After:
from __future__ import absolute_import
try:
from . import waterfall
from .waterfall import Waterfall
from .guppi import GuppiRaw
from . import utils
from . import fil2h5
from . import h52fil
from . import h5diag
from . import bl_scrunch
from . import calcload
from . import rawhdr
from . import stax
from . import stix
from . import match_fils
from . import dsamp
from blimpy.io import file_wrapper
except:
print("Warning: At least one utility could not be imported!")
from pkg_resources import get_distribution, DistributionNotFound
try:
__version__ = get_distribution('blimpy').version
except DistributionNotFound:
__version__ = '0.0.0 - please install via pip/setup.py'
| from __future__ import absolute_import
try:
from . import waterfall
from .waterfall import Waterfall
from .guppi import GuppiRaw
from . import utils
from . import fil2h5
from . import h52fil
from . import h5diag
from . import bl_scrunch
from . import calcload
from . import rawhdr
from . import stax
from . import stix
from . import match_fils
+ from . import dsamp
from blimpy.io import file_wrapper
except:
print("Warning: At least one utility could not be imported!")
from pkg_resources import get_distribution, DistributionNotFound
try:
__version__ = get_distribution('blimpy').version
except DistributionNotFound:
__version__ = '0.0.0 - please install via pip/setup.py' |
7bc693102a5394bb73b3df2320fca5a35bebc91f | test/test_vocab.py | test/test_vocab.py | import numpy as np
import unittest
from torchtext import vocab
from collections import Counter
class TestVocab(unittest.TestCase):
def test_vocab(self):
c = Counter(['hello', 'world'])
v = vocab.Vocab(c, vectors='glove.test_twitter.27B.200d')
self.assertEqual(v.itos, ['<unk>', '<pad>', 'hello', 'world'])
vectors = v.vectors.numpy()
# The first 5 entries in each vector.
expected_glove_twitter = {
'hello': [0.34683, -0.19612, -0.34923, -0.28158, -0.75627],
'world': [0.035771, 0.62946, 0.27443, -0.36455, 0.39189],
}
for word in ['hello', 'world']:
self.assertTrue(
np.allclose(
vectors[v.stoi[word], :5], expected_glove_twitter[word]
)
)
self.assertTrue(np.allclose(vectors[v.stoi['<unk>'], :], np.zeros(200)))
if __name__ == '__main__':
unittest.main()
| from __future__ import unicode_literals
from collections import Counter
import unittest
import numpy as np
from torchtext import vocab
class TestVocab(unittest.TestCase):
def test_vocab(self):
c = Counter({'hello': 4, 'world': 3, 'ᑌᑎIᑕOᗪᕮ_Tᕮ᙭T': 5, 'freq_too_low': 2})
v = vocab.Vocab(c, min_freq=3, specials=['<pad>', '<bos>'],
vectors='glove.test_twitter.27B.200d')
self.assertEqual(v.itos, ['<unk>', '<pad>', '<bos>',
'ᑌᑎIᑕOᗪᕮ_Tᕮ᙭T', 'hello', 'world'])
vectors = v.vectors.numpy()
# The first 5 entries in each vector.
expected_glove_twitter = {
'hello': [0.34683, -0.19612, -0.34923, -0.28158, -0.75627],
'world': [0.035771, 0.62946, 0.27443, -0.36455, 0.39189],
}
for word in ['hello', 'world']:
self.assertTrue(
np.allclose(
vectors[v.stoi[word], :5], expected_glove_twitter[word]
)
)
self.assertTrue(np.allclose(vectors[v.stoi['<unk>'], :], np.zeros(200)))
if __name__ == '__main__':
unittest.main()
| Test vocab min_freq and specials vocab args, as well as unicode input | Test vocab min_freq and specials vocab args, as well as unicode input
| Python | bsd-3-clause | pytorch/text,pytorch/text,pytorch/text,pytorch/text | - import numpy as np
+ from __future__ import unicode_literals
+ from collections import Counter
import unittest
+ import numpy as np
from torchtext import vocab
- from collections import Counter
class TestVocab(unittest.TestCase):
def test_vocab(self):
- c = Counter(['hello', 'world'])
- v = vocab.Vocab(c, vectors='glove.test_twitter.27B.200d')
+ c = Counter({'hello': 4, 'world': 3, 'ᑌᑎIᑕOᗪᕮ_Tᕮ᙭T': 5, 'freq_too_low': 2})
+ v = vocab.Vocab(c, min_freq=3, specials=['<pad>', '<bos>'],
+ vectors='glove.test_twitter.27B.200d')
- self.assertEqual(v.itos, ['<unk>', '<pad>', 'hello', 'world'])
+ self.assertEqual(v.itos, ['<unk>', '<pad>', '<bos>',
+ 'ᑌᑎIᑕOᗪᕮ_Tᕮ᙭T', 'hello', 'world'])
vectors = v.vectors.numpy()
# The first 5 entries in each vector.
expected_glove_twitter = {
'hello': [0.34683, -0.19612, -0.34923, -0.28158, -0.75627],
'world': [0.035771, 0.62946, 0.27443, -0.36455, 0.39189],
}
for word in ['hello', 'world']:
self.assertTrue(
np.allclose(
vectors[v.stoi[word], :5], expected_glove_twitter[word]
)
)
self.assertTrue(np.allclose(vectors[v.stoi['<unk>'], :], np.zeros(200)))
if __name__ == '__main__':
unittest.main()
| Test vocab min_freq and specials vocab args, as well as unicode input | ## Code Before:
import numpy as np
import unittest
from torchtext import vocab
from collections import Counter
class TestVocab(unittest.TestCase):
def test_vocab(self):
c = Counter(['hello', 'world'])
v = vocab.Vocab(c, vectors='glove.test_twitter.27B.200d')
self.assertEqual(v.itos, ['<unk>', '<pad>', 'hello', 'world'])
vectors = v.vectors.numpy()
# The first 5 entries in each vector.
expected_glove_twitter = {
'hello': [0.34683, -0.19612, -0.34923, -0.28158, -0.75627],
'world': [0.035771, 0.62946, 0.27443, -0.36455, 0.39189],
}
for word in ['hello', 'world']:
self.assertTrue(
np.allclose(
vectors[v.stoi[word], :5], expected_glove_twitter[word]
)
)
self.assertTrue(np.allclose(vectors[v.stoi['<unk>'], :], np.zeros(200)))
if __name__ == '__main__':
unittest.main()
## Instruction:
Test vocab min_freq and specials vocab args, as well as unicode input
## Code After:
from __future__ import unicode_literals
from collections import Counter
import unittest
import numpy as np
from torchtext import vocab
class TestVocab(unittest.TestCase):
def test_vocab(self):
c = Counter({'hello': 4, 'world': 3, 'ᑌᑎIᑕOᗪᕮ_Tᕮ᙭T': 5, 'freq_too_low': 2})
v = vocab.Vocab(c, min_freq=3, specials=['<pad>', '<bos>'],
vectors='glove.test_twitter.27B.200d')
self.assertEqual(v.itos, ['<unk>', '<pad>', '<bos>',
'ᑌᑎIᑕOᗪᕮ_Tᕮ᙭T', 'hello', 'world'])
vectors = v.vectors.numpy()
# The first 5 entries in each vector.
expected_glove_twitter = {
'hello': [0.34683, -0.19612, -0.34923, -0.28158, -0.75627],
'world': [0.035771, 0.62946, 0.27443, -0.36455, 0.39189],
}
for word in ['hello', 'world']:
self.assertTrue(
np.allclose(
vectors[v.stoi[word], :5], expected_glove_twitter[word]
)
)
self.assertTrue(np.allclose(vectors[v.stoi['<unk>'], :], np.zeros(200)))
if __name__ == '__main__':
unittest.main()
| - import numpy as np
+ from __future__ import unicode_literals
+ from collections import Counter
import unittest
+ import numpy as np
from torchtext import vocab
- from collections import Counter
class TestVocab(unittest.TestCase):
def test_vocab(self):
- c = Counter(['hello', 'world'])
+ c = Counter({'hello': 4, 'world': 3, 'ᑌᑎIᑕOᗪᕮ_Tᕮ᙭T': 5, 'freq_too_low': 2})
+ v = vocab.Vocab(c, min_freq=3, specials=['<pad>', '<bos>'],
- v = vocab.Vocab(c, vectors='glove.test_twitter.27B.200d')
? - - ^^^^^^^^^^^^^^
+ vectors='glove.test_twitter.27B.200d')
? ^^^^^^^^^^^^^
- self.assertEqual(v.itos, ['<unk>', '<pad>', 'hello', 'world'])
? ^^^^ ----------
+ self.assertEqual(v.itos, ['<unk>', '<pad>', '<bos>',
? ^^ ++
+ 'ᑌᑎIᑕOᗪᕮ_Tᕮ᙭T', 'hello', 'world'])
vectors = v.vectors.numpy()
# The first 5 entries in each vector.
expected_glove_twitter = {
'hello': [0.34683, -0.19612, -0.34923, -0.28158, -0.75627],
'world': [0.035771, 0.62946, 0.27443, -0.36455, 0.39189],
}
for word in ['hello', 'world']:
self.assertTrue(
np.allclose(
vectors[v.stoi[word], :5], expected_glove_twitter[word]
)
)
self.assertTrue(np.allclose(vectors[v.stoi['<unk>'], :], np.zeros(200)))
if __name__ == '__main__':
unittest.main() |
09e0073a2aec6abc32a639fb2791af19e17eed1c | test/588-funicular-monorail.py | test/588-funicular-monorail.py | assert_has_feature(
16, 10486, 25367, 'transit',
{ 'kind': 'monorail' })
| assert_has_feature(
16, 10486, 25367, 'transit',
{ 'kind': 'monorail' })
# relation 6060405
assert_has_feature(
16, 18201, 24705, 'transit',
{ 'kind': 'funicular' })
| Add test for funicular feature | Add test for funicular feature
| Python | mit | mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource | assert_has_feature(
16, 10486, 25367, 'transit',
{ 'kind': 'monorail' })
+ # relation 6060405
+ assert_has_feature(
+ 16, 18201, 24705, 'transit',
+ { 'kind': 'funicular' })
+ | Add test for funicular feature | ## Code Before:
assert_has_feature(
16, 10486, 25367, 'transit',
{ 'kind': 'monorail' })
## Instruction:
Add test for funicular feature
## Code After:
assert_has_feature(
16, 10486, 25367, 'transit',
{ 'kind': 'monorail' })
# relation 6060405
assert_has_feature(
16, 18201, 24705, 'transit',
{ 'kind': 'funicular' })
| assert_has_feature(
16, 10486, 25367, 'transit',
{ 'kind': 'monorail' })
+
+ # relation 6060405
+ assert_has_feature(
+ 16, 18201, 24705, 'transit',
+ { 'kind': 'funicular' }) |
18f9771b5a02621c94b882042547dc2db751e134 | open511/utils/geojson.py | open511/utils/geojson.py | import json
from lxml import etree
GML_NS = 'http://www.opengis.net/gml'
def geojson_to_gml(gj):
"""Given a dict deserialized from a GeoJSON object, returns an lxml Element
of the corresponding GML geometry."""
if gj['type'] == 'Point':
coords = ','.join(str(c) for c in gj['coordinates'])
elif gj['type'] == 'LineString':
coords = ' '.join(
','.join(str(c) for c in ll)
for ll in gj['coordinates']
)
else:
raise NotImplementedError
tag = etree.Element('{%s}%s' % (GML_NS, gj['type']))
coord_tag = etree.Element('{%s}coordinates' % GML_NS)
coord_tag.text = coords
tag.set('srsName', 'EPSG:4326')
tag.append(coord_tag)
return tag
def gml_to_geojson(el):
"""Given an lxml Element of a GML geometry, returns a dict in GeoJSON format."""
# FIXME implement in python, at least for Point / LineString
from open511.utils.postgis import pg_gml_to_geojson
return json.loads(pg_gml_to_geojson(etree.tostring(el)))
| import json
from lxml import etree
GML_NS = 'http://www.opengis.net/gml'
def geojson_to_gml(gj):
"""Given a dict deserialized from a GeoJSON object, returns an lxml Element
of the corresponding GML geometry."""
if gj['type'] == 'Point':
coords = ','.join(str(c) for c in gj['coordinates'])
elif gj['type'] == 'LineString':
coords = ' '.join(
','.join(str(c) for c in ll)
for ll in gj['coordinates']
)
else:
raise NotImplementedError
tag = etree.Element('{%s}%s' % (GML_NS, gj['type']))
coord_tag = etree.Element('{%s}coordinates' % GML_NS)
coord_tag.text = coords
tag.set('srsName', 'EPSG:4326')
tag.append(coord_tag)
return tag
def gml_to_geojson(el):
"""Given an lxml Element of a GML geometry, returns a dict in GeoJSON format."""
coords = el.findtext('{%s}coordinates' % GML_NS)
if el.tag.endswith('Point'):
return {
'type': 'Point',
'coordinates': [float(c) for c in coords.split(',')]
}
elif el.tag.endswith('LineString'):
return {
'type': 'LineString',
'coordinates': [
[float(x) for x in pair.split(',')]
for pair in coords.split(' ')
]
}
else:
from open511.utils.postgis import pg_gml_to_geojson
return json.loads(pg_gml_to_geojson(etree.tostring(el)))
| Implement some GML-to-GeoJSON logic in Python | Implement some GML-to-GeoJSON logic in Python
| Python | mit | Open511/open511-server,Open511/open511-server,Open511/open511-server | import json
from lxml import etree
GML_NS = 'http://www.opengis.net/gml'
def geojson_to_gml(gj):
"""Given a dict deserialized from a GeoJSON object, returns an lxml Element
of the corresponding GML geometry."""
if gj['type'] == 'Point':
coords = ','.join(str(c) for c in gj['coordinates'])
elif gj['type'] == 'LineString':
coords = ' '.join(
','.join(str(c) for c in ll)
for ll in gj['coordinates']
)
else:
raise NotImplementedError
tag = etree.Element('{%s}%s' % (GML_NS, gj['type']))
coord_tag = etree.Element('{%s}coordinates' % GML_NS)
coord_tag.text = coords
tag.set('srsName', 'EPSG:4326')
tag.append(coord_tag)
return tag
+
def gml_to_geojson(el):
"""Given an lxml Element of a GML geometry, returns a dict in GeoJSON format."""
- # FIXME implement in python, at least for Point / LineString
+ coords = el.findtext('{%s}coordinates' % GML_NS)
+ if el.tag.endswith('Point'):
+ return {
+ 'type': 'Point',
+ 'coordinates': [float(c) for c in coords.split(',')]
+ }
+ elif el.tag.endswith('LineString'):
+ return {
+ 'type': 'LineString',
+ 'coordinates': [
+ [float(x) for x in pair.split(',')]
+ for pair in coords.split(' ')
+ ]
+ }
+ else:
- from open511.utils.postgis import pg_gml_to_geojson
+ from open511.utils.postgis import pg_gml_to_geojson
- return json.loads(pg_gml_to_geojson(etree.tostring(el)))
+ return json.loads(pg_gml_to_geojson(etree.tostring(el)))
| Implement some GML-to-GeoJSON logic in Python | ## Code Before:
import json
from lxml import etree
GML_NS = 'http://www.opengis.net/gml'
def geojson_to_gml(gj):
"""Given a dict deserialized from a GeoJSON object, returns an lxml Element
of the corresponding GML geometry."""
if gj['type'] == 'Point':
coords = ','.join(str(c) for c in gj['coordinates'])
elif gj['type'] == 'LineString':
coords = ' '.join(
','.join(str(c) for c in ll)
for ll in gj['coordinates']
)
else:
raise NotImplementedError
tag = etree.Element('{%s}%s' % (GML_NS, gj['type']))
coord_tag = etree.Element('{%s}coordinates' % GML_NS)
coord_tag.text = coords
tag.set('srsName', 'EPSG:4326')
tag.append(coord_tag)
return tag
def gml_to_geojson(el):
"""Given an lxml Element of a GML geometry, returns a dict in GeoJSON format."""
# FIXME implement in python, at least for Point / LineString
from open511.utils.postgis import pg_gml_to_geojson
return json.loads(pg_gml_to_geojson(etree.tostring(el)))
## Instruction:
Implement some GML-to-GeoJSON logic in Python
## Code After:
import json
from lxml import etree
GML_NS = 'http://www.opengis.net/gml'
def geojson_to_gml(gj):
"""Given a dict deserialized from a GeoJSON object, returns an lxml Element
of the corresponding GML geometry."""
if gj['type'] == 'Point':
coords = ','.join(str(c) for c in gj['coordinates'])
elif gj['type'] == 'LineString':
coords = ' '.join(
','.join(str(c) for c in ll)
for ll in gj['coordinates']
)
else:
raise NotImplementedError
tag = etree.Element('{%s}%s' % (GML_NS, gj['type']))
coord_tag = etree.Element('{%s}coordinates' % GML_NS)
coord_tag.text = coords
tag.set('srsName', 'EPSG:4326')
tag.append(coord_tag)
return tag
def gml_to_geojson(el):
"""Given an lxml Element of a GML geometry, returns a dict in GeoJSON format."""
coords = el.findtext('{%s}coordinates' % GML_NS)
if el.tag.endswith('Point'):
return {
'type': 'Point',
'coordinates': [float(c) for c in coords.split(',')]
}
elif el.tag.endswith('LineString'):
return {
'type': 'LineString',
'coordinates': [
[float(x) for x in pair.split(',')]
for pair in coords.split(' ')
]
}
else:
from open511.utils.postgis import pg_gml_to_geojson
return json.loads(pg_gml_to_geojson(etree.tostring(el)))
| import json
from lxml import etree
GML_NS = 'http://www.opengis.net/gml'
def geojson_to_gml(gj):
"""Given a dict deserialized from a GeoJSON object, returns an lxml Element
of the corresponding GML geometry."""
if gj['type'] == 'Point':
coords = ','.join(str(c) for c in gj['coordinates'])
elif gj['type'] == 'LineString':
coords = ' '.join(
','.join(str(c) for c in ll)
for ll in gj['coordinates']
)
else:
raise NotImplementedError
tag = etree.Element('{%s}%s' % (GML_NS, gj['type']))
coord_tag = etree.Element('{%s}coordinates' % GML_NS)
coord_tag.text = coords
tag.set('srsName', 'EPSG:4326')
tag.append(coord_tag)
return tag
+
def gml_to_geojson(el):
"""Given an lxml Element of a GML geometry, returns a dict in GeoJSON format."""
- # FIXME implement in python, at least for Point / LineString
+ coords = el.findtext('{%s}coordinates' % GML_NS)
+ if el.tag.endswith('Point'):
+ return {
+ 'type': 'Point',
+ 'coordinates': [float(c) for c in coords.split(',')]
+ }
+ elif el.tag.endswith('LineString'):
+ return {
+ 'type': 'LineString',
+ 'coordinates': [
+ [float(x) for x in pair.split(',')]
+ for pair in coords.split(' ')
+ ]
+ }
+ else:
- from open511.utils.postgis import pg_gml_to_geojson
+ from open511.utils.postgis import pg_gml_to_geojson
? ++++
- return json.loads(pg_gml_to_geojson(etree.tostring(el)))
+ return json.loads(pg_gml_to_geojson(etree.tostring(el)))
? ++++
|
51781b95b629a31107d16a52b0ea184306fe6163 | pyfakefs/pytest_plugin.py | pyfakefs/pytest_plugin.py |
import linecache
import py
import pytest
from pyfakefs.fake_filesystem_unittest import Patcher
try:
import builtins
except ImportError:
import __builtin__ as builtins
Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem
# The "linecache" module is used to read the test file in case of test failure
# to get traceback information before test tear down.
# In order to make sure that reading the test file is not faked,
# we both skip faking the module, and add the build-in open() function
# as a local function in the module
Patcher.SKIPMODULES.add(linecache)
linecache.open = builtins.open
@pytest.fixture
def fs(request):
""" Fake filesystem. """
patcher = Patcher()
patcher.setUp()
request.addfinalizer(patcher.tearDown)
return patcher.fs
|
import linecache
import sys
import py
import pytest
from pyfakefs.fake_filesystem_unittest import Patcher
if sys.version_info >= (3,):
import builtins
else:
import __builtin__ as builtins
Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem
# The "linecache" module is used to read the test file in case of test failure
# to get traceback information before test tear down.
# In order to make sure that reading the test file is not faked,
# we both skip faking the module, and add the build-in open() function
# as a local function in the module
Patcher.SKIPMODULES.add(linecache)
linecache.open = builtins.open
@pytest.fixture
def fs(request):
""" Fake filesystem. """
patcher = Patcher()
patcher.setUp()
request.addfinalizer(patcher.tearDown)
return patcher.fs
| Fix pytest when pyfakefs + future is installed | Fix pytest when pyfakefs + future is installed
`python-future` is notorious for breaking modules which use `try:` / `except:`
to import modules based on version. In this case, `pyfakefs` imported the
backported `builtins` module which changes the semantics of the `open()`
function. `pyfakefs` then monkeypatches `linecache` which breaks any module
which attempts to use `linecache` (in this case `pytest`).
The downstream issue is https://github.com/pytest-dev/pytest/pull/4074
| Python | apache-2.0 | mrbean-bremen/pyfakefs,mrbean-bremen/pyfakefs,pytest-dev/pyfakefs,jmcgeheeiv/pyfakefs |
import linecache
+ import sys
import py
import pytest
from pyfakefs.fake_filesystem_unittest import Patcher
- try:
+ if sys.version_info >= (3,):
import builtins
- except ImportError:
+ else:
import __builtin__ as builtins
Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem
# The "linecache" module is used to read the test file in case of test failure
# to get traceback information before test tear down.
# In order to make sure that reading the test file is not faked,
# we both skip faking the module, and add the build-in open() function
# as a local function in the module
Patcher.SKIPMODULES.add(linecache)
linecache.open = builtins.open
@pytest.fixture
def fs(request):
""" Fake filesystem. """
patcher = Patcher()
patcher.setUp()
request.addfinalizer(patcher.tearDown)
return patcher.fs
| Fix pytest when pyfakefs + future is installed | ## Code Before:
import linecache
import py
import pytest
from pyfakefs.fake_filesystem_unittest import Patcher
try:
import builtins
except ImportError:
import __builtin__ as builtins
Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem
# The "linecache" module is used to read the test file in case of test failure
# to get traceback information before test tear down.
# In order to make sure that reading the test file is not faked,
# we both skip faking the module, and add the build-in open() function
# as a local function in the module
Patcher.SKIPMODULES.add(linecache)
linecache.open = builtins.open
@pytest.fixture
def fs(request):
""" Fake filesystem. """
patcher = Patcher()
patcher.setUp()
request.addfinalizer(patcher.tearDown)
return patcher.fs
## Instruction:
Fix pytest when pyfakefs + future is installed
## Code After:
import linecache
import sys
import py
import pytest
from pyfakefs.fake_filesystem_unittest import Patcher
if sys.version_info >= (3,):
import builtins
else:
import __builtin__ as builtins
Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem
# The "linecache" module is used to read the test file in case of test failure
# to get traceback information before test tear down.
# In order to make sure that reading the test file is not faked,
# we both skip faking the module, and add the build-in open() function
# as a local function in the module
Patcher.SKIPMODULES.add(linecache)
linecache.open = builtins.open
@pytest.fixture
def fs(request):
""" Fake filesystem. """
patcher = Patcher()
patcher.setUp()
request.addfinalizer(patcher.tearDown)
return patcher.fs
|
import linecache
+ import sys
import py
import pytest
from pyfakefs.fake_filesystem_unittest import Patcher
- try:
+ if sys.version_info >= (3,):
import builtins
- except ImportError:
+ else:
import __builtin__ as builtins
Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem
# The "linecache" module is used to read the test file in case of test failure
# to get traceback information before test tear down.
# In order to make sure that reading the test file is not faked,
# we both skip faking the module, and add the build-in open() function
# as a local function in the module
Patcher.SKIPMODULES.add(linecache)
linecache.open = builtins.open
@pytest.fixture
def fs(request):
""" Fake filesystem. """
patcher = Patcher()
patcher.setUp()
request.addfinalizer(patcher.tearDown)
return patcher.fs |
aa3134912af3e57362310eb486d0f4e1d8660d0c | grains/grains.py | grains/grains.py | import itertools
square = [x for x in range(1, 65)]
grains = [2 ** x for x in range(0, 65)]
board = dict(zip(square, grains))
def on_square(num):
for k, v in board.iteritems():
if k == num:
return v
def total_after(num):
if num == 1:
return 1
else:
for k, v in board.iteritems():
if k == num:
total_after = sum(map(board.get, itertools.takewhile(lambda key: key != v, board)))
return total_after
print (board)
print (total_after(1))
print(on_square(1))
|
square = [x for x in range(1, 65)]
grains = [2 ** x for x in range(0, 65)]
board = dict(zip(square, grains))
def on_square(num):
for k, v in board.iteritems():
if k == num:
return v
def total_after(num):
total = 0
for i in range(1, num+1):
total += on_square(i)
return total
| Reformat total_after function + Remove itertools | Reformat total_after function + Remove itertools
| Python | mit | amalshehu/exercism-python | - import itertools
square = [x for x in range(1, 65)]
grains = [2 ** x for x in range(0, 65)]
board = dict(zip(square, grains))
def on_square(num):
for k, v in board.iteritems():
if k == num:
return v
def total_after(num):
+ total = 0
+ for i in range(1, num+1):
+ total += on_square(i)
- if num == 1:
- return 1
- else:
- for k, v in board.iteritems():
- if k == num:
- total_after = sum(map(board.get, itertools.takewhile(lambda key: key != v, board)))
- return total_after
+ return total
- print (board)
- print (total_after(1))
- print(on_square(1))
- | Reformat total_after function + Remove itertools | ## Code Before:
import itertools
square = [x for x in range(1, 65)]
grains = [2 ** x for x in range(0, 65)]
board = dict(zip(square, grains))
def on_square(num):
for k, v in board.iteritems():
if k == num:
return v
def total_after(num):
if num == 1:
return 1
else:
for k, v in board.iteritems():
if k == num:
total_after = sum(map(board.get, itertools.takewhile(lambda key: key != v, board)))
return total_after
print (board)
print (total_after(1))
print(on_square(1))
## Instruction:
Reformat total_after function + Remove itertools
## Code After:
square = [x for x in range(1, 65)]
grains = [2 ** x for x in range(0, 65)]
board = dict(zip(square, grains))
def on_square(num):
for k, v in board.iteritems():
if k == num:
return v
def total_after(num):
total = 0
for i in range(1, num+1):
total += on_square(i)
return total
| - import itertools
square = [x for x in range(1, 65)]
grains = [2 ** x for x in range(0, 65)]
board = dict(zip(square, grains))
def on_square(num):
for k, v in board.iteritems():
if k == num:
return v
def total_after(num):
+ total = 0
+ for i in range(1, num+1):
+ total += on_square(i)
- if num == 1:
- return 1
- else:
- for k, v in board.iteritems():
- if k == num:
- total_after = sum(map(board.get, itertools.takewhile(lambda key: key != v, board)))
- return total_after
? ------
+ return total
-
- print (board)
- print (total_after(1))
- print(on_square(1)) |
376b327379caeb0845007c3a0e7c33e1f15869f0 | flatisfy/constants.py | flatisfy/constants.py | from __future__ import absolute_import, print_function, unicode_literals
# Some backends give more infos than others. Here is the precedence we want to
# use. First is most important one, last is the one that will always be
# considered as less trustable if two backends have similar info about a
# housing.
BACKENDS_BY_PRECEDENCE = [
"foncia",
"seloger",
"pap",
"leboncoin",
"explorimmo",
"logicimmo",
"entreparticuliers"
]
| from __future__ import absolute_import, print_function, unicode_literals
# Some backends give more infos than others. Here is the precedence we want to
# use. First is most important one, last is the one that will always be
# considered as less trustable if two backends have similar info about a
# housing.
BACKENDS_BY_PRECEDENCE = [
"foncia",
"seloger",
"pap",
"leboncoin",
"explorimmo",
"logicimmo"
]
| Drop support for entreparticuliers Weboob module | Drop support for entreparticuliers Weboob module
| Python | mit | Phyks/Flatisfy,Phyks/Flatisfy,Phyks/Flatisfy,Phyks/Flatisfy | from __future__ import absolute_import, print_function, unicode_literals
# Some backends give more infos than others. Here is the precedence we want to
# use. First is most important one, last is the one that will always be
# considered as less trustable if two backends have similar info about a
# housing.
BACKENDS_BY_PRECEDENCE = [
"foncia",
"seloger",
"pap",
"leboncoin",
"explorimmo",
- "logicimmo",
+ "logicimmo"
- "entreparticuliers"
]
| Drop support for entreparticuliers Weboob module | ## Code Before:
from __future__ import absolute_import, print_function, unicode_literals
# Some backends give more infos than others. Here is the precedence we want to
# use. First is most important one, last is the one that will always be
# considered as less trustable if two backends have similar info about a
# housing.
BACKENDS_BY_PRECEDENCE = [
"foncia",
"seloger",
"pap",
"leboncoin",
"explorimmo",
"logicimmo",
"entreparticuliers"
]
## Instruction:
Drop support for entreparticuliers Weboob module
## Code After:
from __future__ import absolute_import, print_function, unicode_literals
# Some backends give more infos than others. Here is the precedence we want to
# use. First is most important one, last is the one that will always be
# considered as less trustable if two backends have similar info about a
# housing.
BACKENDS_BY_PRECEDENCE = [
"foncia",
"seloger",
"pap",
"leboncoin",
"explorimmo",
"logicimmo"
]
| from __future__ import absolute_import, print_function, unicode_literals
# Some backends give more infos than others. Here is the precedence we want to
# use. First is most important one, last is the one that will always be
# considered as less trustable if two backends have similar info about a
# housing.
BACKENDS_BY_PRECEDENCE = [
"foncia",
"seloger",
"pap",
"leboncoin",
"explorimmo",
- "logicimmo",
? -
+ "logicimmo"
- "entreparticuliers"
] |
744c995ffe1faf55fda68405243551dbb078ae60 | uchicagohvz/production_settings.py | uchicagohvz/production_settings.py | from local_settings import *
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uchicagohvz', # Or path to database file if using sqlite3.
'USER': 'user', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# REST framework settings
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
# Mandrill email settings
EMAIL_HOST = 'smtp.mandrillapp.com'
from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD
EMAIL_PORT = '587'
EMAIL_USE_TLS = True | from local_settings import *
ALLOWED_HOSTS = ['uchicagohvz.org']
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uchicagohvz', # Or path to database file if using sqlite3.
'USER': 'user', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# REST framework settings
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
# Mandrill email settings
EMAIL_HOST = 'smtp.mandrillapp.com'
from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD
EMAIL_PORT = '587'
EMAIL_USE_TLS = True | Add ALLOWED_HOSTS to production settings | Add ALLOWED_HOSTS to production settings
| Python | mit | kz26/uchicago-hvz,kz26/uchicago-hvz,kz26/uchicago-hvz | from local_settings import *
+
+ ALLOWED_HOSTS = ['uchicagohvz.org']
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uchicagohvz', # Or path to database file if using sqlite3.
'USER': 'user', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# REST framework settings
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
# Mandrill email settings
EMAIL_HOST = 'smtp.mandrillapp.com'
from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD
EMAIL_PORT = '587'
EMAIL_USE_TLS = True | Add ALLOWED_HOSTS to production settings | ## Code Before:
from local_settings import *
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uchicagohvz', # Or path to database file if using sqlite3.
'USER': 'user', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# REST framework settings
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
# Mandrill email settings
EMAIL_HOST = 'smtp.mandrillapp.com'
from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD
EMAIL_PORT = '587'
EMAIL_USE_TLS = True
## Instruction:
Add ALLOWED_HOSTS to production settings
## Code After:
from local_settings import *
ALLOWED_HOSTS = ['uchicagohvz.org']
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uchicagohvz', # Or path to database file if using sqlite3.
'USER': 'user', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# REST framework settings
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
# Mandrill email settings
EMAIL_HOST = 'smtp.mandrillapp.com'
from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD
EMAIL_PORT = '587'
EMAIL_USE_TLS = True | from local_settings import *
+
+ ALLOWED_HOSTS = ['uchicagohvz.org']
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uchicagohvz', # Or path to database file if using sqlite3.
'USER': 'user', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# REST framework settings
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
# Mandrill email settings
EMAIL_HOST = 'smtp.mandrillapp.com'
from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD
EMAIL_PORT = '587'
EMAIL_USE_TLS = True |
47b4779b82035d0478985c85c3e7e95581ef8efe | CodeFights/arrayPacking.py | CodeFights/arrayPacking.py |
def arrayPacking():
pass
def main():
tests = [
[],
[]
]
for t in tests:
res = arrayPacking(t[0])
if t[1] == res:
print("PASSED: arrayPacking({}) returned {}"
.format(t[0], res))
else:
print(("FAILED: arrayPacking({}) returned {},"
"answer: {}").format(t[0], res, t[1]))
if __name__ == '__main__':
main()
|
def arrayPacking(a):
return sum([n << 8*i for i, n in enumerate(a)])
def main():
tests = [
[[24, 85, 0], 21784],
[[23, 45, 39], 2567447]
]
for t in tests:
res = arrayPacking(t[0])
if t[1] == res:
print("PASSED: arrayPacking({}) returned {}"
.format(t[0], res))
else:
print(("FAILED: arrayPacking({}) returned {},"
"answer: {}").format(t[0], res, t[1]))
if __name__ == '__main__':
main()
| Solve Code Fights array packing problem | Solve Code Fights array packing problem
| Python | mit | HKuz/Test_Code |
- def arrayPacking():
+ def arrayPacking(a):
- pass
+ return sum([n << 8*i for i, n in enumerate(a)])
def main():
tests = [
- [],
- []
+ [[24, 85, 0], 21784],
+ [[23, 45, 39], 2567447]
]
for t in tests:
res = arrayPacking(t[0])
if t[1] == res:
print("PASSED: arrayPacking({}) returned {}"
.format(t[0], res))
else:
print(("FAILED: arrayPacking({}) returned {},"
"answer: {}").format(t[0], res, t[1]))
if __name__ == '__main__':
main()
| Solve Code Fights array packing problem | ## Code Before:
def arrayPacking():
pass
def main():
tests = [
[],
[]
]
for t in tests:
res = arrayPacking(t[0])
if t[1] == res:
print("PASSED: arrayPacking({}) returned {}"
.format(t[0], res))
else:
print(("FAILED: arrayPacking({}) returned {},"
"answer: {}").format(t[0], res, t[1]))
if __name__ == '__main__':
main()
## Instruction:
Solve Code Fights array packing problem
## Code After:
def arrayPacking(a):
return sum([n << 8*i for i, n in enumerate(a)])
def main():
tests = [
[[24, 85, 0], 21784],
[[23, 45, 39], 2567447]
]
for t in tests:
res = arrayPacking(t[0])
if t[1] == res:
print("PASSED: arrayPacking({}) returned {}"
.format(t[0], res))
else:
print(("FAILED: arrayPacking({}) returned {},"
"answer: {}").format(t[0], res, t[1]))
if __name__ == '__main__':
main()
|
- def arrayPacking():
+ def arrayPacking(a):
? +
- pass
+ return sum([n << 8*i for i, n in enumerate(a)])
def main():
tests = [
- [],
- []
+ [[24, 85, 0], 21784],
+ [[23, 45, 39], 2567447]
]
for t in tests:
res = arrayPacking(t[0])
if t[1] == res:
print("PASSED: arrayPacking({}) returned {}"
.format(t[0], res))
else:
print(("FAILED: arrayPacking({}) returned {},"
"answer: {}").format(t[0], res, t[1]))
if __name__ == '__main__':
main() |
ec24e051e9d10b4cb24d135a3c08e9e9f87c6b8c | social/apps/django_app/utils.py | social/apps/django_app/utils.py | from functools import wraps
from django.conf import settings
from django.core.urlresolvers import reverse
from social.utils import setting_name, module_member
from social.strategies.utils import get_strategy
BACKENDS = settings.AUTHENTICATION_BACKENDS
STRATEGY = getattr(settings, setting_name('STRATEGY'),
'social.strategies.django_strategy.DjangoStrategy')
STORAGE = getattr(settings, setting_name('STORAGE'),
'social.apps.django_app.default.models.DjangoStorage')
Strategy = module_member(STRATEGY)
Storage = module_member(STORAGE)
def load_strategy(*args, **kwargs):
return get_strategy(BACKENDS, STRATEGY, STORAGE, *args, **kwargs)
def strategy(redirect_uri=None):
def decorator(func):
@wraps(func)
def wrapper(request, backend, *args, **kwargs):
uri = redirect_uri
if uri and not uri.startswith('/'):
uri = reverse(redirect_uri, args=(backend,))
request.strategy = load_strategy(request=request, backend=backend,
redirect_uri=uri, *args, **kwargs)
return func(request, backend, *args, **kwargs)
return wrapper
return decorator
def setting(name, default=None):
try:
return getattr(settings, setting_name(name))
except AttributeError:
return getattr(settings, name, default)
class BackendWrapper(object):
def get_user(self, user_id):
return Strategy(storage=Storage).get_user(user_id)
| from functools import wraps
from django.conf import settings
from django.core.urlresolvers import reverse
from social.utils import setting_name, module_member
from social.strategies.utils import get_strategy
BACKENDS = settings.AUTHENTICATION_BACKENDS
STRATEGY = getattr(settings, setting_name('STRATEGY'),
'social.strategies.django_strategy.DjangoStrategy')
STORAGE = getattr(settings, setting_name('STORAGE'),
'social.apps.django_app.default.models.DjangoStorage')
Strategy = module_member(STRATEGY)
Storage = module_member(STORAGE)
def load_strategy(*args, **kwargs):
return get_strategy(BACKENDS, STRATEGY, STORAGE, *args, **kwargs)
def strategy(redirect_uri=None, load_strategy=load_strategy):
def decorator(func):
@wraps(func)
def wrapper(request, backend, *args, **kwargs):
uri = redirect_uri
if uri and not uri.startswith('/'):
uri = reverse(redirect_uri, args=(backend,))
request.strategy = load_strategy(request=request, backend=backend,
redirect_uri=uri, *args, **kwargs)
return func(request, backend, *args, **kwargs)
return wrapper
return decorator
def setting(name, default=None):
try:
return getattr(settings, setting_name(name))
except AttributeError:
return getattr(settings, name, default)
class BackendWrapper(object):
def get_user(self, user_id):
return Strategy(storage=Storage).get_user(user_id)
| Allow to override strategy getter | Allow to override strategy getter
| Python | bsd-3-clause | fearlessspider/python-social-auth,MSOpenTech/python-social-auth,clef/python-social-auth,JJediny/python-social-auth,firstjob/python-social-auth,muhammad-ammar/python-social-auth,henocdz/python-social-auth,ariestiyansyah/python-social-auth,python-social-auth/social-app-django,falcon1kr/python-social-auth,lamby/python-social-auth,joelstanner/python-social-auth,rsteca/python-social-auth,falcon1kr/python-social-auth,lneoe/python-social-auth,wildtetris/python-social-auth,mchdks/python-social-auth,ononeor12/python-social-auth,frankier/python-social-auth,michael-borisov/python-social-auth,ariestiyansyah/python-social-auth,jameslittle/python-social-auth,mark-adams/python-social-auth,wildtetris/python-social-auth,garrett-schlesinger/python-social-auth,jameslittle/python-social-auth,lamby/python-social-auth,jeyraof/python-social-auth,rsalmaso/python-social-auth,bjorand/python-social-auth,Andygmb/python-social-auth,mark-adams/python-social-auth,VishvajitP/python-social-auth,fearlessspider/python-social-auth,JerzySpendel/python-social-auth,garrett-schlesinger/python-social-auth,mathspace/python-social-auth,rsteca/python-social-auth,nirmalvp/python-social-auth,python-social-auth/social-core,henocdz/python-social-auth,lneoe/python-social-auth,S01780/python-social-auth,jneves/python-social-auth,barseghyanartur/python-social-auth,tobias47n9e/social-core,bjorand/python-social-auth,wildtetris/python-social-auth,msampathkumar/python-social-auth,bjorand/python-social-auth,yprez/python-social-auth,lawrence34/python-social-auth,daniula/python-social-auth,jeyraof/python-social-auth,JJediny/python-social-auth,Andygmb/python-social-auth,hsr-ba-fs15-dat/python-social-auth,MSOpenTech/python-social-auth,DhiaEddineSaidi/python-social-auth,hsr-ba-fs15-dat/python-social-auth,tutumcloud/python-social-auth,chandolia/python-social-auth,jameslittle/python-social-auth,noodle-learns-programming/python-social-auth,imsparsh/python-social-auth,mark-adams/python-social-auth,Andygmb/python-social-auth,lawrence34/python-social-auth,barseghyanartur/python-social-auth,daniula/python-social-auth,jeyraof/python-social-auth,falcon1kr/python-social-auth,tkajtoch/python-social-auth,mathspace/python-social-auth,contracode/python-social-auth,lawrence34/python-social-auth,mathspace/python-social-auth,ononeor12/python-social-auth,robbiet480/python-social-auth,iruga090/python-social-auth,fearlessspider/python-social-auth,webjunkie/python-social-auth,clef/python-social-auth,mrwags/python-social-auth,chandolia/python-social-auth,rsteca/python-social-auth,muhammad-ammar/python-social-auth,jneves/python-social-auth,SeanHayes/python-social-auth,S01780/python-social-auth,webjunkie/python-social-auth,ByteInternet/python-social-auth,nvbn/python-social-auth,ononeor12/python-social-auth,S01780/python-social-auth,merutak/python-social-auth,ByteInternet/python-social-auth,noodle-learns-programming/python-social-auth,JerzySpendel/python-social-auth,cmichal/python-social-auth,mchdks/python-social-auth,drxos/python-social-auth,JerzySpendel/python-social-auth,cmichal/python-social-auth,joelstanner/python-social-auth,python-social-auth/social-app-cherrypy,alrusdi/python-social-auth,mrwags/python-social-auth,python-social-auth/social-storage-sqlalchemy,cjltsod/python-social-auth,cjltsod/python-social-auth,degs098/python-social-auth,python-social-auth/social-app-django,contracode/python-social-auth,DhiaEddineSaidi/python-social-auth,imsparsh/python-social-auth,clef/python-social-auth,firstjob/python-social-auth,degs098/python-social-auth,michael-borisov/python-social-auth,lneoe/python-social-auth,nvbn/python-social-auth,drxos/python-social-auth,san-mate/python-social-auth,msampathkumar/python-social-auth,nirmalvp/python-social-auth,rsalmaso/python-social-auth,iruga090/python-social-auth,tkajtoch/python-social-auth,tutumcloud/python-social-auth,python-social-auth/social-core,degs098/python-social-auth,VishvajitP/python-social-auth,mrwags/python-social-auth,michael-borisov/python-social-auth,robbiet480/python-social-auth,henocdz/python-social-auth,barseghyanartur/python-social-auth,hsr-ba-fs15-dat/python-social-auth,ariestiyansyah/python-social-auth,frankier/python-social-auth,joelstanner/python-social-auth,MSOpenTech/python-social-auth,yprez/python-social-auth,yprez/python-social-auth,muhammad-ammar/python-social-auth,alrusdi/python-social-auth,VishvajitP/python-social-auth,webjunkie/python-social-auth,cmichal/python-social-auth,jneves/python-social-auth,tkajtoch/python-social-auth,JJediny/python-social-auth,nirmalvp/python-social-auth,noodle-learns-programming/python-social-auth,lamby/python-social-auth,iruga090/python-social-auth,alrusdi/python-social-auth,merutak/python-social-auth,mchdks/python-social-auth,SeanHayes/python-social-auth,drxos/python-social-auth,ByteInternet/python-social-auth,msampathkumar/python-social-auth,contracode/python-social-auth,daniula/python-social-auth,python-social-auth/social-docs,firstjob/python-social-auth,duoduo369/python-social-auth,san-mate/python-social-auth,robbiet480/python-social-auth,python-social-auth/social-app-django,imsparsh/python-social-auth,merutak/python-social-auth,duoduo369/python-social-auth,DhiaEddineSaidi/python-social-auth,chandolia/python-social-auth,san-mate/python-social-auth | from functools import wraps
from django.conf import settings
from django.core.urlresolvers import reverse
from social.utils import setting_name, module_member
from social.strategies.utils import get_strategy
BACKENDS = settings.AUTHENTICATION_BACKENDS
STRATEGY = getattr(settings, setting_name('STRATEGY'),
'social.strategies.django_strategy.DjangoStrategy')
STORAGE = getattr(settings, setting_name('STORAGE'),
'social.apps.django_app.default.models.DjangoStorage')
Strategy = module_member(STRATEGY)
Storage = module_member(STORAGE)
def load_strategy(*args, **kwargs):
return get_strategy(BACKENDS, STRATEGY, STORAGE, *args, **kwargs)
- def strategy(redirect_uri=None):
+ def strategy(redirect_uri=None, load_strategy=load_strategy):
def decorator(func):
@wraps(func)
def wrapper(request, backend, *args, **kwargs):
uri = redirect_uri
if uri and not uri.startswith('/'):
uri = reverse(redirect_uri, args=(backend,))
request.strategy = load_strategy(request=request, backend=backend,
redirect_uri=uri, *args, **kwargs)
return func(request, backend, *args, **kwargs)
return wrapper
return decorator
def setting(name, default=None):
try:
return getattr(settings, setting_name(name))
except AttributeError:
return getattr(settings, name, default)
class BackendWrapper(object):
def get_user(self, user_id):
return Strategy(storage=Storage).get_user(user_id)
| Allow to override strategy getter | ## Code Before:
from functools import wraps
from django.conf import settings
from django.core.urlresolvers import reverse
from social.utils import setting_name, module_member
from social.strategies.utils import get_strategy
BACKENDS = settings.AUTHENTICATION_BACKENDS
STRATEGY = getattr(settings, setting_name('STRATEGY'),
'social.strategies.django_strategy.DjangoStrategy')
STORAGE = getattr(settings, setting_name('STORAGE'),
'social.apps.django_app.default.models.DjangoStorage')
Strategy = module_member(STRATEGY)
Storage = module_member(STORAGE)
def load_strategy(*args, **kwargs):
return get_strategy(BACKENDS, STRATEGY, STORAGE, *args, **kwargs)
def strategy(redirect_uri=None):
def decorator(func):
@wraps(func)
def wrapper(request, backend, *args, **kwargs):
uri = redirect_uri
if uri and not uri.startswith('/'):
uri = reverse(redirect_uri, args=(backend,))
request.strategy = load_strategy(request=request, backend=backend,
redirect_uri=uri, *args, **kwargs)
return func(request, backend, *args, **kwargs)
return wrapper
return decorator
def setting(name, default=None):
try:
return getattr(settings, setting_name(name))
except AttributeError:
return getattr(settings, name, default)
class BackendWrapper(object):
def get_user(self, user_id):
return Strategy(storage=Storage).get_user(user_id)
## Instruction:
Allow to override strategy getter
## Code After:
from functools import wraps
from django.conf import settings
from django.core.urlresolvers import reverse
from social.utils import setting_name, module_member
from social.strategies.utils import get_strategy
BACKENDS = settings.AUTHENTICATION_BACKENDS
STRATEGY = getattr(settings, setting_name('STRATEGY'),
'social.strategies.django_strategy.DjangoStrategy')
STORAGE = getattr(settings, setting_name('STORAGE'),
'social.apps.django_app.default.models.DjangoStorage')
Strategy = module_member(STRATEGY)
Storage = module_member(STORAGE)
def load_strategy(*args, **kwargs):
return get_strategy(BACKENDS, STRATEGY, STORAGE, *args, **kwargs)
def strategy(redirect_uri=None, load_strategy=load_strategy):
def decorator(func):
@wraps(func)
def wrapper(request, backend, *args, **kwargs):
uri = redirect_uri
if uri and not uri.startswith('/'):
uri = reverse(redirect_uri, args=(backend,))
request.strategy = load_strategy(request=request, backend=backend,
redirect_uri=uri, *args, **kwargs)
return func(request, backend, *args, **kwargs)
return wrapper
return decorator
def setting(name, default=None):
try:
return getattr(settings, setting_name(name))
except AttributeError:
return getattr(settings, name, default)
class BackendWrapper(object):
def get_user(self, user_id):
return Strategy(storage=Storage).get_user(user_id)
| from functools import wraps
from django.conf import settings
from django.core.urlresolvers import reverse
from social.utils import setting_name, module_member
from social.strategies.utils import get_strategy
BACKENDS = settings.AUTHENTICATION_BACKENDS
STRATEGY = getattr(settings, setting_name('STRATEGY'),
'social.strategies.django_strategy.DjangoStrategy')
STORAGE = getattr(settings, setting_name('STORAGE'),
'social.apps.django_app.default.models.DjangoStorage')
Strategy = module_member(STRATEGY)
Storage = module_member(STORAGE)
def load_strategy(*args, **kwargs):
return get_strategy(BACKENDS, STRATEGY, STORAGE, *args, **kwargs)
- def strategy(redirect_uri=None):
+ def strategy(redirect_uri=None, load_strategy=load_strategy):
def decorator(func):
@wraps(func)
def wrapper(request, backend, *args, **kwargs):
uri = redirect_uri
if uri and not uri.startswith('/'):
uri = reverse(redirect_uri, args=(backend,))
request.strategy = load_strategy(request=request, backend=backend,
redirect_uri=uri, *args, **kwargs)
return func(request, backend, *args, **kwargs)
return wrapper
return decorator
def setting(name, default=None):
try:
return getattr(settings, setting_name(name))
except AttributeError:
return getattr(settings, name, default)
class BackendWrapper(object):
def get_user(self, user_id):
return Strategy(storage=Storage).get_user(user_id) |
cb1142d5ac8d144e5ab0fc95ceed156c855b6bd2 | randomize-music.py | randomize-music.py |
import os
import subprocess
import sys
import uuid
if __name__ == '__main__':
dir_name = sys.argv[1]
for file_name in os.listdir(dir_name):
rand_name = uuid.uuid4().hex
src = os.path.join(dir_name, file_name)
subprocess.check_call(['eyeD3', '--artist', rand_name, '--album', rand_name, src])
os.rename(src, os.path.join(dir_name, '{} {}'.format(rand_name, file_name)))
|
import os
import subprocess
import sys
import uuid
if __name__ == '__main__':
dir_name = sys.argv[1]
for root, dirs, files in os.walk(dir_name):
for file_name in files:
rand_name = uuid.uuid4().hex
src = os.path.join(root, file_name)
if src.endswith('.mp3'):
subprocess.check_call(['eyeD3', '--artist', rand_name, '--album', rand_name, src])
os.rename(src, os.path.join(root, '{} {}'.format(rand_name, file_name)))
| Generalize randomize script to work recursively and on more than just music | Generalize randomize script to work recursively and on more than just music
| Python | mit | cataliniacob/misc,cataliniacob/misc |
import os
import subprocess
import sys
import uuid
if __name__ == '__main__':
dir_name = sys.argv[1]
- for file_name in os.listdir(dir_name):
+ for root, dirs, files in os.walk(dir_name):
+ for file_name in files:
- rand_name = uuid.uuid4().hex
+ rand_name = uuid.uuid4().hex
- src = os.path.join(dir_name, file_name)
+ src = os.path.join(root, file_name)
+ if src.endswith('.mp3'):
- subprocess.check_call(['eyeD3', '--artist', rand_name, '--album', rand_name, src])
+ subprocess.check_call(['eyeD3', '--artist', rand_name, '--album', rand_name, src])
- os.rename(src, os.path.join(dir_name, '{} {}'.format(rand_name, file_name)))
+ os.rename(src, os.path.join(root, '{} {}'.format(rand_name, file_name)))
| Generalize randomize script to work recursively and on more than just music | ## Code Before:
import os
import subprocess
import sys
import uuid
if __name__ == '__main__':
dir_name = sys.argv[1]
for file_name in os.listdir(dir_name):
rand_name = uuid.uuid4().hex
src = os.path.join(dir_name, file_name)
subprocess.check_call(['eyeD3', '--artist', rand_name, '--album', rand_name, src])
os.rename(src, os.path.join(dir_name, '{} {}'.format(rand_name, file_name)))
## Instruction:
Generalize randomize script to work recursively and on more than just music
## Code After:
import os
import subprocess
import sys
import uuid
if __name__ == '__main__':
dir_name = sys.argv[1]
for root, dirs, files in os.walk(dir_name):
for file_name in files:
rand_name = uuid.uuid4().hex
src = os.path.join(root, file_name)
if src.endswith('.mp3'):
subprocess.check_call(['eyeD3', '--artist', rand_name, '--album', rand_name, src])
os.rename(src, os.path.join(root, '{} {}'.format(rand_name, file_name)))
|
import os
import subprocess
import sys
import uuid
if __name__ == '__main__':
dir_name = sys.argv[1]
- for file_name in os.listdir(dir_name):
+ for root, dirs, files in os.walk(dir_name):
+ for file_name in files:
- rand_name = uuid.uuid4().hex
+ rand_name = uuid.uuid4().hex
? ++++
- src = os.path.join(dir_name, file_name)
? -- ^^^^^
+ src = os.path.join(root, file_name)
? ++++ ^^^
+ if src.endswith('.mp3'):
- subprocess.check_call(['eyeD3', '--artist', rand_name, '--album', rand_name, src])
+ subprocess.check_call(['eyeD3', '--artist', rand_name, '--album', rand_name, src])
? ++++++++
- os.rename(src, os.path.join(dir_name, '{} {}'.format(rand_name, file_name)))
? -- ^^^^^
+ os.rename(src, os.path.join(root, '{} {}'.format(rand_name, file_name)))
? ++++ ^^^
|
c52e8e27d7b245722e10887dc97440481d0871f4 | scraper/political_parties.py | scraper/political_parties.py | import re
import requests
import lxml.html
from parliament.models import PoliticalParty
def create_parties():
url = 'https://www.tweedekamer.nl/kamerleden/fracties'
page = requests.get(url)
tree = lxml.html.fromstring(page.content)
rows = tree.xpath("//ul[@class='reset grouped-list']/li/a")
for row in rows:
columns = row.text.split('-')
if len(columns) > 1:
name = columns[0].strip()
name_short = columns[1]
name_short = re.sub(r'\(.+?\)', '', name_short).strip()
else:
name = columns[0]
name = re.sub(r'\(.+?\)', '', name).strip()
name_short = name
# print('name: ' + name)
# print('short: ' + name_short)
if PoliticalParty.find_party(name):
print('WARNING: party already exists!')
else:
party = PoliticalParty.objects.create(name=name, name_short=name_short)
party.update_info('nl', 'nl')
party.save()
print('created: ' + str(party))
| import re
import requests
import lxml.html
from parliament.models import PoliticalParty
def create_parties():
url = 'https://www.tweedekamer.nl/kamerleden/fracties'
page = requests.get(url)
tree = lxml.html.fromstring(page.content)
rows = tree.xpath("//ul[@class='reset grouped-list']/li/a")
for row in rows:
columns = row.text.split('-')
if len(columns) > 1:
name = columns[0].strip()
name_short = columns[1]
name_short = re.sub(r'\(.+?\)', '', name_short).strip()
else:
name = columns[0]
name = re.sub(r'\(.+?\)', '', name).strip()
name_short = name
# print('name: ' + name)
# print('short: ' + name_short)
party = PoliticalParty.find_party(name)
if party:
print('WARNING: party already exists!')
else:
party = PoliticalParty.objects.create(name=name, name_short=name_short)
print('created: ' + str(party))
party.update_info('nl', 'nl')
party.save()
| Update party info after creation | Update party info after creation
| Python | mit | openkamer/openkamer,openkamer/openkamer,openkamer/openkamer,openkamer/openkamer | import re
import requests
import lxml.html
from parliament.models import PoliticalParty
def create_parties():
url = 'https://www.tweedekamer.nl/kamerleden/fracties'
page = requests.get(url)
tree = lxml.html.fromstring(page.content)
rows = tree.xpath("//ul[@class='reset grouped-list']/li/a")
for row in rows:
columns = row.text.split('-')
if len(columns) > 1:
name = columns[0].strip()
name_short = columns[1]
name_short = re.sub(r'\(.+?\)', '', name_short).strip()
else:
name = columns[0]
name = re.sub(r'\(.+?\)', '', name).strip()
name_short = name
# print('name: ' + name)
# print('short: ' + name_short)
- if PoliticalParty.find_party(name):
+ party = PoliticalParty.find_party(name)
+ if party:
print('WARNING: party already exists!')
else:
party = PoliticalParty.objects.create(name=name, name_short=name_short)
- party.update_info('nl', 'nl')
- party.save()
print('created: ' + str(party))
+ party.update_info('nl', 'nl')
+ party.save()
| Update party info after creation | ## Code Before:
import re
import requests
import lxml.html
from parliament.models import PoliticalParty
def create_parties():
url = 'https://www.tweedekamer.nl/kamerleden/fracties'
page = requests.get(url)
tree = lxml.html.fromstring(page.content)
rows = tree.xpath("//ul[@class='reset grouped-list']/li/a")
for row in rows:
columns = row.text.split('-')
if len(columns) > 1:
name = columns[0].strip()
name_short = columns[1]
name_short = re.sub(r'\(.+?\)', '', name_short).strip()
else:
name = columns[0]
name = re.sub(r'\(.+?\)', '', name).strip()
name_short = name
# print('name: ' + name)
# print('short: ' + name_short)
if PoliticalParty.find_party(name):
print('WARNING: party already exists!')
else:
party = PoliticalParty.objects.create(name=name, name_short=name_short)
party.update_info('nl', 'nl')
party.save()
print('created: ' + str(party))
## Instruction:
Update party info after creation
## Code After:
import re
import requests
import lxml.html
from parliament.models import PoliticalParty
def create_parties():
url = 'https://www.tweedekamer.nl/kamerleden/fracties'
page = requests.get(url)
tree = lxml.html.fromstring(page.content)
rows = tree.xpath("//ul[@class='reset grouped-list']/li/a")
for row in rows:
columns = row.text.split('-')
if len(columns) > 1:
name = columns[0].strip()
name_short = columns[1]
name_short = re.sub(r'\(.+?\)', '', name_short).strip()
else:
name = columns[0]
name = re.sub(r'\(.+?\)', '', name).strip()
name_short = name
# print('name: ' + name)
# print('short: ' + name_short)
party = PoliticalParty.find_party(name)
if party:
print('WARNING: party already exists!')
else:
party = PoliticalParty.objects.create(name=name, name_short=name_short)
print('created: ' + str(party))
party.update_info('nl', 'nl')
party.save()
| import re
import requests
import lxml.html
from parliament.models import PoliticalParty
def create_parties():
url = 'https://www.tweedekamer.nl/kamerleden/fracties'
page = requests.get(url)
tree = lxml.html.fromstring(page.content)
rows = tree.xpath("//ul[@class='reset grouped-list']/li/a")
for row in rows:
columns = row.text.split('-')
if len(columns) > 1:
name = columns[0].strip()
name_short = columns[1]
name_short = re.sub(r'\(.+?\)', '', name_short).strip()
else:
name = columns[0]
name = re.sub(r'\(.+?\)', '', name).strip()
name_short = name
# print('name: ' + name)
# print('short: ' + name_short)
- if PoliticalParty.find_party(name):
? ^^ -
+ party = PoliticalParty.find_party(name)
? ^^^^^^^
+ if party:
print('WARNING: party already exists!')
else:
party = PoliticalParty.objects.create(name=name, name_short=name_short)
- party.update_info('nl', 'nl')
- party.save()
print('created: ' + str(party))
+ party.update_info('nl', 'nl')
+ party.save() |
1f75d6b1d13814207c5585da166e59f3d67af4c1 | stickord/commands/xkcd.py | stickord/commands/xkcd.py | '''
Provides commands to the xkcd system
'''
from stickord.helpers.xkcd_api import get_random, get_by_id, print_comic, get_recent
from stickord.registry import Command
@Command('xkcd', category='xkcd')
async def get_comic(cont, _mesg):
''' Search for a comic by id, if no id is provided it will post a random comic. '''
if cont:
comic_id = int(cont[0])
comic = await get_by_id(comic_id)
return await print_comic(comic)
comic = await get_random()
return await print_comic(comic)
@Command('newxkcd', category='xkcd')
async def get_latest_comic(_cont, _mesg):
''' Posts the latest xkcd comic. '''
comic = await get_recent()
return await print_comic(comic)
| '''
Provides commands to the xkcd system
'''
from stickord.helpers.xkcd_api import get_random, get_by_id, print_comic, get_recent
from stickord.registry import Command
@Command('xkcd', category='xkcd')
async def get_comic(cont, _mesg):
''' Search for a comic by id, if no id is provided it will post a random comic. '''
if cont:
try:
comic_id = int(cont[0])
comic = await get_by_id(comic_id)
return await print_comic(comic)
except ValueError:
pass
comic = await get_random()
return await print_comic(comic)
@Command('newxkcd', category='xkcd')
async def get_latest_comic(_cont, _mesg):
''' Posts the latest xkcd comic. '''
comic = await get_recent()
return await print_comic(comic)
| Fix crash on invalid int | Fix crash on invalid int
| Python | mit | RobinSikkens/Sticky-discord | '''
Provides commands to the xkcd system
'''
from stickord.helpers.xkcd_api import get_random, get_by_id, print_comic, get_recent
from stickord.registry import Command
@Command('xkcd', category='xkcd')
async def get_comic(cont, _mesg):
''' Search for a comic by id, if no id is provided it will post a random comic. '''
if cont:
+ try:
- comic_id = int(cont[0])
+ comic_id = int(cont[0])
- comic = await get_by_id(comic_id)
+ comic = await get_by_id(comic_id)
- return await print_comic(comic)
+ return await print_comic(comic)
+ except ValueError:
+ pass
comic = await get_random()
return await print_comic(comic)
@Command('newxkcd', category='xkcd')
async def get_latest_comic(_cont, _mesg):
''' Posts the latest xkcd comic. '''
comic = await get_recent()
return await print_comic(comic)
| Fix crash on invalid int | ## Code Before:
'''
Provides commands to the xkcd system
'''
from stickord.helpers.xkcd_api import get_random, get_by_id, print_comic, get_recent
from stickord.registry import Command
@Command('xkcd', category='xkcd')
async def get_comic(cont, _mesg):
''' Search for a comic by id, if no id is provided it will post a random comic. '''
if cont:
comic_id = int(cont[0])
comic = await get_by_id(comic_id)
return await print_comic(comic)
comic = await get_random()
return await print_comic(comic)
@Command('newxkcd', category='xkcd')
async def get_latest_comic(_cont, _mesg):
''' Posts the latest xkcd comic. '''
comic = await get_recent()
return await print_comic(comic)
## Instruction:
Fix crash on invalid int
## Code After:
'''
Provides commands to the xkcd system
'''
from stickord.helpers.xkcd_api import get_random, get_by_id, print_comic, get_recent
from stickord.registry import Command
@Command('xkcd', category='xkcd')
async def get_comic(cont, _mesg):
''' Search for a comic by id, if no id is provided it will post a random comic. '''
if cont:
try:
comic_id = int(cont[0])
comic = await get_by_id(comic_id)
return await print_comic(comic)
except ValueError:
pass
comic = await get_random()
return await print_comic(comic)
@Command('newxkcd', category='xkcd')
async def get_latest_comic(_cont, _mesg):
''' Posts the latest xkcd comic. '''
comic = await get_recent()
return await print_comic(comic)
| '''
Provides commands to the xkcd system
'''
from stickord.helpers.xkcd_api import get_random, get_by_id, print_comic, get_recent
from stickord.registry import Command
@Command('xkcd', category='xkcd')
async def get_comic(cont, _mesg):
''' Search for a comic by id, if no id is provided it will post a random comic. '''
if cont:
+ try:
- comic_id = int(cont[0])
+ comic_id = int(cont[0])
? ++++
- comic = await get_by_id(comic_id)
+ comic = await get_by_id(comic_id)
? ++++
- return await print_comic(comic)
+ return await print_comic(comic)
? ++++
+ except ValueError:
+ pass
comic = await get_random()
return await print_comic(comic)
@Command('newxkcd', category='xkcd')
async def get_latest_comic(_cont, _mesg):
''' Posts the latest xkcd comic. '''
comic = await get_recent()
return await print_comic(comic) |
770f1a5d83a8450e9a16942d1260483f7b1401cd | sauce/model/news.py | sauce/model/news.py | '''News model module
@author: moschlar
'''
from datetime import datetime
from sqlalchemy import ForeignKey, Column
from sqlalchemy.types import Integer, Unicode, DateTime, Boolean
from sqlalchemy.orm import relationship, backref
from sqlalchemy.sql import desc
from sauce.model import DeclarativeBase
class NewsItem(DeclarativeBase):
'''A NewsItem'''
__tablename__ = 'newsitems'
id = Column(Integer, primary_key=True)
date = Column(DateTime, default=datetime.now)
subject = Column(Unicode(255), nullable=False)
message = Column(Unicode(65536))
event_id = Column(Integer, ForeignKey('events.id'))
event = relationship('Event',
backref=backref('news', order_by=desc(date))
)
'''If event == None, NewsItem is to be displayed on front page instead of event page'''
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
user = relationship('User',
#backref=backref('news',
# cascade='all, delete-orphan')
)
'''The User that wrote the NewsItem'''
public = Column(Boolean, nullable=False, default=False)
__mapper_args__ = {'order_by': desc(date)}
| '''News model module
@author: moschlar
'''
from datetime import datetime
from sqlalchemy import ForeignKey, Column
from sqlalchemy.types import Integer, Unicode, DateTime, Boolean
from sqlalchemy.orm import relationship, backref
from sqlalchemy.sql import desc
from sauce.model import DeclarativeBase
class NewsItem(DeclarativeBase):
'''A NewsItem'''
__tablename__ = 'newsitems'
id = Column(Integer, primary_key=True)
date = Column(DateTime, default=datetime.now)
subject = Column(Unicode(255), nullable=False)
message = Column(Unicode(65536))
event_id = Column(Integer, ForeignKey('events.id'))
event = relationship('Event',
backref=backref('news', order_by=desc(date))
)
'''If event == None, NewsItem is to be displayed on front page instead of event page'''
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
user = relationship('User',
#backref=backref('news',
# cascade='all, delete-orphan')
)
'''The User that wrote the NewsItem'''
public = Column(Boolean, nullable=False, default=False)
__mapper_args__ = {'order_by': desc(date)}
def __unicode__(self):
return u'NewsItem %d "%s"' % (self.id or '', self.subject)
| Add unicode repr to NewsItem | Add unicode repr to NewsItem
| Python | agpl-3.0 | moschlar/SAUCE,moschlar/SAUCE,moschlar/SAUCE,moschlar/SAUCE | '''News model module
@author: moschlar
'''
from datetime import datetime
from sqlalchemy import ForeignKey, Column
from sqlalchemy.types import Integer, Unicode, DateTime, Boolean
from sqlalchemy.orm import relationship, backref
from sqlalchemy.sql import desc
from sauce.model import DeclarativeBase
class NewsItem(DeclarativeBase):
'''A NewsItem'''
__tablename__ = 'newsitems'
id = Column(Integer, primary_key=True)
date = Column(DateTime, default=datetime.now)
subject = Column(Unicode(255), nullable=False)
message = Column(Unicode(65536))
event_id = Column(Integer, ForeignKey('events.id'))
event = relationship('Event',
backref=backref('news', order_by=desc(date))
)
'''If event == None, NewsItem is to be displayed on front page instead of event page'''
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
user = relationship('User',
#backref=backref('news',
# cascade='all, delete-orphan')
)
'''The User that wrote the NewsItem'''
public = Column(Boolean, nullable=False, default=False)
__mapper_args__ = {'order_by': desc(date)}
+ def __unicode__(self):
+ return u'NewsItem %d "%s"' % (self.id or '', self.subject)
+ | Add unicode repr to NewsItem | ## Code Before:
'''News model module
@author: moschlar
'''
from datetime import datetime
from sqlalchemy import ForeignKey, Column
from sqlalchemy.types import Integer, Unicode, DateTime, Boolean
from sqlalchemy.orm import relationship, backref
from sqlalchemy.sql import desc
from sauce.model import DeclarativeBase
class NewsItem(DeclarativeBase):
'''A NewsItem'''
__tablename__ = 'newsitems'
id = Column(Integer, primary_key=True)
date = Column(DateTime, default=datetime.now)
subject = Column(Unicode(255), nullable=False)
message = Column(Unicode(65536))
event_id = Column(Integer, ForeignKey('events.id'))
event = relationship('Event',
backref=backref('news', order_by=desc(date))
)
'''If event == None, NewsItem is to be displayed on front page instead of event page'''
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
user = relationship('User',
#backref=backref('news',
# cascade='all, delete-orphan')
)
'''The User that wrote the NewsItem'''
public = Column(Boolean, nullable=False, default=False)
__mapper_args__ = {'order_by': desc(date)}
## Instruction:
Add unicode repr to NewsItem
## Code After:
'''News model module
@author: moschlar
'''
from datetime import datetime
from sqlalchemy import ForeignKey, Column
from sqlalchemy.types import Integer, Unicode, DateTime, Boolean
from sqlalchemy.orm import relationship, backref
from sqlalchemy.sql import desc
from sauce.model import DeclarativeBase
class NewsItem(DeclarativeBase):
'''A NewsItem'''
__tablename__ = 'newsitems'
id = Column(Integer, primary_key=True)
date = Column(DateTime, default=datetime.now)
subject = Column(Unicode(255), nullable=False)
message = Column(Unicode(65536))
event_id = Column(Integer, ForeignKey('events.id'))
event = relationship('Event',
backref=backref('news', order_by=desc(date))
)
'''If event == None, NewsItem is to be displayed on front page instead of event page'''
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
user = relationship('User',
#backref=backref('news',
# cascade='all, delete-orphan')
)
'''The User that wrote the NewsItem'''
public = Column(Boolean, nullable=False, default=False)
__mapper_args__ = {'order_by': desc(date)}
def __unicode__(self):
return u'NewsItem %d "%s"' % (self.id or '', self.subject)
| '''News model module
@author: moschlar
'''
from datetime import datetime
from sqlalchemy import ForeignKey, Column
from sqlalchemy.types import Integer, Unicode, DateTime, Boolean
from sqlalchemy.orm import relationship, backref
from sqlalchemy.sql import desc
from sauce.model import DeclarativeBase
class NewsItem(DeclarativeBase):
'''A NewsItem'''
__tablename__ = 'newsitems'
id = Column(Integer, primary_key=True)
date = Column(DateTime, default=datetime.now)
subject = Column(Unicode(255), nullable=False)
message = Column(Unicode(65536))
event_id = Column(Integer, ForeignKey('events.id'))
event = relationship('Event',
backref=backref('news', order_by=desc(date))
)
'''If event == None, NewsItem is to be displayed on front page instead of event page'''
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
user = relationship('User',
#backref=backref('news',
# cascade='all, delete-orphan')
)
'''The User that wrote the NewsItem'''
public = Column(Boolean, nullable=False, default=False)
__mapper_args__ = {'order_by': desc(date)}
+
+ def __unicode__(self):
+ return u'NewsItem %d "%s"' % (self.id or '', self.subject) |
6e0d583e0c3eea7ca9e7a37567cfc7535d8f406b | django_prices_openexchangerates/tasks.py | django_prices_openexchangerates/tasks.py | from __future__ import division
from __future__ import unicode_literals
from decimal import Decimal
import requests
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .models import ConversionRate
BASE_URL = r'http://openexchangerates.org/api'
ENDPOINT_LATEST = BASE_URL + r'/latest.json'
try:
API_KEY = settings.OPENEXCHANGERATES_API_KEY
except AttributeError:
raise ImproperlyConfigured('OPENEXCHANGERATES_API_KEY is required')
class ExchangeRates(object):
def __init__(self, rates, default_currency=None):
self.rates = rates
self.default_currency = (
default_currency or settings.DEFAULT_CURRENCY)
def __getitem__(self, item):
rate = self.rates[item]
return rate / self.rates[self.default_currency]
def get_latest_exchange_rates():
response = requests.get(ENDPOINT_LATEST, params={'app_id': API_KEY})
response.raise_for_status()
exchange_data = response.json(parse_int=Decimal, parse_float=Decimal)
return ExchangeRates(rates=exchange_data['rates'])
def update_conversion_rates():
exchange_rates = get_latest_exchange_rates()
conversion_rates = ConversionRate.objects.all()
for conversion_rate in conversion_rates:
new_exchange_rate = exchange_rates[conversion_rate.to_currency]
conversion_rate.rate = new_exchange_rate
conversion_rate.save(update_fields=['rate'])
return conversion_rates
| from __future__ import division
from __future__ import unicode_literals
from decimal import Decimal
import requests
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .models import ConversionRate
BASE_URL = r'http://openexchangerates.org/api'
ENDPOINT_LATEST = BASE_URL + r'/latest.json'
try:
API_KEY = settings.OPENEXCHANGERATES_API_KEY
except AttributeError:
raise ImproperlyConfigured('OPENEXCHANGERATES_API_KEY is required')
def extract_rate(rates, currency):
base_rate = rates[settings.DEFAULT_CURRENCY]
return rates[currency] / base_rate
def get_latest_exchange_rates():
response = requests.get(ENDPOINT_LATEST, params={'app_id': API_KEY})
response.raise_for_status()
return response.json(parse_int=Decimal, parse_float=Decimal)
def update_conversion_rates():
exchange_rates = get_latest_exchange_rates()
conversion_rates = ConversionRate.objects.all()
for conversion_rate in conversion_rates:
new_exchange_rate = extract_rate(exchange_rates,
conversion_rate.to_currency)
conversion_rate.rate = new_exchange_rate
conversion_rate.save(update_fields=['rate'])
return conversion_rates
| Make rates parsing more readable | Make rates parsing more readable
| Python | bsd-3-clause | artursmet/django-prices-openexchangerates,mirumee/django-prices-openexchangerates | from __future__ import division
from __future__ import unicode_literals
from decimal import Decimal
import requests
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .models import ConversionRate
BASE_URL = r'http://openexchangerates.org/api'
ENDPOINT_LATEST = BASE_URL + r'/latest.json'
try:
API_KEY = settings.OPENEXCHANGERATES_API_KEY
except AttributeError:
raise ImproperlyConfigured('OPENEXCHANGERATES_API_KEY is required')
+ def extract_rate(rates, currency):
+ base_rate = rates[settings.DEFAULT_CURRENCY]
+ return rates[currency] / base_rate
- class ExchangeRates(object):
-
- def __init__(self, rates, default_currency=None):
- self.rates = rates
- self.default_currency = (
- default_currency or settings.DEFAULT_CURRENCY)
-
- def __getitem__(self, item):
- rate = self.rates[item]
- return rate / self.rates[self.default_currency]
def get_latest_exchange_rates():
response = requests.get(ENDPOINT_LATEST, params={'app_id': API_KEY})
response.raise_for_status()
- exchange_data = response.json(parse_int=Decimal, parse_float=Decimal)
+ return response.json(parse_int=Decimal, parse_float=Decimal)
- return ExchangeRates(rates=exchange_data['rates'])
def update_conversion_rates():
exchange_rates = get_latest_exchange_rates()
conversion_rates = ConversionRate.objects.all()
for conversion_rate in conversion_rates:
- new_exchange_rate = exchange_rates[conversion_rate.to_currency]
+ new_exchange_rate = extract_rate(exchange_rates,
+ conversion_rate.to_currency)
conversion_rate.rate = new_exchange_rate
conversion_rate.save(update_fields=['rate'])
return conversion_rates
| Make rates parsing more readable | ## Code Before:
from __future__ import division
from __future__ import unicode_literals
from decimal import Decimal
import requests
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .models import ConversionRate
BASE_URL = r'http://openexchangerates.org/api'
ENDPOINT_LATEST = BASE_URL + r'/latest.json'
try:
API_KEY = settings.OPENEXCHANGERATES_API_KEY
except AttributeError:
raise ImproperlyConfigured('OPENEXCHANGERATES_API_KEY is required')
class ExchangeRates(object):
def __init__(self, rates, default_currency=None):
self.rates = rates
self.default_currency = (
default_currency or settings.DEFAULT_CURRENCY)
def __getitem__(self, item):
rate = self.rates[item]
return rate / self.rates[self.default_currency]
def get_latest_exchange_rates():
response = requests.get(ENDPOINT_LATEST, params={'app_id': API_KEY})
response.raise_for_status()
exchange_data = response.json(parse_int=Decimal, parse_float=Decimal)
return ExchangeRates(rates=exchange_data['rates'])
def update_conversion_rates():
exchange_rates = get_latest_exchange_rates()
conversion_rates = ConversionRate.objects.all()
for conversion_rate in conversion_rates:
new_exchange_rate = exchange_rates[conversion_rate.to_currency]
conversion_rate.rate = new_exchange_rate
conversion_rate.save(update_fields=['rate'])
return conversion_rates
## Instruction:
Make rates parsing more readable
## Code After:
from __future__ import division
from __future__ import unicode_literals
from decimal import Decimal
import requests
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .models import ConversionRate
BASE_URL = r'http://openexchangerates.org/api'
ENDPOINT_LATEST = BASE_URL + r'/latest.json'
try:
API_KEY = settings.OPENEXCHANGERATES_API_KEY
except AttributeError:
raise ImproperlyConfigured('OPENEXCHANGERATES_API_KEY is required')
def extract_rate(rates, currency):
base_rate = rates[settings.DEFAULT_CURRENCY]
return rates[currency] / base_rate
def get_latest_exchange_rates():
response = requests.get(ENDPOINT_LATEST, params={'app_id': API_KEY})
response.raise_for_status()
return response.json(parse_int=Decimal, parse_float=Decimal)
def update_conversion_rates():
exchange_rates = get_latest_exchange_rates()
conversion_rates = ConversionRate.objects.all()
for conversion_rate in conversion_rates:
new_exchange_rate = extract_rate(exchange_rates,
conversion_rate.to_currency)
conversion_rate.rate = new_exchange_rate
conversion_rate.save(update_fields=['rate'])
return conversion_rates
| from __future__ import division
from __future__ import unicode_literals
from decimal import Decimal
import requests
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .models import ConversionRate
BASE_URL = r'http://openexchangerates.org/api'
ENDPOINT_LATEST = BASE_URL + r'/latest.json'
try:
API_KEY = settings.OPENEXCHANGERATES_API_KEY
except AttributeError:
raise ImproperlyConfigured('OPENEXCHANGERATES_API_KEY is required')
+ def extract_rate(rates, currency):
+ base_rate = rates[settings.DEFAULT_CURRENCY]
+ return rates[currency] / base_rate
- class ExchangeRates(object):
-
- def __init__(self, rates, default_currency=None):
- self.rates = rates
- self.default_currency = (
- default_currency or settings.DEFAULT_CURRENCY)
-
- def __getitem__(self, item):
- rate = self.rates[item]
- return rate / self.rates[self.default_currency]
def get_latest_exchange_rates():
response = requests.get(ENDPOINT_LATEST, params={'app_id': API_KEY})
response.raise_for_status()
- exchange_data = response.json(parse_int=Decimal, parse_float=Decimal)
? ^^^^ ---------
+ return response.json(parse_int=Decimal, parse_float=Decimal)
? + ^^^
- return ExchangeRates(rates=exchange_data['rates'])
def update_conversion_rates():
exchange_rates = get_latest_exchange_rates()
conversion_rates = ConversionRate.objects.all()
for conversion_rate in conversion_rates:
- new_exchange_rate = exchange_rates[conversion_rate.to_currency]
+ new_exchange_rate = extract_rate(exchange_rates,
+ conversion_rate.to_currency)
conversion_rate.rate = new_exchange_rate
conversion_rate.save(update_fields=['rate'])
return conversion_rates |
9d59bca61b2836e7db3c50d5558a46aa2dbaea08 | tests/run_tests.py | tests/run_tests.py |
import unittest
from cubic_elastic_moduli import *
###
unittest.main()
|
import unittest
from cubic_crystal_crack import *
from cubic_elastic_moduli import *
###
unittest.main()
| Add crack test to test runner. | Add crack test to test runner.
| Python | lgpl-2.1 | libAtoms/matscipy,libAtoms/matscipy,libAtoms/matscipy,libAtoms/matscipy |
import unittest
+ from cubic_crystal_crack import *
from cubic_elastic_moduli import *
###
unittest.main()
| Add crack test to test runner. | ## Code Before:
import unittest
from cubic_elastic_moduli import *
###
unittest.main()
## Instruction:
Add crack test to test runner.
## Code After:
import unittest
from cubic_crystal_crack import *
from cubic_elastic_moduli import *
###
unittest.main()
|
import unittest
+ from cubic_crystal_crack import *
from cubic_elastic_moduli import *
###
unittest.main()
|
960520b723d1af1999c647ebea8969b4837aa458 | blister/xmp.py | blister/xmp.py |
class VanillaXMP:
pass
| from collections.abc import MutableMapping
class VanillaXMP (MutableMapping):
def __delitem__ (self, key):
pass
def __getitem__ (self, key):
pass
def __iter__ (self):
pass
def __len__ (self):
pass
def __setitem__ (self, key, value):
pass
| Write minimal code to implement MutableMapping | Write minimal code to implement MutableMapping
| Python | bsd-3-clause | daaang/blister | + from collections.abc import MutableMapping
- class VanillaXMP:
+ class VanillaXMP (MutableMapping):
+ def __delitem__ (self, key):
- pass
+ pass
+ def __getitem__ (self, key):
+ pass
+
+ def __iter__ (self):
+ pass
+
+ def __len__ (self):
+ pass
+
+ def __setitem__ (self, key, value):
+ pass
+ | Write minimal code to implement MutableMapping | ## Code Before:
class VanillaXMP:
pass
## Instruction:
Write minimal code to implement MutableMapping
## Code After:
from collections.abc import MutableMapping
class VanillaXMP (MutableMapping):
def __delitem__ (self, key):
pass
def __getitem__ (self, key):
pass
def __iter__ (self):
pass
def __len__ (self):
pass
def __setitem__ (self, key, value):
pass
| + from collections.abc import MutableMapping
- class VanillaXMP:
+ class VanillaXMP (MutableMapping):
+ def __delitem__ (self, key):
- pass
+ pass
? ++++
+
+ def __getitem__ (self, key):
+ pass
+
+ def __iter__ (self):
+ pass
+
+ def __len__ (self):
+ pass
+
+ def __setitem__ (self, key, value):
+ pass |
4dd5dbf6c1f693c54b31a84756350cb9588921d1 | pybinding/model.py | pybinding/model.py | from scipy.sparse import csr_matrix
from . import _cpp
from .system import System
from .lattice import Lattice
from .support.sparse import SparseMatrix
class Model(_cpp.Model):
def __init__(self, *params):
super().__init__()
self.add(*params)
def add(self, *params):
for param in params:
if param is None:
continue
if isinstance(param, (tuple, list)):
self.add(*param)
else:
super().add(param)
@property
def system(self) -> System:
return System(super().system)
@property
def hamiltonian(self) -> csr_matrix:
matrix = SparseMatrix(super().hamiltonian.matrix)
return matrix.tocsr()
@property
def lattice(self) -> Lattice:
return super().lattice
@property
def modifiers(self) -> list:
return (self.state_modifiers + self.position_modifiers +
self.onsite_modifiers + self.hopping_modifiers)
| import numpy as np
from scipy.sparse import csr_matrix
from . import _cpp
from . import results
from .system import System
from .lattice import Lattice
from .support.sparse import SparseMatrix
class Model(_cpp.Model):
def __init__(self, *params):
super().__init__()
self.add(*params)
def add(self, *params):
for param in params:
if param is None:
continue
if isinstance(param, (tuple, list)):
self.add(*param)
else:
super().add(param)
@property
def system(self) -> System:
return System(super().system)
@property
def hamiltonian(self) -> csr_matrix:
matrix = SparseMatrix(super().hamiltonian.matrix)
return matrix.tocsr()
@property
def lattice(self) -> Lattice:
return super().lattice
@property
def modifiers(self) -> list:
return (self.state_modifiers + self.position_modifiers +
self.onsite_modifiers + self.hopping_modifiers)
@property
def onsite_map(self) -> results.StructureMap:
"""`StructureMap` of the onsite energy"""
onsite_energy = np.real(self.hamiltonian.tocsr().diagonal())
return results.StructureMap.from_system(onsite_energy, self.system)
| Add onsite energy map to Model | Add onsite energy map to Model
| Python | bsd-2-clause | dean0x7d/pybinding,MAndelkovic/pybinding,MAndelkovic/pybinding,dean0x7d/pybinding,dean0x7d/pybinding,MAndelkovic/pybinding | + import numpy as np
from scipy.sparse import csr_matrix
from . import _cpp
+ from . import results
from .system import System
from .lattice import Lattice
from .support.sparse import SparseMatrix
class Model(_cpp.Model):
def __init__(self, *params):
super().__init__()
self.add(*params)
def add(self, *params):
for param in params:
if param is None:
continue
if isinstance(param, (tuple, list)):
self.add(*param)
else:
super().add(param)
@property
def system(self) -> System:
return System(super().system)
@property
def hamiltonian(self) -> csr_matrix:
matrix = SparseMatrix(super().hamiltonian.matrix)
return matrix.tocsr()
@property
def lattice(self) -> Lattice:
return super().lattice
@property
def modifiers(self) -> list:
return (self.state_modifiers + self.position_modifiers +
self.onsite_modifiers + self.hopping_modifiers)
+ @property
+ def onsite_map(self) -> results.StructureMap:
+ """`StructureMap` of the onsite energy"""
+ onsite_energy = np.real(self.hamiltonian.tocsr().diagonal())
+ return results.StructureMap.from_system(onsite_energy, self.system)
+ | Add onsite energy map to Model | ## Code Before:
from scipy.sparse import csr_matrix
from . import _cpp
from .system import System
from .lattice import Lattice
from .support.sparse import SparseMatrix
class Model(_cpp.Model):
def __init__(self, *params):
super().__init__()
self.add(*params)
def add(self, *params):
for param in params:
if param is None:
continue
if isinstance(param, (tuple, list)):
self.add(*param)
else:
super().add(param)
@property
def system(self) -> System:
return System(super().system)
@property
def hamiltonian(self) -> csr_matrix:
matrix = SparseMatrix(super().hamiltonian.matrix)
return matrix.tocsr()
@property
def lattice(self) -> Lattice:
return super().lattice
@property
def modifiers(self) -> list:
return (self.state_modifiers + self.position_modifiers +
self.onsite_modifiers + self.hopping_modifiers)
## Instruction:
Add onsite energy map to Model
## Code After:
import numpy as np
from scipy.sparse import csr_matrix
from . import _cpp
from . import results
from .system import System
from .lattice import Lattice
from .support.sparse import SparseMatrix
class Model(_cpp.Model):
def __init__(self, *params):
super().__init__()
self.add(*params)
def add(self, *params):
for param in params:
if param is None:
continue
if isinstance(param, (tuple, list)):
self.add(*param)
else:
super().add(param)
@property
def system(self) -> System:
return System(super().system)
@property
def hamiltonian(self) -> csr_matrix:
matrix = SparseMatrix(super().hamiltonian.matrix)
return matrix.tocsr()
@property
def lattice(self) -> Lattice:
return super().lattice
@property
def modifiers(self) -> list:
return (self.state_modifiers + self.position_modifiers +
self.onsite_modifiers + self.hopping_modifiers)
@property
def onsite_map(self) -> results.StructureMap:
"""`StructureMap` of the onsite energy"""
onsite_energy = np.real(self.hamiltonian.tocsr().diagonal())
return results.StructureMap.from_system(onsite_energy, self.system)
| + import numpy as np
from scipy.sparse import csr_matrix
from . import _cpp
+ from . import results
from .system import System
from .lattice import Lattice
from .support.sparse import SparseMatrix
class Model(_cpp.Model):
def __init__(self, *params):
super().__init__()
self.add(*params)
def add(self, *params):
for param in params:
if param is None:
continue
if isinstance(param, (tuple, list)):
self.add(*param)
else:
super().add(param)
@property
def system(self) -> System:
return System(super().system)
@property
def hamiltonian(self) -> csr_matrix:
matrix = SparseMatrix(super().hamiltonian.matrix)
return matrix.tocsr()
@property
def lattice(self) -> Lattice:
return super().lattice
@property
def modifiers(self) -> list:
return (self.state_modifiers + self.position_modifiers +
self.onsite_modifiers + self.hopping_modifiers)
+
+ @property
+ def onsite_map(self) -> results.StructureMap:
+ """`StructureMap` of the onsite energy"""
+ onsite_energy = np.real(self.hamiltonian.tocsr().diagonal())
+ return results.StructureMap.from_system(onsite_energy, self.system) |
6d6e83734d0cb034f8fc198df94bc64cf412d8d6 | ceam/framework/components.py | ceam/framework/components.py | from importlib import import_module
import json
def read_component_configuration(path):
if path.endswith('.json'):
with open(path) as f:
config = json.load(f)
return apply_defaults(config)
else:
raise ValueError("Unknown components configuration type: {}".format(path))
def apply_defaults(config):
base_components = config['components']
if 'comparisons' in config:
comparisons = {c['name']:c for c in config['comparisons']}
for comparison in comparisons.values():
comparison['components'] = base_components + comparison['components']
else:
comparisons = {'base': {'name': 'base', 'components': base_components}}
return comparisons
def load(component_list):
components = []
for component in component_list:
if isinstance(component, str) or isinstance(component, list):
if isinstance(component, list):
component, args, kwargs = component
call = True
elif component.endswith('()'):
component = component[:-2]
args = ()
kwargs = {}
call = True
else:
call = False
module_path, _, component_name = component.rpartition('.')
component = getattr(import_module(module_path), component_name)
if call:
component = component(*args, **kwargs)
if isinstance(component, type):
component = component()
components.append(component)
return components
| from importlib import import_module
from collections import Iterable
import json
def read_component_configuration(path):
if path.endswith('.json'):
with open(path) as f:
config = json.load(f)
return apply_defaults(config)
else:
raise ValueError("Unknown components configuration type: {}".format(path))
def apply_defaults(config):
base_components = config['components']
if 'comparisons' in config:
comparisons = {c['name']:c for c in config['comparisons']}
for comparison in comparisons.values():
comparison['components'] = base_components + comparison['components']
else:
comparisons = {'base': {'name': 'base', 'components': base_components}}
return comparisons
def load(component_list):
components = []
for component in component_list:
if isinstance(component, str) or isinstance(component, list):
if isinstance(component, list):
component, args, kwargs = component
call = True
elif component.endswith('()'):
component = component[:-2]
args = ()
kwargs = {}
call = True
else:
call = False
module_path, _, component_name = component.rpartition('.')
component = getattr(import_module(module_path), component_name)
if call:
component = component(*args, **kwargs)
if isinstance(component, type):
component = component()
if isinstance(component, Iterable):
components.extend(component)
else:
components.append(component)
return components
| Add support for component initialization that returns lists | Add support for component initialization that returns lists
| Python | bsd-3-clause | ihmeuw/vivarium | from importlib import import_module
+ from collections import Iterable
import json
def read_component_configuration(path):
if path.endswith('.json'):
with open(path) as f:
config = json.load(f)
return apply_defaults(config)
else:
raise ValueError("Unknown components configuration type: {}".format(path))
def apply_defaults(config):
base_components = config['components']
if 'comparisons' in config:
comparisons = {c['name']:c for c in config['comparisons']}
for comparison in comparisons.values():
comparison['components'] = base_components + comparison['components']
else:
comparisons = {'base': {'name': 'base', 'components': base_components}}
return comparisons
def load(component_list):
components = []
for component in component_list:
if isinstance(component, str) or isinstance(component, list):
if isinstance(component, list):
component, args, kwargs = component
call = True
elif component.endswith('()'):
component = component[:-2]
args = ()
kwargs = {}
call = True
else:
call = False
module_path, _, component_name = component.rpartition('.')
component = getattr(import_module(module_path), component_name)
if call:
component = component(*args, **kwargs)
if isinstance(component, type):
component = component()
+ if isinstance(component, Iterable):
+ components.extend(component)
+ else:
- components.append(component)
+ components.append(component)
return components
| Add support for component initialization that returns lists | ## Code Before:
from importlib import import_module
import json
def read_component_configuration(path):
if path.endswith('.json'):
with open(path) as f:
config = json.load(f)
return apply_defaults(config)
else:
raise ValueError("Unknown components configuration type: {}".format(path))
def apply_defaults(config):
base_components = config['components']
if 'comparisons' in config:
comparisons = {c['name']:c for c in config['comparisons']}
for comparison in comparisons.values():
comparison['components'] = base_components + comparison['components']
else:
comparisons = {'base': {'name': 'base', 'components': base_components}}
return comparisons
def load(component_list):
components = []
for component in component_list:
if isinstance(component, str) or isinstance(component, list):
if isinstance(component, list):
component, args, kwargs = component
call = True
elif component.endswith('()'):
component = component[:-2]
args = ()
kwargs = {}
call = True
else:
call = False
module_path, _, component_name = component.rpartition('.')
component = getattr(import_module(module_path), component_name)
if call:
component = component(*args, **kwargs)
if isinstance(component, type):
component = component()
components.append(component)
return components
## Instruction:
Add support for component initialization that returns lists
## Code After:
from importlib import import_module
from collections import Iterable
import json
def read_component_configuration(path):
if path.endswith('.json'):
with open(path) as f:
config = json.load(f)
return apply_defaults(config)
else:
raise ValueError("Unknown components configuration type: {}".format(path))
def apply_defaults(config):
base_components = config['components']
if 'comparisons' in config:
comparisons = {c['name']:c for c in config['comparisons']}
for comparison in comparisons.values():
comparison['components'] = base_components + comparison['components']
else:
comparisons = {'base': {'name': 'base', 'components': base_components}}
return comparisons
def load(component_list):
components = []
for component in component_list:
if isinstance(component, str) or isinstance(component, list):
if isinstance(component, list):
component, args, kwargs = component
call = True
elif component.endswith('()'):
component = component[:-2]
args = ()
kwargs = {}
call = True
else:
call = False
module_path, _, component_name = component.rpartition('.')
component = getattr(import_module(module_path), component_name)
if call:
component = component(*args, **kwargs)
if isinstance(component, type):
component = component()
if isinstance(component, Iterable):
components.extend(component)
else:
components.append(component)
return components
| from importlib import import_module
+ from collections import Iterable
import json
def read_component_configuration(path):
if path.endswith('.json'):
with open(path) as f:
config = json.load(f)
return apply_defaults(config)
else:
raise ValueError("Unknown components configuration type: {}".format(path))
def apply_defaults(config):
base_components = config['components']
if 'comparisons' in config:
comparisons = {c['name']:c for c in config['comparisons']}
for comparison in comparisons.values():
comparison['components'] = base_components + comparison['components']
else:
comparisons = {'base': {'name': 'base', 'components': base_components}}
return comparisons
def load(component_list):
components = []
for component in component_list:
if isinstance(component, str) or isinstance(component, list):
if isinstance(component, list):
component, args, kwargs = component
call = True
elif component.endswith('()'):
component = component[:-2]
args = ()
kwargs = {}
call = True
else:
call = False
module_path, _, component_name = component.rpartition('.')
component = getattr(import_module(module_path), component_name)
if call:
component = component(*args, **kwargs)
if isinstance(component, type):
component = component()
+ if isinstance(component, Iterable):
+ components.extend(component)
+ else:
- components.append(component)
+ components.append(component)
? ++++
return components |
01d812f83c5526cc304f8d691ce9203d3e95633a | sampleproj/settings/travis.py | sampleproj/settings/travis.py | from __future__ import absolute_import
from .base import *
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'travis-xxxxxxxxxxxxxxxx'
| from __future__ import absolute_import
from .base import *
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'travis-xxxxxxxxxxxxxxxx'
#Emails
MDOT_HELP_EMAIL = 'test@testcase.edu' # String for help desk email address
MDOT_UX_EMAIL = 'test@testcase.edu' # String for UX team email address
MDOT_FORM_EMAIL = 'test@testcase.edu' # String to email app publishing requests
| Add dummy email addresses for unit tests. | Add dummy email addresses for unit tests.
| Python | apache-2.0 | charlon/mdot,uw-it-aca/mdot,uw-it-aca/mdot,charlon/mdot,uw-it-aca/mdot,uw-it-aca/mdot,charlon/mdot | from __future__ import absolute_import
from .base import *
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'travis-xxxxxxxxxxxxxxxx'
+ #Emails
+ MDOT_HELP_EMAIL = 'test@testcase.edu' # String for help desk email address
+ MDOT_UX_EMAIL = 'test@testcase.edu' # String for UX team email address
+ MDOT_FORM_EMAIL = 'test@testcase.edu' # String to email app publishing requests
+ | Add dummy email addresses for unit tests. | ## Code Before:
from __future__ import absolute_import
from .base import *
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'travis-xxxxxxxxxxxxxxxx'
## Instruction:
Add dummy email addresses for unit tests.
## Code After:
from __future__ import absolute_import
from .base import *
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'travis-xxxxxxxxxxxxxxxx'
#Emails
MDOT_HELP_EMAIL = 'test@testcase.edu' # String for help desk email address
MDOT_UX_EMAIL = 'test@testcase.edu' # String for UX team email address
MDOT_FORM_EMAIL = 'test@testcase.edu' # String to email app publishing requests
| from __future__ import absolute_import
from .base import *
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'travis-xxxxxxxxxxxxxxxx'
+
+ #Emails
+ MDOT_HELP_EMAIL = 'test@testcase.edu' # String for help desk email address
+ MDOT_UX_EMAIL = 'test@testcase.edu' # String for UX team email address
+ MDOT_FORM_EMAIL = 'test@testcase.edu' # String to email app publishing requests |
7aaef53e5547abfca8eb64ceb4ac477a14b79536 | tensorflow_datasets/core/visualization/__init__.py | tensorflow_datasets/core/visualization/__init__.py |
"""Visualizer utils."""
from tensorflow_datasets.core.visualization.image_visualizer import ImageGridVisualizer
from tensorflow_datasets.core.visualization.show_examples import show_examples
from tensorflow_datasets.core.visualization.show_examples import show_statistics
from tensorflow_datasets.core.visualization.visualizer import Visualizer
__all__ = [
"ImageGridVisualizer",
"show_examples",
"Visualizer",
]
|
"""Visualizer utils."""
from tensorflow_datasets.core.visualization.image_visualizer import ImageGridVisualizer
from tensorflow_datasets.core.visualization.show_examples import show_examples
from tensorflow_datasets.core.visualization.show_examples import show_statistics
from tensorflow_datasets.core.visualization.visualizer import Visualizer
__all__ = [
"ImageGridVisualizer",
"show_examples",
"show_statistics",
"Visualizer",
]
| Add show_statistics to public API | Add show_statistics to public API
PiperOrigin-RevId: 322842576
| Python | apache-2.0 | tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets |
"""Visualizer utils."""
from tensorflow_datasets.core.visualization.image_visualizer import ImageGridVisualizer
from tensorflow_datasets.core.visualization.show_examples import show_examples
from tensorflow_datasets.core.visualization.show_examples import show_statistics
from tensorflow_datasets.core.visualization.visualizer import Visualizer
__all__ = [
"ImageGridVisualizer",
"show_examples",
+ "show_statistics",
"Visualizer",
]
| Add show_statistics to public API | ## Code Before:
"""Visualizer utils."""
from tensorflow_datasets.core.visualization.image_visualizer import ImageGridVisualizer
from tensorflow_datasets.core.visualization.show_examples import show_examples
from tensorflow_datasets.core.visualization.show_examples import show_statistics
from tensorflow_datasets.core.visualization.visualizer import Visualizer
__all__ = [
"ImageGridVisualizer",
"show_examples",
"Visualizer",
]
## Instruction:
Add show_statistics to public API
## Code After:
"""Visualizer utils."""
from tensorflow_datasets.core.visualization.image_visualizer import ImageGridVisualizer
from tensorflow_datasets.core.visualization.show_examples import show_examples
from tensorflow_datasets.core.visualization.show_examples import show_statistics
from tensorflow_datasets.core.visualization.visualizer import Visualizer
__all__ = [
"ImageGridVisualizer",
"show_examples",
"show_statistics",
"Visualizer",
]
|
"""Visualizer utils."""
from tensorflow_datasets.core.visualization.image_visualizer import ImageGridVisualizer
from tensorflow_datasets.core.visualization.show_examples import show_examples
from tensorflow_datasets.core.visualization.show_examples import show_statistics
from tensorflow_datasets.core.visualization.visualizer import Visualizer
__all__ = [
"ImageGridVisualizer",
"show_examples",
+ "show_statistics",
"Visualizer",
] |
e2aa41bb84984fea4c6b8ea475caf7f7af051dd9 | gaphor/codegen/codegen.py | gaphor/codegen/codegen.py |
import argparse
from distutils.util import byte_compile
from pathlib import Path
from gaphor.codegen import profile_coder, uml_coder
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("modelfile", type=Path, help="gaphor model filename")
parser.add_argument("outfile", type=Path, help="python data model filename")
parser.add_argument("overrides", type=Path, help="override filename")
parser.add_argument(
"--uml_profile", help="generate a UML profile", action="store_true"
)
parser.add_argument(
"--sysml_profile", help="generate a SysML profile", action="store_true"
)
args = parser.parse_args()
print(f"Generating {args.outfile} from {args.modelfile}...")
print(" (warnings can be ignored)")
if args.uml_profile:
profile_coder.generate(args.modelfile, args.outfile, args.overrides)
elif args.sysml_profile:
profile_coder.generate(args.modelfile, args.outfile, args.overrides, True)
else:
uml_coder.generate(args.modelfile, args.outfile, args.overrides)
byte_compile([str(args.outfile)])
if __name__ == "__main__":
main()
|
import argparse
from distutils.util import byte_compile
from pathlib import Path
from gaphor.codegen import profile_coder, uml_coder
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("modelfile", type=Path, help="gaphor model filename")
parser.add_argument("outfile", type=Path, help="python data model filename")
parser.add_argument("overrides", type=Path, help="override filename")
parser.add_argument(
"--uml_profile", help="generate a UML profile", action="store_true"
)
parser.add_argument(
"--sysml_profile", help="generate a SysML profile", action="store_true"
)
args = parser.parse_args()
print(f"Generating {args.outfile} from {args.modelfile}...")
print(" (warnings can be ignored)")
if args.uml_profile:
profile_coder.generate(args.modelfile, args.outfile, args.overrides)
elif args.sysml_profile:
profile_coder.generate(
args.modelfile, args.outfile, args.overrides, includes_sysml=True
)
else:
uml_coder.generate(args.modelfile, args.outfile, args.overrides)
byte_compile([str(args.outfile)])
if __name__ == "__main__":
main()
| Use positional argument to improve clarity | Use positional argument to improve clarity
Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
| Python | lgpl-2.1 | amolenaar/gaphor,amolenaar/gaphor |
import argparse
from distutils.util import byte_compile
from pathlib import Path
from gaphor.codegen import profile_coder, uml_coder
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("modelfile", type=Path, help="gaphor model filename")
parser.add_argument("outfile", type=Path, help="python data model filename")
parser.add_argument("overrides", type=Path, help="override filename")
parser.add_argument(
"--uml_profile", help="generate a UML profile", action="store_true"
)
parser.add_argument(
"--sysml_profile", help="generate a SysML profile", action="store_true"
)
args = parser.parse_args()
print(f"Generating {args.outfile} from {args.modelfile}...")
print(" (warnings can be ignored)")
if args.uml_profile:
profile_coder.generate(args.modelfile, args.outfile, args.overrides)
elif args.sysml_profile:
- profile_coder.generate(args.modelfile, args.outfile, args.overrides, True)
+ profile_coder.generate(
+ args.modelfile, args.outfile, args.overrides, includes_sysml=True
+ )
else:
uml_coder.generate(args.modelfile, args.outfile, args.overrides)
byte_compile([str(args.outfile)])
if __name__ == "__main__":
main()
| Use positional argument to improve clarity | ## Code Before:
import argparse
from distutils.util import byte_compile
from pathlib import Path
from gaphor.codegen import profile_coder, uml_coder
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("modelfile", type=Path, help="gaphor model filename")
parser.add_argument("outfile", type=Path, help="python data model filename")
parser.add_argument("overrides", type=Path, help="override filename")
parser.add_argument(
"--uml_profile", help="generate a UML profile", action="store_true"
)
parser.add_argument(
"--sysml_profile", help="generate a SysML profile", action="store_true"
)
args = parser.parse_args()
print(f"Generating {args.outfile} from {args.modelfile}...")
print(" (warnings can be ignored)")
if args.uml_profile:
profile_coder.generate(args.modelfile, args.outfile, args.overrides)
elif args.sysml_profile:
profile_coder.generate(args.modelfile, args.outfile, args.overrides, True)
else:
uml_coder.generate(args.modelfile, args.outfile, args.overrides)
byte_compile([str(args.outfile)])
if __name__ == "__main__":
main()
## Instruction:
Use positional argument to improve clarity
## Code After:
import argparse
from distutils.util import byte_compile
from pathlib import Path
from gaphor.codegen import profile_coder, uml_coder
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("modelfile", type=Path, help="gaphor model filename")
parser.add_argument("outfile", type=Path, help="python data model filename")
parser.add_argument("overrides", type=Path, help="override filename")
parser.add_argument(
"--uml_profile", help="generate a UML profile", action="store_true"
)
parser.add_argument(
"--sysml_profile", help="generate a SysML profile", action="store_true"
)
args = parser.parse_args()
print(f"Generating {args.outfile} from {args.modelfile}...")
print(" (warnings can be ignored)")
if args.uml_profile:
profile_coder.generate(args.modelfile, args.outfile, args.overrides)
elif args.sysml_profile:
profile_coder.generate(
args.modelfile, args.outfile, args.overrides, includes_sysml=True
)
else:
uml_coder.generate(args.modelfile, args.outfile, args.overrides)
byte_compile([str(args.outfile)])
if __name__ == "__main__":
main()
|
import argparse
from distutils.util import byte_compile
from pathlib import Path
from gaphor.codegen import profile_coder, uml_coder
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("modelfile", type=Path, help="gaphor model filename")
parser.add_argument("outfile", type=Path, help="python data model filename")
parser.add_argument("overrides", type=Path, help="override filename")
parser.add_argument(
"--uml_profile", help="generate a UML profile", action="store_true"
)
parser.add_argument(
"--sysml_profile", help="generate a SysML profile", action="store_true"
)
args = parser.parse_args()
print(f"Generating {args.outfile} from {args.modelfile}...")
print(" (warnings can be ignored)")
if args.uml_profile:
profile_coder.generate(args.modelfile, args.outfile, args.overrides)
elif args.sysml_profile:
- profile_coder.generate(args.modelfile, args.outfile, args.overrides, True)
+ profile_coder.generate(
+ args.modelfile, args.outfile, args.overrides, includes_sysml=True
+ )
else:
uml_coder.generate(args.modelfile, args.outfile, args.overrides)
byte_compile([str(args.outfile)])
if __name__ == "__main__":
main() |
8b351036f6431bd760565b23d9e887e7d8a73840 | mysql_statsd/thread_manager.py | mysql_statsd/thread_manager.py | import Queue
import signal
import threading
import time
class ThreadManager():
"""Knows how to manage dem threads"""
quit = False
quitting = False
threads = []
def __init__(self, queue=Queue.Queue(), threads=[], config={}):
"""Program entry point"""
# Set up queue
self.queue = Queue.Queue()
self.config = config
self.threads = threads
self.register_signal_handlers()
def register_signal_handlers(self):
# Register signal handler
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler)
def run(self):
# Main loop
self.start_threads()
while not self.quit:
time.sleep(1)
def start_threads(self):
for t in self.threads:
t.start()
def signal_handler(self, signal, frame):
""" Handle signals """
print("Caught CTRL+C / SIGKILL")
if not self.quitting:
self.quitting = True
self.stop_threads()
self.quit = True
else:
print("BE PATIENT!@#~!#!@#$~!`1111")
def stop_threads(self):
"""Stops all threads and waits for them to quit"""
print("Stopping threads")
for thread in self.threads:
thread.stop()
while threading.activeCount() > 1:
print("Waiting for %s threads" % threading.activeCount())
time.sleep(1)
print("All threads stopped")
| import Queue
import signal
import threading
import time
class ThreadManager():
"""Knows how to manage dem threads"""
quit = False
quitting = False
threads = []
def __init__(self, threads=[]):
"""Program entry point"""
self.threads = threads
self.register_signal_handlers()
def register_signal_handlers(self):
# Register signal handler
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler)
def run(self):
# Main loop
self.start_threads()
while not self.quit:
time.sleep(1)
def start_threads(self):
for t in self.threads:
t.start()
def signal_handler(self, signal, frame):
""" Handle signals """
print("Caught CTRL+C / SIGKILL")
if not self.quitting:
self.quitting = True
self.stop_threads()
self.quit = True
else:
print("BE PATIENT!@#~!#!@#$~!`1111")
def stop_threads(self):
"""Stops all threads and waits for them to quit"""
print("Stopping threads")
for thread in self.threads:
thread.stop()
while threading.activeCount() > 1:
print("Waiting for %s threads" % threading.activeCount())
time.sleep(1)
print("All threads stopped")
| Remove config handling from threadmanager (was unused) | Remove config handling from threadmanager (was unused)
| Python | bsd-3-clause | spilgames/mysql-statsd,medvedik/mysql-statsd,art-spilgames/mysql-statsd,db-art/mysql-statsd,medvedik/mysql-statsd,bnkr/mysql-statsd | import Queue
import signal
import threading
import time
class ThreadManager():
"""Knows how to manage dem threads"""
quit = False
quitting = False
threads = []
- def __init__(self, queue=Queue.Queue(), threads=[], config={}):
+ def __init__(self, threads=[]):
"""Program entry point"""
-
- # Set up queue
- self.queue = Queue.Queue()
- self.config = config
self.threads = threads
-
self.register_signal_handlers()
def register_signal_handlers(self):
# Register signal handler
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler)
def run(self):
# Main loop
self.start_threads()
while not self.quit:
time.sleep(1)
def start_threads(self):
for t in self.threads:
t.start()
def signal_handler(self, signal, frame):
""" Handle signals """
print("Caught CTRL+C / SIGKILL")
if not self.quitting:
self.quitting = True
self.stop_threads()
self.quit = True
else:
print("BE PATIENT!@#~!#!@#$~!`1111")
def stop_threads(self):
"""Stops all threads and waits for them to quit"""
print("Stopping threads")
for thread in self.threads:
thread.stop()
while threading.activeCount() > 1:
print("Waiting for %s threads" % threading.activeCount())
time.sleep(1)
print("All threads stopped")
| Remove config handling from threadmanager (was unused) | ## Code Before:
import Queue
import signal
import threading
import time
class ThreadManager():
"""Knows how to manage dem threads"""
quit = False
quitting = False
threads = []
def __init__(self, queue=Queue.Queue(), threads=[], config={}):
"""Program entry point"""
# Set up queue
self.queue = Queue.Queue()
self.config = config
self.threads = threads
self.register_signal_handlers()
def register_signal_handlers(self):
# Register signal handler
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler)
def run(self):
# Main loop
self.start_threads()
while not self.quit:
time.sleep(1)
def start_threads(self):
for t in self.threads:
t.start()
def signal_handler(self, signal, frame):
""" Handle signals """
print("Caught CTRL+C / SIGKILL")
if not self.quitting:
self.quitting = True
self.stop_threads()
self.quit = True
else:
print("BE PATIENT!@#~!#!@#$~!`1111")
def stop_threads(self):
"""Stops all threads and waits for them to quit"""
print("Stopping threads")
for thread in self.threads:
thread.stop()
while threading.activeCount() > 1:
print("Waiting for %s threads" % threading.activeCount())
time.sleep(1)
print("All threads stopped")
## Instruction:
Remove config handling from threadmanager (was unused)
## Code After:
import Queue
import signal
import threading
import time
class ThreadManager():
"""Knows how to manage dem threads"""
quit = False
quitting = False
threads = []
def __init__(self, threads=[]):
"""Program entry point"""
self.threads = threads
self.register_signal_handlers()
def register_signal_handlers(self):
# Register signal handler
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler)
def run(self):
# Main loop
self.start_threads()
while not self.quit:
time.sleep(1)
def start_threads(self):
for t in self.threads:
t.start()
def signal_handler(self, signal, frame):
""" Handle signals """
print("Caught CTRL+C / SIGKILL")
if not self.quitting:
self.quitting = True
self.stop_threads()
self.quit = True
else:
print("BE PATIENT!@#~!#!@#$~!`1111")
def stop_threads(self):
"""Stops all threads and waits for them to quit"""
print("Stopping threads")
for thread in self.threads:
thread.stop()
while threading.activeCount() > 1:
print("Waiting for %s threads" % threading.activeCount())
time.sleep(1)
print("All threads stopped")
| import Queue
import signal
import threading
import time
class ThreadManager():
"""Knows how to manage dem threads"""
quit = False
quitting = False
threads = []
- def __init__(self, queue=Queue.Queue(), threads=[], config={}):
+ def __init__(self, threads=[]):
"""Program entry point"""
-
- # Set up queue
- self.queue = Queue.Queue()
- self.config = config
self.threads = threads
-
self.register_signal_handlers()
def register_signal_handlers(self):
# Register signal handler
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler)
def run(self):
# Main loop
self.start_threads()
while not self.quit:
time.sleep(1)
def start_threads(self):
for t in self.threads:
t.start()
def signal_handler(self, signal, frame):
""" Handle signals """
print("Caught CTRL+C / SIGKILL")
if not self.quitting:
self.quitting = True
self.stop_threads()
self.quit = True
else:
print("BE PATIENT!@#~!#!@#$~!`1111")
def stop_threads(self):
"""Stops all threads and waits for them to quit"""
print("Stopping threads")
for thread in self.threads:
thread.stop()
while threading.activeCount() > 1:
print("Waiting for %s threads" % threading.activeCount())
time.sleep(1)
print("All threads stopped") |
281a096cea735845bdb74d60abf14f1422f2c624 | test_runner/executable.py | test_runner/executable.py | import argh
from .environments import Environment
from .frameworks import Tempest
from .utils import cleanup, Reporter
LOG = Reporter(__name__).setup()
def main(endpoint, username='admin', password='secrete', test_path='api'):
environment = Environment(username, password, endpoint)
with cleanup(environment):
environment.build()
framework = Tempest(environment, repo_dir='/opt/tempest',
test_path=test_path)
results = framework.run_tests()
LOG.info('Results: {0}'.format(results))
if __name__ == '__main__':
argh.dispatch_command(main)
| import argh
from .environments import Environment
from .frameworks import Tempest
from .utils import cleanup, Reporter
LOG = Reporter(__name__).setup()
def main(endpoint, username='admin', password='secrete', test_path='api'):
environment = Environment(username, password, endpoint)
with cleanup(environment):
environment.build()
framework = Tempest(environment, repo_dir='/opt/tempest',
test_path=test_path)
results = framework.run_tests()
LOG.info('Results: {0}'.format(results))
argh.dispatch_command(main)
| Move command dispatch into full module | Move command dispatch into full module
| Python | mit | rcbops-qa/test_runner | import argh
from .environments import Environment
from .frameworks import Tempest
from .utils import cleanup, Reporter
LOG = Reporter(__name__).setup()
def main(endpoint, username='admin', password='secrete', test_path='api'):
environment = Environment(username, password, endpoint)
with cleanup(environment):
environment.build()
framework = Tempest(environment, repo_dir='/opt/tempest',
test_path=test_path)
results = framework.run_tests()
LOG.info('Results: {0}'.format(results))
+ argh.dispatch_command(main)
- if __name__ == '__main__':
- argh.dispatch_command(main)
- | Move command dispatch into full module | ## Code Before:
import argh
from .environments import Environment
from .frameworks import Tempest
from .utils import cleanup, Reporter
LOG = Reporter(__name__).setup()
def main(endpoint, username='admin', password='secrete', test_path='api'):
environment = Environment(username, password, endpoint)
with cleanup(environment):
environment.build()
framework = Tempest(environment, repo_dir='/opt/tempest',
test_path=test_path)
results = framework.run_tests()
LOG.info('Results: {0}'.format(results))
if __name__ == '__main__':
argh.dispatch_command(main)
## Instruction:
Move command dispatch into full module
## Code After:
import argh
from .environments import Environment
from .frameworks import Tempest
from .utils import cleanup, Reporter
LOG = Reporter(__name__).setup()
def main(endpoint, username='admin', password='secrete', test_path='api'):
environment = Environment(username, password, endpoint)
with cleanup(environment):
environment.build()
framework = Tempest(environment, repo_dir='/opt/tempest',
test_path=test_path)
results = framework.run_tests()
LOG.info('Results: {0}'.format(results))
argh.dispatch_command(main)
| import argh
from .environments import Environment
from .frameworks import Tempest
from .utils import cleanup, Reporter
LOG = Reporter(__name__).setup()
def main(endpoint, username='admin', password='secrete', test_path='api'):
environment = Environment(username, password, endpoint)
with cleanup(environment):
environment.build()
framework = Tempest(environment, repo_dir='/opt/tempest',
test_path=test_path)
results = framework.run_tests()
LOG.info('Results: {0}'.format(results))
-
- if __name__ == '__main__':
- argh.dispatch_command(main)
? ----
+ argh.dispatch_command(main) |
642908032012baf200ab227803982730c6d4b083 | stdnum/ca/__init__.py | stdnum/ca/__init__.py |
"""Collection of Canadian numbers."""
|
"""Collection of Canadian numbers."""
from stdnum.ca import bn as vat # noqa: F401
| Add missing vat alias for Canada | Add missing vat alias for Canada
| Python | lgpl-2.1 | arthurdejong/python-stdnum,arthurdejong/python-stdnum,arthurdejong/python-stdnum |
"""Collection of Canadian numbers."""
+ from stdnum.ca import bn as vat # noqa: F401
| Add missing vat alias for Canada | ## Code Before:
"""Collection of Canadian numbers."""
## Instruction:
Add missing vat alias for Canada
## Code After:
"""Collection of Canadian numbers."""
from stdnum.ca import bn as vat # noqa: F401
|
"""Collection of Canadian numbers."""
+ from stdnum.ca import bn as vat # noqa: F401 |
1acd2471f667abf78155ee71fe9c6d8487a284ee | sklearn/linear_model/tests/test_isotonic_regression.py | sklearn/linear_model/tests/test_isotonic_regression.py | import numpy as np
from numpy.testing import assert_array_equal
from sklearn.linear_model.isotonic_regression_ import isotonic_regression
from sklearn.linear_model import IsotonicRegression
from nose.tools import assert_raises
def test_isotonic_regression():
y = np.array([3, 7, 5, 9, 8, 7, 10])
y_ = np.array([3, 6, 6, 8, 8, 8, 10])
assert_array_equal(y_, isotonic_regression(y))
x = np.arange(len(y))
ir = IsotonicRegression(x_min=0., x_max=1.)
ir.fit(x, y)
assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y))
assert_array_equal(ir.transform(x), ir.predict(x))
def test_assert_raises_exceptions():
ir = IsotonicRegression()
assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7, 3], [0.1, 0.6])
assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7])
assert_raises(ValueError, ir.fit, np.random.randn(3, 10), [0, 1, 2])
assert_raises(ValueError, ir.transform, np.random.randn(3, 10))
| import numpy as np
from numpy.testing import assert_array_equal
from sklearn.linear_model.isotonic_regression_ import isotonic_regression
from sklearn.linear_model import IsotonicRegression
from nose.tools import assert_raises
def test_isotonic_regression():
y = np.array([3, 7, 5, 9, 8, 7, 10])
y_ = np.array([3, 6, 6, 8, 8, 8, 10])
assert_array_equal(y_, isotonic_regression(y))
x = np.arange(len(y))
ir = IsotonicRegression(x_min=0., x_max=1.)
ir.fit(x, y)
assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y))
assert_array_equal(ir.transform(x), ir.predict(x))
def test_assert_raises_exceptions():
ir = IsotonicRegression()
rng = np.random.RandomState(42)
assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7, 3], [0.1, 0.6])
assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7])
assert_raises(ValueError, ir.fit, rng.randn(3, 10), [0, 1, 2])
assert_raises(ValueError, ir.transform, rng.randn(3, 10))
| FIX : fix LLE test (don't ask me why...) | FIX : fix LLE test (don't ask me why...)
| Python | bsd-3-clause | untom/scikit-learn,trungnt13/scikit-learn,nrhine1/scikit-learn,hrjn/scikit-learn,arjoly/scikit-learn,rohanp/scikit-learn,khkaminska/scikit-learn,ky822/scikit-learn,JosmanPS/scikit-learn,madjelan/scikit-learn,PatrickOReilly/scikit-learn,arjoly/scikit-learn,fabioticconi/scikit-learn,olologin/scikit-learn,saiwing-yeung/scikit-learn,nhejazi/scikit-learn,abhishekgahlot/scikit-learn,rahul-c1/scikit-learn,zhenv5/scikit-learn,MechCoder/scikit-learn,lenovor/scikit-learn,elkingtonmcb/scikit-learn,abhishekkrthakur/scikit-learn,LiaoPan/scikit-learn,ClimbsRocks/scikit-learn,rvraghav93/scikit-learn,pypot/scikit-learn,jereze/scikit-learn,yonglehou/scikit-learn,Obus/scikit-learn,larsmans/scikit-learn,shangwuhencc/scikit-learn,JPFrancoia/scikit-learn,f3r/scikit-learn,jm-begon/scikit-learn,pianomania/scikit-learn,treycausey/scikit-learn,sanketloke/scikit-learn,jayflo/scikit-learn,aabadie/scikit-learn,wzbozon/scikit-learn,mwv/scikit-learn,NunoEdgarGub1/scikit-learn,Myasuka/scikit-learn,mrshu/scikit-learn,Srisai85/scikit-learn,procoder317/scikit-learn,CVML/scikit-learn,petosegan/scikit-learn,hainm/scikit-learn,xiaoxiamii/scikit-learn,aabadie/scikit-learn,kagayakidan/scikit-learn,ashhher3/scikit-learn,bigdataelephants/scikit-learn,ashhher3/scikit-learn,CforED/Machine-Learning,MartinDelzant/scikit-learn,wlamond/scikit-learn,anurag313/scikit-learn,moutai/scikit-learn,Barmaley-exe/scikit-learn,waterponey/scikit-learn,qifeigit/scikit-learn,espg/scikit-learn,iismd17/scikit-learn,xubenben/scikit-learn,Achuth17/scikit-learn,treycausey/scikit-learn,maheshakya/scikit-learn,Garrett-R/scikit-learn,depet/scikit-learn,anirudhjayaraman/scikit-learn,andaag/scikit-learn,ahoyosid/scikit-learn,lesteve/scikit-learn,DonBeo/scikit-learn,kagayakidan/scikit-learn,lazywei/scikit-learn,saiwing-yeung/scikit-learn,Vimos/scikit-learn,nvoron23/scikit-learn,vybstat/scikit-learn,spallavolu/scikit-learn,AlexandreAbraham/scikit-learn,ishanic/scikit-learn,sonnyhu/scikit-learn,ZenDevelopmentSystems/scikit-learn,mattilyra/scikit-learn,ilyes14/scikit-learn,hsuantien/scikit-learn,aabadie/scikit-learn,robbymeals/scikit-learn,vibhorag/scikit-learn,mattilyra/scikit-learn,glemaitre/scikit-learn,ltiao/scikit-learn,jakobworldpeace/scikit-learn,jkarnows/scikit-learn,deepesch/scikit-learn,cainiaocome/scikit-learn,r-mart/scikit-learn,jjx02230808/project0223,AlexanderFabisch/scikit-learn,carrillo/scikit-learn,imaculate/scikit-learn,carrillo/scikit-learn,chrsrds/scikit-learn,shenzebang/scikit-learn,trankmichael/scikit-learn,btabibian/scikit-learn,nomadcube/scikit-learn,mikebenfield/scikit-learn,Lawrence-Liu/scikit-learn,wlamond/scikit-learn,henrykironde/scikit-learn,huobaowangxi/scikit-learn,nikitasingh981/scikit-learn,fabianp/scikit-learn,lucidfrontier45/scikit-learn,waterponey/scikit-learn,joernhees/scikit-learn,xyguo/scikit-learn,Obus/scikit-learn,fredhusser/scikit-learn,bhargav/scikit-learn,harshaneelhg/scikit-learn,florian-f/sklearn,adamgreenhall/scikit-learn,eickenberg/scikit-learn,UNR-AERIAL/scikit-learn,mayblue9/scikit-learn,murali-munna/scikit-learn,3manuek/scikit-learn,aflaxman/scikit-learn,saiwing-yeung/scikit-learn,potash/scikit-learn,mikebenfield/scikit-learn,ivannz/scikit-learn,jayflo/scikit-learn,massmutual/scikit-learn,zaxtax/scikit-learn,r-mart/scikit-learn,dhruv13J/scikit-learn,0x0all/scikit-learn,theoryno3/scikit-learn,pianomania/scikit-learn,olologin/scikit-learn,kjung/scikit-learn,zuku1985/scikit-learn,AIML/scikit-learn,abhishekgahlot/scikit-learn,ivannz/scikit-learn,ChanderG/scikit-learn,Obus/scikit-learn,shangwuhencc/scikit-learn,bikong2/scikit-learn,xiaoxiamii/scikit-learn,Lawrence-Liu/scikit-learn,altairpearl/scikit-learn,kevin-intel/scikit-learn,tmhm/scikit-learn,aewhatley/scikit-learn,russel1237/scikit-learn,belltailjp/scikit-learn,yanlend/scikit-learn,wzbozon/scikit-learn,hrjn/scikit-learn,smartscheduling/scikit-learn-categorical-tree,shyamalschandra/scikit-learn,chrsrds/scikit-learn,xwolf12/scikit-learn,DSLituiev/scikit-learn,zorojean/scikit-learn,zuku1985/scikit-learn,fbagirov/scikit-learn,jblackburne/scikit-learn,beepee14/scikit-learn,Fireblend/scikit-learn,saiwing-yeung/scikit-learn,huzq/scikit-learn,espg/scikit-learn,fabioticconi/scikit-learn,giorgiop/scikit-learn,ilo10/scikit-learn,rexshihaoren/scikit-learn,Srisai85/scikit-learn,ZenDevelopmentSystems/scikit-learn,liangz0707/scikit-learn,NunoEdgarGub1/scikit-learn,Akshay0724/scikit-learn,q1ang/scikit-learn,poryfly/scikit-learn,arabenjamin/scikit-learn,UNR-AERIAL/scikit-learn,CforED/Machine-Learning,marcocaccin/scikit-learn,Jimmy-Morzaria/scikit-learn,alvarofierroclavero/scikit-learn,madjelan/scikit-learn,wzbozon/scikit-learn,hsuantien/scikit-learn,MatthieuBizien/scikit-learn,cybernet14/scikit-learn,fyffyt/scikit-learn,PrashntS/scikit-learn,IshankGulati/scikit-learn,kashif/scikit-learn,ClimbsRocks/scikit-learn,HolgerPeters/scikit-learn,shyamalschandra/scikit-learn,sergeyf/scikit-learn,joernhees/scikit-learn,mrshu/scikit-learn,billy-inn/scikit-learn,zaxtax/scikit-learn,xyguo/scikit-learn,TomDLT/scikit-learn,fabianp/scikit-learn,0asa/scikit-learn,bnaul/scikit-learn,pnedunuri/scikit-learn,cybernet14/scikit-learn,procoder317/scikit-learn,jakirkham/scikit-learn,amueller/scikit-learn,imaculate/scikit-learn,elkingtonmcb/scikit-learn,frank-tancf/scikit-learn,pratapvardhan/scikit-learn,devanshdalal/scikit-learn,fbagirov/scikit-learn,AlexandreAbraham/scikit-learn,B3AU/waveTree,gclenaghan/scikit-learn,q1ang/scikit-learn,walterreade/scikit-learn,hainm/scikit-learn,billy-inn/scikit-learn,samzhang111/scikit-learn,DSLituiev/scikit-learn,tdhopper/scikit-learn,xyguo/scikit-learn,sonnyhu/scikit-learn,harshaneelhg/scikit-learn,Jimmy-Morzaria/scikit-learn,BiaDarkia/scikit-learn,davidgbe/scikit-learn,murali-munna/scikit-learn,shikhardb/scikit-learn,nvoron23/scikit-learn,mhdella/scikit-learn,evgchz/scikit-learn,schets/scikit-learn,smartscheduling/scikit-learn-categorical-tree,nelson-liu/scikit-learn,aminert/scikit-learn,ephes/scikit-learn,kashif/scikit-learn,procoder317/scikit-learn,PatrickChrist/scikit-learn,PrashntS/scikit-learn,bigdataelephants/scikit-learn,ngoix/OCRF,f3r/scikit-learn,phdowling/scikit-learn,vibhorag/scikit-learn,jm-begon/scikit-learn,xiaoxiamii/scikit-learn,Titan-C/scikit-learn,giorgiop/scikit-learn,manashmndl/scikit-learn,yonglehou/scikit-learn,henridwyer/scikit-learn,mhue/scikit-learn,terkkila/scikit-learn,ycaihua/scikit-learn,kjung/scikit-learn,ashhher3/scikit-learn,herilalaina/scikit-learn,moutai/scikit-learn,mjudsp/Tsallis,alexsavio/scikit-learn,glouppe/scikit-learn,pythonvietnam/scikit-learn,ldirer/scikit-learn,arahuja/scikit-learn,YinongLong/scikit-learn,ky822/scikit-learn,theoryno3/scikit-learn,cl4rke/scikit-learn,devanshdalal/scikit-learn,aminert/scikit-learn,amueller/scikit-learn,potash/scikit-learn,MartinDelzant/scikit-learn,bhargav/scikit-learn,CforED/Machine-Learning,ogrisel/scikit-learn,tosolveit/scikit-learn,rahuldhote/scikit-learn,marcocaccin/scikit-learn,thilbern/scikit-learn,hitszxp/scikit-learn,JPFrancoia/scikit-learn,ogrisel/scikit-learn,etkirsch/scikit-learn,xwolf12/scikit-learn,tmhm/scikit-learn,simon-pepin/scikit-learn,fengzhyuan/scikit-learn,Fireblend/scikit-learn,wazeerzulfikar/scikit-learn,sarahgrogan/scikit-learn,equialgo/scikit-learn,PatrickOReilly/scikit-learn,mugizico/scikit-learn,rrohan/scikit-learn,jm-begon/scikit-learn,bigdataelephants/scikit-learn,RayMick/scikit-learn,treycausey/scikit-learn,bhargav/scikit-learn,vinayak-mehta/scikit-learn,cainiaocome/scikit-learn,plissonf/scikit-learn,murali-munna/scikit-learn,Vimos/scikit-learn,abimannans/scikit-learn,cwu2011/scikit-learn,mayblue9/scikit-learn,shangwuhencc/scikit-learn,ngoix/OCRF,yanlend/scikit-learn,jlegendary/scikit-learn,yask123/scikit-learn,stylianos-kampakis/scikit-learn,bigdataelephants/scikit-learn,liyu1990/sklearn,ClimbsRocks/scikit-learn,themrmax/scikit-learn,Windy-Ground/scikit-learn,zihua/scikit-learn,vshtanko/scikit-learn,PatrickChrist/scikit-learn,CVML/scikit-learn,mugizico/scikit-learn,russel1237/scikit-learn,cauchycui/scikit-learn,costypetrisor/scikit-learn,B3AU/waveTree,jjx02230808/project0223,beepee14/scikit-learn,yunfeilu/scikit-learn,kylerbrown/scikit-learn,jakirkham/scikit-learn,kmike/scikit-learn,Aasmi/scikit-learn,NelisVerhoef/scikit-learn,xavierwu/scikit-learn,lesteve/scikit-learn,ltiao/scikit-learn,joernhees/scikit-learn,ephes/scikit-learn,abimannans/scikit-learn,tomlof/scikit-learn,samzhang111/scikit-learn,hlin117/scikit-learn,ankurankan/scikit-learn,kmike/scikit-learn,thientu/scikit-learn,maheshakya/scikit-learn,anntzer/scikit-learn,davidgbe/scikit-learn,luo66/scikit-learn,gotomypc/scikit-learn,ZENGXH/scikit-learn,sanketloke/scikit-learn,djgagne/scikit-learn,yonglehou/scikit-learn,MartinSavc/scikit-learn,clemkoa/scikit-learn,MohammedWasim/scikit-learn,aewhatley/scikit-learn,jorik041/scikit-learn,xavierwu/scikit-learn,adamgreenhall/scikit-learn,rahuldhote/scikit-learn,manhhomienbienthuy/scikit-learn,evgchz/scikit-learn,maheshakya/scikit-learn,shangwuhencc/scikit-learn,madjelan/scikit-learn,lazywei/scikit-learn,kevin-intel/scikit-learn,Achuth17/scikit-learn,hdmetor/scikit-learn,yanlend/scikit-learn,ldirer/scikit-learn,alexsavio/scikit-learn,AlexanderFabisch/scikit-learn,Nyker510/scikit-learn,jmetzen/scikit-learn,RPGOne/scikit-learn,466152112/scikit-learn,xuewei4d/scikit-learn,0asa/scikit-learn,alexsavio/scikit-learn,murali-munna/scikit-learn,ilo10/scikit-learn,h2educ/scikit-learn,h2educ/scikit-learn,manashmndl/scikit-learn,0asa/scikit-learn,Srisai85/scikit-learn,zorojean/scikit-learn,manhhomienbienthuy/scikit-learn,rvraghav93/scikit-learn,kylerbrown/scikit-learn,fabianp/scikit-learn,moutai/scikit-learn,lesteve/scikit-learn,sinhrks/scikit-learn,ningchi/scikit-learn,aflaxman/scikit-learn,etkirsch/scikit-learn,jorge2703/scikit-learn,fzalkow/scikit-learn,mxjl620/scikit-learn,jereze/scikit-learn,nvoron23/scikit-learn,massmutual/scikit-learn,Myasuka/scikit-learn,samuel1208/scikit-learn,vinayak-mehta/scikit-learn,r-mart/scikit-learn,krez13/scikit-learn,Windy-Ground/scikit-learn,kaichogami/scikit-learn,xuewei4d/scikit-learn,appapantula/scikit-learn,joshloyal/scikit-learn,justincassidy/scikit-learn,jaidevd/scikit-learn,LohithBlaze/scikit-learn,fengzhyuan/scikit-learn,AnasGhrab/scikit-learn,0x0all/scikit-learn,mrshu/scikit-learn,IndraVikas/scikit-learn,alexeyum/scikit-learn,anntzer/scikit-learn,Myasuka/scikit-learn,NunoEdgarGub1/scikit-learn,mjudsp/Tsallis,henridwyer/scikit-learn,vivekmishra1991/scikit-learn,yyjiang/scikit-learn,UNR-AERIAL/scikit-learn,Djabbz/scikit-learn,Garrett-R/scikit-learn,nhejazi/scikit-learn,henridwyer/scikit-learn,sergeyf/scikit-learn,zihua/scikit-learn,Aasmi/scikit-learn,kylerbrown/scikit-learn,glennq/scikit-learn,jmschrei/scikit-learn,voxlol/scikit-learn,f3r/scikit-learn,JosmanPS/scikit-learn,dsquareindia/scikit-learn,icdishb/scikit-learn,loli/semisupervisedforests,466152112/scikit-learn,pompiduskus/scikit-learn,roxyboy/scikit-learn,anntzer/scikit-learn,xzh86/scikit-learn,ogrisel/scikit-learn,akionakamura/scikit-learn,Garrett-R/scikit-learn,mlyundin/scikit-learn,RayMick/scikit-learn,nesterione/scikit-learn,abimannans/scikit-learn,AlexandreAbraham/scikit-learn,evgchz/scikit-learn,arjoly/scikit-learn,betatim/scikit-learn,kevin-intel/scikit-learn,pypot/scikit-learn,lazywei/scikit-learn,jjx02230808/project0223,potash/scikit-learn,jakobworldpeace/scikit-learn,dingocuster/scikit-learn,dingocuster/scikit-learn,sumspr/scikit-learn,bnaul/scikit-learn,Adai0808/scikit-learn,pompiduskus/scikit-learn,trankmichael/scikit-learn,elkingtonmcb/scikit-learn,vibhorag/scikit-learn,petosegan/scikit-learn,dsullivan7/scikit-learn,eickenberg/scikit-learn,equialgo/scikit-learn,petosegan/scikit-learn,ishanic/scikit-learn,lin-credible/scikit-learn,shahankhatch/scikit-learn,shusenl/scikit-learn,equialgo/scikit-learn,glennq/scikit-learn,xavierwu/scikit-learn,mxjl620/scikit-learn,anirudhjayaraman/scikit-learn,justincassidy/scikit-learn,nesterione/scikit-learn,schets/scikit-learn,tmhm/scikit-learn,siutanwong/scikit-learn,bthirion/scikit-learn,Myasuka/scikit-learn,IssamLaradji/scikit-learn,jzt5132/scikit-learn,abimannans/scikit-learn,ycaihua/scikit-learn,cauchycui/scikit-learn,BiaDarkia/scikit-learn,kylerbrown/scikit-learn,altairpearl/scikit-learn,tawsifkhan/scikit-learn,huobaowangxi/scikit-learn,florian-f/sklearn,ZENGXH/scikit-learn,nmayorov/scikit-learn,ogrisel/scikit-learn,jkarnows/scikit-learn,yask123/scikit-learn,huobaowangxi/scikit-learn,YinongLong/scikit-learn,jaidevd/scikit-learn,anntzer/scikit-learn,terkkila/scikit-learn,dsullivan7/scikit-learn,xzh86/scikit-learn,amueller/scikit-learn,fyffyt/scikit-learn,fbagirov/scikit-learn,jayflo/scikit-learn,rishikksh20/scikit-learn,marcocaccin/scikit-learn,vybstat/scikit-learn,walterreade/scikit-learn,vshtanko/scikit-learn,raghavrv/scikit-learn,DSLituiev/scikit-learn,loli/sklearn-ensembletrees,abhishekkrthakur/scikit-learn,q1ang/scikit-learn,dsquareindia/scikit-learn,luo66/scikit-learn,sonnyhu/scikit-learn,roxyboy/scikit-learn,alvarofierroclavero/scikit-learn,hugobowne/scikit-learn,betatim/scikit-learn,abhishekkrthakur/scikit-learn,yunfeilu/scikit-learn,vermouthmjl/scikit-learn,kjung/scikit-learn,mattgiguere/scikit-learn,h2educ/scikit-learn,icdishb/scikit-learn,djgagne/scikit-learn,Clyde-fare/scikit-learn,pianomania/scikit-learn,rohanp/scikit-learn,lbishal/scikit-learn,waterponey/scikit-learn,michigraber/scikit-learn,jakobworldpeace/scikit-learn,mikebenfield/scikit-learn,mattilyra/scikit-learn,mfjb/scikit-learn,Adai0808/scikit-learn,ngoix/OCRF,mfjb/scikit-learn,nelson-liu/scikit-learn,r-mart/scikit-learn,IshankGulati/scikit-learn,fzalkow/scikit-learn,MartinDelzant/scikit-learn,imaculate/scikit-learn,mhdella/scikit-learn,yyjiang/scikit-learn,rsivapr/scikit-learn,AlexRobson/scikit-learn,cwu2011/scikit-learn,wanggang3333/scikit-learn,ankurankan/scikit-learn,dingocuster/scikit-learn,ephes/scikit-learn,hitszxp/scikit-learn,BiaDarkia/scikit-learn,nikitasingh981/scikit-learn,mugizico/scikit-learn,mojoboss/scikit-learn,sinhrks/scikit-learn,Akshay0724/scikit-learn,ivannz/scikit-learn,ashhher3/scikit-learn,JeanKossaifi/scikit-learn,zaxtax/scikit-learn,btabibian/scikit-learn,mjgrav2001/scikit-learn,akionakamura/scikit-learn,mxjl620/scikit-learn,Adai0808/scikit-learn,HolgerPeters/scikit-learn,zihua/scikit-learn,gotomypc/scikit-learn,hrjn/scikit-learn,zuku1985/scikit-learn,zihua/scikit-learn,fyffyt/scikit-learn,ZENGXH/scikit-learn,akionakamura/scikit-learn,bthirion/scikit-learn,voxlol/scikit-learn,lazywei/scikit-learn,IndraVikas/scikit-learn,joshloyal/scikit-learn,rrohan/scikit-learn,jblackburne/scikit-learn,lbishal/scikit-learn,ChanChiChoi/scikit-learn,Vimos/scikit-learn,zhenv5/scikit-learn,cwu2011/scikit-learn,dsquareindia/scikit-learn,rajat1994/scikit-learn,Nyker510/scikit-learn,ndingwall/scikit-learn,michigraber/scikit-learn,rajat1994/scikit-learn,ElDeveloper/scikit-learn,joshloyal/scikit-learn,pythonvietnam/scikit-learn,spallavolu/scikit-learn,pompiduskus/scikit-learn,ilo10/scikit-learn,IndraVikas/scikit-learn,xubenben/scikit-learn,giorgiop/scikit-learn,dsquareindia/scikit-learn,hsiaoyi0504/scikit-learn,arahuja/scikit-learn,ltiao/scikit-learn,hsuantien/scikit-learn,MartinDelzant/scikit-learn,heli522/scikit-learn,tomlof/scikit-learn,schets/scikit-learn,MartinSavc/scikit-learn,yonglehou/scikit-learn,hugobowne/scikit-learn,joernhees/scikit-learn,betatim/scikit-learn,MatthieuBizien/scikit-learn,nomadcube/scikit-learn,carrillo/scikit-learn,loli/semisupervisedforests,hdmetor/scikit-learn,Clyde-fare/scikit-learn,anurag313/scikit-learn,kagayakidan/scikit-learn,liberatorqjw/scikit-learn,fredhusser/scikit-learn,hsiaoyi0504/scikit-learn,qifeigit/scikit-learn,thilbern/scikit-learn,billy-inn/scikit-learn,djgagne/scikit-learn,liangz0707/scikit-learn,ankurankan/scikit-learn,betatim/scikit-learn,xubenben/scikit-learn,samuel1208/scikit-learn,0asa/scikit-learn,pkruskal/scikit-learn,spallavolu/scikit-learn,shenzebang/scikit-learn,mjgrav2001/scikit-learn,yanlend/scikit-learn,krez13/scikit-learn,mblondel/scikit-learn,PatrickOReilly/scikit-learn,Djabbz/scikit-learn,evgchz/scikit-learn,untom/scikit-learn,deepesch/scikit-learn,MechCoder/scikit-learn,ssaeger/scikit-learn,xyguo/scikit-learn,robbymeals/scikit-learn,fbagirov/scikit-learn,RayMick/scikit-learn,jereze/scikit-learn,nelson-liu/scikit-learn,hsiaoyi0504/scikit-learn,abhishekgahlot/scikit-learn,Sentient07/scikit-learn,nikitasingh981/scikit-learn,pypot/scikit-learn,AnasGhrab/scikit-learn,Barmaley-exe/scikit-learn,tosolveit/scikit-learn,wazeerzulfikar/scikit-learn,phdowling/scikit-learn,kaichogami/scikit-learn,mxjl620/scikit-learn,ningchi/scikit-learn,vigilv/scikit-learn,hitszxp/scikit-learn,466152112/scikit-learn,yask123/scikit-learn,ankurankan/scikit-learn,scikit-learn/scikit-learn,meduz/scikit-learn,cybernet14/scikit-learn,liberatorqjw/scikit-learn,walterreade/scikit-learn,fzalkow/scikit-learn,OshynSong/scikit-learn,kmike/scikit-learn,aetilley/scikit-learn,chrisburr/scikit-learn,mwv/scikit-learn,sarahgrogan/scikit-learn,ssaeger/scikit-learn,Clyde-fare/scikit-learn,ndingwall/scikit-learn,ycaihua/scikit-learn,aflaxman/scikit-learn,chrsrds/scikit-learn,vinayak-mehta/scikit-learn,kaichogami/scikit-learn,frank-tancf/scikit-learn,dhruv13J/scikit-learn,Djabbz/scikit-learn,scikit-learn/scikit-learn,ilyes14/scikit-learn,mattgiguere/scikit-learn,pv/scikit-learn,yask123/scikit-learn,aminert/scikit-learn,khkaminska/scikit-learn,fredhusser/scikit-learn,PatrickChrist/scikit-learn,altairpearl/scikit-learn,Windy-Ground/scikit-learn,rohanp/scikit-learn,mlyundin/scikit-learn,lenovor/scikit-learn,rvraghav93/scikit-learn,samzhang111/scikit-learn,costypetrisor/scikit-learn,mikebenfield/scikit-learn,jjx02230808/project0223,jblackburne/scikit-learn,huzq/scikit-learn,alexeyum/scikit-learn,ssaeger/scikit-learn,wzbozon/scikit-learn,mhue/scikit-learn,pv/scikit-learn,aewhatley/scikit-learn,stylianos-kampakis/scikit-learn,ChanderG/scikit-learn,AIML/scikit-learn,tomlof/scikit-learn,krez13/scikit-learn,shikhardb/scikit-learn,MechCoder/scikit-learn,mojoboss/scikit-learn,justincassidy/scikit-learn,NelisVerhoef/scikit-learn,tomlof/scikit-learn,raghavrv/scikit-learn,meduz/scikit-learn,xuewei4d/scikit-learn,rahul-c1/scikit-learn,0x0all/scikit-learn,rrohan/scikit-learn,xavierwu/scikit-learn,billy-inn/scikit-learn,rsivapr/scikit-learn,jzt5132/scikit-learn,arabenjamin/scikit-learn,icdishb/scikit-learn,466152112/scikit-learn,JsNoNo/scikit-learn,joshloyal/scikit-learn,siutanwong/scikit-learn,shahankhatch/scikit-learn,meduz/scikit-learn,gotomypc/scikit-learn,bikong2/scikit-learn,terkkila/scikit-learn,vybstat/scikit-learn,thientu/scikit-learn,manhhomienbienthuy/scikit-learn,0x0all/scikit-learn,evgchz/scikit-learn,raghavrv/scikit-learn,rajat1994/scikit-learn,tosolveit/scikit-learn,Lawrence-Liu/scikit-learn,qifeigit/scikit-learn,q1ang/scikit-learn,fyffyt/scikit-learn,ilyes14/scikit-learn,shusenl/scikit-learn,ChanderG/scikit-learn,mrshu/scikit-learn,pypot/scikit-learn,xwolf12/scikit-learn,rrohan/scikit-learn,idlead/scikit-learn,Fireblend/scikit-learn,f3r/scikit-learn,hlin117/scikit-learn,jseabold/scikit-learn,Fireblend/scikit-learn,anirudhjayaraman/scikit-learn,gclenaghan/scikit-learn,Garrett-R/scikit-learn,mehdidc/scikit-learn,zorroblue/scikit-learn,nelson-liu/scikit-learn,btabibian/scikit-learn,clemkoa/scikit-learn,AIML/scikit-learn,RomainBrault/scikit-learn,JosmanPS/scikit-learn,IshankGulati/scikit-learn,bhargav/scikit-learn,larsmans/scikit-learn,aetilley/scikit-learn,kmike/scikit-learn,nvoron23/scikit-learn,ahoyosid/scikit-learn,eickenberg/scikit-learn,huzq/scikit-learn,jkarnows/scikit-learn,zorojean/scikit-learn,wanggang3333/scikit-learn,yyjiang/scikit-learn,pompiduskus/scikit-learn,altairpearl/scikit-learn,rajat1994/scikit-learn,loli/semisupervisedforests,glouppe/scikit-learn,michigraber/scikit-learn,luo66/scikit-learn,jseabold/scikit-learn,mugizico/scikit-learn,RomainBrault/scikit-learn,jorge2703/scikit-learn,loli/sklearn-ensembletrees,hdmetor/scikit-learn,abhishekgahlot/scikit-learn,jmetzen/scikit-learn,pratapvardhan/scikit-learn,vortex-ape/scikit-learn,ElDeveloper/scikit-learn,etkirsch/scikit-learn,untom/scikit-learn,poryfly/scikit-learn,dsullivan7/scikit-learn,procoder317/scikit-learn,alvarofierroclavero/scikit-learn,vibhorag/scikit-learn,ningchi/scikit-learn,lin-credible/scikit-learn,AIML/scikit-learn,vermouthmjl/scikit-learn,alexeyum/scikit-learn,mjudsp/Tsallis,vigilv/scikit-learn,3manuek/scikit-learn,LohithBlaze/scikit-learn,jakirkham/scikit-learn,vivekmishra1991/scikit-learn,herilalaina/scikit-learn,rishikksh20/scikit-learn,aewhatley/scikit-learn,vivekmishra1991/scikit-learn,CforED/Machine-Learning,ky822/scikit-learn,zorroblue/scikit-learn,alexsavio/scikit-learn,elkingtonmcb/scikit-learn,themrmax/scikit-learn,themrmax/scikit-learn,massmutual/scikit-learn,hsiaoyi0504/scikit-learn,iismd17/scikit-learn,robin-lai/scikit-learn,lucidfrontier45/scikit-learn,samzhang111/scikit-learn,arjoly/scikit-learn,jakirkham/scikit-learn,maheshakya/scikit-learn,aflaxman/scikit-learn,bnaul/scikit-learn,iismd17/scikit-learn,eickenberg/scikit-learn,JsNoNo/scikit-learn,bthirion/scikit-learn,devanshdalal/scikit-learn,LiaoPan/scikit-learn,chrisburr/scikit-learn,belltailjp/scikit-learn,michigraber/scikit-learn,depet/scikit-learn,stylianos-kampakis/scikit-learn,rishikksh20/scikit-learn,sergeyf/scikit-learn,zhenv5/scikit-learn,terkkila/scikit-learn,glemaitre/scikit-learn,frank-tancf/scikit-learn,robin-lai/scikit-learn,spallavolu/scikit-learn,wlamond/scikit-learn,Barmaley-exe/scikit-learn,thientu/scikit-learn,bthirion/scikit-learn,zaxtax/scikit-learn,theoryno3/scikit-learn,espg/scikit-learn,mblondel/scikit-learn,Titan-C/scikit-learn,icdishb/scikit-learn,liberatorqjw/scikit-learn,smartscheduling/scikit-learn-categorical-tree,RayMick/scikit-learn,florian-f/sklearn,marcocaccin/scikit-learn,rahul-c1/scikit-learn,arahuja/scikit-learn,thilbern/scikit-learn,glemaitre/scikit-learn,abhishekkrthakur/scikit-learn,belltailjp/scikit-learn,CVML/scikit-learn,cainiaocome/scikit-learn,amueller/scikit-learn,herilalaina/scikit-learn,lucidfrontier45/scikit-learn,jlegendary/scikit-learn,Nyker510/scikit-learn,idlead/scikit-learn,cybernet14/scikit-learn,jlegendary/scikit-learn,larsmans/scikit-learn,appapantula/scikit-learn,Vimos/scikit-learn,giorgiop/scikit-learn,sinhrks/scikit-learn,ephes/scikit-learn,rexshihaoren/scikit-learn,liangz0707/scikit-learn,rexshihaoren/scikit-learn,aabadie/scikit-learn,shahankhatch/scikit-learn,JosmanPS/scikit-learn,trungnt13/scikit-learn,tawsifkhan/scikit-learn,LiaoPan/scikit-learn,massmutual/scikit-learn,jaidevd/scikit-learn,pythonvietnam/scikit-learn,CVML/scikit-learn,glennq/scikit-learn,BiaDarkia/scikit-learn,RPGOne/scikit-learn,MohammedWasim/scikit-learn,TomDLT/scikit-learn,macks22/scikit-learn,AlexRobson/scikit-learn,andrewnc/scikit-learn,vigilv/scikit-learn,jlegendary/scikit-learn,chrisburr/scikit-learn,andrewnc/scikit-learn,RachitKansal/scikit-learn,jorik041/scikit-learn,jereze/scikit-learn,DonBeo/scikit-learn,etkirsch/scikit-learn,yunfeilu/scikit-learn,RachitKansal/scikit-learn,jorik041/scikit-learn,plissonf/scikit-learn,chrsrds/scikit-learn,belltailjp/scikit-learn,AlexRobson/scikit-learn,ilo10/scikit-learn,vinayak-mehta/scikit-learn,vermouthmjl/scikit-learn,themrmax/scikit-learn,victorbergelin/scikit-learn,ky822/scikit-learn,simon-pepin/scikit-learn,russel1237/scikit-learn,DonBeo/scikit-learn,0asa/scikit-learn,fabioticconi/scikit-learn,deepesch/scikit-learn,shenzebang/scikit-learn,JPFrancoia/scikit-learn,pv/scikit-learn,HolgerPeters/scikit-learn,imaculate/scikit-learn,rahuldhote/scikit-learn,jayflo/scikit-learn,lbishal/scikit-learn,ssaeger/scikit-learn,mayblue9/scikit-learn,AlexanderFabisch/scikit-learn,alvarofierroclavero/scikit-learn,clemkoa/scikit-learn,walterreade/scikit-learn,roxyboy/scikit-learn,3manuek/scikit-learn,gclenaghan/scikit-learn,kjung/scikit-learn,aetilley/scikit-learn,xubenben/scikit-learn,RPGOne/scikit-learn,mjudsp/Tsallis,ngoix/OCRF,vortex-ape/scikit-learn,nikitasingh981/scikit-learn,khkaminska/scikit-learn,vivekmishra1991/scikit-learn,costypetrisor/scikit-learn,wazeerzulfikar/scikit-learn,zorroblue/scikit-learn,hrjn/scikit-learn,hugobowne/scikit-learn,mrshu/scikit-learn,smartscheduling/scikit-learn-categorical-tree,hlin117/scikit-learn,poryfly/scikit-learn,ishanic/scikit-learn,liberatorqjw/scikit-learn,lin-credible/scikit-learn,AnasGhrab/scikit-learn,bikong2/scikit-learn,trungnt13/scikit-learn,robin-lai/scikit-learn,ilyes14/scikit-learn,andrewnc/scikit-learn,NelisVerhoef/scikit-learn,rsivapr/scikit-learn,zorojean/scikit-learn,wanggang3333/scikit-learn,russel1237/scikit-learn,RomainBrault/scikit-learn,IssamLaradji/scikit-learn,voxlol/scikit-learn,Adai0808/scikit-learn,shikhardb/scikit-learn,appapantula/scikit-learn,eg-zhang/scikit-learn,thilbern/scikit-learn,B3AU/waveTree,IshankGulati/scikit-learn,tdhopper/scikit-learn,nrhine1/scikit-learn,eg-zhang/scikit-learn,untom/scikit-learn,manashmndl/scikit-learn,dhruv13J/scikit-learn,depet/scikit-learn,ElDeveloper/scikit-learn,roxyboy/scikit-learn,anirudhjayaraman/scikit-learn,equialgo/scikit-learn,davidgbe/scikit-learn,mhue/scikit-learn,kashif/scikit-learn,mblondel/scikit-learn,jzt5132/scikit-learn,plissonf/scikit-learn,hainm/scikit-learn,tdhopper/scikit-learn,cwu2011/scikit-learn,MohammedWasim/scikit-learn,lesteve/scikit-learn,jseabold/scikit-learn,B3AU/waveTree,sarahgrogan/scikit-learn,raghavrv/scikit-learn,florian-f/sklearn,MechCoder/scikit-learn,liyu1990/sklearn,MatthieuBizien/scikit-learn,Titan-C/scikit-learn,iismd17/scikit-learn,olologin/scikit-learn,loli/semisupervisedforests,dingocuster/scikit-learn,heli522/scikit-learn,simon-pepin/scikit-learn,jmetzen/scikit-learn,mfjb/scikit-learn,appapantula/scikit-learn,luo66/scikit-learn,PatrickChrist/scikit-learn,zorroblue/scikit-learn,mjgrav2001/scikit-learn,sanketloke/scikit-learn,macks22/scikit-learn,mlyundin/scikit-learn,Barmaley-exe/scikit-learn,henrykironde/scikit-learn,xwolf12/scikit-learn,loli/sklearn-ensembletrees,nomadcube/scikit-learn,beepee14/scikit-learn,rsivapr/scikit-learn,hitszxp/scikit-learn,TomDLT/scikit-learn,loli/sklearn-ensembletrees,nhejazi/scikit-learn,mwv/scikit-learn,bnaul/scikit-learn,ElDeveloper/scikit-learn,rahuldhote/scikit-learn,mjudsp/Tsallis,ahoyosid/scikit-learn,jpautom/scikit-learn,PrashntS/scikit-learn,0x0all/scikit-learn,nhejazi/scikit-learn,zuku1985/scikit-learn,schets/scikit-learn,toastedcornflakes/scikit-learn,mehdidc/scikit-learn,shyamalschandra/scikit-learn,fengzhyuan/scikit-learn,potash/scikit-learn,jkarnows/scikit-learn,LohithBlaze/scikit-learn,robbymeals/scikit-learn,heli522/scikit-learn,wazeerzulfikar/scikit-learn,deepesch/scikit-learn,idlead/scikit-learn,HolgerPeters/scikit-learn,ankurankan/scikit-learn,Achuth17/scikit-learn,Akshay0724/scikit-learn,heli522/scikit-learn,poryfly/scikit-learn,nmayorov/scikit-learn,sonnyhu/scikit-learn,ndingwall/scikit-learn,vermouthmjl/scikit-learn,phdowling/scikit-learn,ChanChiChoi/scikit-learn,xzh86/scikit-learn,Achuth17/scikit-learn,glennq/scikit-learn,DSLituiev/scikit-learn,stylianos-kampakis/scikit-learn,liangz0707/scikit-learn,JeanKossaifi/scikit-learn,krez13/scikit-learn,qifeigit/scikit-learn,siutanwong/scikit-learn,alexeyum/scikit-learn,depet/scikit-learn,trungnt13/scikit-learn,abhishekgahlot/scikit-learn,YinongLong/scikit-learn,macks22/scikit-learn,h2educ/scikit-learn,jmetzen/scikit-learn,jpautom/scikit-learn,hlin117/scikit-learn,adamgreenhall/scikit-learn,DonBeo/scikit-learn,nomadcube/scikit-learn,djgagne/scikit-learn,jakobworldpeace/scikit-learn,harshaneelhg/scikit-learn,beepee14/scikit-learn,henrykironde/scikit-learn,vshtanko/scikit-learn,idlead/scikit-learn,ldirer/scikit-learn,vybstat/scikit-learn,jpautom/scikit-learn,anurag313/scikit-learn,scikit-learn/scikit-learn,arabenjamin/scikit-learn,moutai/scikit-learn,dhruv13J/scikit-learn,trankmichael/scikit-learn,nmayorov/scikit-learn,jseabold/scikit-learn,aminert/scikit-learn,MatthieuBizien/scikit-learn,theoryno3/scikit-learn,anurag313/scikit-learn,fabianp/scikit-learn,pnedunuri/scikit-learn,huzq/scikit-learn,glouppe/scikit-learn,victorbergelin/scikit-learn,trankmichael/scikit-learn,xzh86/scikit-learn,Akshay0724/scikit-learn,hainm/scikit-learn,Sentient07/scikit-learn,frank-tancf/scikit-learn,jm-begon/scikit-learn,mehdidc/scikit-learn,simon-pepin/scikit-learn,jorge2703/scikit-learn,wanggang3333/scikit-learn,lenovor/scikit-learn,Garrett-R/scikit-learn,andaag/scikit-learn,jblackburne/scikit-learn,ningchi/scikit-learn,IssamLaradji/scikit-learn,vigilv/scikit-learn,tosolveit/scikit-learn,RPGOne/scikit-learn,OshynSong/scikit-learn,lbishal/scikit-learn,sinhrks/scikit-learn,nesterione/scikit-learn,ZenDevelopmentSystems/scikit-learn,samuel1208/scikit-learn,MartinSavc/scikit-learn,eg-zhang/scikit-learn,arabenjamin/scikit-learn,pkruskal/scikit-learn,rexshihaoren/scikit-learn,meduz/scikit-learn,phdowling/scikit-learn,Jimmy-Morzaria/scikit-learn,robin-lai/scikit-learn,Clyde-fare/scikit-learn,eg-zhang/scikit-learn,arahuja/scikit-learn,mhdella/scikit-learn,shahankhatch/scikit-learn,rsivapr/scikit-learn,espg/scikit-learn,ClimbsRocks/scikit-learn,ishanic/scikit-learn,lucidfrontier45/scikit-learn,MartinSavc/scikit-learn,manashmndl/scikit-learn,Nyker510/scikit-learn,pkruskal/scikit-learn,vortex-ape/scikit-learn,mojoboss/scikit-learn,ndingwall/scikit-learn,andaag/scikit-learn,LohithBlaze/scikit-learn,mehdidc/scikit-learn,xiaoxiamii/scikit-learn,glouppe/scikit-learn,thientu/scikit-learn,mblondel/scikit-learn,AnasGhrab/scikit-learn,Sentient07/scikit-learn,ChanderG/scikit-learn,quheng/scikit-learn,jzt5132/scikit-learn,jaidevd/scikit-learn,liyu1990/sklearn,pnedunuri/scikit-learn,ahoyosid/scikit-learn,waterponey/scikit-learn,akionakamura/scikit-learn,eickenberg/scikit-learn,justincassidy/scikit-learn,siutanwong/scikit-learn,jmschrei/scikit-learn,JsNoNo/scikit-learn,sumspr/scikit-learn,chrisburr/scikit-learn,larsmans/scikit-learn,hitszxp/scikit-learn,mlyundin/scikit-learn,mwv/scikit-learn,pv/scikit-learn,jpautom/scikit-learn,Aasmi/scikit-learn,B3AU/waveTree,andrewnc/scikit-learn,ChanChiChoi/scikit-learn,lenovor/scikit-learn,treycausey/scikit-learn,kmike/scikit-learn,3manuek/scikit-learn,YinongLong/scikit-learn,dsullivan7/scikit-learn,ivannz/scikit-learn,pratapvardhan/scikit-learn,aetilley/scikit-learn,herilalaina/scikit-learn,shyamalschandra/scikit-learn,jorge2703/scikit-learn,loli/sklearn-ensembletrees,victorbergelin/scikit-learn,kashif/scikit-learn,toastedcornflakes/scikit-learn,pianomania/scikit-learn,quheng/scikit-learn,Sentient07/scikit-learn,NelisVerhoef/scikit-learn,hdmetor/scikit-learn,shikhardb/scikit-learn,henridwyer/scikit-learn,kaichogami/scikit-learn,cauchycui/scikit-learn,btabibian/scikit-learn,Lawrence-Liu/scikit-learn,voxlol/scikit-learn,adamgreenhall/scikit-learn,RomainBrault/scikit-learn,JeanKossaifi/scikit-learn,scikit-learn/scikit-learn,gotomypc/scikit-learn,harshaneelhg/scikit-learn,carrillo/scikit-learn,liyu1990/sklearn,toastedcornflakes/scikit-learn,fzalkow/scikit-learn,quheng/scikit-learn,Windy-Ground/scikit-learn,andaag/scikit-learn,huobaowangxi/scikit-learn,cauchycui/scikit-learn,costypetrisor/scikit-learn,devanshdalal/scikit-learn,pnedunuri/scikit-learn,Srisai85/scikit-learn,nmayorov/scikit-learn,ldirer/scikit-learn,ChanChiChoi/scikit-learn,victorbergelin/scikit-learn,mattilyra/scikit-learn,JsNoNo/scikit-learn,toastedcornflakes/scikit-learn,cl4rke/scikit-learn,sanketloke/scikit-learn,mayblue9/scikit-learn,macks22/scikit-learn,RachitKansal/scikit-learn,ZENGXH/scikit-learn,rishikksh20/scikit-learn,quheng/scikit-learn,ycaihua/scikit-learn,ngoix/OCRF,jmschrei/scikit-learn,ycaihua/scikit-learn,Obus/scikit-learn,sarahgrogan/scikit-learn,lucidfrontier45/scikit-learn,pythonvietnam/scikit-learn,bikong2/scikit-learn,zhenv5/scikit-learn,petosegan/scikit-learn,mojoboss/scikit-learn,nrhine1/scikit-learn,nesterione/scikit-learn,jmschrei/scikit-learn,larsmans/scikit-learn,fabioticconi/scikit-learn,shusenl/scikit-learn,davidgbe/scikit-learn,rahul-c1/scikit-learn,plissonf/scikit-learn,mattilyra/scikit-learn,henrykironde/scikit-learn,khkaminska/scikit-learn,gclenaghan/scikit-learn,vortex-ape/scikit-learn,kagayakidan/scikit-learn,tmhm/scikit-learn,glemaitre/scikit-learn,PrashntS/scikit-learn,madjelan/scikit-learn,Aasmi/scikit-learn,JPFrancoia/scikit-learn,cl4rke/scikit-learn,cainiaocome/scikit-learn,fengzhyuan/scikit-learn,samuel1208/scikit-learn,kevin-intel/scikit-learn,OshynSong/scikit-learn,mfjb/scikit-learn,IssamLaradji/scikit-learn,pkruskal/scikit-learn,sumspr/scikit-learn,yunfeilu/scikit-learn,UNR-AERIAL/scikit-learn,florian-f/sklearn,ngoix/OCRF,nrhine1/scikit-learn,tawsifkhan/scikit-learn,jorik041/scikit-learn,RachitKansal/scikit-learn,AlexandreAbraham/scikit-learn,mjgrav2001/scikit-learn,Djabbz/scikit-learn,pratapvardhan/scikit-learn,fredhusser/scikit-learn,AlexanderFabisch/scikit-learn,PatrickOReilly/scikit-learn,mhue/scikit-learn,rohanp/scikit-learn,IndraVikas/scikit-learn,Titan-C/scikit-learn,mattgiguere/scikit-learn,clemkoa/scikit-learn,maheshakya/scikit-learn,depet/scikit-learn,sergeyf/scikit-learn,rvraghav93/scikit-learn,mattgiguere/scikit-learn,wlamond/scikit-learn,hsuantien/scikit-learn,NunoEdgarGub1/scikit-learn,robbymeals/scikit-learn,ZenDevelopmentSystems/scikit-learn,ltiao/scikit-learn,JeanKossaifi/scikit-learn,sumspr/scikit-learn,tdhopper/scikit-learn,OshynSong/scikit-learn,cl4rke/scikit-learn,manhhomienbienthuy/scikit-learn,tawsifkhan/scikit-learn,mhdella/scikit-learn,xuewei4d/scikit-learn,treycausey/scikit-learn,MohammedWasim/scikit-learn,olologin/scikit-learn,shusenl/scikit-learn,hugobowne/scikit-learn,shenzebang/scikit-learn,TomDLT/scikit-learn,vshtanko/scikit-learn,LiaoPan/scikit-learn,Jimmy-Morzaria/scikit-learn,AlexRobson/scikit-learn,yyjiang/scikit-learn,lin-credible/scikit-learn | import numpy as np
from numpy.testing import assert_array_equal
from sklearn.linear_model.isotonic_regression_ import isotonic_regression
from sklearn.linear_model import IsotonicRegression
from nose.tools import assert_raises
def test_isotonic_regression():
y = np.array([3, 7, 5, 9, 8, 7, 10])
y_ = np.array([3, 6, 6, 8, 8, 8, 10])
assert_array_equal(y_, isotonic_regression(y))
x = np.arange(len(y))
ir = IsotonicRegression(x_min=0., x_max=1.)
ir.fit(x, y)
assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y))
assert_array_equal(ir.transform(x), ir.predict(x))
def test_assert_raises_exceptions():
ir = IsotonicRegression()
+ rng = np.random.RandomState(42)
assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7, 3], [0.1, 0.6])
assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7])
- assert_raises(ValueError, ir.fit, np.random.randn(3, 10), [0, 1, 2])
+ assert_raises(ValueError, ir.fit, rng.randn(3, 10), [0, 1, 2])
- assert_raises(ValueError, ir.transform, np.random.randn(3, 10))
+ assert_raises(ValueError, ir.transform, rng.randn(3, 10))
| FIX : fix LLE test (don't ask me why...) | ## Code Before:
import numpy as np
from numpy.testing import assert_array_equal
from sklearn.linear_model.isotonic_regression_ import isotonic_regression
from sklearn.linear_model import IsotonicRegression
from nose.tools import assert_raises
def test_isotonic_regression():
y = np.array([3, 7, 5, 9, 8, 7, 10])
y_ = np.array([3, 6, 6, 8, 8, 8, 10])
assert_array_equal(y_, isotonic_regression(y))
x = np.arange(len(y))
ir = IsotonicRegression(x_min=0., x_max=1.)
ir.fit(x, y)
assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y))
assert_array_equal(ir.transform(x), ir.predict(x))
def test_assert_raises_exceptions():
ir = IsotonicRegression()
assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7, 3], [0.1, 0.6])
assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7])
assert_raises(ValueError, ir.fit, np.random.randn(3, 10), [0, 1, 2])
assert_raises(ValueError, ir.transform, np.random.randn(3, 10))
## Instruction:
FIX : fix LLE test (don't ask me why...)
## Code After:
import numpy as np
from numpy.testing import assert_array_equal
from sklearn.linear_model.isotonic_regression_ import isotonic_regression
from sklearn.linear_model import IsotonicRegression
from nose.tools import assert_raises
def test_isotonic_regression():
y = np.array([3, 7, 5, 9, 8, 7, 10])
y_ = np.array([3, 6, 6, 8, 8, 8, 10])
assert_array_equal(y_, isotonic_regression(y))
x = np.arange(len(y))
ir = IsotonicRegression(x_min=0., x_max=1.)
ir.fit(x, y)
assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y))
assert_array_equal(ir.transform(x), ir.predict(x))
def test_assert_raises_exceptions():
ir = IsotonicRegression()
rng = np.random.RandomState(42)
assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7, 3], [0.1, 0.6])
assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7])
assert_raises(ValueError, ir.fit, rng.randn(3, 10), [0, 1, 2])
assert_raises(ValueError, ir.transform, rng.randn(3, 10))
| import numpy as np
from numpy.testing import assert_array_equal
from sklearn.linear_model.isotonic_regression_ import isotonic_regression
from sklearn.linear_model import IsotonicRegression
from nose.tools import assert_raises
def test_isotonic_regression():
y = np.array([3, 7, 5, 9, 8, 7, 10])
y_ = np.array([3, 6, 6, 8, 8, 8, 10])
assert_array_equal(y_, isotonic_regression(y))
x = np.arange(len(y))
ir = IsotonicRegression(x_min=0., x_max=1.)
ir.fit(x, y)
assert_array_equal(ir.fit(x, y).transform(x), ir.fit_transform(x, y))
assert_array_equal(ir.transform(x), ir.predict(x))
def test_assert_raises_exceptions():
ir = IsotonicRegression()
+ rng = np.random.RandomState(42)
assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7, 3], [0.1, 0.6])
assert_raises(ValueError, ir.fit, [0, 1, 2], [5, 7])
- assert_raises(ValueError, ir.fit, np.random.randn(3, 10), [0, 1, 2])
? ^^^^^^^^
+ assert_raises(ValueError, ir.fit, rng.randn(3, 10), [0, 1, 2])
? + ^
- assert_raises(ValueError, ir.transform, np.random.randn(3, 10))
? ^^^^^^^^
+ assert_raises(ValueError, ir.transform, rng.randn(3, 10))
? + ^
|
1517bb31a8ec0d5df96e2693977081b3d1a64f69 | tests/integration/minion/test_timeout.py | tests/integration/minion/test_timeout.py | '''
Tests for various minion timeouts
'''
# Import Python libs
from __future__ import absolute_import
import os
import sys
import salt.utils
# Import Salt Testing libs
from tests.support.case import ShellCase
class MinionTimeoutTestCase(ShellCase):
'''
Test minion timing functions
'''
def test_long_running_job(self):
'''
Test that we will wait longer than the job timeout for a minion to
return.
'''
# Launch the command
sleep_length = 30
if salt.utils.is_windows():
popen_kwargs = {'env': dict(os.environ, PYTHONPATH=';'.join(sys.path))}
else:
popen_kwargs = None
ret = self.run_salt(
'minion test.sleep {0}'.format(sleep_length),
timeout=45,
catch_stderr=True,
popen_kwargs=popen_kwargs,
)
self.assertTrue(isinstance(ret[0], list), 'Return is not a list. Minion'
' may have returned error: {0}'.format(ret))
self.assertEqual(len(ret[0]), 2, 'Standard out wrong length {}'.format(ret))
self.assertTrue('True' in ret[0][1], 'Minion did not return True after '
'{0} seconds. ret={1}'.format(sleep_length, ret))
| '''
Tests for various minion timeouts
'''
# Import Python libs
from __future__ import absolute_import
import os
import sys
import salt.utils.platform
# Import Salt Testing libs
from tests.support.case import ShellCase
class MinionTimeoutTestCase(ShellCase):
'''
Test minion timing functions
'''
def test_long_running_job(self):
'''
Test that we will wait longer than the job timeout for a minion to
return.
'''
# Launch the command
sleep_length = 30
if salt.utils.platform.is_windows():
popen_kwargs = {'env': dict(os.environ, PYTHONPATH=';'.join(sys.path))}
else:
popen_kwargs = None
ret = self.run_salt(
'minion test.sleep {0}'.format(sleep_length),
timeout=45,
catch_stderr=True,
popen_kwargs=popen_kwargs,
)
self.assertTrue(isinstance(ret[0], list), 'Return is not a list. Minion'
' may have returned error: {0}'.format(ret))
self.assertEqual(len(ret[0]), 2, 'Standard out wrong length {}'.format(ret))
self.assertTrue('True' in ret[0][1], 'Minion did not return True after '
'{0} seconds. ret={1}'.format(sleep_length, ret))
| Update old utils paths to use new paths | Update old utils paths to use new paths
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | '''
Tests for various minion timeouts
'''
# Import Python libs
from __future__ import absolute_import
import os
import sys
- import salt.utils
+ import salt.utils.platform
# Import Salt Testing libs
from tests.support.case import ShellCase
class MinionTimeoutTestCase(ShellCase):
'''
Test minion timing functions
'''
def test_long_running_job(self):
'''
Test that we will wait longer than the job timeout for a minion to
return.
'''
# Launch the command
sleep_length = 30
- if salt.utils.is_windows():
+ if salt.utils.platform.is_windows():
popen_kwargs = {'env': dict(os.environ, PYTHONPATH=';'.join(sys.path))}
else:
popen_kwargs = None
ret = self.run_salt(
'minion test.sleep {0}'.format(sleep_length),
timeout=45,
catch_stderr=True,
popen_kwargs=popen_kwargs,
)
self.assertTrue(isinstance(ret[0], list), 'Return is not a list. Minion'
' may have returned error: {0}'.format(ret))
self.assertEqual(len(ret[0]), 2, 'Standard out wrong length {}'.format(ret))
self.assertTrue('True' in ret[0][1], 'Minion did not return True after '
'{0} seconds. ret={1}'.format(sleep_length, ret))
| Update old utils paths to use new paths | ## Code Before:
'''
Tests for various minion timeouts
'''
# Import Python libs
from __future__ import absolute_import
import os
import sys
import salt.utils
# Import Salt Testing libs
from tests.support.case import ShellCase
class MinionTimeoutTestCase(ShellCase):
'''
Test minion timing functions
'''
def test_long_running_job(self):
'''
Test that we will wait longer than the job timeout for a minion to
return.
'''
# Launch the command
sleep_length = 30
if salt.utils.is_windows():
popen_kwargs = {'env': dict(os.environ, PYTHONPATH=';'.join(sys.path))}
else:
popen_kwargs = None
ret = self.run_salt(
'minion test.sleep {0}'.format(sleep_length),
timeout=45,
catch_stderr=True,
popen_kwargs=popen_kwargs,
)
self.assertTrue(isinstance(ret[0], list), 'Return is not a list. Minion'
' may have returned error: {0}'.format(ret))
self.assertEqual(len(ret[0]), 2, 'Standard out wrong length {}'.format(ret))
self.assertTrue('True' in ret[0][1], 'Minion did not return True after '
'{0} seconds. ret={1}'.format(sleep_length, ret))
## Instruction:
Update old utils paths to use new paths
## Code After:
'''
Tests for various minion timeouts
'''
# Import Python libs
from __future__ import absolute_import
import os
import sys
import salt.utils.platform
# Import Salt Testing libs
from tests.support.case import ShellCase
class MinionTimeoutTestCase(ShellCase):
'''
Test minion timing functions
'''
def test_long_running_job(self):
'''
Test that we will wait longer than the job timeout for a minion to
return.
'''
# Launch the command
sleep_length = 30
if salt.utils.platform.is_windows():
popen_kwargs = {'env': dict(os.environ, PYTHONPATH=';'.join(sys.path))}
else:
popen_kwargs = None
ret = self.run_salt(
'minion test.sleep {0}'.format(sleep_length),
timeout=45,
catch_stderr=True,
popen_kwargs=popen_kwargs,
)
self.assertTrue(isinstance(ret[0], list), 'Return is not a list. Minion'
' may have returned error: {0}'.format(ret))
self.assertEqual(len(ret[0]), 2, 'Standard out wrong length {}'.format(ret))
self.assertTrue('True' in ret[0][1], 'Minion did not return True after '
'{0} seconds. ret={1}'.format(sleep_length, ret))
| '''
Tests for various minion timeouts
'''
# Import Python libs
from __future__ import absolute_import
import os
import sys
- import salt.utils
+ import salt.utils.platform
? +++++++++
# Import Salt Testing libs
from tests.support.case import ShellCase
class MinionTimeoutTestCase(ShellCase):
'''
Test minion timing functions
'''
def test_long_running_job(self):
'''
Test that we will wait longer than the job timeout for a minion to
return.
'''
# Launch the command
sleep_length = 30
- if salt.utils.is_windows():
+ if salt.utils.platform.is_windows():
? +++++++++
popen_kwargs = {'env': dict(os.environ, PYTHONPATH=';'.join(sys.path))}
else:
popen_kwargs = None
ret = self.run_salt(
'minion test.sleep {0}'.format(sleep_length),
timeout=45,
catch_stderr=True,
popen_kwargs=popen_kwargs,
)
self.assertTrue(isinstance(ret[0], list), 'Return is not a list. Minion'
' may have returned error: {0}'.format(ret))
self.assertEqual(len(ret[0]), 2, 'Standard out wrong length {}'.format(ret))
self.assertTrue('True' in ret[0][1], 'Minion did not return True after '
'{0} seconds. ret={1}'.format(sleep_length, ret)) |
be30b8220900eaf549fbe1bff7a1e7c3a9be8529 | settings_test.py | settings_test.py | CELERY_ALWAYS_EAGER = True
# Make sure the doctypes (the keys) match the doctypes in ES_INDEXES
# in settings.py and settings_local.py.
ES_INDEXES = {'default': 'sumo_test'}
ES_WRITE_INDEXES = ES_INDEXES
# This makes sure we only turn on ES stuff when we're testing ES
# stuff.
ES_LIVE_INDEXING = False
# Make sure we use port 6383 db 2 redis for tests. That's db 2 of the
# redis test config. That shouldn't collide with anything else.
REDIS_BACKENDS = {
'default': 'redis://localhost:6383?socket_timeout=0.5&db=2',
'karma': 'redis://localhost:6383?socket_timeout=0.5&db=2',
'helpfulvotes': 'redis://localhost:6383?socket_timeout=0.5&db=2',
}
# Use fake webtrends settings.
WEBTRENDS_PROFILE_ID = 'ABC123'
| from django.conf import settings
# The test system uses this to override settings in settings.py and
# settings_local.py with settings appropriate for testing.
# Make sure Celery is EAGER.
CELERY_ALWAYS_EAGER = True
# Make sure the doctypes (the keys) match the doctypes in ES_INDEXES
# in settings.py and settings_local.py.
ES_INDEXES = {'default': 'sumo_test' + settings.ES_INDEX_PREFIX}
ES_WRITE_INDEXES = ES_INDEXES
# This makes sure we only turn on ES stuff when we're testing ES
# stuff.
ES_LIVE_INDEXING = False
# Make sure we use port 6383 db 2 redis for tests. That's db 2 of the
# redis test config. That shouldn't collide with anything else.
REDIS_BACKENDS = {
'default': 'redis://localhost:6383?socket_timeout=0.5&db=2',
'karma': 'redis://localhost:6383?socket_timeout=0.5&db=2',
'helpfulvotes': 'redis://localhost:6383?socket_timeout=0.5&db=2',
}
# Use fake webtrends settings.
WEBTRENDS_PROFILE_ID = 'ABC123'
| Make settings test respect ES_INDEX_PREFIX. | Make settings test respect ES_INDEX_PREFIX.
| Python | bsd-3-clause | chirilo/kitsune,H1ghT0p/kitsune,feer56/Kitsune1,NewPresident1/kitsune,safwanrahman/kitsune,asdofindia/kitsune,brittanystoroz/kitsune,MikkCZ/kitsune,H1ghT0p/kitsune,philipp-sumo/kitsune,mozilla/kitsune,safwanrahman/kitsune,Osmose/kitsune,YOTOV-LIMITED/kitsune,philipp-sumo/kitsune,feer56/Kitsune1,dbbhattacharya/kitsune,anushbmx/kitsune,silentbob73/kitsune,turtleloveshoes/kitsune,asdofindia/kitsune,mozilla/kitsune,feer56/Kitsune1,feer56/Kitsune2,YOTOV-LIMITED/kitsune,mozilla/kitsune,YOTOV-LIMITED/kitsune,mythmon/kitsune,orvi2014/kitsune,MikkCZ/kitsune,YOTOV-LIMITED/kitsune,rlr/kitsune,dbbhattacharya/kitsune,MziRintu/kitsune,NewPresident1/kitsune,asdofindia/kitsune,anushbmx/kitsune,H1ghT0p/kitsune,feer56/Kitsune2,rlr/kitsune,brittanystoroz/kitsune,iDTLabssl/kitsune,Osmose/kitsune,brittanystoroz/kitsune,rlr/kitsune,safwanrahman/kitsune,asdofindia/kitsune,mythmon/kitsune,safwanrahman/kitsune,philipp-sumo/kitsune,orvi2014/kitsune,silentbob73/kitsune,Osmose/kitsune,dbbhattacharya/kitsune,orvi2014/kitsune,mozilla/kitsune,chirilo/kitsune,dbbhattacharya/kitsune,orvi2014/kitsune,iDTLabssl/kitsune,anushbmx/kitsune,silentbob73/kitsune,H1ghT0p/kitsune,turtleloveshoes/kitsune,iDTLabssl/kitsune,safwanrahman/linuxdesh,mythmon/kitsune,turtleloveshoes/kitsune,mythmon/kitsune,NewPresident1/kitsune,chirilo/kitsune,safwanrahman/linuxdesh,NewPresident1/kitsune,anushbmx/kitsune,MikkCZ/kitsune,feer56/Kitsune2,safwanrahman/linuxdesh,iDTLabssl/kitsune,MziRintu/kitsune,Osmose/kitsune,MikkCZ/kitsune,rlr/kitsune,brittanystoroz/kitsune,chirilo/kitsune,MziRintu/kitsune,feer56/Kitsune2,MziRintu/kitsune,turtleloveshoes/kitsune,silentbob73/kitsune | + from django.conf import settings
+ # The test system uses this to override settings in settings.py and
+ # settings_local.py with settings appropriate for testing.
+
+ # Make sure Celery is EAGER.
CELERY_ALWAYS_EAGER = True
# Make sure the doctypes (the keys) match the doctypes in ES_INDEXES
# in settings.py and settings_local.py.
- ES_INDEXES = {'default': 'sumo_test'}
+ ES_INDEXES = {'default': 'sumo_test' + settings.ES_INDEX_PREFIX}
ES_WRITE_INDEXES = ES_INDEXES
# This makes sure we only turn on ES stuff when we're testing ES
# stuff.
ES_LIVE_INDEXING = False
# Make sure we use port 6383 db 2 redis for tests. That's db 2 of the
# redis test config. That shouldn't collide with anything else.
REDIS_BACKENDS = {
'default': 'redis://localhost:6383?socket_timeout=0.5&db=2',
'karma': 'redis://localhost:6383?socket_timeout=0.5&db=2',
'helpfulvotes': 'redis://localhost:6383?socket_timeout=0.5&db=2',
}
# Use fake webtrends settings.
WEBTRENDS_PROFILE_ID = 'ABC123'
| Make settings test respect ES_INDEX_PREFIX. | ## Code Before:
CELERY_ALWAYS_EAGER = True
# Make sure the doctypes (the keys) match the doctypes in ES_INDEXES
# in settings.py and settings_local.py.
ES_INDEXES = {'default': 'sumo_test'}
ES_WRITE_INDEXES = ES_INDEXES
# This makes sure we only turn on ES stuff when we're testing ES
# stuff.
ES_LIVE_INDEXING = False
# Make sure we use port 6383 db 2 redis for tests. That's db 2 of the
# redis test config. That shouldn't collide with anything else.
REDIS_BACKENDS = {
'default': 'redis://localhost:6383?socket_timeout=0.5&db=2',
'karma': 'redis://localhost:6383?socket_timeout=0.5&db=2',
'helpfulvotes': 'redis://localhost:6383?socket_timeout=0.5&db=2',
}
# Use fake webtrends settings.
WEBTRENDS_PROFILE_ID = 'ABC123'
## Instruction:
Make settings test respect ES_INDEX_PREFIX.
## Code After:
from django.conf import settings
# The test system uses this to override settings in settings.py and
# settings_local.py with settings appropriate for testing.
# Make sure Celery is EAGER.
CELERY_ALWAYS_EAGER = True
# Make sure the doctypes (the keys) match the doctypes in ES_INDEXES
# in settings.py and settings_local.py.
ES_INDEXES = {'default': 'sumo_test' + settings.ES_INDEX_PREFIX}
ES_WRITE_INDEXES = ES_INDEXES
# This makes sure we only turn on ES stuff when we're testing ES
# stuff.
ES_LIVE_INDEXING = False
# Make sure we use port 6383 db 2 redis for tests. That's db 2 of the
# redis test config. That shouldn't collide with anything else.
REDIS_BACKENDS = {
'default': 'redis://localhost:6383?socket_timeout=0.5&db=2',
'karma': 'redis://localhost:6383?socket_timeout=0.5&db=2',
'helpfulvotes': 'redis://localhost:6383?socket_timeout=0.5&db=2',
}
# Use fake webtrends settings.
WEBTRENDS_PROFILE_ID = 'ABC123'
| + from django.conf import settings
+ # The test system uses this to override settings in settings.py and
+ # settings_local.py with settings appropriate for testing.
+
+ # Make sure Celery is EAGER.
CELERY_ALWAYS_EAGER = True
# Make sure the doctypes (the keys) match the doctypes in ES_INDEXES
# in settings.py and settings_local.py.
- ES_INDEXES = {'default': 'sumo_test'}
+ ES_INDEXES = {'default': 'sumo_test' + settings.ES_INDEX_PREFIX}
ES_WRITE_INDEXES = ES_INDEXES
# This makes sure we only turn on ES stuff when we're testing ES
# stuff.
ES_LIVE_INDEXING = False
# Make sure we use port 6383 db 2 redis for tests. That's db 2 of the
# redis test config. That shouldn't collide with anything else.
REDIS_BACKENDS = {
'default': 'redis://localhost:6383?socket_timeout=0.5&db=2',
'karma': 'redis://localhost:6383?socket_timeout=0.5&db=2',
'helpfulvotes': 'redis://localhost:6383?socket_timeout=0.5&db=2',
}
# Use fake webtrends settings.
WEBTRENDS_PROFILE_ID = 'ABC123' |
2bfd89b7fe7c4ac4c70f324a745dedbd84dd0672 | __main__.py | __main__.py | from . import *
import readline
ps1 = '\n% '
ps2 = '| '
try:
from blessings import Terminal
term = Terminal()
ps1 = term.bold_blue(ps1)
ps2 = term.bold_blue(ps2)
def fancy_movement():
print(term.move_up() + term.clear_eol() + term.move_up())
except ImportError:
def fancy_movement():
pass
def getfilefunc(mod, droplast=True):
return Func(tuple(fixtags(flattenbody(mod, droplast=droplast))))
def runfile(fname):
invoke(getfilefunc(parseFile(fname)), stdlib())
def readProgram():
try:
yield input(ps1)
while True:
line = input(ps2)
if not line:
fancy_movement()
return
yield line
except EOFError:
print()
raise SystemExit
def interactive():
env = stdlib()
while True:
try:
retval, = invoke(getfilefunc(parseString('\n'.join(readProgram())), droplast=False), env)
if retval is not None:
print(arepr(retval))
except KeyboardInterrupt:
print()
except Exception as e:
print(e)
import sys
if len(sys.argv) > 1:
runfile(sys.argv[1])
else:
interactive()
| from . import *
import readline
ps1 = '\n% '
ps2 = '| '
try:
from blessings import Terminal
term = Terminal()
def fancy_movement():
print(term.move_up() + term.clear_eol() + term.move_up())
except ImportError:
def fancy_movement():
pass
def getfilefunc(mod, droplast=True):
return Func(tuple(fixtags(flattenbody(mod, droplast=droplast))))
def runfile(fname):
invoke(getfilefunc(parseFile(fname)), stdlib())
def readProgram():
try:
yield input(ps1)
while True:
line = input(ps2)
if not line:
fancy_movement()
return
yield line
except EOFError:
print()
raise SystemExit
def interactive():
env = stdlib()
while True:
try:
retval, = invoke(getfilefunc(parseString('\n'.join(readProgram())), droplast=False), env)
if retval is not None:
print(arepr(retval))
except KeyboardInterrupt:
print()
except Exception as e:
print(e)
import sys
if len(sys.argv) > 1:
runfile(sys.argv[1])
else:
interactive()
| Remove colors from REPL prompt | Remove colors from REPL prompt
They weren't playing nice with Readline.
There's still an optional dependency on Blessings, but that is only
used to strip away the trailing ps2.
| Python | isc | gvx/isle | from . import *
import readline
ps1 = '\n% '
ps2 = '| '
try:
from blessings import Terminal
term = Terminal()
- ps1 = term.bold_blue(ps1)
- ps2 = term.bold_blue(ps2)
def fancy_movement():
print(term.move_up() + term.clear_eol() + term.move_up())
except ImportError:
def fancy_movement():
pass
def getfilefunc(mod, droplast=True):
return Func(tuple(fixtags(flattenbody(mod, droplast=droplast))))
def runfile(fname):
invoke(getfilefunc(parseFile(fname)), stdlib())
def readProgram():
try:
yield input(ps1)
while True:
line = input(ps2)
if not line:
fancy_movement()
return
yield line
except EOFError:
print()
raise SystemExit
def interactive():
env = stdlib()
while True:
try:
retval, = invoke(getfilefunc(parseString('\n'.join(readProgram())), droplast=False), env)
if retval is not None:
print(arepr(retval))
except KeyboardInterrupt:
print()
except Exception as e:
print(e)
import sys
if len(sys.argv) > 1:
runfile(sys.argv[1])
else:
interactive()
| Remove colors from REPL prompt | ## Code Before:
from . import *
import readline
ps1 = '\n% '
ps2 = '| '
try:
from blessings import Terminal
term = Terminal()
ps1 = term.bold_blue(ps1)
ps2 = term.bold_blue(ps2)
def fancy_movement():
print(term.move_up() + term.clear_eol() + term.move_up())
except ImportError:
def fancy_movement():
pass
def getfilefunc(mod, droplast=True):
return Func(tuple(fixtags(flattenbody(mod, droplast=droplast))))
def runfile(fname):
invoke(getfilefunc(parseFile(fname)), stdlib())
def readProgram():
try:
yield input(ps1)
while True:
line = input(ps2)
if not line:
fancy_movement()
return
yield line
except EOFError:
print()
raise SystemExit
def interactive():
env = stdlib()
while True:
try:
retval, = invoke(getfilefunc(parseString('\n'.join(readProgram())), droplast=False), env)
if retval is not None:
print(arepr(retval))
except KeyboardInterrupt:
print()
except Exception as e:
print(e)
import sys
if len(sys.argv) > 1:
runfile(sys.argv[1])
else:
interactive()
## Instruction:
Remove colors from REPL prompt
## Code After:
from . import *
import readline
ps1 = '\n% '
ps2 = '| '
try:
from blessings import Terminal
term = Terminal()
def fancy_movement():
print(term.move_up() + term.clear_eol() + term.move_up())
except ImportError:
def fancy_movement():
pass
def getfilefunc(mod, droplast=True):
return Func(tuple(fixtags(flattenbody(mod, droplast=droplast))))
def runfile(fname):
invoke(getfilefunc(parseFile(fname)), stdlib())
def readProgram():
try:
yield input(ps1)
while True:
line = input(ps2)
if not line:
fancy_movement()
return
yield line
except EOFError:
print()
raise SystemExit
def interactive():
env = stdlib()
while True:
try:
retval, = invoke(getfilefunc(parseString('\n'.join(readProgram())), droplast=False), env)
if retval is not None:
print(arepr(retval))
except KeyboardInterrupt:
print()
except Exception as e:
print(e)
import sys
if len(sys.argv) > 1:
runfile(sys.argv[1])
else:
interactive()
| from . import *
import readline
ps1 = '\n% '
ps2 = '| '
try:
from blessings import Terminal
term = Terminal()
- ps1 = term.bold_blue(ps1)
- ps2 = term.bold_blue(ps2)
def fancy_movement():
print(term.move_up() + term.clear_eol() + term.move_up())
except ImportError:
def fancy_movement():
pass
def getfilefunc(mod, droplast=True):
return Func(tuple(fixtags(flattenbody(mod, droplast=droplast))))
def runfile(fname):
invoke(getfilefunc(parseFile(fname)), stdlib())
def readProgram():
try:
yield input(ps1)
while True:
line = input(ps2)
if not line:
fancy_movement()
return
yield line
except EOFError:
print()
raise SystemExit
def interactive():
env = stdlib()
while True:
try:
retval, = invoke(getfilefunc(parseString('\n'.join(readProgram())), droplast=False), env)
if retval is not None:
print(arepr(retval))
except KeyboardInterrupt:
print()
except Exception as e:
print(e)
import sys
if len(sys.argv) > 1:
runfile(sys.argv[1])
else:
interactive() |
cddcc7e5735022c7a4faeee5331e7b80a6349406 | src/functions.py | src/functions.py | def getTableColumnLabel(c):
label = ''
while True:
label += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[c % 26]
if c <= 26:
break
c = int(c/26)
return label
def parseTableColumnLabel(label):
ret = 0
for c in map(ord, reversed(label)):
if 0x41 <= c <= 0x5A:
ret = ret*26 + (c-0x41)
else:
raise ValueError('Invalid label: %s' % label)
return ret
| def getTableColumnLabel(c):
label = ''
while True:
label = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[c % 26] + label
if c < 26:
break
c = c//26-1
return label
def parseTableColumnLabel(label):
if not label:
raise ValueError('Invalid label: %s' % label)
ret = -1
for c in map(ord, label):
if 0x41 <= c <= 0x5A:
ret = (ret+1)*26 + (c-0x41)
else:
raise ValueError('Invalid label: %s' % label)
return ret
| Fix (parse|generate) table header label function | Fix (parse|generate) table header label function
| Python | mit | takumak/tuna,takumak/tuna | def getTableColumnLabel(c):
label = ''
while True:
- label += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[c % 26]
+ label = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[c % 26] + label
- if c <= 26:
+ if c < 26:
break
- c = int(c/26)
+ c = c//26-1
return label
def parseTableColumnLabel(label):
+ if not label:
+ raise ValueError('Invalid label: %s' % label)
- ret = 0
+ ret = -1
- for c in map(ord, reversed(label)):
+ for c in map(ord, label):
if 0x41 <= c <= 0x5A:
- ret = ret*26 + (c-0x41)
+ ret = (ret+1)*26 + (c-0x41)
else:
raise ValueError('Invalid label: %s' % label)
return ret
| Fix (parse|generate) table header label function | ## Code Before:
def getTableColumnLabel(c):
label = ''
while True:
label += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[c % 26]
if c <= 26:
break
c = int(c/26)
return label
def parseTableColumnLabel(label):
ret = 0
for c in map(ord, reversed(label)):
if 0x41 <= c <= 0x5A:
ret = ret*26 + (c-0x41)
else:
raise ValueError('Invalid label: %s' % label)
return ret
## Instruction:
Fix (parse|generate) table header label function
## Code After:
def getTableColumnLabel(c):
label = ''
while True:
label = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[c % 26] + label
if c < 26:
break
c = c//26-1
return label
def parseTableColumnLabel(label):
if not label:
raise ValueError('Invalid label: %s' % label)
ret = -1
for c in map(ord, label):
if 0x41 <= c <= 0x5A:
ret = (ret+1)*26 + (c-0x41)
else:
raise ValueError('Invalid label: %s' % label)
return ret
| def getTableColumnLabel(c):
label = ''
while True:
- label += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[c % 26]
? -
+ label = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[c % 26] + label
? ++++++++
- if c <= 26:
? -
+ if c < 26:
break
- c = int(c/26)
? ---- ^
+ c = c//26-1
? + ^^
return label
def parseTableColumnLabel(label):
+ if not label:
+ raise ValueError('Invalid label: %s' % label)
- ret = 0
? ^
+ ret = -1
? ^^
- for c in map(ord, reversed(label)):
? --------- -
+ for c in map(ord, label):
if 0x41 <= c <= 0x5A:
- ret = ret*26 + (c-0x41)
+ ret = (ret+1)*26 + (c-0x41)
? + +++
else:
raise ValueError('Invalid label: %s' % label)
return ret |
25e7b4a2e297e9944b5065851c6e65eb40b11bcd | scripts/examples/OpenMV/99-Tests/unittests.py | scripts/examples/OpenMV/99-Tests/unittests.py | import os, sensor, gc
TEST_DIR = "unittest"
TEMP_DIR = "unittest/temp"
DATA_DIR = "unittest/data"
SCRIPT_DIR = "unittest/script"
if not (TEST_DIR in os.listdir("")):
raise Exception('Unittest dir not found!')
print("")
test_failed = False
def print_result(test, passed):
s = "Unittest (%s)"%(test)
padding = "."*(60-len(s))
print(s + padding + ("PASSED" if passed == True else "FAILED"))
for test in sorted(os.listdir(SCRIPT_DIR)):
if test.endswith(".py"):
test_passed = True
test_path = "/".join((SCRIPT_DIR, test))
try:
exec(open(test_path).read())
gc.collect()
if unittest(DATA_DIR, TEMP_DIR) == False:
raise Exception()
except Exception as e:
test_failed = True
test_passed = False
print_result(test, test_passed)
if test_failed:
print("\nSome tests have FAILED!!!\n\n")
else:
print("\nAll tests PASSED.\n\n")
| import os, sensor, gc
TEST_DIR = "unittest"
TEMP_DIR = "unittest/temp"
DATA_DIR = "unittest/data"
SCRIPT_DIR = "unittest/script"
if not (TEST_DIR in os.listdir("")):
raise Exception('Unittest dir not found!')
print("")
test_failed = False
def print_result(test, result):
s = "Unittest (%s)"%(test)
padding = "."*(60-len(s))
print(s + padding + result)
for test in sorted(os.listdir(SCRIPT_DIR)):
if test.endswith(".py"):
test_result = "PASSED"
test_path = "/".join((SCRIPT_DIR, test))
try:
exec(open(test_path).read())
gc.collect()
if unittest(DATA_DIR, TEMP_DIR) == False:
raise Exception()
except Exception as e:
test_failed = True
test_result = "DISABLED" if "unavailable" in str(e) else "FAILED"
print_result(test, test_result)
if test_failed:
print("\nSome tests have FAILED!!!\n\n")
else:
print("\nAll tests PASSED.\n\n")
| Update unittest to ignore disabled functions. | Update unittest to ignore disabled functions.
| Python | mit | kwagyeman/openmv,kwagyeman/openmv,iabdalkader/openmv,kwagyeman/openmv,iabdalkader/openmv,openmv/openmv,kwagyeman/openmv,iabdalkader/openmv,openmv/openmv,openmv/openmv,iabdalkader/openmv,openmv/openmv | import os, sensor, gc
TEST_DIR = "unittest"
TEMP_DIR = "unittest/temp"
DATA_DIR = "unittest/data"
SCRIPT_DIR = "unittest/script"
if not (TEST_DIR in os.listdir("")):
raise Exception('Unittest dir not found!')
print("")
test_failed = False
- def print_result(test, passed):
+ def print_result(test, result):
s = "Unittest (%s)"%(test)
padding = "."*(60-len(s))
- print(s + padding + ("PASSED" if passed == True else "FAILED"))
+ print(s + padding + result)
for test in sorted(os.listdir(SCRIPT_DIR)):
if test.endswith(".py"):
- test_passed = True
+ test_result = "PASSED"
test_path = "/".join((SCRIPT_DIR, test))
try:
exec(open(test_path).read())
gc.collect()
if unittest(DATA_DIR, TEMP_DIR) == False:
raise Exception()
except Exception as e:
test_failed = True
- test_passed = False
+ test_result = "DISABLED" if "unavailable" in str(e) else "FAILED"
- print_result(test, test_passed)
+ print_result(test, test_result)
if test_failed:
print("\nSome tests have FAILED!!!\n\n")
else:
print("\nAll tests PASSED.\n\n")
| Update unittest to ignore disabled functions. | ## Code Before:
import os, sensor, gc
TEST_DIR = "unittest"
TEMP_DIR = "unittest/temp"
DATA_DIR = "unittest/data"
SCRIPT_DIR = "unittest/script"
if not (TEST_DIR in os.listdir("")):
raise Exception('Unittest dir not found!')
print("")
test_failed = False
def print_result(test, passed):
s = "Unittest (%s)"%(test)
padding = "."*(60-len(s))
print(s + padding + ("PASSED" if passed == True else "FAILED"))
for test in sorted(os.listdir(SCRIPT_DIR)):
if test.endswith(".py"):
test_passed = True
test_path = "/".join((SCRIPT_DIR, test))
try:
exec(open(test_path).read())
gc.collect()
if unittest(DATA_DIR, TEMP_DIR) == False:
raise Exception()
except Exception as e:
test_failed = True
test_passed = False
print_result(test, test_passed)
if test_failed:
print("\nSome tests have FAILED!!!\n\n")
else:
print("\nAll tests PASSED.\n\n")
## Instruction:
Update unittest to ignore disabled functions.
## Code After:
import os, sensor, gc
TEST_DIR = "unittest"
TEMP_DIR = "unittest/temp"
DATA_DIR = "unittest/data"
SCRIPT_DIR = "unittest/script"
if not (TEST_DIR in os.listdir("")):
raise Exception('Unittest dir not found!')
print("")
test_failed = False
def print_result(test, result):
s = "Unittest (%s)"%(test)
padding = "."*(60-len(s))
print(s + padding + result)
for test in sorted(os.listdir(SCRIPT_DIR)):
if test.endswith(".py"):
test_result = "PASSED"
test_path = "/".join((SCRIPT_DIR, test))
try:
exec(open(test_path).read())
gc.collect()
if unittest(DATA_DIR, TEMP_DIR) == False:
raise Exception()
except Exception as e:
test_failed = True
test_result = "DISABLED" if "unavailable" in str(e) else "FAILED"
print_result(test, test_result)
if test_failed:
print("\nSome tests have FAILED!!!\n\n")
else:
print("\nAll tests PASSED.\n\n")
| import os, sensor, gc
TEST_DIR = "unittest"
TEMP_DIR = "unittest/temp"
DATA_DIR = "unittest/data"
SCRIPT_DIR = "unittest/script"
if not (TEST_DIR in os.listdir("")):
raise Exception('Unittest dir not found!')
print("")
test_failed = False
- def print_result(test, passed):
? ^^ ^^^
+ def print_result(test, result):
? ^^ ^^^
s = "Unittest (%s)"%(test)
padding = "."*(60-len(s))
- print(s + padding + ("PASSED" if passed == True else "FAILED"))
+ print(s + padding + result)
for test in sorted(os.listdir(SCRIPT_DIR)):
if test.endswith(".py"):
- test_passed = True
+ test_result = "PASSED"
test_path = "/".join((SCRIPT_DIR, test))
try:
exec(open(test_path).read())
gc.collect()
if unittest(DATA_DIR, TEMP_DIR) == False:
raise Exception()
except Exception as e:
test_failed = True
- test_passed = False
+ test_result = "DISABLED" if "unavailable" in str(e) else "FAILED"
- print_result(test, test_passed)
? ^^ ^^^
+ print_result(test, test_result)
? ^^ ^^^
if test_failed:
print("\nSome tests have FAILED!!!\n\n")
else:
print("\nAll tests PASSED.\n\n") |
16767206ba1a40dbe217ec9e16b052c848f84b10 | converter.py | converter.py | from pydub import AudioSegment
from io import BytesIO
def convert_to_ogg(f):
bio = BytesIO()
AudioSegment.from_file(f).export(bio, format='ogg')
bio.seek(0)
return bio
| from pydub import AudioSegment
from io import BytesIO
def convert_to_ogg(f):
bio = BytesIO()
AudioSegment.from_file(f).export(bio, format='ogg', codec='libopus')
bio.seek(0)
return bio
| Use libopus codec while converting to Voice | Use libopus codec while converting to Voice
| Python | mit | MelomanCool/telegram-audiomemes | from pydub import AudioSegment
from io import BytesIO
def convert_to_ogg(f):
bio = BytesIO()
- AudioSegment.from_file(f).export(bio, format='ogg')
+ AudioSegment.from_file(f).export(bio, format='ogg', codec='libopus')
bio.seek(0)
return bio
| Use libopus codec while converting to Voice | ## Code Before:
from pydub import AudioSegment
from io import BytesIO
def convert_to_ogg(f):
bio = BytesIO()
AudioSegment.from_file(f).export(bio, format='ogg')
bio.seek(0)
return bio
## Instruction:
Use libopus codec while converting to Voice
## Code After:
from pydub import AudioSegment
from io import BytesIO
def convert_to_ogg(f):
bio = BytesIO()
AudioSegment.from_file(f).export(bio, format='ogg', codec='libopus')
bio.seek(0)
return bio
| from pydub import AudioSegment
from io import BytesIO
def convert_to_ogg(f):
bio = BytesIO()
- AudioSegment.from_file(f).export(bio, format='ogg')
+ AudioSegment.from_file(f).export(bio, format='ogg', codec='libopus')
? +++++++++++++++++
bio.seek(0)
return bio |
96755c5e3ccf0573e7190da2a4a9264fdf409710 | linter.py | linter.py |
"""This module exports the Markdownlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class MarkdownLint(NodeLinter):
"""Provides an interface to markdownlint."""
syntax = ('markdown', 'markdown gfm', 'multimarkdown', 'markdown extended')
cmd = ('markdownlint', '${args}', '${file}')
npm_name = 'markdownlint'
config_file = ('--config', '.markdownlintrc')
regex = r'.+?[:]\s(?P<line>\d+)[:]\s(?P<error>MD\d+)?[/]?(?P<message>.+)'
multiline = False
line_col_base = (1, 1)
tempfile_suffix = '-'
error_stream = util.STREAM_STDERR
word_re = None
comment_re = r'\s*/[/*]'
|
"""This module exports the Markdownlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class MarkdownLint(NodeLinter):
"""Provides an interface to markdownlint."""
defaults = {
'selector': 'text.html.markdown,'
'text.html.markdown.multimarkdown,'
'text.html.markdown.extended,'
'text.html.markdown.gfm'
}
cmd = ('markdownlint', '${args}', '${file}')
npm_name = 'markdownlint'
config_file = ('--config', '.markdownlintrc')
regex = r'.+?[:]\s(?P<line>\d+)[:]\s(?P<error>MD\d+)?[/]?(?P<message>.+)'
multiline = False
line_col_base = (1, 1)
tempfile_suffix = '-'
error_stream = util.STREAM_STDERR
word_re = None
comment_re = r'\s*/[/*]'
| Remove deprecated SL 'syntax' property override | Remove deprecated SL 'syntax' property override
Replaced by 'defaults/selector':
http://www.sublimelinter.com/en/stable/linter_settings.html#selector
| Python | mit | jonlabelle/SublimeLinter-contrib-markdownlint,jonlabelle/SublimeLinter-contrib-markdownlint |
"""This module exports the Markdownlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class MarkdownLint(NodeLinter):
"""Provides an interface to markdownlint."""
-
- syntax = ('markdown', 'markdown gfm', 'multimarkdown', 'markdown extended')
+ defaults = {
+ 'selector': 'text.html.markdown,'
+ 'text.html.markdown.multimarkdown,'
+ 'text.html.markdown.extended,'
+ 'text.html.markdown.gfm'
+ }
cmd = ('markdownlint', '${args}', '${file}')
npm_name = 'markdownlint'
config_file = ('--config', '.markdownlintrc')
regex = r'.+?[:]\s(?P<line>\d+)[:]\s(?P<error>MD\d+)?[/]?(?P<message>.+)'
multiline = False
line_col_base = (1, 1)
tempfile_suffix = '-'
error_stream = util.STREAM_STDERR
word_re = None
comment_re = r'\s*/[/*]'
| Remove deprecated SL 'syntax' property override | ## Code Before:
"""This module exports the Markdownlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class MarkdownLint(NodeLinter):
"""Provides an interface to markdownlint."""
syntax = ('markdown', 'markdown gfm', 'multimarkdown', 'markdown extended')
cmd = ('markdownlint', '${args}', '${file}')
npm_name = 'markdownlint'
config_file = ('--config', '.markdownlintrc')
regex = r'.+?[:]\s(?P<line>\d+)[:]\s(?P<error>MD\d+)?[/]?(?P<message>.+)'
multiline = False
line_col_base = (1, 1)
tempfile_suffix = '-'
error_stream = util.STREAM_STDERR
word_re = None
comment_re = r'\s*/[/*]'
## Instruction:
Remove deprecated SL 'syntax' property override
## Code After:
"""This module exports the Markdownlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class MarkdownLint(NodeLinter):
"""Provides an interface to markdownlint."""
defaults = {
'selector': 'text.html.markdown,'
'text.html.markdown.multimarkdown,'
'text.html.markdown.extended,'
'text.html.markdown.gfm'
}
cmd = ('markdownlint', '${args}', '${file}')
npm_name = 'markdownlint'
config_file = ('--config', '.markdownlintrc')
regex = r'.+?[:]\s(?P<line>\d+)[:]\s(?P<error>MD\d+)?[/]?(?P<message>.+)'
multiline = False
line_col_base = (1, 1)
tempfile_suffix = '-'
error_stream = util.STREAM_STDERR
word_re = None
comment_re = r'\s*/[/*]'
|
"""This module exports the Markdownlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class MarkdownLint(NodeLinter):
"""Provides an interface to markdownlint."""
-
- syntax = ('markdown', 'markdown gfm', 'multimarkdown', 'markdown extended')
+ defaults = {
+ 'selector': 'text.html.markdown,'
+ 'text.html.markdown.multimarkdown,'
+ 'text.html.markdown.extended,'
+ 'text.html.markdown.gfm'
+ }
cmd = ('markdownlint', '${args}', '${file}')
npm_name = 'markdownlint'
config_file = ('--config', '.markdownlintrc')
regex = r'.+?[:]\s(?P<line>\d+)[:]\s(?P<error>MD\d+)?[/]?(?P<message>.+)'
multiline = False
line_col_base = (1, 1)
tempfile_suffix = '-'
error_stream = util.STREAM_STDERR
word_re = None
comment_re = r'\s*/[/*]' |
ca97a29dded7278b40785fe88b5e8c9ceb542d86 | urllib3/util/wait.py | urllib3/util/wait.py | from .selectors import (
HAS_SELECT,
DefaultSelector,
EVENT_READ,
EVENT_WRITE
)
def _wait_for_io_events(socks, events, timeout=None):
""" Waits for IO events to be available from a list of sockets
or optionally a single socket if passed in. Returns a list of
sockets that can be interacted with immediately. """
if not HAS_SELECT:
raise ValueError('Platform does not have a selector')
if not isinstance(socks, list):
# Probably just a single socket.
if hasattr(socks, "fileno"):
socks = [socks]
# Otherwise it might be a non-list iterable.
else:
socks = list(socks)
selector = DefaultSelector()
for sock in socks:
selector.register(sock, events)
return [key[0].fileobj for key in
selector.select(timeout) if key[1] & events]
def wait_for_read(socks, timeout=None):
""" Waits for reading to be available from a list of sockets
or optionally a single socket if passed in. Returns a list of
sockets that can be read from immediately. """
return _wait_for_io_events(socks, EVENT_READ, timeout)
def wait_for_write(socks, timeout=None):
""" Waits for writing to be available from a list of sockets
or optionally a single socket if passed in. Returns a list of
sockets that can be written to immediately. """
return _wait_for_io_events(socks, EVENT_WRITE, timeout)
| from .selectors import (
HAS_SELECT,
DefaultSelector,
EVENT_READ,
EVENT_WRITE
)
def _wait_for_io_events(socks, events, timeout=None):
""" Waits for IO events to be available from a list of sockets
or optionally a single socket if passed in. Returns a list of
sockets that can be interacted with immediately. """
if not HAS_SELECT:
raise ValueError('Platform does not have a selector')
if not isinstance(socks, list):
# Probably just a single socket.
if hasattr(socks, "fileno"):
socks = [socks]
# Otherwise it might be a non-list iterable.
else:
socks = list(socks)
with DefaultSelector() as selector:
for sock in socks:
selector.register(sock, events)
return [key[0].fileobj for key in
selector.select(timeout) if key[1] & events]
def wait_for_read(socks, timeout=None):
""" Waits for reading to be available from a list of sockets
or optionally a single socket if passed in. Returns a list of
sockets that can be read from immediately. """
return _wait_for_io_events(socks, EVENT_READ, timeout)
def wait_for_write(socks, timeout=None):
""" Waits for writing to be available from a list of sockets
or optionally a single socket if passed in. Returns a list of
sockets that can be written to immediately. """
return _wait_for_io_events(socks, EVENT_WRITE, timeout)
| Use DefaultSelector as context manager. | Use DefaultSelector as context manager. | Python | mit | sigmavirus24/urllib3,Lukasa/urllib3,Disassem/urllib3,Lukasa/urllib3,Disassem/urllib3,urllib3/urllib3,urllib3/urllib3,sigmavirus24/urllib3 | from .selectors import (
HAS_SELECT,
DefaultSelector,
EVENT_READ,
EVENT_WRITE
)
def _wait_for_io_events(socks, events, timeout=None):
""" Waits for IO events to be available from a list of sockets
or optionally a single socket if passed in. Returns a list of
sockets that can be interacted with immediately. """
if not HAS_SELECT:
raise ValueError('Platform does not have a selector')
if not isinstance(socks, list):
# Probably just a single socket.
if hasattr(socks, "fileno"):
socks = [socks]
# Otherwise it might be a non-list iterable.
else:
socks = list(socks)
- selector = DefaultSelector()
+ with DefaultSelector() as selector:
- for sock in socks:
+ for sock in socks:
- selector.register(sock, events)
+ selector.register(sock, events)
- return [key[0].fileobj for key in
+ return [key[0].fileobj for key in
- selector.select(timeout) if key[1] & events]
+ selector.select(timeout) if key[1] & events]
def wait_for_read(socks, timeout=None):
""" Waits for reading to be available from a list of sockets
or optionally a single socket if passed in. Returns a list of
sockets that can be read from immediately. """
return _wait_for_io_events(socks, EVENT_READ, timeout)
def wait_for_write(socks, timeout=None):
""" Waits for writing to be available from a list of sockets
or optionally a single socket if passed in. Returns a list of
sockets that can be written to immediately. """
return _wait_for_io_events(socks, EVENT_WRITE, timeout)
| Use DefaultSelector as context manager. | ## Code Before:
from .selectors import (
HAS_SELECT,
DefaultSelector,
EVENT_READ,
EVENT_WRITE
)
def _wait_for_io_events(socks, events, timeout=None):
""" Waits for IO events to be available from a list of sockets
or optionally a single socket if passed in. Returns a list of
sockets that can be interacted with immediately. """
if not HAS_SELECT:
raise ValueError('Platform does not have a selector')
if not isinstance(socks, list):
# Probably just a single socket.
if hasattr(socks, "fileno"):
socks = [socks]
# Otherwise it might be a non-list iterable.
else:
socks = list(socks)
selector = DefaultSelector()
for sock in socks:
selector.register(sock, events)
return [key[0].fileobj for key in
selector.select(timeout) if key[1] & events]
def wait_for_read(socks, timeout=None):
""" Waits for reading to be available from a list of sockets
or optionally a single socket if passed in. Returns a list of
sockets that can be read from immediately. """
return _wait_for_io_events(socks, EVENT_READ, timeout)
def wait_for_write(socks, timeout=None):
""" Waits for writing to be available from a list of sockets
or optionally a single socket if passed in. Returns a list of
sockets that can be written to immediately. """
return _wait_for_io_events(socks, EVENT_WRITE, timeout)
## Instruction:
Use DefaultSelector as context manager.
## Code After:
from .selectors import (
HAS_SELECT,
DefaultSelector,
EVENT_READ,
EVENT_WRITE
)
def _wait_for_io_events(socks, events, timeout=None):
""" Waits for IO events to be available from a list of sockets
or optionally a single socket if passed in. Returns a list of
sockets that can be interacted with immediately. """
if not HAS_SELECT:
raise ValueError('Platform does not have a selector')
if not isinstance(socks, list):
# Probably just a single socket.
if hasattr(socks, "fileno"):
socks = [socks]
# Otherwise it might be a non-list iterable.
else:
socks = list(socks)
with DefaultSelector() as selector:
for sock in socks:
selector.register(sock, events)
return [key[0].fileobj for key in
selector.select(timeout) if key[1] & events]
def wait_for_read(socks, timeout=None):
""" Waits for reading to be available from a list of sockets
or optionally a single socket if passed in. Returns a list of
sockets that can be read from immediately. """
return _wait_for_io_events(socks, EVENT_READ, timeout)
def wait_for_write(socks, timeout=None):
""" Waits for writing to be available from a list of sockets
or optionally a single socket if passed in. Returns a list of
sockets that can be written to immediately. """
return _wait_for_io_events(socks, EVENT_WRITE, timeout)
| from .selectors import (
HAS_SELECT,
DefaultSelector,
EVENT_READ,
EVENT_WRITE
)
def _wait_for_io_events(socks, events, timeout=None):
""" Waits for IO events to be available from a list of sockets
or optionally a single socket if passed in. Returns a list of
sockets that can be interacted with immediately. """
if not HAS_SELECT:
raise ValueError('Platform does not have a selector')
if not isinstance(socks, list):
# Probably just a single socket.
if hasattr(socks, "fileno"):
socks = [socks]
# Otherwise it might be a non-list iterable.
else:
socks = list(socks)
- selector = DefaultSelector()
+ with DefaultSelector() as selector:
- for sock in socks:
+ for sock in socks:
? ++++
- selector.register(sock, events)
+ selector.register(sock, events)
? ++++
- return [key[0].fileobj for key in
+ return [key[0].fileobj for key in
? ++++
- selector.select(timeout) if key[1] & events]
+ selector.select(timeout) if key[1] & events]
? ++++
def wait_for_read(socks, timeout=None):
""" Waits for reading to be available from a list of sockets
or optionally a single socket if passed in. Returns a list of
sockets that can be read from immediately. """
return _wait_for_io_events(socks, EVENT_READ, timeout)
def wait_for_write(socks, timeout=None):
""" Waits for writing to be available from a list of sockets
or optionally a single socket if passed in. Returns a list of
sockets that can be written to immediately. """
return _wait_for_io_events(socks, EVENT_WRITE, timeout) |
6e8efdbb31c8713eeee0105ddafbd88d6286cfc9 | ganttcharts/cli/send_summary_emails.py | ganttcharts/cli/send_summary_emails.py | import datetime
import time
from .. import emails
from ..database import get_sql_connection
from ..models import Account, Session as SqlSession
__description__ = 'Send out summary emails.'
def send_out_emails():
session = SqlSession()
today = datetime.date.today()
accounts = session.query(Account) \
.filter(Account.receive_summary_email == True)
for account in accounts:
email = emails.Summary(account, today)
with emails.Mailer() as mailer:
mailer.send(email)
def command(args):
get_sql_connection()
if args.forever:
while True:
tomorrow = datetime.datetime.utcnow() + datetime.timedelta(days=1)
tomorrow = tomorrow.replace(hour=4, minute=0)
diff = tomorrow - datetime.datetime.utcnow()
time.sleep(diff.total_seconds())
send_out_emails()
else:
send_out_emails()
def add_subparser(subparsers):
parser = subparsers.add_parser('send-summary-emails', help=__description__)
parser.add_argument('--forever', action='store_true')
parser.set_defaults(func=command)
| import datetime
import time
from .. import emails
from ..database import get_sql_connection
from ..models import Account, Session as SqlSession
__description__ = 'Send out summary emails.'
def send_out_emails():
session = SqlSession()
today = datetime.date.today()
accounts = session.query(Account) \
.filter(Account.receive_summary_email == True)
for account in accounts:
try:
email = emails.Summary(account, today)
except RuntimeError: # no tasks
continue
with emails.Mailer() as mailer:
mailer.send(email)
def command(args):
get_sql_connection()
if args.forever:
while True:
tomorrow = datetime.datetime.utcnow() + datetime.timedelta(days=1)
tomorrow = tomorrow.replace(hour=4, minute=0)
diff = tomorrow - datetime.datetime.utcnow()
time.sleep(diff.total_seconds())
send_out_emails()
else:
send_out_emails()
def add_subparser(subparsers):
parser = subparsers.add_parser('send-summary-emails', help=__description__)
parser.add_argument('--forever', action='store_true')
parser.set_defaults(func=command)
| Add check for no tasks | Add check for no tasks
| Python | mit | thomasleese/gantt-charts,thomasleese/gantt-charts,thomasleese/gantt-charts,thomasleese/gantt-charts,thomasleese/gantt-charts | import datetime
import time
from .. import emails
from ..database import get_sql_connection
from ..models import Account, Session as SqlSession
__description__ = 'Send out summary emails.'
def send_out_emails():
session = SqlSession()
today = datetime.date.today()
accounts = session.query(Account) \
.filter(Account.receive_summary_email == True)
for account in accounts:
+ try:
- email = emails.Summary(account, today)
+ email = emails.Summary(account, today)
+ except RuntimeError: # no tasks
+ continue
+
with emails.Mailer() as mailer:
mailer.send(email)
def command(args):
get_sql_connection()
if args.forever:
while True:
tomorrow = datetime.datetime.utcnow() + datetime.timedelta(days=1)
tomorrow = tomorrow.replace(hour=4, minute=0)
diff = tomorrow - datetime.datetime.utcnow()
time.sleep(diff.total_seconds())
send_out_emails()
else:
send_out_emails()
def add_subparser(subparsers):
parser = subparsers.add_parser('send-summary-emails', help=__description__)
parser.add_argument('--forever', action='store_true')
parser.set_defaults(func=command)
| Add check for no tasks | ## Code Before:
import datetime
import time
from .. import emails
from ..database import get_sql_connection
from ..models import Account, Session as SqlSession
__description__ = 'Send out summary emails.'
def send_out_emails():
session = SqlSession()
today = datetime.date.today()
accounts = session.query(Account) \
.filter(Account.receive_summary_email == True)
for account in accounts:
email = emails.Summary(account, today)
with emails.Mailer() as mailer:
mailer.send(email)
def command(args):
get_sql_connection()
if args.forever:
while True:
tomorrow = datetime.datetime.utcnow() + datetime.timedelta(days=1)
tomorrow = tomorrow.replace(hour=4, minute=0)
diff = tomorrow - datetime.datetime.utcnow()
time.sleep(diff.total_seconds())
send_out_emails()
else:
send_out_emails()
def add_subparser(subparsers):
parser = subparsers.add_parser('send-summary-emails', help=__description__)
parser.add_argument('--forever', action='store_true')
parser.set_defaults(func=command)
## Instruction:
Add check for no tasks
## Code After:
import datetime
import time
from .. import emails
from ..database import get_sql_connection
from ..models import Account, Session as SqlSession
__description__ = 'Send out summary emails.'
def send_out_emails():
session = SqlSession()
today = datetime.date.today()
accounts = session.query(Account) \
.filter(Account.receive_summary_email == True)
for account in accounts:
try:
email = emails.Summary(account, today)
except RuntimeError: # no tasks
continue
with emails.Mailer() as mailer:
mailer.send(email)
def command(args):
get_sql_connection()
if args.forever:
while True:
tomorrow = datetime.datetime.utcnow() + datetime.timedelta(days=1)
tomorrow = tomorrow.replace(hour=4, minute=0)
diff = tomorrow - datetime.datetime.utcnow()
time.sleep(diff.total_seconds())
send_out_emails()
else:
send_out_emails()
def add_subparser(subparsers):
parser = subparsers.add_parser('send-summary-emails', help=__description__)
parser.add_argument('--forever', action='store_true')
parser.set_defaults(func=command)
| import datetime
import time
from .. import emails
from ..database import get_sql_connection
from ..models import Account, Session as SqlSession
__description__ = 'Send out summary emails.'
def send_out_emails():
session = SqlSession()
today = datetime.date.today()
accounts = session.query(Account) \
.filter(Account.receive_summary_email == True)
for account in accounts:
+ try:
- email = emails.Summary(account, today)
+ email = emails.Summary(account, today)
? ++++
+ except RuntimeError: # no tasks
+ continue
+
with emails.Mailer() as mailer:
mailer.send(email)
def command(args):
get_sql_connection()
if args.forever:
while True:
tomorrow = datetime.datetime.utcnow() + datetime.timedelta(days=1)
tomorrow = tomorrow.replace(hour=4, minute=0)
diff = tomorrow - datetime.datetime.utcnow()
time.sleep(diff.total_seconds())
send_out_emails()
else:
send_out_emails()
def add_subparser(subparsers):
parser = subparsers.add_parser('send-summary-emails', help=__description__)
parser.add_argument('--forever', action='store_true')
parser.set_defaults(func=command) |
61c4b0952e198fd5335f110349b4cc3fe840a02f | bynamodb/patcher.py | bynamodb/patcher.py | from boto.dynamodb2.layer1 import DynamoDBConnection
from .model import Model
def patch_dynamodb_connection(**kwargs):
""":class:`boto.dynamodb2.layer1.DynamoDBConnection` patcher.
It partially applies the keyword arguments to the
:class:`boto.dynamodb2.layer1.DynamoDBConnection` initializer method.
The common usage of this function would be patching host and port
to the local DynamoDB or remote DynamoDB as the project configuration
changes.
"""
if hasattr(DynamoDBConnection, '__original_init__'):
return
DynamoDBConnection.__original_init__ = DynamoDBConnection.__init__
def init(self, **fkwargs):
fkwargs.update(kwargs)
self.__original_init__(**fkwargs)
DynamoDBConnection.__init__ = init
def patch_table_name_prefix(prefix):
"""Patch the table name prefix"""
Model._table_prefix = prefix
| from boto.dynamodb2.layer1 import DynamoDBConnection
from .model import Model
def patch_from_config(config):
if 'DYNAMODB_CONNECTION' in config:
patch_dynamodb_connection(**config['DYNAMODB_CONNECTION'])
if 'DYNAMODB_PREFIX' in config:
patch_table_name_prefix(config['DYNAMODB_PREFIX'])
def patch_dynamodb_connection(**kwargs):
""":class:`boto.dynamodb2.layer1.DynamoDBConnection` patcher.
It partially applies the keyword arguments to the
:class:`boto.dynamodb2.layer1.DynamoDBConnection` initializer method.
The common usage of this function would be patching host and port
to the local DynamoDB or remote DynamoDB as the project configuration
changes.
"""
if hasattr(DynamoDBConnection, '__original_init__'):
return
DynamoDBConnection.__original_init__ = DynamoDBConnection.__init__
def init(self, **fkwargs):
fkwargs.update(kwargs)
self.__original_init__(**fkwargs)
DynamoDBConnection.__init__ = init
def patch_table_name_prefix(prefix):
"""Patch the table name prefix"""
Model._table_prefix = prefix
| Add support for the patching connection and the prefix through config dict | Add support for the patching connection and the prefix through config dict
| Python | mit | teddychoi/BynamoDB | from boto.dynamodb2.layer1 import DynamoDBConnection
from .model import Model
+
+
+ def patch_from_config(config):
+ if 'DYNAMODB_CONNECTION' in config:
+ patch_dynamodb_connection(**config['DYNAMODB_CONNECTION'])
+ if 'DYNAMODB_PREFIX' in config:
+ patch_table_name_prefix(config['DYNAMODB_PREFIX'])
def patch_dynamodb_connection(**kwargs):
""":class:`boto.dynamodb2.layer1.DynamoDBConnection` patcher.
It partially applies the keyword arguments to the
:class:`boto.dynamodb2.layer1.DynamoDBConnection` initializer method.
The common usage of this function would be patching host and port
to the local DynamoDB or remote DynamoDB as the project configuration
changes.
"""
if hasattr(DynamoDBConnection, '__original_init__'):
return
DynamoDBConnection.__original_init__ = DynamoDBConnection.__init__
def init(self, **fkwargs):
fkwargs.update(kwargs)
self.__original_init__(**fkwargs)
DynamoDBConnection.__init__ = init
def patch_table_name_prefix(prefix):
"""Patch the table name prefix"""
Model._table_prefix = prefix
| Add support for the patching connection and the prefix through config dict | ## Code Before:
from boto.dynamodb2.layer1 import DynamoDBConnection
from .model import Model
def patch_dynamodb_connection(**kwargs):
""":class:`boto.dynamodb2.layer1.DynamoDBConnection` patcher.
It partially applies the keyword arguments to the
:class:`boto.dynamodb2.layer1.DynamoDBConnection` initializer method.
The common usage of this function would be patching host and port
to the local DynamoDB or remote DynamoDB as the project configuration
changes.
"""
if hasattr(DynamoDBConnection, '__original_init__'):
return
DynamoDBConnection.__original_init__ = DynamoDBConnection.__init__
def init(self, **fkwargs):
fkwargs.update(kwargs)
self.__original_init__(**fkwargs)
DynamoDBConnection.__init__ = init
def patch_table_name_prefix(prefix):
"""Patch the table name prefix"""
Model._table_prefix = prefix
## Instruction:
Add support for the patching connection and the prefix through config dict
## Code After:
from boto.dynamodb2.layer1 import DynamoDBConnection
from .model import Model
def patch_from_config(config):
if 'DYNAMODB_CONNECTION' in config:
patch_dynamodb_connection(**config['DYNAMODB_CONNECTION'])
if 'DYNAMODB_PREFIX' in config:
patch_table_name_prefix(config['DYNAMODB_PREFIX'])
def patch_dynamodb_connection(**kwargs):
""":class:`boto.dynamodb2.layer1.DynamoDBConnection` patcher.
It partially applies the keyword arguments to the
:class:`boto.dynamodb2.layer1.DynamoDBConnection` initializer method.
The common usage of this function would be patching host and port
to the local DynamoDB or remote DynamoDB as the project configuration
changes.
"""
if hasattr(DynamoDBConnection, '__original_init__'):
return
DynamoDBConnection.__original_init__ = DynamoDBConnection.__init__
def init(self, **fkwargs):
fkwargs.update(kwargs)
self.__original_init__(**fkwargs)
DynamoDBConnection.__init__ = init
def patch_table_name_prefix(prefix):
"""Patch the table name prefix"""
Model._table_prefix = prefix
| from boto.dynamodb2.layer1 import DynamoDBConnection
from .model import Model
+
+
+ def patch_from_config(config):
+ if 'DYNAMODB_CONNECTION' in config:
+ patch_dynamodb_connection(**config['DYNAMODB_CONNECTION'])
+ if 'DYNAMODB_PREFIX' in config:
+ patch_table_name_prefix(config['DYNAMODB_PREFIX'])
def patch_dynamodb_connection(**kwargs):
""":class:`boto.dynamodb2.layer1.DynamoDBConnection` patcher.
It partially applies the keyword arguments to the
:class:`boto.dynamodb2.layer1.DynamoDBConnection` initializer method.
The common usage of this function would be patching host and port
to the local DynamoDB or remote DynamoDB as the project configuration
changes.
"""
if hasattr(DynamoDBConnection, '__original_init__'):
return
DynamoDBConnection.__original_init__ = DynamoDBConnection.__init__
def init(self, **fkwargs):
fkwargs.update(kwargs)
self.__original_init__(**fkwargs)
DynamoDBConnection.__init__ = init
def patch_table_name_prefix(prefix):
"""Patch the table name prefix"""
Model._table_prefix = prefix |
bcde8104bd77f18d7061f7f4d4831ad49644a913 | common/management/commands/build_index.py | common/management/commands/build_index.py | from django.core.management import BaseCommand
from django.db.models import get_app, get_models
from django.conf import settings
from common.utilities.search_utils import index_instance
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'--test',
action='store_true',
dest='test',
default=False,
help='Provide this if you want to create a test index')
def handle(self, *args, **options):
# optimize this to index in bulk
apps_lists = settings.LOCAL_APPS
for app_name in apps_lists:
app = get_app(app_name)
for model in get_models(app):
all_instances = model.objects.all()[0:3] \
if options.get('test') else model.objects.all()
[index_instance(obj) for obj in all_instances]
message = "Indexed {} {}".format(
all_instances.count(),
model._meta.verbose_name_plural.capitalize())
self.stdout.write(message)
self.stdout.write("Finished indexing")
| from django.core.management import BaseCommand
from django.db.models import get_app, get_models
from django.conf import settings
from common.utilities.search_utils import index_instance
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'--test',
action='store_true',
dest='test',
default=False,
help='Provide this if you want to create a test index')
def handle(self, *args, **options):
# optimize this to index in bulk
apps_lists = settings.LOCAL_APPS
for app_name in apps_lists:
app = get_app(app_name)
for model in get_models(app):
if model.__name__.lower() != 'testmodel':
all_instances = model.objects.all()[0:3] \
if options.get('test') else model.objects.all()
[index_instance(obj) for obj in all_instances]
message = "Indexed {} {}".format(
all_instances.count(),
model._meta.verbose_name_plural.capitalize())
self.stdout.write(message)
else:
# relation "common_testmodel" does not exist
# Will be fixed
pass
self.stdout.write("Finished indexing")
| Check the model beig indexed | Check the model beig indexed
| Python | mit | urandu/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,urandu/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,urandu/mfl_api,urandu/mfl_api | from django.core.management import BaseCommand
from django.db.models import get_app, get_models
from django.conf import settings
from common.utilities.search_utils import index_instance
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'--test',
action='store_true',
dest='test',
default=False,
help='Provide this if you want to create a test index')
def handle(self, *args, **options):
# optimize this to index in bulk
apps_lists = settings.LOCAL_APPS
for app_name in apps_lists:
app = get_app(app_name)
for model in get_models(app):
+ if model.__name__.lower() != 'testmodel':
- all_instances = model.objects.all()[0:3] \
+ all_instances = model.objects.all()[0:3] \
- if options.get('test') else model.objects.all()
+ if options.get('test') else model.objects.all()
- [index_instance(obj) for obj in all_instances]
+ [index_instance(obj) for obj in all_instances]
- message = "Indexed {} {}".format(
+ message = "Indexed {} {}".format(
- all_instances.count(),
+ all_instances.count(),
- model._meta.verbose_name_plural.capitalize())
+ model._meta.verbose_name_plural.capitalize())
- self.stdout.write(message)
+ self.stdout.write(message)
+ else:
+ # relation "common_testmodel" does not exist
+ # Will be fixed
+ pass
self.stdout.write("Finished indexing")
| Check the model beig indexed | ## Code Before:
from django.core.management import BaseCommand
from django.db.models import get_app, get_models
from django.conf import settings
from common.utilities.search_utils import index_instance
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'--test',
action='store_true',
dest='test',
default=False,
help='Provide this if you want to create a test index')
def handle(self, *args, **options):
# optimize this to index in bulk
apps_lists = settings.LOCAL_APPS
for app_name in apps_lists:
app = get_app(app_name)
for model in get_models(app):
all_instances = model.objects.all()[0:3] \
if options.get('test') else model.objects.all()
[index_instance(obj) for obj in all_instances]
message = "Indexed {} {}".format(
all_instances.count(),
model._meta.verbose_name_plural.capitalize())
self.stdout.write(message)
self.stdout.write("Finished indexing")
## Instruction:
Check the model beig indexed
## Code After:
from django.core.management import BaseCommand
from django.db.models import get_app, get_models
from django.conf import settings
from common.utilities.search_utils import index_instance
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'--test',
action='store_true',
dest='test',
default=False,
help='Provide this if you want to create a test index')
def handle(self, *args, **options):
# optimize this to index in bulk
apps_lists = settings.LOCAL_APPS
for app_name in apps_lists:
app = get_app(app_name)
for model in get_models(app):
if model.__name__.lower() != 'testmodel':
all_instances = model.objects.all()[0:3] \
if options.get('test') else model.objects.all()
[index_instance(obj) for obj in all_instances]
message = "Indexed {} {}".format(
all_instances.count(),
model._meta.verbose_name_plural.capitalize())
self.stdout.write(message)
else:
# relation "common_testmodel" does not exist
# Will be fixed
pass
self.stdout.write("Finished indexing")
| from django.core.management import BaseCommand
from django.db.models import get_app, get_models
from django.conf import settings
from common.utilities.search_utils import index_instance
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'--test',
action='store_true',
dest='test',
default=False,
help='Provide this if you want to create a test index')
def handle(self, *args, **options):
# optimize this to index in bulk
apps_lists = settings.LOCAL_APPS
for app_name in apps_lists:
app = get_app(app_name)
for model in get_models(app):
+ if model.__name__.lower() != 'testmodel':
- all_instances = model.objects.all()[0:3] \
+ all_instances = model.objects.all()[0:3] \
? ++++
- if options.get('test') else model.objects.all()
+ if options.get('test') else model.objects.all()
? ++++
- [index_instance(obj) for obj in all_instances]
+ [index_instance(obj) for obj in all_instances]
? ++++
- message = "Indexed {} {}".format(
+ message = "Indexed {} {}".format(
? ++++
- all_instances.count(),
+ all_instances.count(),
? ++++
- model._meta.verbose_name_plural.capitalize())
+ model._meta.verbose_name_plural.capitalize())
? ++++
- self.stdout.write(message)
+ self.stdout.write(message)
? ++++
+ else:
+ # relation "common_testmodel" does not exist
+ # Will be fixed
+ pass
self.stdout.write("Finished indexing") |
cadee051a462de765bab59ac42d6b372fa49c033 | examples/logfile.py | examples/logfile.py | from __future__ import unicode_literals, print_function
from twisted.internet.task import react
from eliot.logwriter import ThreadedFileWriter
from eliot import Message, Logger, addDestination
_logger = Logger()
def main(reactor):
print("Logging to example-eliot.log...")
logWriter = ThreadedFileWriter(open("example-eliot.log", "ab"), reactor)
addDestination(logWriter)
# Manually start the service. Normally we'd register ThreadedFileWriter
# with the usual Twisted Service/Application infrastructure.
logWriter.startService()
# Log a message:
Message.new(value="hello", another=1).write(_logger)
# Manually stop the service.
done = logWriter.stopService()
return done
if __name__ == '__main__':
react(main, [])
| from __future__ import unicode_literals, print_function
from twisted.internet.task import react
from eliot.logwriter import ThreadedFileWriter
from eliot import Message, Logger
_logger = Logger()
def main(reactor):
print("Logging to example-eliot.log...")
logWriter = ThreadedFileWriter(open("example-eliot.log", "ab"), reactor)
# Manually start the service, which will add it as a
# destination. Normally we'd register ThreadedFileWriter with the usual
# Twisted Service/Application infrastructure.
logWriter.startService()
# Log a message:
Message.new(value="hello", another=1).write(_logger)
# Manually stop the service.
done = logWriter.stopService()
return done
if __name__ == '__main__':
react(main, [])
| Fix bug where the service was added as a destination one time too many. | Fix bug where the service was added as a destination one time too many.
| Python | apache-2.0 | iffy/eliot,ClusterHQ/eliot,ScatterHQ/eliot,ScatterHQ/eliot,ScatterHQ/eliot | from __future__ import unicode_literals, print_function
from twisted.internet.task import react
from eliot.logwriter import ThreadedFileWriter
- from eliot import Message, Logger, addDestination
+ from eliot import Message, Logger
_logger = Logger()
def main(reactor):
print("Logging to example-eliot.log...")
logWriter = ThreadedFileWriter(open("example-eliot.log", "ab"), reactor)
- addDestination(logWriter)
- # Manually start the service. Normally we'd register ThreadedFileWriter
+ # Manually start the service, which will add it as a
+ # destination. Normally we'd register ThreadedFileWriter with the usual
- # with the usual Twisted Service/Application infrastructure.
+ # Twisted Service/Application infrastructure.
logWriter.startService()
# Log a message:
Message.new(value="hello", another=1).write(_logger)
# Manually stop the service.
done = logWriter.stopService()
return done
if __name__ == '__main__':
react(main, [])
| Fix bug where the service was added as a destination one time too many. | ## Code Before:
from __future__ import unicode_literals, print_function
from twisted.internet.task import react
from eliot.logwriter import ThreadedFileWriter
from eliot import Message, Logger, addDestination
_logger = Logger()
def main(reactor):
print("Logging to example-eliot.log...")
logWriter = ThreadedFileWriter(open("example-eliot.log", "ab"), reactor)
addDestination(logWriter)
# Manually start the service. Normally we'd register ThreadedFileWriter
# with the usual Twisted Service/Application infrastructure.
logWriter.startService()
# Log a message:
Message.new(value="hello", another=1).write(_logger)
# Manually stop the service.
done = logWriter.stopService()
return done
if __name__ == '__main__':
react(main, [])
## Instruction:
Fix bug where the service was added as a destination one time too many.
## Code After:
from __future__ import unicode_literals, print_function
from twisted.internet.task import react
from eliot.logwriter import ThreadedFileWriter
from eliot import Message, Logger
_logger = Logger()
def main(reactor):
print("Logging to example-eliot.log...")
logWriter = ThreadedFileWriter(open("example-eliot.log", "ab"), reactor)
# Manually start the service, which will add it as a
# destination. Normally we'd register ThreadedFileWriter with the usual
# Twisted Service/Application infrastructure.
logWriter.startService()
# Log a message:
Message.new(value="hello", another=1).write(_logger)
# Manually stop the service.
done = logWriter.stopService()
return done
if __name__ == '__main__':
react(main, [])
| from __future__ import unicode_literals, print_function
from twisted.internet.task import react
from eliot.logwriter import ThreadedFileWriter
- from eliot import Message, Logger, addDestination
? ----------------
+ from eliot import Message, Logger
_logger = Logger()
def main(reactor):
print("Logging to example-eliot.log...")
logWriter = ThreadedFileWriter(open("example-eliot.log", "ab"), reactor)
- addDestination(logWriter)
- # Manually start the service. Normally we'd register ThreadedFileWriter
+ # Manually start the service, which will add it as a
+ # destination. Normally we'd register ThreadedFileWriter with the usual
- # with the usual Twisted Service/Application infrastructure.
? ---------------
+ # Twisted Service/Application infrastructure.
logWriter.startService()
# Log a message:
Message.new(value="hello", another=1).write(_logger)
# Manually stop the service.
done = logWriter.stopService()
return done
if __name__ == '__main__':
react(main, []) |
adb458132b4e633052c9e46e1dc4e67306f9fc6d | tikplay/database/models.py | tikplay/database/models.py | import sqlalchemy as sa
from database import Base
class Song(Base):
__tablename__ = 'songs'
song_hash = sa.Column(sa.String(40), primary_key=True)
filename = sa.Column(sa.Text, nullable=False)
play_count = sa.Column(sa.Integer, nullable=False)
artist = sa.Column(sa.Text, nullable=True)
title = sa.Column(sa.Text, nullable=True)
length = sa.Column(sa.Integer, nullable=True)
last_played = sa.Column(sa.DateTime, nullable=True)
date_added = sa.Column(sa.DateTime, nullable=True)
| import sqlalchemy as sa
from database import Base
class Song(Base):
__tablename__ = 'songs'
song_hash = sa.Column(sa.String(40), primary_key=True)
filename = sa.Column(sa.Text, nullable=False)
play_count = sa.Column(sa.Integer, nullable=False)
artist = sa.Column(sa.Text, nullable=True)
title = sa.Column(sa.Text, nullable=True)
length = sa.Column(sa.Integer, nullable=True)
last_played = sa.Column(sa.DateTime, nullable=True)
date_added = sa.Column(sa.DateTime, nullable=True)
def __repr__(self):
return "<Song(song_hash={!r}, filename={!r}, play_count={!r}, artist={!r}, title={!r}, length={!r}, last_played={!r}, date_added={!r})>".format(
self.song_hash, self.filename, self.play_count, self.artist,
self.title, self.length, self.last_played, self.date_added)
def __str__(self):
return "<Song(song_hash={!s}, filename={!s}, play_count={!s}, artist={!s}, title={!s}, length={!s}, last_played={!s}, date_added={!s})>".format(
self.song_hash, self.filename, self.play_count, self.artist,
self.title, self.length, self.last_played, self.date_added)
| Add __repr__ and __str__ for DB model | Add __repr__ and __str__ for DB model
| Python | mit | tietokilta-saato/tikplay,tietokilta-saato/tikplay,tietokilta-saato/tikplay,tietokilta-saato/tikplay | import sqlalchemy as sa
from database import Base
class Song(Base):
__tablename__ = 'songs'
song_hash = sa.Column(sa.String(40), primary_key=True)
filename = sa.Column(sa.Text, nullable=False)
play_count = sa.Column(sa.Integer, nullable=False)
artist = sa.Column(sa.Text, nullable=True)
title = sa.Column(sa.Text, nullable=True)
length = sa.Column(sa.Integer, nullable=True)
last_played = sa.Column(sa.DateTime, nullable=True)
date_added = sa.Column(sa.DateTime, nullable=True)
+ def __repr__(self):
+ return "<Song(song_hash={!r}, filename={!r}, play_count={!r}, artist={!r}, title={!r}, length={!r}, last_played={!r}, date_added={!r})>".format(
+ self.song_hash, self.filename, self.play_count, self.artist,
+ self.title, self.length, self.last_played, self.date_added)
+
+ def __str__(self):
+ return "<Song(song_hash={!s}, filename={!s}, play_count={!s}, artist={!s}, title={!s}, length={!s}, last_played={!s}, date_added={!s})>".format(
+ self.song_hash, self.filename, self.play_count, self.artist,
+ self.title, self.length, self.last_played, self.date_added)
+ | Add __repr__ and __str__ for DB model | ## Code Before:
import sqlalchemy as sa
from database import Base
class Song(Base):
__tablename__ = 'songs'
song_hash = sa.Column(sa.String(40), primary_key=True)
filename = sa.Column(sa.Text, nullable=False)
play_count = sa.Column(sa.Integer, nullable=False)
artist = sa.Column(sa.Text, nullable=True)
title = sa.Column(sa.Text, nullable=True)
length = sa.Column(sa.Integer, nullable=True)
last_played = sa.Column(sa.DateTime, nullable=True)
date_added = sa.Column(sa.DateTime, nullable=True)
## Instruction:
Add __repr__ and __str__ for DB model
## Code After:
import sqlalchemy as sa
from database import Base
class Song(Base):
__tablename__ = 'songs'
song_hash = sa.Column(sa.String(40), primary_key=True)
filename = sa.Column(sa.Text, nullable=False)
play_count = sa.Column(sa.Integer, nullable=False)
artist = sa.Column(sa.Text, nullable=True)
title = sa.Column(sa.Text, nullable=True)
length = sa.Column(sa.Integer, nullable=True)
last_played = sa.Column(sa.DateTime, nullable=True)
date_added = sa.Column(sa.DateTime, nullable=True)
def __repr__(self):
return "<Song(song_hash={!r}, filename={!r}, play_count={!r}, artist={!r}, title={!r}, length={!r}, last_played={!r}, date_added={!r})>".format(
self.song_hash, self.filename, self.play_count, self.artist,
self.title, self.length, self.last_played, self.date_added)
def __str__(self):
return "<Song(song_hash={!s}, filename={!s}, play_count={!s}, artist={!s}, title={!s}, length={!s}, last_played={!s}, date_added={!s})>".format(
self.song_hash, self.filename, self.play_count, self.artist,
self.title, self.length, self.last_played, self.date_added)
| import sqlalchemy as sa
from database import Base
class Song(Base):
__tablename__ = 'songs'
song_hash = sa.Column(sa.String(40), primary_key=True)
filename = sa.Column(sa.Text, nullable=False)
play_count = sa.Column(sa.Integer, nullable=False)
artist = sa.Column(sa.Text, nullable=True)
title = sa.Column(sa.Text, nullable=True)
length = sa.Column(sa.Integer, nullable=True)
last_played = sa.Column(sa.DateTime, nullable=True)
date_added = sa.Column(sa.DateTime, nullable=True)
+
+ def __repr__(self):
+ return "<Song(song_hash={!r}, filename={!r}, play_count={!r}, artist={!r}, title={!r}, length={!r}, last_played={!r}, date_added={!r})>".format(
+ self.song_hash, self.filename, self.play_count, self.artist,
+ self.title, self.length, self.last_played, self.date_added)
+
+ def __str__(self):
+ return "<Song(song_hash={!s}, filename={!s}, play_count={!s}, artist={!s}, title={!s}, length={!s}, last_played={!s}, date_added={!s})>".format(
+ self.song_hash, self.filename, self.play_count, self.artist,
+ self.title, self.length, self.last_played, self.date_added) |
087925b336794b71675b31b70f845042e1f635fb | metro_accounts/metro_account.py | metro_accounts/metro_account.py | import time
from openerp.report import report_sxw
from openerp.osv import fields, osv
class account_account(osv.osv):
_inherit = "account.account"
_columns={
'name': fields.char('Name', size=256, required=True, select=True, translate=True),
'bal_direct': fields.selection([
('d', 'Debit'),
('c', 'Credit'),
], 'Balance Direction',)
}
account_account()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: | import time
from openerp.report import report_sxw
from openerp.osv import fields, osv
class account_account(osv.osv):
_inherit = "account.account"
_columns={
'name': fields.char('Name', size=256, required=True, select=True, translate=True),
'bal_direct': fields.selection([
('d', 'Debit'),
('c', 'Credit'),
], 'Balance Direction',)
}
'''
Update SQL:
update account_account set bal_direct = 'd' where user_type in (select id from account_account_type where name in('Check','Asset','Bank','Cash','Receivable'))
update account_account set bal_direct = 'c' where user_type in (select id from account_account_type where name in('Equity','Liability','Payable','Tax'))
'''
account_account()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: | Add the SQL to update account balance direction field bal_direct | Add the SQL to update account balance direction field bal_direct
| Python | agpl-3.0 | 837278709/metro-openerp,john-wang-metro/metro-openerp,john-wang-metro/metro-openerp,837278709/metro-openerp,837278709/metro-openerp,john-wang-metro/metro-openerp | import time
from openerp.report import report_sxw
from openerp.osv import fields, osv
class account_account(osv.osv):
_inherit = "account.account"
_columns={
'name': fields.char('Name', size=256, required=True, select=True, translate=True),
'bal_direct': fields.selection([
('d', 'Debit'),
('c', 'Credit'),
], 'Balance Direction',)
}
+ '''
+ Update SQL:
+ update account_account set bal_direct = 'd' where user_type in (select id from account_account_type where name in('Check','Asset','Bank','Cash','Receivable'))
+ update account_account set bal_direct = 'c' where user_type in (select id from account_account_type where name in('Equity','Liability','Payable','Tax'))
+ '''
account_account()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: | Add the SQL to update account balance direction field bal_direct | ## Code Before:
import time
from openerp.report import report_sxw
from openerp.osv import fields, osv
class account_account(osv.osv):
_inherit = "account.account"
_columns={
'name': fields.char('Name', size=256, required=True, select=True, translate=True),
'bal_direct': fields.selection([
('d', 'Debit'),
('c', 'Credit'),
], 'Balance Direction',)
}
account_account()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
## Instruction:
Add the SQL to update account balance direction field bal_direct
## Code After:
import time
from openerp.report import report_sxw
from openerp.osv import fields, osv
class account_account(osv.osv):
_inherit = "account.account"
_columns={
'name': fields.char('Name', size=256, required=True, select=True, translate=True),
'bal_direct': fields.selection([
('d', 'Debit'),
('c', 'Credit'),
], 'Balance Direction',)
}
'''
Update SQL:
update account_account set bal_direct = 'd' where user_type in (select id from account_account_type where name in('Check','Asset','Bank','Cash','Receivable'))
update account_account set bal_direct = 'c' where user_type in (select id from account_account_type where name in('Equity','Liability','Payable','Tax'))
'''
account_account()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: | import time
from openerp.report import report_sxw
from openerp.osv import fields, osv
class account_account(osv.osv):
_inherit = "account.account"
_columns={
'name': fields.char('Name', size=256, required=True, select=True, translate=True),
'bal_direct': fields.selection([
('d', 'Debit'),
('c', 'Credit'),
], 'Balance Direction',)
}
+ '''
+ Update SQL:
+ update account_account set bal_direct = 'd' where user_type in (select id from account_account_type where name in('Check','Asset','Bank','Cash','Receivable'))
+ update account_account set bal_direct = 'c' where user_type in (select id from account_account_type where name in('Equity','Liability','Payable','Tax'))
+ '''
account_account()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
62c51799953c1299e7c89c61a23270bf55e9cd69 | PortalEnrollment/models.py | PortalEnrollment/models.py | from django.db import models
# Create your models here.
| from django.db import models
from Portal.models import CharacterAttribute
from django.utils.translation import ugettext as _
# Create your models here.
class Enrollment(models.Model):
roles = models.ManyToManyField(_('Role'), CharacterAttribute)
open = models.BooleanField(_('Open Enrollment'), default=False)
limit = models.SmallIntegerField(_('Limit'))
background_image = models.ImageField(_('Background image'), upload_to='/enrollment/background/', blank=True)
thumbnail = models.ImageField(_('Thumbnail image'), upload_to='/enrollment/thumbnail/', blank=True)
def reach_limit(self):
pass
class Meta:
verbose_name = _('Enrollment')
verbose_name_plural = _('Enrollments') | Add first model for Enrollment application | Add first model for Enrollment application
| Python | mit | elryndir/GuildPortal,elryndir/GuildPortal | from django.db import models
+ from Portal.models import CharacterAttribute
+ from django.utils.translation import ugettext as _
# Create your models here.
+ class Enrollment(models.Model):
+ roles = models.ManyToManyField(_('Role'), CharacterAttribute)
+ open = models.BooleanField(_('Open Enrollment'), default=False)
+ limit = models.SmallIntegerField(_('Limit'))
+ background_image = models.ImageField(_('Background image'), upload_to='/enrollment/background/', blank=True)
+ thumbnail = models.ImageField(_('Thumbnail image'), upload_to='/enrollment/thumbnail/', blank=True)
+
+ def reach_limit(self):
+ pass
+
+ class Meta:
+ verbose_name = _('Enrollment')
+ verbose_name_plural = _('Enrollments') | Add first model for Enrollment application | ## Code Before:
from django.db import models
# Create your models here.
## Instruction:
Add first model for Enrollment application
## Code After:
from django.db import models
from Portal.models import CharacterAttribute
from django.utils.translation import ugettext as _
# Create your models here.
class Enrollment(models.Model):
roles = models.ManyToManyField(_('Role'), CharacterAttribute)
open = models.BooleanField(_('Open Enrollment'), default=False)
limit = models.SmallIntegerField(_('Limit'))
background_image = models.ImageField(_('Background image'), upload_to='/enrollment/background/', blank=True)
thumbnail = models.ImageField(_('Thumbnail image'), upload_to='/enrollment/thumbnail/', blank=True)
def reach_limit(self):
pass
class Meta:
verbose_name = _('Enrollment')
verbose_name_plural = _('Enrollments') | from django.db import models
+ from Portal.models import CharacterAttribute
+ from django.utils.translation import ugettext as _
# Create your models here.
+
+ class Enrollment(models.Model):
+ roles = models.ManyToManyField(_('Role'), CharacterAttribute)
+ open = models.BooleanField(_('Open Enrollment'), default=False)
+ limit = models.SmallIntegerField(_('Limit'))
+ background_image = models.ImageField(_('Background image'), upload_to='/enrollment/background/', blank=True)
+ thumbnail = models.ImageField(_('Thumbnail image'), upload_to='/enrollment/thumbnail/', blank=True)
+
+ def reach_limit(self):
+ pass
+
+ class Meta:
+ verbose_name = _('Enrollment')
+ verbose_name_plural = _('Enrollments') |
1b179405245bc7d7d6157528bd64e2b399491090 | quantecon/optimize/__init__.py | quantecon/optimize/__init__.py |
from .scalar_maximization import brent_max
from .root_finding import *
|
from .scalar_maximization import brent_max
from .root_finding import newton, newton_halley, newton_secant, bisect, brentq
| Fix import to list items | Fix import to list items
| Python | bsd-3-clause | oyamad/QuantEcon.py,QuantEcon/QuantEcon.py,oyamad/QuantEcon.py,QuantEcon/QuantEcon.py |
from .scalar_maximization import brent_max
- from .root_finding import *
+ from .root_finding import newton, newton_halley, newton_secant, bisect, brentq
| Fix import to list items | ## Code Before:
from .scalar_maximization import brent_max
from .root_finding import *
## Instruction:
Fix import to list items
## Code After:
from .scalar_maximization import brent_max
from .root_finding import newton, newton_halley, newton_secant, bisect, brentq
|
from .scalar_maximization import brent_max
- from .root_finding import *
+ from .root_finding import newton, newton_halley, newton_secant, bisect, brentq |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.