commit
stringlengths 40
40
| old_file
stringlengths 4
118
| new_file
stringlengths 4
118
| old_contents
stringlengths 10
2.94k
| new_contents
stringlengths 21
3.18k
| subject
stringlengths 16
444
| message
stringlengths 17
2.63k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 5
43k
| ndiff
stringlengths 52
3.32k
| instruction
stringlengths 16
444
| content
stringlengths 133
4.32k
| fuzzy_diff
stringlengths 16
3.18k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4c19fea0ff628666e24b2a4d133fa25903a155ff
|
tests/test_people.py
|
tests/test_people.py
|
from models.people import Person, Fellow, Staff
from unittest import TestCase
class PersonTestCases(TestCase):
"""Tests the functionality of the person parent class
"""
def setUp(self):
"""Passes an instance of class Person to all the methods in this class
"""
self.person = Person('Oluwafemi', 'Sule', 'Fellow')
def test_full_name_is_correct(self):
self.assertEqual(self.person.first_name + ' ' + self.person.last_name, 'Oluwafemi Sule')
class FellowTestCases(TestCase):
def setUp(self):
self.fellow = Fellow('Nadia', 'Alexis', 'Fellow')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Fellow, Person))
def test_person_name_is_correct(self):
self.assertEqual(self.fellow.first_name + ' ' + self.fellow.last_name, 'Nadia Alexis')
def test_fellow_id_generation(self):
self.assertEqual(self.fellow.id, 'fel57')
class StaffTestCases(TestCase):
def setUp(self):
self.staff = Staff('Nadia', 'Alexis', 'Staff')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Staff, Person))
def test_full_name_is_correct(self):
self.assertEqual(self.staff.first_name + ' ' + self.staff.last_name, 'Nadia Alexis')
def test_staff_id_generation(self):
self.assertEqual(self.staff.id, 'stf62')
|
from models.people import Person, Fellow, Staff
from unittest import TestCase
class FellowTestCases(TestCase):
def setUp(self):
self.fellow = Fellow('Nadia', 'Alexis', 'Fellow')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Fellow, Person))
def test_person_name_is_correct(self):
self.assertEqual(self.fellow.first_name + ' ' + self.fellow.last_name, 'Nadia Alexis')
def test_fellow_id_generation(self):
self.assertEqual(self.fellow.id, 'fel57')
class StaffTestCases(TestCase):
def setUp(self):
self.staff = Staff('Nadia', 'Alexis', 'Staff')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Staff, Person))
def test_full_name_is_correct(self):
self.assertEqual(self.staff.first_name + ' ' + self.staff.last_name, 'Nadia Alexis')
def test_staff_id_generation(self):
self.assertEqual(self.staff.id, 'stf62')
|
Remove test for parent class
|
Remove test for parent class
|
Python
|
mit
|
Alweezy/alvin-mutisya-dojo-project
|
from models.people import Person, Fellow, Staff
from unittest import TestCase
-
-
- class PersonTestCases(TestCase):
- """Tests the functionality of the person parent class
- """
- def setUp(self):
- """Passes an instance of class Person to all the methods in this class
- """
- self.person = Person('Oluwafemi', 'Sule', 'Fellow')
-
- def test_full_name_is_correct(self):
- self.assertEqual(self.person.first_name + ' ' + self.person.last_name, 'Oluwafemi Sule')
class FellowTestCases(TestCase):
def setUp(self):
self.fellow = Fellow('Nadia', 'Alexis', 'Fellow')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Fellow, Person))
def test_person_name_is_correct(self):
self.assertEqual(self.fellow.first_name + ' ' + self.fellow.last_name, 'Nadia Alexis')
def test_fellow_id_generation(self):
self.assertEqual(self.fellow.id, 'fel57')
class StaffTestCases(TestCase):
def setUp(self):
self.staff = Staff('Nadia', 'Alexis', 'Staff')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Staff, Person))
def test_full_name_is_correct(self):
self.assertEqual(self.staff.first_name + ' ' + self.staff.last_name, 'Nadia Alexis')
def test_staff_id_generation(self):
self.assertEqual(self.staff.id, 'stf62')
|
Remove test for parent class
|
## Code Before:
from models.people import Person, Fellow, Staff
from unittest import TestCase
class PersonTestCases(TestCase):
"""Tests the functionality of the person parent class
"""
def setUp(self):
"""Passes an instance of class Person to all the methods in this class
"""
self.person = Person('Oluwafemi', 'Sule', 'Fellow')
def test_full_name_is_correct(self):
self.assertEqual(self.person.first_name + ' ' + self.person.last_name, 'Oluwafemi Sule')
class FellowTestCases(TestCase):
def setUp(self):
self.fellow = Fellow('Nadia', 'Alexis', 'Fellow')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Fellow, Person))
def test_person_name_is_correct(self):
self.assertEqual(self.fellow.first_name + ' ' + self.fellow.last_name, 'Nadia Alexis')
def test_fellow_id_generation(self):
self.assertEqual(self.fellow.id, 'fel57')
class StaffTestCases(TestCase):
def setUp(self):
self.staff = Staff('Nadia', 'Alexis', 'Staff')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Staff, Person))
def test_full_name_is_correct(self):
self.assertEqual(self.staff.first_name + ' ' + self.staff.last_name, 'Nadia Alexis')
def test_staff_id_generation(self):
self.assertEqual(self.staff.id, 'stf62')
## Instruction:
Remove test for parent class
## Code After:
from models.people import Person, Fellow, Staff
from unittest import TestCase
class FellowTestCases(TestCase):
def setUp(self):
self.fellow = Fellow('Nadia', 'Alexis', 'Fellow')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Fellow, Person))
def test_person_name_is_correct(self):
self.assertEqual(self.fellow.first_name + ' ' + self.fellow.last_name, 'Nadia Alexis')
def test_fellow_id_generation(self):
self.assertEqual(self.fellow.id, 'fel57')
class StaffTestCases(TestCase):
def setUp(self):
self.staff = Staff('Nadia', 'Alexis', 'Staff')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Staff, Person))
def test_full_name_is_correct(self):
self.assertEqual(self.staff.first_name + ' ' + self.staff.last_name, 'Nadia Alexis')
def test_staff_id_generation(self):
self.assertEqual(self.staff.id, 'stf62')
|
// ... existing code ...
from unittest import TestCase
// ... rest of the code ...
|
4b459a367c67b40561b170b86c2df8882880d2be
|
test/test_examples.py
|
test/test_examples.py
|
import os
import pytest
from os.path import join, dirname
from glob import glob
# tests to exclude
excludes = ['authorization_v1.py', 'alchemy_data_news_v1.py', 'alchemy_language_v1.py']
# examples path. /examples
examples_path = join(dirname(__file__), '../', 'examples', '*.py')
# environment variables
try:
from dotenv import load_dotenv
except:
print('warning: dotenv module could not be imported')
try:
dotenv_path = join(dirname(__file__), '../', '.env')
load_dotenv(dotenv_path)
except:
print('warning: no .env file loaded')
@pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, reason='requires VCAP_SERVICES')
def test_examples():
examples = glob(examples_path)
for example in examples:
name = example.split('/')[-1]
# exclude some tests cases like authorization
if name in excludes:
continue
try:
exec(open(example).read(), globals())
except Exception as e:
assert False, 'example in file ' + name + ' failed with error: ' + str(e)
|
import os
import pytest
import json as json_import
from os.path import join, dirname
from glob import glob
# tests to exclude
excludes = ['authorization_v1.py', 'alchemy_data_news_v1.py', 'alchemy_language_v1.py', 'discovery_v1.ipynb', '__init__.py']
# examples path. /examples
examples_path = join(dirname(__file__), '../', 'examples', '*.py')
# environment variables
try:
from dotenv import load_dotenv
except:
print('warning: dotenv module could not be imported')
try:
dotenv_path = join(dirname(__file__), '../', '.env')
load_dotenv(dotenv_path)
except:
print('warning: no .env file loaded')
@pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, reason='requires VCAP_SERVICES')
def test_examples():
vcapServices = json_import.loads(os.getenv('VCAP_SERVICES'))
examples = glob(examples_path)
for example in examples:
name = example.split('/')[-1]
# exclude some tests cases like authorization
if name in excludes:
continue
# exclude tests if there are no credentials for that service
serviceName = name[:-6] if not name.startswith('visual_recognition') else 'watson_vision_combined'
if serviceName not in vcapServices:
print('%s does not have credentials in VCAP_SERVICES', serviceName)
continue
try:
exec(open(example).read(), globals())
except Exception as e:
assert False, 'example in file ' + name + ' failed with error: ' + str(e)
|
Exclude tests if there are no credentials in VCAP_SERVICES
|
Exclude tests if there are no credentials in VCAP_SERVICES
|
Python
|
apache-2.0
|
ehdsouza/python-sdk,ehdsouza/python-sdk,ehdsouza/python-sdk
|
import os
import pytest
+ import json as json_import
+
from os.path import join, dirname
from glob import glob
# tests to exclude
- excludes = ['authorization_v1.py', 'alchemy_data_news_v1.py', 'alchemy_language_v1.py']
+ excludes = ['authorization_v1.py', 'alchemy_data_news_v1.py', 'alchemy_language_v1.py', 'discovery_v1.ipynb', '__init__.py']
# examples path. /examples
examples_path = join(dirname(__file__), '../', 'examples', '*.py')
# environment variables
try:
from dotenv import load_dotenv
except:
print('warning: dotenv module could not be imported')
try:
dotenv_path = join(dirname(__file__), '../', '.env')
load_dotenv(dotenv_path)
except:
print('warning: no .env file loaded')
@pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, reason='requires VCAP_SERVICES')
def test_examples():
+ vcapServices = json_import.loads(os.getenv('VCAP_SERVICES'))
examples = glob(examples_path)
for example in examples:
name = example.split('/')[-1]
+
# exclude some tests cases like authorization
if name in excludes:
+ continue
+
+ # exclude tests if there are no credentials for that service
+ serviceName = name[:-6] if not name.startswith('visual_recognition') else 'watson_vision_combined'
+
+ if serviceName not in vcapServices:
+ print('%s does not have credentials in VCAP_SERVICES', serviceName)
continue
try:
exec(open(example).read(), globals())
except Exception as e:
assert False, 'example in file ' + name + ' failed with error: ' + str(e)
-
|
Exclude tests if there are no credentials in VCAP_SERVICES
|
## Code Before:
import os
import pytest
from os.path import join, dirname
from glob import glob
# tests to exclude
excludes = ['authorization_v1.py', 'alchemy_data_news_v1.py', 'alchemy_language_v1.py']
# examples path. /examples
examples_path = join(dirname(__file__), '../', 'examples', '*.py')
# environment variables
try:
from dotenv import load_dotenv
except:
print('warning: dotenv module could not be imported')
try:
dotenv_path = join(dirname(__file__), '../', '.env')
load_dotenv(dotenv_path)
except:
print('warning: no .env file loaded')
@pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, reason='requires VCAP_SERVICES')
def test_examples():
examples = glob(examples_path)
for example in examples:
name = example.split('/')[-1]
# exclude some tests cases like authorization
if name in excludes:
continue
try:
exec(open(example).read(), globals())
except Exception as e:
assert False, 'example in file ' + name + ' failed with error: ' + str(e)
## Instruction:
Exclude tests if there are no credentials in VCAP_SERVICES
## Code After:
import os
import pytest
import json as json_import
from os.path import join, dirname
from glob import glob
# tests to exclude
excludes = ['authorization_v1.py', 'alchemy_data_news_v1.py', 'alchemy_language_v1.py', 'discovery_v1.ipynb', '__init__.py']
# examples path. /examples
examples_path = join(dirname(__file__), '../', 'examples', '*.py')
# environment variables
try:
from dotenv import load_dotenv
except:
print('warning: dotenv module could not be imported')
try:
dotenv_path = join(dirname(__file__), '../', '.env')
load_dotenv(dotenv_path)
except:
print('warning: no .env file loaded')
@pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, reason='requires VCAP_SERVICES')
def test_examples():
vcapServices = json_import.loads(os.getenv('VCAP_SERVICES'))
examples = glob(examples_path)
for example in examples:
name = example.split('/')[-1]
# exclude some tests cases like authorization
if name in excludes:
continue
# exclude tests if there are no credentials for that service
serviceName = name[:-6] if not name.startswith('visual_recognition') else 'watson_vision_combined'
if serviceName not in vcapServices:
print('%s does not have credentials in VCAP_SERVICES', serviceName)
continue
try:
exec(open(example).read(), globals())
except Exception as e:
assert False, 'example in file ' + name + ' failed with error: ' + str(e)
|
...
import pytest
import json as json_import
from os.path import join, dirname
...
# tests to exclude
excludes = ['authorization_v1.py', 'alchemy_data_news_v1.py', 'alchemy_language_v1.py', 'discovery_v1.ipynb', '__init__.py']
...
def test_examples():
vcapServices = json_import.loads(os.getenv('VCAP_SERVICES'))
examples = glob(examples_path)
...
name = example.split('/')[-1]
# exclude some tests cases like authorization
...
if name in excludes:
continue
# exclude tests if there are no credentials for that service
serviceName = name[:-6] if not name.startswith('visual_recognition') else 'watson_vision_combined'
if serviceName not in vcapServices:
print('%s does not have credentials in VCAP_SERVICES', serviceName)
continue
...
assert False, 'example in file ' + name + ' failed with error: ' + str(e)
...
|
0a5331c36cb469b2af10d87ab375d9bd0c6c3fb8
|
tests/test_lattice.py
|
tests/test_lattice.py
|
import rml.lattice
def test_create_lattice():
l = rml.lattice.Lattice()
assert(len(l)) == 0
|
import rml.lattice
def test_create_lattice():
l = rml.lattice.Lattice()
assert(len(l)) == 0
def test_non_negative_lattice():
l = rml.lattice.Lattice()
assert(len(l)) >= 0
|
Test lattince length for non-negative values
|
Test lattince length for non-negative values
|
Python
|
apache-2.0
|
willrogers/pml,razvanvasile/RML,willrogers/pml
|
import rml.lattice
def test_create_lattice():
l = rml.lattice.Lattice()
assert(len(l)) == 0
+ def test_non_negative_lattice():
+ l = rml.lattice.Lattice()
+ assert(len(l)) >= 0
|
Test lattince length for non-negative values
|
## Code Before:
import rml.lattice
def test_create_lattice():
l = rml.lattice.Lattice()
assert(len(l)) == 0
## Instruction:
Test lattince length for non-negative values
## Code After:
import rml.lattice
def test_create_lattice():
l = rml.lattice.Lattice()
assert(len(l)) == 0
def test_non_negative_lattice():
l = rml.lattice.Lattice()
assert(len(l)) >= 0
|
...
def test_non_negative_lattice():
l = rml.lattice.Lattice()
assert(len(l)) >= 0
...
|
6620032e9f8574c3e1dad37c111040eca570a751
|
features/memberships/models.py
|
features/memberships/models.py
|
from django.contrib.contenttypes import fields as contenttypes
from django.db import models
class Membership(models.Model):
created_by = models.ForeignKey(
'gestalten.Gestalt', related_name='memberships_created')
date_joined = models.DateField(auto_now_add=True)
group = models.ForeignKey('groups.Group', related_name='memberships')
member = models.ForeignKey('gestalten.Gestalt', related_name='memberships')
def __str__(self):
return "%s is member of %s since %s" % (
str(self.member.user.get_username()),
str(self.group.slug), str(self.date_joined)
)
class Meta:
unique_together = ('group', 'member')
class Application(models.Model):
group = models.ForeignKey('groups.Group', related_name='applications')
contributions = contenttypes.GenericRelation(
'contributions.Contribution',
content_type_field='contribution_type',
object_id_field='contribution_id',
related_query_name='membership_application')
@property
def contribution(self):
return self.contributions.first()
|
from django.contrib.contenttypes import fields as contenttypes
from django.db import models
from . import querysets
class Membership(models.Model):
class Meta:
unique_together = ('group', 'member')
created_by = models.ForeignKey(
'gestalten.Gestalt', related_name='memberships_created')
date_joined = models.DateField(auto_now_add=True)
group = models.ForeignKey('groups.Group', related_name='memberships')
member = models.ForeignKey('gestalten.Gestalt', related_name='memberships')
objects = models.Manager.from_queryset(querysets.MembershipQuerySet)()
def __str__(self):
return "%s is member of %s since %s" % (
str(self.member.user.get_username()),
str(self.group.slug), str(self.date_joined)
)
class Application(models.Model):
group = models.ForeignKey('groups.Group', related_name='applications')
contributions = contenttypes.GenericRelation(
'contributions.Contribution',
content_type_field='contribution_type',
object_id_field='contribution_id',
related_query_name='membership_application')
@property
def contribution(self):
return self.contributions.first()
|
Add queryset for ordering memberships by activity
|
Add queryset for ordering memberships by activity
|
Python
|
agpl-3.0
|
stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten
|
from django.contrib.contenttypes import fields as contenttypes
from django.db import models
+ from . import querysets
+
class Membership(models.Model):
+ class Meta:
+ unique_together = ('group', 'member')
+
created_by = models.ForeignKey(
'gestalten.Gestalt', related_name='memberships_created')
date_joined = models.DateField(auto_now_add=True)
group = models.ForeignKey('groups.Group', related_name='memberships')
member = models.ForeignKey('gestalten.Gestalt', related_name='memberships')
+ objects = models.Manager.from_queryset(querysets.MembershipQuerySet)()
+
def __str__(self):
return "%s is member of %s since %s" % (
str(self.member.user.get_username()),
str(self.group.slug), str(self.date_joined)
)
-
- class Meta:
- unique_together = ('group', 'member')
class Application(models.Model):
group = models.ForeignKey('groups.Group', related_name='applications')
contributions = contenttypes.GenericRelation(
'contributions.Contribution',
content_type_field='contribution_type',
object_id_field='contribution_id',
related_query_name='membership_application')
@property
def contribution(self):
return self.contributions.first()
|
Add queryset for ordering memberships by activity
|
## Code Before:
from django.contrib.contenttypes import fields as contenttypes
from django.db import models
class Membership(models.Model):
created_by = models.ForeignKey(
'gestalten.Gestalt', related_name='memberships_created')
date_joined = models.DateField(auto_now_add=True)
group = models.ForeignKey('groups.Group', related_name='memberships')
member = models.ForeignKey('gestalten.Gestalt', related_name='memberships')
def __str__(self):
return "%s is member of %s since %s" % (
str(self.member.user.get_username()),
str(self.group.slug), str(self.date_joined)
)
class Meta:
unique_together = ('group', 'member')
class Application(models.Model):
group = models.ForeignKey('groups.Group', related_name='applications')
contributions = contenttypes.GenericRelation(
'contributions.Contribution',
content_type_field='contribution_type',
object_id_field='contribution_id',
related_query_name='membership_application')
@property
def contribution(self):
return self.contributions.first()
## Instruction:
Add queryset for ordering memberships by activity
## Code After:
from django.contrib.contenttypes import fields as contenttypes
from django.db import models
from . import querysets
class Membership(models.Model):
class Meta:
unique_together = ('group', 'member')
created_by = models.ForeignKey(
'gestalten.Gestalt', related_name='memberships_created')
date_joined = models.DateField(auto_now_add=True)
group = models.ForeignKey('groups.Group', related_name='memberships')
member = models.ForeignKey('gestalten.Gestalt', related_name='memberships')
objects = models.Manager.from_queryset(querysets.MembershipQuerySet)()
def __str__(self):
return "%s is member of %s since %s" % (
str(self.member.user.get_username()),
str(self.group.slug), str(self.date_joined)
)
class Application(models.Model):
group = models.ForeignKey('groups.Group', related_name='applications')
contributions = contenttypes.GenericRelation(
'contributions.Contribution',
content_type_field='contribution_type',
object_id_field='contribution_id',
related_query_name='membership_application')
@property
def contribution(self):
return self.contributions.first()
|
// ... existing code ...
from . import querysets
// ... modified code ...
class Membership(models.Model):
class Meta:
unique_together = ('group', 'member')
created_by = models.ForeignKey(
...
objects = models.Manager.from_queryset(querysets.MembershipQuerySet)()
def __str__(self):
...
)
// ... rest of the code ...
|
094380f4e30608713de549389adc1657f55b97b6
|
UCP/login/serializers.py
|
UCP/login/serializers.py
|
from rest_framework import serializers
from django.contrib.auth.models import User
from login.models import UserProfile
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'password')
write_only_fields = ('password',)
read_only_fields = ('id',)
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('id', 'first_name', 'last_name', 'designation', 'profile_image')
read_only_fields = ('id',)
|
from rest_framework import serializers
from django.contrib.auth.models import User
from login.models import UserProfile
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'password')
write_only_fields = ('password',)
read_only_fields = ('id',)
def create(self, validated_data):
user = User(email=validated_data['email'], username=validated_data['username'])
user.set_password(validated_data['password'])
user.save()
return user
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('id', 'first_name', 'last_name', 'designation', 'profile_image')
read_only_fields = ('id',)
|
Fix saving passwords in Register API
|
Fix saving passwords in Register API
override the create method in UserSerializer and set password there
|
Python
|
bsd-3-clause
|
BuildmLearn/University-Campus-Portal-UCP,BuildmLearn/University-Campus-Portal-UCP,BuildmLearn/University-Campus-Portal-UCP
|
from rest_framework import serializers
from django.contrib.auth.models import User
from login.models import UserProfile
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'password')
write_only_fields = ('password',)
read_only_fields = ('id',)
+
+ def create(self, validated_data):
+ user = User(email=validated_data['email'], username=validated_data['username'])
+ user.set_password(validated_data['password'])
+ user.save()
+ return user
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('id', 'first_name', 'last_name', 'designation', 'profile_image')
read_only_fields = ('id',)
|
Fix saving passwords in Register API
|
## Code Before:
from rest_framework import serializers
from django.contrib.auth.models import User
from login.models import UserProfile
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'password')
write_only_fields = ('password',)
read_only_fields = ('id',)
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('id', 'first_name', 'last_name', 'designation', 'profile_image')
read_only_fields = ('id',)
## Instruction:
Fix saving passwords in Register API
## Code After:
from rest_framework import serializers
from django.contrib.auth.models import User
from login.models import UserProfile
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'password')
write_only_fields = ('password',)
read_only_fields = ('id',)
def create(self, validated_data):
user = User(email=validated_data['email'], username=validated_data['username'])
user.set_password(validated_data['password'])
user.save()
return user
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('id', 'first_name', 'last_name', 'designation', 'profile_image')
read_only_fields = ('id',)
|
// ... existing code ...
read_only_fields = ('id',)
def create(self, validated_data):
user = User(email=validated_data['email'], username=validated_data['username'])
user.set_password(validated_data['password'])
user.save()
return user
// ... rest of the code ...
|
2c9d5a8b167f77a69995d55e2b2ef52c90807124
|
pytest_vw.py
|
pytest_vw.py
|
import os
import pytest
# You didn't see that.
#
# I hope you don't understand this code.
_config = None
EXAMINATORS = [
'CI',
'CONTINUOUS_INTEGRATION',
'BUILD_ID',
'BUILD_NUMBER',
'TEAMCITY_VERSION',
'TRAVIS',
'CIRCLECI',
'JENKINS_URL',
'HUDSON_URL',
'bamboo.buildKey',
'BUILDKITE',
]
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item):
"""Failing test cases are not a problem anymore."""
outcome = yield
rep = outcome.get_result()
examinators = EXAMINATORS
for examinator in _config.getini('vw_examinators').split('\n'):
examinators.append(examinator.strip())
if any(os.environ.get(gaze, False) for gaze in examinators):
rep.outcome = 'passed'
def pytest_configure(config):
global _config
_config = config
def pytest_addoption(parser):
parser.addini('vw_examinators', 'List of additional VW examinators.')
|
import os
import pytest
# You didn't see that.
#
# I hope you don't understand this code.
EXAMINATORS = [
'CI',
'CONTINUOUS_INTEGRATION',
'BUILD_ID',
'BUILD_NUMBER',
'TEAMCITY_VERSION',
'TRAVIS',
'CIRCLECI',
'JENKINS_URL',
'HUDSON_URL',
'bamboo.buildKey',
'BUILDKITE',
]
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item):
"""Failing test cases are not a problem anymore."""
outcome = yield
rep = outcome.get_result()
examinators = EXAMINATORS
for examinator in item.config.getini('vw_examinators').split('\n'):
examinators.append(examinator.strip())
if any(os.environ.get(gaze, False) for gaze in examinators):
rep.outcome = 'passed'
def pytest_addoption(parser):
parser.addini('vw_examinators', 'List of additional VW examinators.')
|
Use item.config to access config.
|
Use item.config to access config.
Fixes #1.
|
Python
|
mit
|
The-Compiler/pytest-vw
|
import os
import pytest
# You didn't see that.
#
# I hope you don't understand this code.
-
-
- _config = None
EXAMINATORS = [
'CI',
'CONTINUOUS_INTEGRATION',
'BUILD_ID',
'BUILD_NUMBER',
'TEAMCITY_VERSION',
'TRAVIS',
'CIRCLECI',
'JENKINS_URL',
'HUDSON_URL',
'bamboo.buildKey',
'BUILDKITE',
]
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item):
"""Failing test cases are not a problem anymore."""
outcome = yield
rep = outcome.get_result()
examinators = EXAMINATORS
- for examinator in _config.getini('vw_examinators').split('\n'):
+ for examinator in item.config.getini('vw_examinators').split('\n'):
examinators.append(examinator.strip())
if any(os.environ.get(gaze, False) for gaze in examinators):
rep.outcome = 'passed'
- def pytest_configure(config):
- global _config
- _config = config
-
-
def pytest_addoption(parser):
parser.addini('vw_examinators', 'List of additional VW examinators.')
|
Use item.config to access config.
|
## Code Before:
import os
import pytest
# You didn't see that.
#
# I hope you don't understand this code.
_config = None
EXAMINATORS = [
'CI',
'CONTINUOUS_INTEGRATION',
'BUILD_ID',
'BUILD_NUMBER',
'TEAMCITY_VERSION',
'TRAVIS',
'CIRCLECI',
'JENKINS_URL',
'HUDSON_URL',
'bamboo.buildKey',
'BUILDKITE',
]
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item):
"""Failing test cases are not a problem anymore."""
outcome = yield
rep = outcome.get_result()
examinators = EXAMINATORS
for examinator in _config.getini('vw_examinators').split('\n'):
examinators.append(examinator.strip())
if any(os.environ.get(gaze, False) for gaze in examinators):
rep.outcome = 'passed'
def pytest_configure(config):
global _config
_config = config
def pytest_addoption(parser):
parser.addini('vw_examinators', 'List of additional VW examinators.')
## Instruction:
Use item.config to access config.
## Code After:
import os
import pytest
# You didn't see that.
#
# I hope you don't understand this code.
EXAMINATORS = [
'CI',
'CONTINUOUS_INTEGRATION',
'BUILD_ID',
'BUILD_NUMBER',
'TEAMCITY_VERSION',
'TRAVIS',
'CIRCLECI',
'JENKINS_URL',
'HUDSON_URL',
'bamboo.buildKey',
'BUILDKITE',
]
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item):
"""Failing test cases are not a problem anymore."""
outcome = yield
rep = outcome.get_result()
examinators = EXAMINATORS
for examinator in item.config.getini('vw_examinators').split('\n'):
examinators.append(examinator.strip())
if any(os.environ.get(gaze, False) for gaze in examinators):
rep.outcome = 'passed'
def pytest_addoption(parser):
parser.addini('vw_examinators', 'List of additional VW examinators.')
|
# ... existing code ...
# I hope you don't understand this code.
# ... modified code ...
examinators = EXAMINATORS
for examinator in item.config.getini('vw_examinators').split('\n'):
examinators.append(examinator.strip())
...
def pytest_addoption(parser):
# ... rest of the code ...
|
1f50f159de11a6ff48ce9ce1a502e990228f8dc0
|
builtin_fns.py
|
builtin_fns.py
|
import object as obj
import ast
from evaluator import NULL, TRUE, FALSE
class Builtin(object):
builtins = []
"""a builtin function"""
def __init__(self, pattern, fn):
self.pattern = pattern # e.g. ["print", "$obj"]
self.fn = fn # fn(args) where args is a dictionary
Builtin.builtins.append(self)
def builtin(pattern):
def builtin_gen(fn):
Builtin(pattern, fn)
return fn
return builtin_gen
## Builtin definitions ##
@builtin(["print", "$obj"])
def print_builtin(args, context):
print(args["obj"])
return NULL
|
import object as obj
import ast
from evaluator import NULL, TRUE, FALSE
class Builtin(object):
builtins = []
"""a builtin function"""
def __init__(self, pattern, fn):
self.pattern = pattern # e.g. ["print", "$obj"]
self.fn = fn # fn(args) where args is a dictionary
Builtin.builtins.append(self)
def builtin(pattern):
def builtin_gen(fn):
Builtin(pattern, fn)
return fn
return builtin_gen
## Builtin definitions ##
@builtin(["print", "$obj"])
def print_builtin(args, context):
print(args["obj"])
return NULL
@builtin(["print", "$obj", "without", "newline"])
def print_wn(args, context):
print(args["obj"], end="")
return NULL
@builtin(["input"])
def input_builtin(args, context):
try:
return obj.String(input())
except (KeyboardInterrupt, EOFError):
return NULL
@builtin(["input", "with", "prompt", "$prompt"])
def input_prompt_builtin(args, context):
try:
return obj.String(input(args["prompt"]))
except (KeyboardInterrupt, EOFError):
return NULL
|
Add a few more builtins
|
Add a few more builtins
- print $obj without newline
- input
- input with prompt $prompt
|
Python
|
mit
|
Zac-Garby/pluto-lang
|
import object as obj
import ast
from evaluator import NULL, TRUE, FALSE
class Builtin(object):
builtins = []
"""a builtin function"""
def __init__(self, pattern, fn):
self.pattern = pattern # e.g. ["print", "$obj"]
self.fn = fn # fn(args) where args is a dictionary
Builtin.builtins.append(self)
def builtin(pattern):
def builtin_gen(fn):
Builtin(pattern, fn)
return fn
return builtin_gen
## Builtin definitions ##
@builtin(["print", "$obj"])
def print_builtin(args, context):
print(args["obj"])
return NULL
+
+ @builtin(["print", "$obj", "without", "newline"])
+ def print_wn(args, context):
+ print(args["obj"], end="")
+ return NULL
+
+ @builtin(["input"])
+ def input_builtin(args, context):
+ try:
+ return obj.String(input())
+ except (KeyboardInterrupt, EOFError):
+ return NULL
+
+ @builtin(["input", "with", "prompt", "$prompt"])
+ def input_prompt_builtin(args, context):
+ try:
+ return obj.String(input(args["prompt"]))
+ except (KeyboardInterrupt, EOFError):
+ return NULL
|
Add a few more builtins
|
## Code Before:
import object as obj
import ast
from evaluator import NULL, TRUE, FALSE
class Builtin(object):
builtins = []
"""a builtin function"""
def __init__(self, pattern, fn):
self.pattern = pattern # e.g. ["print", "$obj"]
self.fn = fn # fn(args) where args is a dictionary
Builtin.builtins.append(self)
def builtin(pattern):
def builtin_gen(fn):
Builtin(pattern, fn)
return fn
return builtin_gen
## Builtin definitions ##
@builtin(["print", "$obj"])
def print_builtin(args, context):
print(args["obj"])
return NULL
## Instruction:
Add a few more builtins
## Code After:
import object as obj
import ast
from evaluator import NULL, TRUE, FALSE
class Builtin(object):
builtins = []
"""a builtin function"""
def __init__(self, pattern, fn):
self.pattern = pattern # e.g. ["print", "$obj"]
self.fn = fn # fn(args) where args is a dictionary
Builtin.builtins.append(self)
def builtin(pattern):
def builtin_gen(fn):
Builtin(pattern, fn)
return fn
return builtin_gen
## Builtin definitions ##
@builtin(["print", "$obj"])
def print_builtin(args, context):
print(args["obj"])
return NULL
@builtin(["print", "$obj", "without", "newline"])
def print_wn(args, context):
print(args["obj"], end="")
return NULL
@builtin(["input"])
def input_builtin(args, context):
try:
return obj.String(input())
except (KeyboardInterrupt, EOFError):
return NULL
@builtin(["input", "with", "prompt", "$prompt"])
def input_prompt_builtin(args, context):
try:
return obj.String(input(args["prompt"]))
except (KeyboardInterrupt, EOFError):
return NULL
|
# ... existing code ...
return NULL
@builtin(["print", "$obj", "without", "newline"])
def print_wn(args, context):
print(args["obj"], end="")
return NULL
@builtin(["input"])
def input_builtin(args, context):
try:
return obj.String(input())
except (KeyboardInterrupt, EOFError):
return NULL
@builtin(["input", "with", "prompt", "$prompt"])
def input_prompt_builtin(args, context):
try:
return obj.String(input(args["prompt"]))
except (KeyboardInterrupt, EOFError):
return NULL
# ... rest of the code ...
|
2b8377d968dc336cd344dd4191e24b3c4f76857d
|
openedx/core/djangoapps/content/course_overviews/migrations/0009_readd_facebook_url.py
|
openedx/core/djangoapps/content/course_overviews/migrations/0009_readd_facebook_url.py
|
from __future__ import unicode_literals
from django.db import migrations, models, OperationalError, connection
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
class Migration(migrations.Migration):
dependencies = [
('course_overviews', '0008_remove_courseoverview_facebook_url'),
]
# An original version of 0008 removed the facebook_url field
# We need to handle the case where our noop 0008 ran AND the case
# where the original 0008 ran. We do that by using Django's introspection
# API to query INFORMATION_SCHEMA. _meta is unavailable as the
# column has already been removed from the model.
fields = connection.introspection.get_table_description(connection.cursor(),'course_overviews_courseoverview')
operations = []
if not any(f.name == 'facebook_url' for f in fields):
operations += migrations.AddField(
model_name='courseoverview',
name='facebook_url',
field=models.TextField(null=True),
),
|
from __future__ import unicode_literals
from django.db import migrations, models, connection
def table_description():
"""Handle Mysql/Pg vs Sqlite"""
# django's mysql/pg introspection.get_table_description tries to select *
# from table and fails during initial migrations from scratch.
# sqlite does not have this failure, so we can use the API.
# For not-sqlite, query information-schema directly with code lifted
# from the internals of django.db.backends.mysql.introspection.py
if connection.vendor == 'sqlite':
fields = connection.introspection.get_table_description(connection.cursor(), 'course_overviews_courseoverview')
return [f.name for f in fields]
else:
cursor = connection.cursor()
cursor.execute("""
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'course_overviews_courseoverview' AND table_schema = DATABASE()""")
rows = cursor.fetchall()
return [r[0] for r in rows]
class Migration(migrations.Migration):
dependencies = [
('course_overviews', '0008_remove_courseoverview_facebook_url'),
]
# An original version of 0008 removed the facebook_url field We need to
# handle the case where our noop 0008 ran AND the case where the original
# 0008 ran. We do that by using the standard information_schema to find out
# what columns exist. _meta is unavailable as the column has already been
# removed from the model
operations = []
fields = table_description()
# during a migration from scratch, fields will be empty, but we do not want to add
# an additional facebook_url
if fields and not any(f == 'facebook_url' for f in fields):
operations += migrations.AddField(
model_name='courseoverview',
name='facebook_url',
field=models.TextField(null=True),
),
|
Migrate correctly from scratch also
|
Migrate correctly from scratch also
Unfortunately, instrospection.get_table_description runs
select * from course_overview_courseoverview, which of course
does not exist while django is calculating initial migrations, causing
this to fail. Additionally, sqlite does not support information_schema,
but does not do a select * from the table.
Lift the main part of mysql's get_table_description up to the migration itself
and just inspect it directly. Continue to call the API for sqlite.
|
Python
|
agpl-3.0
|
Edraak/circleci-edx-platform,Edraak/edx-platform,Edraak/edx-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform,Edraak/edx-platform,Edraak/edx-platform,Edraak/edx-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform
|
from __future__ import unicode_literals
- from django.db import migrations, models, OperationalError, connection
+ from django.db import migrations, models, connection
- from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
+
+ def table_description():
+ """Handle Mysql/Pg vs Sqlite"""
+ # django's mysql/pg introspection.get_table_description tries to select *
+ # from table and fails during initial migrations from scratch.
+ # sqlite does not have this failure, so we can use the API.
+ # For not-sqlite, query information-schema directly with code lifted
+ # from the internals of django.db.backends.mysql.introspection.py
+
+ if connection.vendor == 'sqlite':
+ fields = connection.introspection.get_table_description(connection.cursor(), 'course_overviews_courseoverview')
+ return [f.name for f in fields]
+ else:
+ cursor = connection.cursor()
+ cursor.execute("""
+ SELECT column_name
+ FROM information_schema.columns
+ WHERE table_name = 'course_overviews_courseoverview' AND table_schema = DATABASE()""")
+ rows = cursor.fetchall()
+ return [r[0] for r in rows]
class Migration(migrations.Migration):
dependencies = [
('course_overviews', '0008_remove_courseoverview_facebook_url'),
]
- # An original version of 0008 removed the facebook_url field
+ # An original version of 0008 removed the facebook_url field We need to
- # We need to handle the case where our noop 0008 ran AND the case
+ # handle the case where our noop 0008 ran AND the case where the original
+ # 0008 ran. We do that by using the standard information_schema to find out
+ # what columns exist. _meta is unavailable as the column has already been
+ # removed from the model
- # where the original 0008 ran. We do that by using Django's introspection
- # API to query INFORMATION_SCHEMA. _meta is unavailable as the
- # column has already been removed from the model.
- fields = connection.introspection.get_table_description(connection.cursor(),'course_overviews_courseoverview')
operations = []
+ fields = table_description()
+ # during a migration from scratch, fields will be empty, but we do not want to add
+ # an additional facebook_url
- if not any(f.name == 'facebook_url' for f in fields):
+ if fields and not any(f == 'facebook_url' for f in fields):
operations += migrations.AddField(
model_name='courseoverview',
name='facebook_url',
field=models.TextField(null=True),
),
|
Migrate correctly from scratch also
|
## Code Before:
from __future__ import unicode_literals
from django.db import migrations, models, OperationalError, connection
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
class Migration(migrations.Migration):
dependencies = [
('course_overviews', '0008_remove_courseoverview_facebook_url'),
]
# An original version of 0008 removed the facebook_url field
# We need to handle the case where our noop 0008 ran AND the case
# where the original 0008 ran. We do that by using Django's introspection
# API to query INFORMATION_SCHEMA. _meta is unavailable as the
# column has already been removed from the model.
fields = connection.introspection.get_table_description(connection.cursor(),'course_overviews_courseoverview')
operations = []
if not any(f.name == 'facebook_url' for f in fields):
operations += migrations.AddField(
model_name='courseoverview',
name='facebook_url',
field=models.TextField(null=True),
),
## Instruction:
Migrate correctly from scratch also
## Code After:
from __future__ import unicode_literals
from django.db import migrations, models, connection
def table_description():
"""Handle Mysql/Pg vs Sqlite"""
# django's mysql/pg introspection.get_table_description tries to select *
# from table and fails during initial migrations from scratch.
# sqlite does not have this failure, so we can use the API.
# For not-sqlite, query information-schema directly with code lifted
# from the internals of django.db.backends.mysql.introspection.py
if connection.vendor == 'sqlite':
fields = connection.introspection.get_table_description(connection.cursor(), 'course_overviews_courseoverview')
return [f.name for f in fields]
else:
cursor = connection.cursor()
cursor.execute("""
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'course_overviews_courseoverview' AND table_schema = DATABASE()""")
rows = cursor.fetchall()
return [r[0] for r in rows]
class Migration(migrations.Migration):
dependencies = [
('course_overviews', '0008_remove_courseoverview_facebook_url'),
]
# An original version of 0008 removed the facebook_url field We need to
# handle the case where our noop 0008 ran AND the case where the original
# 0008 ran. We do that by using the standard information_schema to find out
# what columns exist. _meta is unavailable as the column has already been
# removed from the model
operations = []
fields = table_description()
# during a migration from scratch, fields will be empty, but we do not want to add
# an additional facebook_url
if fields and not any(f == 'facebook_url' for f in fields):
operations += migrations.AddField(
model_name='courseoverview',
name='facebook_url',
field=models.TextField(null=True),
),
|
...
from django.db import migrations, models, connection
def table_description():
"""Handle Mysql/Pg vs Sqlite"""
# django's mysql/pg introspection.get_table_description tries to select *
# from table and fails during initial migrations from scratch.
# sqlite does not have this failure, so we can use the API.
# For not-sqlite, query information-schema directly with code lifted
# from the internals of django.db.backends.mysql.introspection.py
if connection.vendor == 'sqlite':
fields = connection.introspection.get_table_description(connection.cursor(), 'course_overviews_courseoverview')
return [f.name for f in fields]
else:
cursor = connection.cursor()
cursor.execute("""
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'course_overviews_courseoverview' AND table_schema = DATABASE()""")
rows = cursor.fetchall()
return [r[0] for r in rows]
...
# An original version of 0008 removed the facebook_url field We need to
# handle the case where our noop 0008 ran AND the case where the original
# 0008 ran. We do that by using the standard information_schema to find out
# what columns exist. _meta is unavailable as the column has already been
# removed from the model
operations = []
fields = table_description()
# during a migration from scratch, fields will be empty, but we do not want to add
# an additional facebook_url
if fields and not any(f == 'facebook_url' for f in fields):
operations += migrations.AddField(
...
|
8bf1e479f1dd8423613d6eb0f5c78dd78fdc9c67
|
troposphere/sns.py
|
troposphere/sns.py
|
from . import AWSObject, AWSProperty
class Subscription(AWSProperty):
props = {
'Endpoint': (basestring, True),
'Protocol': (basestring, True),
}
class TopicPolicy(AWSObject):
props = {
'PolicyDocument': (dict, True),
'Topics': (list, True),
}
def __init__(self, name, **kwargs):
self.type = "AWS::SNS::TopicPolicy"
sup = super(TopicPolicy, self)
sup.__init__(name, self.type, "Properties", self.props, **kwargs)
class Topic(AWSObject):
props = {
'DisplayName': (basestring, False),
'Subscription': (list, True),
}
def __init__(self, name, **kwargs):
self.type = "AWS::SNS::Topic"
sup = super(Topic, self)
sup.__init__(name, self.type, "Properties", self.props, **kwargs)
|
from . import AWSObject, AWSProperty
class Subscription(AWSProperty):
props = {
'Endpoint': (basestring, True),
'Protocol': (basestring, True),
}
class TopicPolicy(AWSObject):
props = {
'PolicyDocument': (dict, True),
'Topics': (list, True),
}
def __init__(self, name, **kwargs):
self.type = "AWS::SNS::TopicPolicy"
sup = super(TopicPolicy, self)
sup.__init__(name, self.type, "Properties", self.props, **kwargs)
class Topic(AWSObject):
props = {
'DisplayName': (basestring, False),
'Subscription': ([Subscription], True),
}
def __init__(self, name, **kwargs):
self.type = "AWS::SNS::Topic"
sup = super(Topic, self)
sup.__init__(name, self.type, "Properties", self.props, **kwargs)
|
Validate the Subscription policy is made up of Subscription objects
|
Validate the Subscription policy is made up of Subscription objects
|
Python
|
bsd-2-clause
|
wangqiang8511/troposphere,7digital/troposphere,pas256/troposphere,Hons/troposphere,WeAreCloudar/troposphere,johnctitus/troposphere,nicolaka/troposphere,LouTheBrew/troposphere,yxd-hde/troposphere,jantman/troposphere,alonsodomin/troposphere,micahhausler/troposphere,inetCatapult/troposphere,garnaat/troposphere,cloudtools/troposphere,samcrang/troposphere,dmm92/troposphere,ikben/troposphere,dmm92/troposphere,pas256/troposphere,ptoraskar/troposphere,ikben/troposphere,craigbruce/troposphere,7digital/troposphere,iblazevic/troposphere,horacio3/troposphere,amosshapira/troposphere,mhahn/troposphere,ccortezb/troposphere,Yipit/troposphere,mannytoledo/troposphere,jdc0589/troposphere,DualSpark/troposphere,unravelin/troposphere,horacio3/troposphere,cryptickp/troposphere,kid/troposphere,alonsodomin/troposphere,cloudtools/troposphere,xxxVxxx/troposphere,johnctitus/troposphere
|
from . import AWSObject, AWSProperty
class Subscription(AWSProperty):
props = {
'Endpoint': (basestring, True),
'Protocol': (basestring, True),
}
class TopicPolicy(AWSObject):
props = {
'PolicyDocument': (dict, True),
'Topics': (list, True),
}
def __init__(self, name, **kwargs):
self.type = "AWS::SNS::TopicPolicy"
sup = super(TopicPolicy, self)
sup.__init__(name, self.type, "Properties", self.props, **kwargs)
class Topic(AWSObject):
props = {
'DisplayName': (basestring, False),
- 'Subscription': (list, True),
+ 'Subscription': ([Subscription], True),
}
def __init__(self, name, **kwargs):
self.type = "AWS::SNS::Topic"
sup = super(Topic, self)
sup.__init__(name, self.type, "Properties", self.props, **kwargs)
|
Validate the Subscription policy is made up of Subscription objects
|
## Code Before:
from . import AWSObject, AWSProperty
class Subscription(AWSProperty):
props = {
'Endpoint': (basestring, True),
'Protocol': (basestring, True),
}
class TopicPolicy(AWSObject):
props = {
'PolicyDocument': (dict, True),
'Topics': (list, True),
}
def __init__(self, name, **kwargs):
self.type = "AWS::SNS::TopicPolicy"
sup = super(TopicPolicy, self)
sup.__init__(name, self.type, "Properties", self.props, **kwargs)
class Topic(AWSObject):
props = {
'DisplayName': (basestring, False),
'Subscription': (list, True),
}
def __init__(self, name, **kwargs):
self.type = "AWS::SNS::Topic"
sup = super(Topic, self)
sup.__init__(name, self.type, "Properties", self.props, **kwargs)
## Instruction:
Validate the Subscription policy is made up of Subscription objects
## Code After:
from . import AWSObject, AWSProperty
class Subscription(AWSProperty):
props = {
'Endpoint': (basestring, True),
'Protocol': (basestring, True),
}
class TopicPolicy(AWSObject):
props = {
'PolicyDocument': (dict, True),
'Topics': (list, True),
}
def __init__(self, name, **kwargs):
self.type = "AWS::SNS::TopicPolicy"
sup = super(TopicPolicy, self)
sup.__init__(name, self.type, "Properties", self.props, **kwargs)
class Topic(AWSObject):
props = {
'DisplayName': (basestring, False),
'Subscription': ([Subscription], True),
}
def __init__(self, name, **kwargs):
self.type = "AWS::SNS::Topic"
sup = super(Topic, self)
sup.__init__(name, self.type, "Properties", self.props, **kwargs)
|
...
'DisplayName': (basestring, False),
'Subscription': ([Subscription], True),
}
...
|
3e4360e831d98dadca3f9346f324f3d17769257f
|
alg_selection_sort.py
|
alg_selection_sort.py
|
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def selection_sort(a_list):
"""Selection Sort algortihm.
Time complexity: O(n^2).
"""
for max_slot in reversed(range(len(a_list))):
select_slot = 0
for slot in range(1, max_slot + 1):
if a_list[slot] > a_list[select_slot]:
select_slot = slot
a_list[select_slot], a_list[max_slot] = (
a_list[max_slot], a_list[select_slot])
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('By selection sort: ')
selection_sort(a_list)
print(a_list)
if __name__ == '__main__':
main()
|
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def selection_sort(ls):
"""Selection Sort algortihm.
Time complexity: O(n^2).
Space complexity: O(1).
"""
# Start from the last elemenet reversely: len(ls) - 1, ..., 0.
for i_max in reversed(range(len(ls))):
# Select the next max, and interchange it with corresponding element.
s = 0
for i in range(1, i_max + 1):
if ls[i] > ls[s]:
s = i
ls[s], ls[i_max] = ls[i_max], ls[s]
def main():
ls = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('List: {}'.format(ls))
print('By selection sort: ')
selection_sort(ls)
print(ls)
if __name__ == '__main__':
main()
|
Refactor selection sort w/ adding comments
|
Refactor selection sort w/ adding comments
|
Python
|
bsd-2-clause
|
bowen0701/algorithms_data_structures
|
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
- def selection_sort(a_list):
+ def selection_sort(ls):
"""Selection Sort algortihm.
Time complexity: O(n^2).
+ Space complexity: O(1).
"""
+ # Start from the last elemenet reversely: len(ls) - 1, ..., 0.
- for max_slot in reversed(range(len(a_list))):
+ for i_max in reversed(range(len(ls))):
- select_slot = 0
+ # Select the next max, and interchange it with corresponding element.
+ s = 0
- for slot in range(1, max_slot + 1):
+ for i in range(1, i_max + 1):
+ if ls[i] > ls[s]:
+ s = i
+ ls[s], ls[i_max] = ls[i_max], ls[s]
- if a_list[slot] > a_list[select_slot]:
- select_slot = slot
-
- a_list[select_slot], a_list[max_slot] = (
- a_list[max_slot], a_list[select_slot])
def main():
- a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
+ ls = [54, 26, 93, 17, 77, 31, 44, 55, 20]
- print('a_list: {}'.format(a_list))
+ print('List: {}'.format(ls))
print('By selection sort: ')
- selection_sort(a_list)
+ selection_sort(ls)
- print(a_list)
+ print(ls)
if __name__ == '__main__':
main()
|
Refactor selection sort w/ adding comments
|
## Code Before:
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def selection_sort(a_list):
"""Selection Sort algortihm.
Time complexity: O(n^2).
"""
for max_slot in reversed(range(len(a_list))):
select_slot = 0
for slot in range(1, max_slot + 1):
if a_list[slot] > a_list[select_slot]:
select_slot = slot
a_list[select_slot], a_list[max_slot] = (
a_list[max_slot], a_list[select_slot])
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('By selection sort: ')
selection_sort(a_list)
print(a_list)
if __name__ == '__main__':
main()
## Instruction:
Refactor selection sort w/ adding comments
## Code After:
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def selection_sort(ls):
"""Selection Sort algortihm.
Time complexity: O(n^2).
Space complexity: O(1).
"""
# Start from the last elemenet reversely: len(ls) - 1, ..., 0.
for i_max in reversed(range(len(ls))):
# Select the next max, and interchange it with corresponding element.
s = 0
for i in range(1, i_max + 1):
if ls[i] > ls[s]:
s = i
ls[s], ls[i_max] = ls[i_max], ls[s]
def main():
ls = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('List: {}'.format(ls))
print('By selection sort: ')
selection_sort(ls)
print(ls)
if __name__ == '__main__':
main()
|
# ... existing code ...
def selection_sort(ls):
"""Selection Sort algortihm.
# ... modified code ...
Time complexity: O(n^2).
Space complexity: O(1).
"""
# Start from the last elemenet reversely: len(ls) - 1, ..., 0.
for i_max in reversed(range(len(ls))):
# Select the next max, and interchange it with corresponding element.
s = 0
for i in range(1, i_max + 1):
if ls[i] > ls[s]:
s = i
ls[s], ls[i_max] = ls[i_max], ls[s]
...
def main():
ls = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('List: {}'.format(ls))
print('By selection sort: ')
selection_sort(ls)
print(ls)
# ... rest of the code ...
|
f7caec9d0c0058b5d760992172b434b461f70d90
|
molecule/default/tests/test_default.py
|
molecule/default/tests/test_default.py
|
import os
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_docker_service_enabled(host):
service = host.service('docker')
assert service.is_enabled
def test_docker_service_running(host):
service = host.service('docker')
assert service.is_running
@pytest.mark.parametrize('socket_def', [
# listening on localhost, for tcp sockets on port 1883 (MQQT)
('tcp://127.0.0.1:1883'),
# all IPv4 tcp sockets on port 8883 (MQQTS)
('tcp://8883'),
])
def test_listening_sockets(host, socket_def):
socket = host.socket(socket_def)
assert socket.is_listening
# Tests to write:
# - using the localhost listener:
# - verify that a message can be published
# - verify that a published message can be subscribed to
|
import os
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_docker_service_enabled(host):
service = host.service('docker')
assert service.is_enabled
def test_docker_service_running(host):
service = host.service('docker')
assert service.is_running
@pytest.mark.parametrize('socket_def', [
# all IPv4 tcp sockets on port 8883 (MQQTS)
('tcp://8883'),
])
def test_listening_sockets(host, socket_def):
socket = host.socket(socket_def)
assert socket.is_listening
# Tests to write:
# - using the localhost listener:
# - verify that a message can be published
# - verify that a published message can be subscribed to
|
Remove test enforcing listening on port 1883
|
Remove test enforcing listening on port 1883
|
Python
|
mit
|
triplepoint/ansible-mosquitto
|
import os
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_docker_service_enabled(host):
service = host.service('docker')
assert service.is_enabled
def test_docker_service_running(host):
service = host.service('docker')
assert service.is_running
@pytest.mark.parametrize('socket_def', [
- # listening on localhost, for tcp sockets on port 1883 (MQQT)
- ('tcp://127.0.0.1:1883'),
# all IPv4 tcp sockets on port 8883 (MQQTS)
('tcp://8883'),
])
def test_listening_sockets(host, socket_def):
socket = host.socket(socket_def)
assert socket.is_listening
# Tests to write:
# - using the localhost listener:
# - verify that a message can be published
# - verify that a published message can be subscribed to
|
Remove test enforcing listening on port 1883
|
## Code Before:
import os
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_docker_service_enabled(host):
service = host.service('docker')
assert service.is_enabled
def test_docker_service_running(host):
service = host.service('docker')
assert service.is_running
@pytest.mark.parametrize('socket_def', [
# listening on localhost, for tcp sockets on port 1883 (MQQT)
('tcp://127.0.0.1:1883'),
# all IPv4 tcp sockets on port 8883 (MQQTS)
('tcp://8883'),
])
def test_listening_sockets(host, socket_def):
socket = host.socket(socket_def)
assert socket.is_listening
# Tests to write:
# - using the localhost listener:
# - verify that a message can be published
# - verify that a published message can be subscribed to
## Instruction:
Remove test enforcing listening on port 1883
## Code After:
import os
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_docker_service_enabled(host):
service = host.service('docker')
assert service.is_enabled
def test_docker_service_running(host):
service = host.service('docker')
assert service.is_running
@pytest.mark.parametrize('socket_def', [
# all IPv4 tcp sockets on port 8883 (MQQTS)
('tcp://8883'),
])
def test_listening_sockets(host, socket_def):
socket = host.socket(socket_def)
assert socket.is_listening
# Tests to write:
# - using the localhost listener:
# - verify that a message can be published
# - verify that a published message can be subscribed to
|
// ... existing code ...
@pytest.mark.parametrize('socket_def', [
# all IPv4 tcp sockets on port 8883 (MQQTS)
// ... rest of the code ...
|
38efa77f8831b2fcceb5f86f31a1ec7dc6aa5627
|
src/odometry.py
|
src/odometry.py
|
import rospy
from nav_msgs.msg import Odometry
current_odometry = None
def get_odometry(message):
global current_odometry
current_odometry = message
if __name__ == '__main__':
rospy.init_node('odometry')
subscriber = rospy.Subscriber('odom', Odometry, get_odometry)
publisher = rospy.Publisher('odometry_10_hz', Odometry, queue_size=1)
while current_odometry == None:
pass
rate = rospy.Rate(10)
while not rospy.is_shutdown():
publisher.publish(current_odometry)
rate.sleep()
|
import rospy
from gazebo_msgs.msg import ModelStates
from geometry_msgs.msg import Pose
current_pose = None
def get_pose(message):
global current_pose
current_pose = message.pose[0]
if __name__ == '__main__':
rospy.init_node('pose')
subscriber = rospy.Subscriber('gazebo/model_states', ModelStates, get_pose)
publisher = rospy.Publisher('pose_10_hz', Pose, queue_size=1)
while current_pose == None:
pass
rate = rospy.Rate(10)
while not rospy.is_shutdown():
publisher.publish(current_pose)
rate.sleep()
|
Change subscribed topic and message type
|
Change subscribed topic and message type
|
Python
|
mit
|
bit0001/trajectory_tracking,bit0001/trajectory_tracking
|
import rospy
- from nav_msgs.msg import Odometry
+ from gazebo_msgs.msg import ModelStates
+ from geometry_msgs.msg import Pose
- current_odometry = None
+ current_pose = None
- def get_odometry(message):
+ def get_pose(message):
- global current_odometry
+ global current_pose
+
- current_odometry = message
+ current_pose = message.pose[0]
if __name__ == '__main__':
- rospy.init_node('odometry')
+ rospy.init_node('pose')
- subscriber = rospy.Subscriber('odom', Odometry, get_odometry)
+ subscriber = rospy.Subscriber('gazebo/model_states', ModelStates, get_pose)
- publisher = rospy.Publisher('odometry_10_hz', Odometry, queue_size=1)
+ publisher = rospy.Publisher('pose_10_hz', Pose, queue_size=1)
- while current_odometry == None:
+ while current_pose == None:
pass
rate = rospy.Rate(10)
while not rospy.is_shutdown():
- publisher.publish(current_odometry)
+ publisher.publish(current_pose)
rate.sleep()
|
Change subscribed topic and message type
|
## Code Before:
import rospy
from nav_msgs.msg import Odometry
current_odometry = None
def get_odometry(message):
global current_odometry
current_odometry = message
if __name__ == '__main__':
rospy.init_node('odometry')
subscriber = rospy.Subscriber('odom', Odometry, get_odometry)
publisher = rospy.Publisher('odometry_10_hz', Odometry, queue_size=1)
while current_odometry == None:
pass
rate = rospy.Rate(10)
while not rospy.is_shutdown():
publisher.publish(current_odometry)
rate.sleep()
## Instruction:
Change subscribed topic and message type
## Code After:
import rospy
from gazebo_msgs.msg import ModelStates
from geometry_msgs.msg import Pose
current_pose = None
def get_pose(message):
global current_pose
current_pose = message.pose[0]
if __name__ == '__main__':
rospy.init_node('pose')
subscriber = rospy.Subscriber('gazebo/model_states', ModelStates, get_pose)
publisher = rospy.Publisher('pose_10_hz', Pose, queue_size=1)
while current_pose == None:
pass
rate = rospy.Rate(10)
while not rospy.is_shutdown():
publisher.publish(current_pose)
rate.sleep()
|
# ... existing code ...
import rospy
from gazebo_msgs.msg import ModelStates
from geometry_msgs.msg import Pose
current_pose = None
def get_pose(message):
global current_pose
current_pose = message.pose[0]
# ... modified code ...
if __name__ == '__main__':
rospy.init_node('pose')
subscriber = rospy.Subscriber('gazebo/model_states', ModelStates, get_pose)
publisher = rospy.Publisher('pose_10_hz', Pose, queue_size=1)
while current_pose == None:
pass
...
while not rospy.is_shutdown():
publisher.publish(current_pose)
rate.sleep()
# ... rest of the code ...
|
9d14c70b68eb1b00b8b6826ee6fc2e58fb4a0ab6
|
settings_test.py
|
settings_test.py
|
EMAIL_FROM_ADDRESS = '[email protected]'
|
EMAIL_FROM_ADDRESS = '[email protected]'
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
|
Use only md5 to hash passwords when running tests
|
Use only md5 to hash passwords when running tests
|
Python
|
bsd-3-clause
|
peterbe/airmozilla,ehsan/airmozilla,lcamacho/airmozilla,anu7495/airmozilla,anu7495/airmozilla,anu7495/airmozilla,blossomica/airmozilla,lcamacho/airmozilla,EricSekyere/airmozilla,Nolski/airmozilla,tannishk/airmozilla,ehsan/airmozilla,blossomica/airmozilla,anjalymehla/airmozilla,ehsan/airmozilla,zofuthan/airmozilla,chirilo/airmozilla,bugzPDX/airmozilla,EricSekyere/airmozilla,mozilla/airmozilla,tannishk/airmozilla,chirilo/airmozilla,chirilo/airmozilla,mythmon/airmozilla,kenrick95/airmozilla,tannishk/airmozilla,a-buck/airmozilla,mythmon/airmozilla,Nolski/airmozilla,ehsan/airmozilla,mozilla/airmozilla,kenrick95/airmozilla,anu7495/airmozilla,kenrick95/airmozilla,bugzPDX/airmozilla,anjalymehla/airmozilla,zofuthan/airmozilla,ehsan/airmozilla,chirilo/airmozilla,mythmon/airmozilla,a-buck/airmozilla,tannishk/airmozilla,lcamacho/airmozilla,mozilla/airmozilla,peterbe/airmozilla,mozilla/airmozilla,mythmon/airmozilla,anjalymehla/airmozilla,anu7495/airmozilla,a-buck/airmozilla,anjalymehla/airmozilla,mythmon/airmozilla,lcamacho/airmozilla,lcamacho/airmozilla,bugzPDX/airmozilla,blossomica/airmozilla,Nolski/airmozilla,EricSekyere/airmozilla,bugzPDX/airmozilla,EricSekyere/airmozilla,zofuthan/airmozilla,chirilo/airmozilla,Nolski/airmozilla,kenrick95/airmozilla,a-buck/airmozilla,blossomica/airmozilla,anjalymehla/airmozilla,zofuthan/airmozilla,peterbe/airmozilla,kenrick95/airmozilla,Nolski/airmozilla,zofuthan/airmozilla,tannishk/airmozilla,EricSekyere/airmozilla
|
EMAIL_FROM_ADDRESS = '[email protected]'
+ PASSWORD_HASHERS = (
+ 'django.contrib.auth.hashers.MD5PasswordHasher',
+ )
+
|
Use only md5 to hash passwords when running tests
|
## Code Before:
EMAIL_FROM_ADDRESS = '[email protected]'
## Instruction:
Use only md5 to hash passwords when running tests
## Code After:
EMAIL_FROM_ADDRESS = '[email protected]'
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
|
...
EMAIL_FROM_ADDRESS = '[email protected]'
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
...
|
d5d33f9fb77fd0d9bb4410971e0acd54b8cbf084
|
latest_tweets/management/commands/latest_tweets_update.py
|
latest_tweets/management/commands/latest_tweets_update.py
|
from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import transaction
from twitter import OAuth, Twitter
from ..models import Tweet
from ..utils import update_tweets
@transaction.atomic
def update_user(user):
t = Twitter(auth=OAuth(
settings.TWITTER_OAUTH_TOKEN,
settings.TWITTER_OAUTH_SECRET,
settings.TWITTER_CONSUMER_KEY,
settings.TWITTER_CONSUMER_SECRET
))
messages = t.statuses.user_timeline(screen_name=user, include_rts=True)
tweet_list = update_tweets(messages=messages)
# To ensure we delete any deleted tweets
oldest_date = None
tweet_id_list = []
for i in tweet_list:
# Help prune out deleted tweets
if not oldest_date or i.created < oldest_date:
oldest_date = i.created
tweet_id_list.append(i.id)
# Remove any deleted tweets in our date range
Tweet.objects.filter(user=user, created__gt=oldest_date).exclude(id__in=tweet_id_list).delete()
class Command(BaseCommand):
args = 'user [user ...]'
def handle(self, *args, **options):
for i in args:
update_user(i)
|
from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import transaction
from twitter import OAuth, Twitter
from latest_tweets.models import Tweet
from latest_tweets.utils import update_tweets
@transaction.atomic
def update_user(user):
t = Twitter(auth=OAuth(
settings.TWITTER_OAUTH_TOKEN,
settings.TWITTER_OAUTH_SECRET,
settings.TWITTER_CONSUMER_KEY,
settings.TWITTER_CONSUMER_SECRET
))
messages = t.statuses.user_timeline(screen_name=user, include_rts=True)
tweet_list = update_tweets(messages=messages)
# To ensure we delete any deleted tweets
oldest_date = None
tweet_id_list = []
for i in tweet_list:
# Help prune out deleted tweets
if not oldest_date or i.created < oldest_date:
oldest_date = i.created
tweet_id_list.append(i.id)
# Remove any deleted tweets in our date range
Tweet.objects.filter(user=user, created__gt=oldest_date).exclude(id__in=tweet_id_list).delete()
class Command(BaseCommand):
args = 'user [user ...]'
def handle(self, *args, **options):
for i in args:
update_user(i)
|
Fix imports for management command
|
Fix imports for management command
|
Python
|
bsd-3-clause
|
blancltd/django-latest-tweets
|
from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import transaction
from twitter import OAuth, Twitter
- from ..models import Tweet
+ from latest_tweets.models import Tweet
- from ..utils import update_tweets
+ from latest_tweets.utils import update_tweets
@transaction.atomic
def update_user(user):
t = Twitter(auth=OAuth(
settings.TWITTER_OAUTH_TOKEN,
settings.TWITTER_OAUTH_SECRET,
settings.TWITTER_CONSUMER_KEY,
settings.TWITTER_CONSUMER_SECRET
))
messages = t.statuses.user_timeline(screen_name=user, include_rts=True)
tweet_list = update_tweets(messages=messages)
# To ensure we delete any deleted tweets
oldest_date = None
tweet_id_list = []
for i in tweet_list:
# Help prune out deleted tweets
if not oldest_date or i.created < oldest_date:
oldest_date = i.created
tweet_id_list.append(i.id)
# Remove any deleted tweets in our date range
Tweet.objects.filter(user=user, created__gt=oldest_date).exclude(id__in=tweet_id_list).delete()
class Command(BaseCommand):
args = 'user [user ...]'
def handle(self, *args, **options):
for i in args:
update_user(i)
|
Fix imports for management command
|
## Code Before:
from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import transaction
from twitter import OAuth, Twitter
from ..models import Tweet
from ..utils import update_tweets
@transaction.atomic
def update_user(user):
t = Twitter(auth=OAuth(
settings.TWITTER_OAUTH_TOKEN,
settings.TWITTER_OAUTH_SECRET,
settings.TWITTER_CONSUMER_KEY,
settings.TWITTER_CONSUMER_SECRET
))
messages = t.statuses.user_timeline(screen_name=user, include_rts=True)
tweet_list = update_tweets(messages=messages)
# To ensure we delete any deleted tweets
oldest_date = None
tweet_id_list = []
for i in tweet_list:
# Help prune out deleted tweets
if not oldest_date or i.created < oldest_date:
oldest_date = i.created
tweet_id_list.append(i.id)
# Remove any deleted tweets in our date range
Tweet.objects.filter(user=user, created__gt=oldest_date).exclude(id__in=tweet_id_list).delete()
class Command(BaseCommand):
args = 'user [user ...]'
def handle(self, *args, **options):
for i in args:
update_user(i)
## Instruction:
Fix imports for management command
## Code After:
from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import transaction
from twitter import OAuth, Twitter
from latest_tweets.models import Tweet
from latest_tweets.utils import update_tweets
@transaction.atomic
def update_user(user):
t = Twitter(auth=OAuth(
settings.TWITTER_OAUTH_TOKEN,
settings.TWITTER_OAUTH_SECRET,
settings.TWITTER_CONSUMER_KEY,
settings.TWITTER_CONSUMER_SECRET
))
messages = t.statuses.user_timeline(screen_name=user, include_rts=True)
tweet_list = update_tweets(messages=messages)
# To ensure we delete any deleted tweets
oldest_date = None
tweet_id_list = []
for i in tweet_list:
# Help prune out deleted tweets
if not oldest_date or i.created < oldest_date:
oldest_date = i.created
tweet_id_list.append(i.id)
# Remove any deleted tweets in our date range
Tweet.objects.filter(user=user, created__gt=oldest_date).exclude(id__in=tweet_id_list).delete()
class Command(BaseCommand):
args = 'user [user ...]'
def handle(self, *args, **options):
for i in args:
update_user(i)
|
// ... existing code ...
from latest_tweets.models import Tweet
from latest_tweets.utils import update_tweets
// ... rest of the code ...
|
26f984a7732491e87e4eb756caf0056a7ac71484
|
contract_invoice_merge_by_partner/models/account_analytic_analysis.py
|
contract_invoice_merge_by_partner/models/account_analytic_analysis.py
|
from openerp import api, models
class PurchaseOrderLine(models.Model):
_inherit = 'account.analytic.account'
@api.multi
def _recurring_create_invoice(self, automatic=False):
invoice_obj = self.env['account.invoice']
invoices = invoice_obj.browse(
super(PurchaseOrderLine, self)._recurring_create_invoice(automatic))
res = []
unlink_list = []
for partner in invoices.mapped('partner_id'):
inv_to_merge = invoices.filtered(
lambda x: x.partner_id.id == partner)
if partner.contract_invoice_merge:
invoices_merged = inv_to_merge.do_merge()
res.extend(invoices_merged)
unlink_list.extend(inv_to_merge)
else:
res.extend(inv_to_merge)
if unlink_list:
invoice_obj.unlink([x.id for x in unlink_list])
return res
|
from openerp import api, models
class PurchaseOrderLine(models.Model):
_inherit = 'account.analytic.account'
@api.multi
def _recurring_create_invoice(self, automatic=False):
invoice_obj = self.env['account.invoice']
invoices = invoice_obj.browse(
super(PurchaseOrderLine, self)._recurring_create_invoice(
automatic))
res = []
unlink_list = []
for partner in invoices.mapped('partner_id'):
inv_to_merge = invoices.filtered(
lambda x: x.partner_id.id == partner)
if partner.contract_invoice_merge and len(inv_to_merge) > 1:
invoices_merged = inv_to_merge.do_merge()
res.extend(invoices_merged)
unlink_list.extend(inv_to_merge)
else:
res.extend(inv_to_merge)
if unlink_list:
invoice_obj.browse(unlink_list).unlink()
return res
|
Fix unlink, >1 filter and lines too long
|
Fix unlink, >1 filter and lines too long
|
Python
|
agpl-3.0
|
bullet92/contract,open-synergy/contract
|
from openerp import api, models
class PurchaseOrderLine(models.Model):
_inherit = 'account.analytic.account'
@api.multi
def _recurring_create_invoice(self, automatic=False):
invoice_obj = self.env['account.invoice']
invoices = invoice_obj.browse(
- super(PurchaseOrderLine, self)._recurring_create_invoice(automatic))
+ super(PurchaseOrderLine, self)._recurring_create_invoice(
+ automatic))
res = []
unlink_list = []
for partner in invoices.mapped('partner_id'):
inv_to_merge = invoices.filtered(
lambda x: x.partner_id.id == partner)
- if partner.contract_invoice_merge:
+ if partner.contract_invoice_merge and len(inv_to_merge) > 1:
invoices_merged = inv_to_merge.do_merge()
res.extend(invoices_merged)
unlink_list.extend(inv_to_merge)
else:
res.extend(inv_to_merge)
if unlink_list:
- invoice_obj.unlink([x.id for x in unlink_list])
+ invoice_obj.browse(unlink_list).unlink()
return res
|
Fix unlink, >1 filter and lines too long
|
## Code Before:
from openerp import api, models
class PurchaseOrderLine(models.Model):
_inherit = 'account.analytic.account'
@api.multi
def _recurring_create_invoice(self, automatic=False):
invoice_obj = self.env['account.invoice']
invoices = invoice_obj.browse(
super(PurchaseOrderLine, self)._recurring_create_invoice(automatic))
res = []
unlink_list = []
for partner in invoices.mapped('partner_id'):
inv_to_merge = invoices.filtered(
lambda x: x.partner_id.id == partner)
if partner.contract_invoice_merge:
invoices_merged = inv_to_merge.do_merge()
res.extend(invoices_merged)
unlink_list.extend(inv_to_merge)
else:
res.extend(inv_to_merge)
if unlink_list:
invoice_obj.unlink([x.id for x in unlink_list])
return res
## Instruction:
Fix unlink, >1 filter and lines too long
## Code After:
from openerp import api, models
class PurchaseOrderLine(models.Model):
_inherit = 'account.analytic.account'
@api.multi
def _recurring_create_invoice(self, automatic=False):
invoice_obj = self.env['account.invoice']
invoices = invoice_obj.browse(
super(PurchaseOrderLine, self)._recurring_create_invoice(
automatic))
res = []
unlink_list = []
for partner in invoices.mapped('partner_id'):
inv_to_merge = invoices.filtered(
lambda x: x.partner_id.id == partner)
if partner.contract_invoice_merge and len(inv_to_merge) > 1:
invoices_merged = inv_to_merge.do_merge()
res.extend(invoices_merged)
unlink_list.extend(inv_to_merge)
else:
res.extend(inv_to_merge)
if unlink_list:
invoice_obj.browse(unlink_list).unlink()
return res
|
# ... existing code ...
invoices = invoice_obj.browse(
super(PurchaseOrderLine, self)._recurring_create_invoice(
automatic))
res = []
# ... modified code ...
lambda x: x.partner_id.id == partner)
if partner.contract_invoice_merge and len(inv_to_merge) > 1:
invoices_merged = inv_to_merge.do_merge()
...
if unlink_list:
invoice_obj.browse(unlink_list).unlink()
return res
# ... rest of the code ...
|
da9c0743657ecc890c2a8503ea4bbb681ae00178
|
tests/chainer_tests/functions_tests/math_tests/test_arctanh.py
|
tests/chainer_tests/functions_tests/math_tests/test_arctanh.py
|
import unittest
from chainer import testing
import chainer.functions as F
import numpy
def make_data(shape, dtype):
# Input values close to -1 or 1 would make tests unstable
x = numpy.random.uniform(-0.9, 0.9, shape).astype(dtype, copy=False)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False)
ggx = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False)
return x, gy, ggx
@testing.unary_math_function_unittest(F.arctanh, make_data=make_data)
class TestArctanh(unittest.TestCase):
pass
|
import unittest
from chainer import testing
import chainer.functions as F
import numpy
def make_data(shape, dtype):
# Input values close to -1 or 1 would make tests unstable
x = numpy.random.uniform(-0.9, 0.9, shape).astype(dtype, copy=False)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False)
ggx = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False)
return x, gy, ggx
@testing.unary_math_function_unittest(F.arctanh, make_data=make_data)
class TestArctanh(unittest.TestCase):
pass
testing.run_module(__name__, __file__)
|
Call testing.run_module at the end of the test
|
Call testing.run_module at the end of the test
|
Python
|
mit
|
okuta/chainer,keisuke-umezawa/chainer,wkentaro/chainer,wkentaro/chainer,okuta/chainer,chainer/chainer,niboshi/chainer,okuta/chainer,pfnet/chainer,chainer/chainer,tkerola/chainer,chainer/chainer,niboshi/chainer,keisuke-umezawa/chainer,okuta/chainer,wkentaro/chainer,hvy/chainer,wkentaro/chainer,niboshi/chainer,niboshi/chainer,keisuke-umezawa/chainer,chainer/chainer,hvy/chainer,keisuke-umezawa/chainer,hvy/chainer,hvy/chainer
|
import unittest
from chainer import testing
import chainer.functions as F
import numpy
def make_data(shape, dtype):
# Input values close to -1 or 1 would make tests unstable
x = numpy.random.uniform(-0.9, 0.9, shape).astype(dtype, copy=False)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False)
ggx = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False)
return x, gy, ggx
@testing.unary_math_function_unittest(F.arctanh, make_data=make_data)
class TestArctanh(unittest.TestCase):
pass
+
+ testing.run_module(__name__, __file__)
+
|
Call testing.run_module at the end of the test
|
## Code Before:
import unittest
from chainer import testing
import chainer.functions as F
import numpy
def make_data(shape, dtype):
# Input values close to -1 or 1 would make tests unstable
x = numpy.random.uniform(-0.9, 0.9, shape).astype(dtype, copy=False)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False)
ggx = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False)
return x, gy, ggx
@testing.unary_math_function_unittest(F.arctanh, make_data=make_data)
class TestArctanh(unittest.TestCase):
pass
## Instruction:
Call testing.run_module at the end of the test
## Code After:
import unittest
from chainer import testing
import chainer.functions as F
import numpy
def make_data(shape, dtype):
# Input values close to -1 or 1 would make tests unstable
x = numpy.random.uniform(-0.9, 0.9, shape).astype(dtype, copy=False)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False)
ggx = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False)
return x, gy, ggx
@testing.unary_math_function_unittest(F.arctanh, make_data=make_data)
class TestArctanh(unittest.TestCase):
pass
testing.run_module(__name__, __file__)
|
...
pass
testing.run_module(__name__, __file__)
...
|
04f4c11ff52069475a3818de74b4cd89695cfa2c
|
scrapi/harvesters/tdar/__init__.py
|
scrapi/harvesters/tdar/__init__.py
|
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
tdar = OAIHarvester(
name='tdar',
base_url='http://core.tdar.org/oai-pmh/oai',
property_list=['type', 'date', 'setSpec', 'type', 'publisher', 'coverage']
)
harvest = tdar.harvest
normalize = tdar.normalize
|
from __future__ import unicode_literals
from scrapi import util
from scrapi.base import OAIHarvester
class tdarHarvester(OAIHarvester):
def get_ids(self, result, doc):
"""
Gather the DOI and url from identifiers, if possible.
Tries to save the DOI alone without a url extension.
Tries to save a link to the original content at the source,
instead of direct to a PDF, which is usually linked with viewcontent.cgi?
in the url field
"""
serviceID = doc.get('docID')
url = 'http://core.tdar.org/document/' + serviceID.replace('oai:tdar.org:Resource:', '')
print(url)
return {
'serviceID': serviceID,
'url': util.copy_to_unicode(url),
'doi': ''
}
tdar = tdarHarvester(
name='tdar',
base_url='http://core.tdar.org/oai-pmh/oai',
property_list=['type', 'date', 'setSpec', 'type', 'publisher', 'coverage']
)
harvest = tdar.harvest
normalize = tdar.normalize
|
Update tdar harvester with custom url gatheriing
|
Update tdar harvester with custom url gatheriing
|
Python
|
apache-2.0
|
icereval/scrapi,ostwald/scrapi,mehanig/scrapi,CenterForOpenScience/scrapi,erinspace/scrapi,erinspace/scrapi,fabianvf/scrapi,CenterForOpenScience/scrapi,alexgarciac/scrapi,mehanig/scrapi,felliott/scrapi,fabianvf/scrapi,felliott/scrapi,jeffreyliu3230/scrapi
|
from __future__ import unicode_literals
+ from scrapi import util
from scrapi.base import OAIHarvester
+ class tdarHarvester(OAIHarvester):
+
+ def get_ids(self, result, doc):
+ """
+ Gather the DOI and url from identifiers, if possible.
+ Tries to save the DOI alone without a url extension.
+ Tries to save a link to the original content at the source,
+ instead of direct to a PDF, which is usually linked with viewcontent.cgi?
+ in the url field
+ """
+ serviceID = doc.get('docID')
+
+ url = 'http://core.tdar.org/document/' + serviceID.replace('oai:tdar.org:Resource:', '')
+ print(url)
+
+ return {
+ 'serviceID': serviceID,
+ 'url': util.copy_to_unicode(url),
+ 'doi': ''
+ }
+
+
- tdar = OAIHarvester(
+ tdar = tdarHarvester(
name='tdar',
base_url='http://core.tdar.org/oai-pmh/oai',
property_list=['type', 'date', 'setSpec', 'type', 'publisher', 'coverage']
)
harvest = tdar.harvest
normalize = tdar.normalize
|
Update tdar harvester with custom url gatheriing
|
## Code Before:
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
tdar = OAIHarvester(
name='tdar',
base_url='http://core.tdar.org/oai-pmh/oai',
property_list=['type', 'date', 'setSpec', 'type', 'publisher', 'coverage']
)
harvest = tdar.harvest
normalize = tdar.normalize
## Instruction:
Update tdar harvester with custom url gatheriing
## Code After:
from __future__ import unicode_literals
from scrapi import util
from scrapi.base import OAIHarvester
class tdarHarvester(OAIHarvester):
def get_ids(self, result, doc):
"""
Gather the DOI and url from identifiers, if possible.
Tries to save the DOI alone without a url extension.
Tries to save a link to the original content at the source,
instead of direct to a PDF, which is usually linked with viewcontent.cgi?
in the url field
"""
serviceID = doc.get('docID')
url = 'http://core.tdar.org/document/' + serviceID.replace('oai:tdar.org:Resource:', '')
print(url)
return {
'serviceID': serviceID,
'url': util.copy_to_unicode(url),
'doi': ''
}
tdar = tdarHarvester(
name='tdar',
base_url='http://core.tdar.org/oai-pmh/oai',
property_list=['type', 'date', 'setSpec', 'type', 'publisher', 'coverage']
)
harvest = tdar.harvest
normalize = tdar.normalize
|
# ... existing code ...
from scrapi import util
from scrapi.base import OAIHarvester
# ... modified code ...
class tdarHarvester(OAIHarvester):
def get_ids(self, result, doc):
"""
Gather the DOI and url from identifiers, if possible.
Tries to save the DOI alone without a url extension.
Tries to save a link to the original content at the source,
instead of direct to a PDF, which is usually linked with viewcontent.cgi?
in the url field
"""
serviceID = doc.get('docID')
url = 'http://core.tdar.org/document/' + serviceID.replace('oai:tdar.org:Resource:', '')
print(url)
return {
'serviceID': serviceID,
'url': util.copy_to_unicode(url),
'doi': ''
}
tdar = tdarHarvester(
name='tdar',
# ... rest of the code ...
|
daceec30fc422ea035163e80c826423a806d0b85
|
django/wwwhisper_auth/backend.py
|
django/wwwhisper_auth/backend.py
|
"""Authentication backend used by wwwhisper_auth."""
from django.contrib.auth.backends import ModelBackend
from django_browserid.base import verify
from wwwhisper_auth import models
class AssertionVerificationException(Exception):
"""Raised when BrowserId assertion was not verified successfully."""
pass
class BrowserIDBackend(ModelBackend):
""""Backend that verifies BrowserID assertion.
Similar backend is defined in django_browserid application. It is not
used here, because it does not allow to distinguish between an
assertion verification error and an unknown user.
Attributes:
users_collection: Allows to find a user with a given email.
"""
users_collection = models.UsersCollection()
def authenticate(self, assertion):
"""Verifies BrowserID assertion
Returns:
Object that represents a user with an email verified by
the assertion. None if user with such email does not exist.
Raises:
AssertionVerificationException: verification failed.
"""
result = verify(assertion=assertion, audience=models.SITE_URL)
if result is None:
raise AssertionVerificationException(
'BrowserID assertion verification failed.')
return self.users_collection.find_item_by_email(result['email'])
|
"""Authentication backend used by wwwhisper_auth."""
from django.contrib.auth.backends import ModelBackend
from django_browserid.base import verify
from wwwhisper_auth import models
class AssertionVerificationException(Exception):
"""Raised when BrowserId assertion was not verified successfully."""
pass
class BrowserIDBackend(ModelBackend):
""""Backend that verifies BrowserID assertion.
Similar backend is defined in django_browserid application. It is not
used here, because it does not allow to distinguish between an
assertion verification error and an unknown user.
Attributes:
users_collection: Allows to find a user with a given email.
"""
users_collection = models.UsersCollection()
def authenticate(self, assertion):
"""Verifies BrowserID assertion
Returns:
Object that represents a user with an email verified by
the assertion. None if user with such email does not exist.
Raises:
AssertionVerificationException: verification failed.
"""
result = verify(assertion=assertion, audience=models.SITE_URL)
if not result:
raise AssertionVerificationException(
'BrowserID assertion verification failed.')
return self.users_collection.find_item_by_email(result['email'])
|
Correct check if assertion verification failed.
|
Correct check if assertion verification failed.
|
Python
|
mit
|
wrr/wwwhisper,wrr/wwwhisper,wrr/wwwhisper,wrr/wwwhisper
|
"""Authentication backend used by wwwhisper_auth."""
from django.contrib.auth.backends import ModelBackend
from django_browserid.base import verify
from wwwhisper_auth import models
class AssertionVerificationException(Exception):
"""Raised when BrowserId assertion was not verified successfully."""
pass
class BrowserIDBackend(ModelBackend):
""""Backend that verifies BrowserID assertion.
Similar backend is defined in django_browserid application. It is not
used here, because it does not allow to distinguish between an
assertion verification error and an unknown user.
Attributes:
users_collection: Allows to find a user with a given email.
"""
users_collection = models.UsersCollection()
def authenticate(self, assertion):
"""Verifies BrowserID assertion
Returns:
Object that represents a user with an email verified by
the assertion. None if user with such email does not exist.
Raises:
AssertionVerificationException: verification failed.
"""
result = verify(assertion=assertion, audience=models.SITE_URL)
- if result is None:
+ if not result:
raise AssertionVerificationException(
'BrowserID assertion verification failed.')
return self.users_collection.find_item_by_email(result['email'])
|
Correct check if assertion verification failed.
|
## Code Before:
"""Authentication backend used by wwwhisper_auth."""
from django.contrib.auth.backends import ModelBackend
from django_browserid.base import verify
from wwwhisper_auth import models
class AssertionVerificationException(Exception):
"""Raised when BrowserId assertion was not verified successfully."""
pass
class BrowserIDBackend(ModelBackend):
""""Backend that verifies BrowserID assertion.
Similar backend is defined in django_browserid application. It is not
used here, because it does not allow to distinguish between an
assertion verification error and an unknown user.
Attributes:
users_collection: Allows to find a user with a given email.
"""
users_collection = models.UsersCollection()
def authenticate(self, assertion):
"""Verifies BrowserID assertion
Returns:
Object that represents a user with an email verified by
the assertion. None if user with such email does not exist.
Raises:
AssertionVerificationException: verification failed.
"""
result = verify(assertion=assertion, audience=models.SITE_URL)
if result is None:
raise AssertionVerificationException(
'BrowserID assertion verification failed.')
return self.users_collection.find_item_by_email(result['email'])
## Instruction:
Correct check if assertion verification failed.
## Code After:
"""Authentication backend used by wwwhisper_auth."""
from django.contrib.auth.backends import ModelBackend
from django_browserid.base import verify
from wwwhisper_auth import models
class AssertionVerificationException(Exception):
"""Raised when BrowserId assertion was not verified successfully."""
pass
class BrowserIDBackend(ModelBackend):
""""Backend that verifies BrowserID assertion.
Similar backend is defined in django_browserid application. It is not
used here, because it does not allow to distinguish between an
assertion verification error and an unknown user.
Attributes:
users_collection: Allows to find a user with a given email.
"""
users_collection = models.UsersCollection()
def authenticate(self, assertion):
"""Verifies BrowserID assertion
Returns:
Object that represents a user with an email verified by
the assertion. None if user with such email does not exist.
Raises:
AssertionVerificationException: verification failed.
"""
result = verify(assertion=assertion, audience=models.SITE_URL)
if not result:
raise AssertionVerificationException(
'BrowserID assertion verification failed.')
return self.users_collection.find_item_by_email(result['email'])
|
# ... existing code ...
result = verify(assertion=assertion, audience=models.SITE_URL)
if not result:
raise AssertionVerificationException(
# ... rest of the code ...
|
16b663441c0d994b02e68b8c785ec6c7a2805f03
|
onepercentclub/settings/payments.py
|
onepercentclub/settings/payments.py
|
from bluebottle.payments_docdata.settings import DOCDATA_SETTINGS, DOCDATA_PAYMENT_METHODS
PAYMENT_METHODS = DOCDATA_PAYMENT_METHODS
VAT_RATE = 0.21
|
from bluebottle.payments_docdata.settings import DOCDATA_SETTINGS
PAYMENT_METHODS = (
{
'provider': 'docdata',
'id': 'docdata-ideal',
'profile': 'ideal',
'name': 'iDEAL',
'restricted_countries': ('NL', 'Netherlands'),
'supports_recurring': False,
},
{
'provider': 'docdata',
'id': 'docdata-directdebit',
'profile': 'directdebit',
'name': 'Direct Debit',
'supports_recurring': True,
},
{
'provider': 'docdata',
'id': 'docdata-creditcard',
'profile': 'creditcard',
'name': 'CreditCard',
'supports_recurring': False,
},
# {
# 'provider': 'docdata',
# 'id': 'docdata-paypal',
# 'profile': 'paypal',
# 'name': 'Paypal',
# 'supports_recurring': False,
# },
)
VAT_RATE = 0.21
|
Disable Paypal, up Direct debit
|
Disable Paypal, up Direct debit
|
Python
|
bsd-3-clause
|
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
|
- from bluebottle.payments_docdata.settings import DOCDATA_SETTINGS, DOCDATA_PAYMENT_METHODS
+ from bluebottle.payments_docdata.settings import DOCDATA_SETTINGS
- PAYMENT_METHODS = DOCDATA_PAYMENT_METHODS
+ PAYMENT_METHODS = (
+ {
+ 'provider': 'docdata',
+ 'id': 'docdata-ideal',
+ 'profile': 'ideal',
+ 'name': 'iDEAL',
+ 'restricted_countries': ('NL', 'Netherlands'),
+ 'supports_recurring': False,
+ },
+ {
+ 'provider': 'docdata',
+ 'id': 'docdata-directdebit',
+ 'profile': 'directdebit',
+ 'name': 'Direct Debit',
+ 'supports_recurring': True,
+ },
+ {
+ 'provider': 'docdata',
+ 'id': 'docdata-creditcard',
+ 'profile': 'creditcard',
+ 'name': 'CreditCard',
+ 'supports_recurring': False,
+ },
+ # {
+ # 'provider': 'docdata',
+ # 'id': 'docdata-paypal',
+ # 'profile': 'paypal',
+ # 'name': 'Paypal',
+ # 'supports_recurring': False,
+ # },
+ )
VAT_RATE = 0.21
|
Disable Paypal, up Direct debit
|
## Code Before:
from bluebottle.payments_docdata.settings import DOCDATA_SETTINGS, DOCDATA_PAYMENT_METHODS
PAYMENT_METHODS = DOCDATA_PAYMENT_METHODS
VAT_RATE = 0.21
## Instruction:
Disable Paypal, up Direct debit
## Code After:
from bluebottle.payments_docdata.settings import DOCDATA_SETTINGS
PAYMENT_METHODS = (
{
'provider': 'docdata',
'id': 'docdata-ideal',
'profile': 'ideal',
'name': 'iDEAL',
'restricted_countries': ('NL', 'Netherlands'),
'supports_recurring': False,
},
{
'provider': 'docdata',
'id': 'docdata-directdebit',
'profile': 'directdebit',
'name': 'Direct Debit',
'supports_recurring': True,
},
{
'provider': 'docdata',
'id': 'docdata-creditcard',
'profile': 'creditcard',
'name': 'CreditCard',
'supports_recurring': False,
},
# {
# 'provider': 'docdata',
# 'id': 'docdata-paypal',
# 'profile': 'paypal',
# 'name': 'Paypal',
# 'supports_recurring': False,
# },
)
VAT_RATE = 0.21
|
# ... existing code ...
from bluebottle.payments_docdata.settings import DOCDATA_SETTINGS
PAYMENT_METHODS = (
{
'provider': 'docdata',
'id': 'docdata-ideal',
'profile': 'ideal',
'name': 'iDEAL',
'restricted_countries': ('NL', 'Netherlands'),
'supports_recurring': False,
},
{
'provider': 'docdata',
'id': 'docdata-directdebit',
'profile': 'directdebit',
'name': 'Direct Debit',
'supports_recurring': True,
},
{
'provider': 'docdata',
'id': 'docdata-creditcard',
'profile': 'creditcard',
'name': 'CreditCard',
'supports_recurring': False,
},
# {
# 'provider': 'docdata',
# 'id': 'docdata-paypal',
# 'profile': 'paypal',
# 'name': 'Paypal',
# 'supports_recurring': False,
# },
)
VAT_RATE = 0.21
# ... rest of the code ...
|
18ec52a1c34e263e4d909fc1ee19500f9adac26b
|
examples/django_example/example/app/models.py
|
examples/django_example/example/app/models.py
|
from django.db import models
# Create your models here.
|
from django.contrib.auth.models import AbstractUser, UserManager
class CustomUser(AbstractUser):
objects = UserManager()
|
Define a custom user model
|
Define a custom user model
|
Python
|
bsd-3-clause
|
S01780/python-social-auth,tobias47n9e/social-core,falcon1kr/python-social-auth,ByteInternet/python-social-auth,muhammad-ammar/python-social-auth,contracode/python-social-auth,S01780/python-social-auth,clef/python-social-auth,lawrence34/python-social-auth,python-social-auth/social-storage-sqlalchemy,fearlessspider/python-social-auth,MSOpenTech/python-social-auth,Andygmb/python-social-auth,mrwags/python-social-auth,ariestiyansyah/python-social-auth,clef/python-social-auth,bjorand/python-social-auth,cjltsod/python-social-auth,barseghyanartur/python-social-auth,nirmalvp/python-social-auth,Andygmb/python-social-auth,garrett-schlesinger/python-social-auth,henocdz/python-social-auth,VishvajitP/python-social-auth,duoduo369/python-social-auth,merutak/python-social-auth,drxos/python-social-auth,firstjob/python-social-auth,webjunkie/python-social-auth,DhiaEddineSaidi/python-social-auth,python-social-auth/social-app-django,barseghyanartur/python-social-auth,rsteca/python-social-auth,jneves/python-social-auth,mrwags/python-social-auth,mrwags/python-social-auth,frankier/python-social-auth,JJediny/python-social-auth,joelstanner/python-social-auth,lamby/python-social-auth,bjorand/python-social-auth,python-social-auth/social-core,chandolia/python-social-auth,jeyraof/python-social-auth,cmichal/python-social-auth,falcon1kr/python-social-auth,robbiet480/python-social-auth,contracode/python-social-auth,lawrence34/python-social-auth,yprez/python-social-auth,bjorand/python-social-auth,garrett-schlesinger/python-social-auth,clef/python-social-auth,python-social-auth/social-app-django,jameslittle/python-social-auth,tkajtoch/python-social-auth,python-social-auth/social-app-django,JerzySpendel/python-social-auth,muhammad-ammar/python-social-auth,msampathkumar/python-social-auth,webjunkie/python-social-auth,mark-adams/python-social-auth,iruga090/python-social-auth,contracode/python-social-auth,JJediny/python-social-auth,lamby/python-social-auth,cmichal/python-social-auth,alrusdi/python-social-auth,python-social-auth/social-docs,yprez/python-social-auth,san-mate/python-social-auth,jeyraof/python-social-auth,ononeor12/python-social-auth,jneves/python-social-auth,lawrence34/python-social-auth,DhiaEddineSaidi/python-social-auth,python-social-auth/social-app-cherrypy,michael-borisov/python-social-auth,SeanHayes/python-social-auth,lneoe/python-social-auth,joelstanner/python-social-auth,duoduo369/python-social-auth,lneoe/python-social-auth,fearlessspider/python-social-auth,chandolia/python-social-auth,hsr-ba-fs15-dat/python-social-auth,daniula/python-social-auth,VishvajitP/python-social-auth,daniula/python-social-auth,alrusdi/python-social-auth,mark-adams/python-social-auth,barseghyanartur/python-social-auth,rsalmaso/python-social-auth,mathspace/python-social-auth,JJediny/python-social-auth,michael-borisov/python-social-auth,san-mate/python-social-auth,lneoe/python-social-auth,jameslittle/python-social-auth,rsteca/python-social-auth,henocdz/python-social-auth,S01780/python-social-auth,tkajtoch/python-social-auth,tutumcloud/python-social-auth,michael-borisov/python-social-auth,JerzySpendel/python-social-auth,degs098/python-social-auth,robbiet480/python-social-auth,rsalmaso/python-social-auth,nirmalvp/python-social-auth,falcon1kr/python-social-auth,python-social-auth/social-core,ariestiyansyah/python-social-auth,ariestiyansyah/python-social-auth,ByteInternet/python-social-auth,hsr-ba-fs15-dat/python-social-auth,nirmalvp/python-social-auth,DhiaEddineSaidi/python-social-auth,joelstanner/python-social-auth,ononeor12/python-social-auth,wildtetris/python-social-auth,henocdz/python-social-auth,mathspace/python-social-auth,MSOpenTech/python-social-auth,wildtetris/python-social-auth,degs098/python-social-auth,noodle-learns-programming/python-social-auth,SeanHayes/python-social-auth,mchdks/python-social-auth,lamby/python-social-auth,merutak/python-social-auth,jneves/python-social-auth,chandolia/python-social-auth,mchdks/python-social-auth,webjunkie/python-social-auth,ByteInternet/python-social-auth,fearlessspider/python-social-auth,firstjob/python-social-auth,noodle-learns-programming/python-social-auth,VishvajitP/python-social-auth,daniula/python-social-auth,mark-adams/python-social-auth,tkajtoch/python-social-auth,san-mate/python-social-auth,jeyraof/python-social-auth,robbiet480/python-social-auth,wildtetris/python-social-auth,jameslittle/python-social-auth,msampathkumar/python-social-auth,alrusdi/python-social-auth,msampathkumar/python-social-auth,yprez/python-social-auth,firstjob/python-social-auth,ononeor12/python-social-auth,tutumcloud/python-social-auth,noodle-learns-programming/python-social-auth,mathspace/python-social-auth,hsr-ba-fs15-dat/python-social-auth,muhammad-ammar/python-social-auth,degs098/python-social-auth,rsteca/python-social-auth,JerzySpendel/python-social-auth,frankier/python-social-auth,mchdks/python-social-auth,Andygmb/python-social-auth,iruga090/python-social-auth,merutak/python-social-auth,MSOpenTech/python-social-auth,cjltsod/python-social-auth,cmichal/python-social-auth,drxos/python-social-auth,drxos/python-social-auth,iruga090/python-social-auth
|
- from django.db import models
+ from django.contrib.auth.models import AbstractUser, UserManager
- # Create your models here.
+ class CustomUser(AbstractUser):
+ objects = UserManager()
+
|
Define a custom user model
|
## Code Before:
from django.db import models
# Create your models here.
## Instruction:
Define a custom user model
## Code After:
from django.contrib.auth.models import AbstractUser, UserManager
class CustomUser(AbstractUser):
objects = UserManager()
|
// ... existing code ...
from django.contrib.auth.models import AbstractUser, UserManager
class CustomUser(AbstractUser):
objects = UserManager()
// ... rest of the code ...
|
067bbbc6c9edbf55606fe6f236c70affd86a1fc0
|
tests/convert/test_unit.py
|
tests/convert/test_unit.py
|
from unittest.mock import patch
from smif.convert.unit import parse_unit
def test_parse_unit_valid():
"""Parse a valid unit
"""
meter = parse_unit('m')
assert str(meter) == 'meter'
@patch('smif.convert.unit.LOGGER.warning')
def test_parse_unit_invalid(warning_logger):
"""Warn if unit not recognised
"""
unit = 'unrecognisable'
parse_unit(unit)
msg = "Unrecognised unit: %s"
warning_logger.assert_called_with(msg, unit)
|
import numpy as np
from unittest.mock import patch
from smif.convert.unit import parse_unit
from smif.convert import UnitConvertor
def test_parse_unit_valid():
"""Parse a valid unit
"""
meter = parse_unit('m')
assert str(meter) == 'meter'
@patch('smif.convert.unit.LOGGER.warning')
def test_parse_unit_invalid(warning_logger):
"""Warn if unit not recognised
"""
unit = 'unrecognisable'
parse_unit(unit)
msg = "Unrecognised unit: %s"
warning_logger.assert_called_with(msg, unit)
def test_convert_unit():
data = np.array([[1, 2], [3, 4]], dtype=float)
convertor = UnitConvertor()
actual = convertor.convert(data, 'liter', 'milliliter')
expected = np.array([[1000, 2000], [3000, 4000]], dtype=float)
np.allclose(actual, expected)
|
Add test for normal unit conversion
|
Add test for normal unit conversion
|
Python
|
mit
|
tomalrussell/smif,tomalrussell/smif,nismod/smif,nismod/smif,tomalrussell/smif,nismod/smif,nismod/smif,willu47/smif,willu47/smif,willu47/smif,willu47/smif,tomalrussell/smif
|
+ import numpy as np
from unittest.mock import patch
from smif.convert.unit import parse_unit
+ from smif.convert import UnitConvertor
def test_parse_unit_valid():
"""Parse a valid unit
"""
meter = parse_unit('m')
assert str(meter) == 'meter'
@patch('smif.convert.unit.LOGGER.warning')
def test_parse_unit_invalid(warning_logger):
"""Warn if unit not recognised
"""
unit = 'unrecognisable'
parse_unit(unit)
msg = "Unrecognised unit: %s"
warning_logger.assert_called_with(msg, unit)
+
+ def test_convert_unit():
+
+ data = np.array([[1, 2], [3, 4]], dtype=float)
+
+ convertor = UnitConvertor()
+ actual = convertor.convert(data, 'liter', 'milliliter')
+
+ expected = np.array([[1000, 2000], [3000, 4000]], dtype=float)
+
+ np.allclose(actual, expected)
+
|
Add test for normal unit conversion
|
## Code Before:
from unittest.mock import patch
from smif.convert.unit import parse_unit
def test_parse_unit_valid():
"""Parse a valid unit
"""
meter = parse_unit('m')
assert str(meter) == 'meter'
@patch('smif.convert.unit.LOGGER.warning')
def test_parse_unit_invalid(warning_logger):
"""Warn if unit not recognised
"""
unit = 'unrecognisable'
parse_unit(unit)
msg = "Unrecognised unit: %s"
warning_logger.assert_called_with(msg, unit)
## Instruction:
Add test for normal unit conversion
## Code After:
import numpy as np
from unittest.mock import patch
from smif.convert.unit import parse_unit
from smif.convert import UnitConvertor
def test_parse_unit_valid():
"""Parse a valid unit
"""
meter = parse_unit('m')
assert str(meter) == 'meter'
@patch('smif.convert.unit.LOGGER.warning')
def test_parse_unit_invalid(warning_logger):
"""Warn if unit not recognised
"""
unit = 'unrecognisable'
parse_unit(unit)
msg = "Unrecognised unit: %s"
warning_logger.assert_called_with(msg, unit)
def test_convert_unit():
data = np.array([[1, 2], [3, 4]], dtype=float)
convertor = UnitConvertor()
actual = convertor.convert(data, 'liter', 'milliliter')
expected = np.array([[1000, 2000], [3000, 4000]], dtype=float)
np.allclose(actual, expected)
|
# ... existing code ...
import numpy as np
from unittest.mock import patch
# ... modified code ...
from smif.convert.unit import parse_unit
from smif.convert import UnitConvertor
...
warning_logger.assert_called_with(msg, unit)
def test_convert_unit():
data = np.array([[1, 2], [3, 4]], dtype=float)
convertor = UnitConvertor()
actual = convertor.convert(data, 'liter', 'milliliter')
expected = np.array([[1000, 2000], [3000, 4000]], dtype=float)
np.allclose(actual, expected)
# ... rest of the code ...
|
0ff797d60c2ddc93579e7c486e8ebb77593014d8
|
apiclient/__init__.py
|
apiclient/__init__.py
|
"""Retain apiclient as an alias for googleapiclient."""
import googleapiclient
from googleapiclient import channel
from googleapiclient import discovery
from googleapiclient import errors
from googleapiclient import http
from googleapiclient import mimeparse
from googleapiclient import model
from googleapiclient import sample_tools
from googleapiclient import schema
__version__ = googleapiclient.__version__
|
"""Retain apiclient as an alias for googleapiclient."""
import googleapiclient
try:
import oauth2client
except ImportError:
raise RuntimeError(
'Previous version of google-api-python-client detected; due to a '
'packaging issue, we cannot perform an in-place upgrade. To repair, '
'remove and reinstall this package, along with oauth2client and '
'uritemplate. One can do this with pip via\n'
' pip install -I google-api-python-client'
)
from googleapiclient import channel
from googleapiclient import discovery
from googleapiclient import errors
from googleapiclient import http
from googleapiclient import mimeparse
from googleapiclient import model
from googleapiclient import sample_tools
from googleapiclient import schema
__version__ = googleapiclient.__version__
|
Add another check for a failed googleapiclient upgrade.
|
Add another check for a failed googleapiclient upgrade.
This adds one more check for a failed 1.2 -> 1.3 upgrade, specifically in the
`apiclient` import (which was the only import available in 1.2). Even combined
with the check in setup.py, this won't catch everything, but it now covers all
the most common cases.
|
Python
|
apache-2.0
|
googleapis/google-api-python-client,googleapis/google-api-python-client
|
"""Retain apiclient as an alias for googleapiclient."""
import googleapiclient
+
+ try:
+ import oauth2client
+ except ImportError:
+ raise RuntimeError(
+ 'Previous version of google-api-python-client detected; due to a '
+ 'packaging issue, we cannot perform an in-place upgrade. To repair, '
+ 'remove and reinstall this package, along with oauth2client and '
+ 'uritemplate. One can do this with pip via\n'
+ ' pip install -I google-api-python-client'
+ )
from googleapiclient import channel
from googleapiclient import discovery
from googleapiclient import errors
from googleapiclient import http
from googleapiclient import mimeparse
from googleapiclient import model
from googleapiclient import sample_tools
from googleapiclient import schema
__version__ = googleapiclient.__version__
|
Add another check for a failed googleapiclient upgrade.
|
## Code Before:
"""Retain apiclient as an alias for googleapiclient."""
import googleapiclient
from googleapiclient import channel
from googleapiclient import discovery
from googleapiclient import errors
from googleapiclient import http
from googleapiclient import mimeparse
from googleapiclient import model
from googleapiclient import sample_tools
from googleapiclient import schema
__version__ = googleapiclient.__version__
## Instruction:
Add another check for a failed googleapiclient upgrade.
## Code After:
"""Retain apiclient as an alias for googleapiclient."""
import googleapiclient
try:
import oauth2client
except ImportError:
raise RuntimeError(
'Previous version of google-api-python-client detected; due to a '
'packaging issue, we cannot perform an in-place upgrade. To repair, '
'remove and reinstall this package, along with oauth2client and '
'uritemplate. One can do this with pip via\n'
' pip install -I google-api-python-client'
)
from googleapiclient import channel
from googleapiclient import discovery
from googleapiclient import errors
from googleapiclient import http
from googleapiclient import mimeparse
from googleapiclient import model
from googleapiclient import sample_tools
from googleapiclient import schema
__version__ = googleapiclient.__version__
|
# ... existing code ...
import googleapiclient
try:
import oauth2client
except ImportError:
raise RuntimeError(
'Previous version of google-api-python-client detected; due to a '
'packaging issue, we cannot perform an in-place upgrade. To repair, '
'remove and reinstall this package, along with oauth2client and '
'uritemplate. One can do this with pip via\n'
' pip install -I google-api-python-client'
)
# ... rest of the code ...
|
46807ee4923a5799ec371cd8094c36f0b672f4b4
|
common/highlights.py
|
common/highlights.py
|
import common.time
SPREADSHEET = "1yrf6d7dPyTiWksFkhISqEc-JR71dxZMkUoYrX4BR40Y"
def format_row(title, description, video, timestamp, nick):
if '_id' in video:
url = "https://www.twitch.tv/loadingreadyrun/manager/%s/highlight" % video['_id']
else:
url = video['url']
return [
("SHOW", title),
("QUOTE or MOMENT", description),
("YOUTUBE VIDEO LINK", url),
("ROUGH TIME THEREIN", "before " + common.time.nice_duration(timestamp, 0)),
("NOTES", "from chat user '%s'" % nick),
]
|
import common.time
SPREADSHEET = "1yrf6d7dPyTiWksFkhISqEc-JR71dxZMkUoYrX4BR40Y"
def format_row(title, description, video, timestamp, nick):
if '_id' in video:
# Allow roughly 15 seconds for chat delay, 10 seconds for chat reaction time,
# 20 seconds for how long the actual event is...
linkts = timestamp - 45
linkts = "%02dh%02dm%02ds" % (linkts//3600, linkts//60 % 60, linkts % 60)
url = "https://www.twitch.tv/loadingreadyrun/manager/%s/highlight?t=%s" % (video['_id'], linkts)
else:
url = video['url']
return [
("SHOW", title),
("QUOTE or MOMENT", description),
("YOUTUBE VIDEO LINK", url),
("ROUGH TIME THEREIN", "before " + common.time.nice_duration(timestamp, 0)),
("NOTES", "from chat user '%s'" % nick),
]
|
Add timestamp to link too
|
Add timestamp to link too
|
Python
|
apache-2.0
|
andreasots/lrrbot,mrphlip/lrrbot,mrphlip/lrrbot,andreasots/lrrbot,mrphlip/lrrbot,andreasots/lrrbot
|
import common.time
SPREADSHEET = "1yrf6d7dPyTiWksFkhISqEc-JR71dxZMkUoYrX4BR40Y"
def format_row(title, description, video, timestamp, nick):
if '_id' in video:
+ # Allow roughly 15 seconds for chat delay, 10 seconds for chat reaction time,
+ # 20 seconds for how long the actual event is...
+ linkts = timestamp - 45
+ linkts = "%02dh%02dm%02ds" % (linkts//3600, linkts//60 % 60, linkts % 60)
- url = "https://www.twitch.tv/loadingreadyrun/manager/%s/highlight" % video['_id']
+ url = "https://www.twitch.tv/loadingreadyrun/manager/%s/highlight?t=%s" % (video['_id'], linkts)
else:
url = video['url']
return [
("SHOW", title),
("QUOTE or MOMENT", description),
("YOUTUBE VIDEO LINK", url),
("ROUGH TIME THEREIN", "before " + common.time.nice_duration(timestamp, 0)),
("NOTES", "from chat user '%s'" % nick),
]
|
Add timestamp to link too
|
## Code Before:
import common.time
SPREADSHEET = "1yrf6d7dPyTiWksFkhISqEc-JR71dxZMkUoYrX4BR40Y"
def format_row(title, description, video, timestamp, nick):
if '_id' in video:
url = "https://www.twitch.tv/loadingreadyrun/manager/%s/highlight" % video['_id']
else:
url = video['url']
return [
("SHOW", title),
("QUOTE or MOMENT", description),
("YOUTUBE VIDEO LINK", url),
("ROUGH TIME THEREIN", "before " + common.time.nice_duration(timestamp, 0)),
("NOTES", "from chat user '%s'" % nick),
]
## Instruction:
Add timestamp to link too
## Code After:
import common.time
SPREADSHEET = "1yrf6d7dPyTiWksFkhISqEc-JR71dxZMkUoYrX4BR40Y"
def format_row(title, description, video, timestamp, nick):
if '_id' in video:
# Allow roughly 15 seconds for chat delay, 10 seconds for chat reaction time,
# 20 seconds for how long the actual event is...
linkts = timestamp - 45
linkts = "%02dh%02dm%02ds" % (linkts//3600, linkts//60 % 60, linkts % 60)
url = "https://www.twitch.tv/loadingreadyrun/manager/%s/highlight?t=%s" % (video['_id'], linkts)
else:
url = video['url']
return [
("SHOW", title),
("QUOTE or MOMENT", description),
("YOUTUBE VIDEO LINK", url),
("ROUGH TIME THEREIN", "before " + common.time.nice_duration(timestamp, 0)),
("NOTES", "from chat user '%s'" % nick),
]
|
...
if '_id' in video:
# Allow roughly 15 seconds for chat delay, 10 seconds for chat reaction time,
# 20 seconds for how long the actual event is...
linkts = timestamp - 45
linkts = "%02dh%02dm%02ds" % (linkts//3600, linkts//60 % 60, linkts % 60)
url = "https://www.twitch.tv/loadingreadyrun/manager/%s/highlight?t=%s" % (video['_id'], linkts)
else:
...
|
2d9fce5715b2d7d5b920d2e77212f076e9ebd1be
|
staticgen_demo/staticgen_views.py
|
staticgen_demo/staticgen_views.py
|
from __future__ import unicode_literals
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
class StaicgenDemoStaticViews(StaticgenView):
def items(self):
return (
'sitemap.xml',
'robots.txt',
'page_not_found',
'server_error',
)
staticgen_pool.register(StaicgenDemoStaticViews)
|
from __future__ import unicode_literals
from django.conf import settings
from django.utils import translation
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
class StaicgenDemoStaticViews(StaticgenView):
def items(self):
return (
'sitemap.xml',
'robots.txt',
'page_not_found',
'server_error',
)
staticgen_pool.register(StaicgenDemoStaticViews)
class StaticgenCMSView(StaticgenView):
def items(self):
try:
from cms.models import Title
except ImportError: # pragma: no cover
# django-cms is not installed.
return super(StaticgenCMSView, self).items()
items = Title.objects.public().filter(
page__login_required=False,
page__site_id=settings.SITE_ID,
).order_by('page__path')
return items
def url(self, obj):
translation.activate(obj.language)
url = obj.page.get_absolute_url(obj.language)
translation.deactivate()
return url
staticgen_pool.register(StaticgenCMSView)
|
Add CMS Pages to staticgen registry.
|
Add CMS Pages to staticgen registry.
|
Python
|
bsd-3-clause
|
mishbahr/staticgen-demo,mishbahr/staticgen-demo,mishbahr/staticgen-demo
|
from __future__ import unicode_literals
+
+ from django.conf import settings
+ from django.utils import translation
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
class StaicgenDemoStaticViews(StaticgenView):
def items(self):
return (
'sitemap.xml',
'robots.txt',
'page_not_found',
'server_error',
)
staticgen_pool.register(StaicgenDemoStaticViews)
+
+ class StaticgenCMSView(StaticgenView):
+
+ def items(self):
+ try:
+ from cms.models import Title
+ except ImportError: # pragma: no cover
+ # django-cms is not installed.
+ return super(StaticgenCMSView, self).items()
+
+ items = Title.objects.public().filter(
+ page__login_required=False,
+ page__site_id=settings.SITE_ID,
+ ).order_by('page__path')
+ return items
+
+ def url(self, obj):
+ translation.activate(obj.language)
+ url = obj.page.get_absolute_url(obj.language)
+ translation.deactivate()
+ return url
+
+ staticgen_pool.register(StaticgenCMSView)
+
|
Add CMS Pages to staticgen registry.
|
## Code Before:
from __future__ import unicode_literals
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
class StaicgenDemoStaticViews(StaticgenView):
def items(self):
return (
'sitemap.xml',
'robots.txt',
'page_not_found',
'server_error',
)
staticgen_pool.register(StaicgenDemoStaticViews)
## Instruction:
Add CMS Pages to staticgen registry.
## Code After:
from __future__ import unicode_literals
from django.conf import settings
from django.utils import translation
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
class StaicgenDemoStaticViews(StaticgenView):
def items(self):
return (
'sitemap.xml',
'robots.txt',
'page_not_found',
'server_error',
)
staticgen_pool.register(StaicgenDemoStaticViews)
class StaticgenCMSView(StaticgenView):
def items(self):
try:
from cms.models import Title
except ImportError: # pragma: no cover
# django-cms is not installed.
return super(StaticgenCMSView, self).items()
items = Title.objects.public().filter(
page__login_required=False,
page__site_id=settings.SITE_ID,
).order_by('page__path')
return items
def url(self, obj):
translation.activate(obj.language)
url = obj.page.get_absolute_url(obj.language)
translation.deactivate()
return url
staticgen_pool.register(StaticgenCMSView)
|
# ... existing code ...
from __future__ import unicode_literals
from django.conf import settings
from django.utils import translation
# ... modified code ...
staticgen_pool.register(StaicgenDemoStaticViews)
class StaticgenCMSView(StaticgenView):
def items(self):
try:
from cms.models import Title
except ImportError: # pragma: no cover
# django-cms is not installed.
return super(StaticgenCMSView, self).items()
items = Title.objects.public().filter(
page__login_required=False,
page__site_id=settings.SITE_ID,
).order_by('page__path')
return items
def url(self, obj):
translation.activate(obj.language)
url = obj.page.get_absolute_url(obj.language)
translation.deactivate()
return url
staticgen_pool.register(StaticgenCMSView)
# ... rest of the code ...
|
fd5f3875d0d7e0fdb7b7ef33a94cf50d1d2b5fa4
|
tests/write_to_stringio_test.py
|
tests/write_to_stringio_test.py
|
import pycurl
import unittest
from . import appmanager
from . import util
setup_module, teardown_module = appmanager.setup(('app', 8380))
class WriteToStringioTest(unittest.TestCase):
def setUp(self):
self.curl = pycurl.Curl()
def tearDown(self):
self.curl.close()
def test_write_to_bytesio(self):
self.curl.setopt(pycurl.URL, 'http://localhost:8380/success')
sio = util.BytesIO()
self.curl.setopt(pycurl.WRITEFUNCTION, sio.write)
self.curl.perform()
self.assertEqual('success', sio.getvalue().decode())
|
import pycurl
import unittest
import sys
from . import appmanager
from . import util
setup_module, teardown_module = appmanager.setup(('app', 8380))
class WriteToStringioTest(unittest.TestCase):
def setUp(self):
self.curl = pycurl.Curl()
def tearDown(self):
self.curl.close()
def test_write_to_bytesio(self):
self.curl.setopt(pycurl.URL, 'http://localhost:8380/success')
sio = util.BytesIO()
self.curl.setopt(pycurl.WRITEFUNCTION, sio.write)
self.curl.perform()
self.assertEqual('success', sio.getvalue().decode())
@util.only_python3
def test_write_to_stringio(self):
self.curl.setopt(pycurl.URL, 'http://localhost:8380/success')
# stringio in python 3
sio = util.StringIO()
self.curl.setopt(pycurl.WRITEFUNCTION, sio.write)
try:
self.curl.perform()
self.fail('Should have received a write error')
except pycurl.error:
err, msg = sys.exc_info()[1].args
# we expect pycurl.E_WRITE_ERROR as the response
assert pycurl.E_WRITE_ERROR == err
|
Add a test for writing to StringIO which is now different and does not work
|
Add a test for writing to StringIO which is now different and does not work
|
Python
|
lgpl-2.1
|
pycurl/pycurl,pycurl/pycurl,pycurl/pycurl
|
import pycurl
import unittest
+ import sys
from . import appmanager
from . import util
setup_module, teardown_module = appmanager.setup(('app', 8380))
class WriteToStringioTest(unittest.TestCase):
def setUp(self):
self.curl = pycurl.Curl()
def tearDown(self):
self.curl.close()
def test_write_to_bytesio(self):
self.curl.setopt(pycurl.URL, 'http://localhost:8380/success')
sio = util.BytesIO()
self.curl.setopt(pycurl.WRITEFUNCTION, sio.write)
self.curl.perform()
self.assertEqual('success', sio.getvalue().decode())
+
+ @util.only_python3
+ def test_write_to_stringio(self):
+ self.curl.setopt(pycurl.URL, 'http://localhost:8380/success')
+ # stringio in python 3
+ sio = util.StringIO()
+ self.curl.setopt(pycurl.WRITEFUNCTION, sio.write)
+ try:
+ self.curl.perform()
+
+ self.fail('Should have received a write error')
+ except pycurl.error:
+ err, msg = sys.exc_info()[1].args
+ # we expect pycurl.E_WRITE_ERROR as the response
+ assert pycurl.E_WRITE_ERROR == err
|
Add a test for writing to StringIO which is now different and does not work
|
## Code Before:
import pycurl
import unittest
from . import appmanager
from . import util
setup_module, teardown_module = appmanager.setup(('app', 8380))
class WriteToStringioTest(unittest.TestCase):
def setUp(self):
self.curl = pycurl.Curl()
def tearDown(self):
self.curl.close()
def test_write_to_bytesio(self):
self.curl.setopt(pycurl.URL, 'http://localhost:8380/success')
sio = util.BytesIO()
self.curl.setopt(pycurl.WRITEFUNCTION, sio.write)
self.curl.perform()
self.assertEqual('success', sio.getvalue().decode())
## Instruction:
Add a test for writing to StringIO which is now different and does not work
## Code After:
import pycurl
import unittest
import sys
from . import appmanager
from . import util
setup_module, teardown_module = appmanager.setup(('app', 8380))
class WriteToStringioTest(unittest.TestCase):
def setUp(self):
self.curl = pycurl.Curl()
def tearDown(self):
self.curl.close()
def test_write_to_bytesio(self):
self.curl.setopt(pycurl.URL, 'http://localhost:8380/success')
sio = util.BytesIO()
self.curl.setopt(pycurl.WRITEFUNCTION, sio.write)
self.curl.perform()
self.assertEqual('success', sio.getvalue().decode())
@util.only_python3
def test_write_to_stringio(self):
self.curl.setopt(pycurl.URL, 'http://localhost:8380/success')
# stringio in python 3
sio = util.StringIO()
self.curl.setopt(pycurl.WRITEFUNCTION, sio.write)
try:
self.curl.perform()
self.fail('Should have received a write error')
except pycurl.error:
err, msg = sys.exc_info()[1].args
# we expect pycurl.E_WRITE_ERROR as the response
assert pycurl.E_WRITE_ERROR == err
|
...
import unittest
import sys
...
self.assertEqual('success', sio.getvalue().decode())
@util.only_python3
def test_write_to_stringio(self):
self.curl.setopt(pycurl.URL, 'http://localhost:8380/success')
# stringio in python 3
sio = util.StringIO()
self.curl.setopt(pycurl.WRITEFUNCTION, sio.write)
try:
self.curl.perform()
self.fail('Should have received a write error')
except pycurl.error:
err, msg = sys.exc_info()[1].args
# we expect pycurl.E_WRITE_ERROR as the response
assert pycurl.E_WRITE_ERROR == err
...
|
ebb5a2f56c691456b5b65b9448d11b113c4efa46
|
fedmsg/meta/announce.py
|
fedmsg/meta/announce.py
|
from fedmsg.meta.base import BaseProcessor
class AnnounceProcessor(BaseProcessor):
__name__ = "announce"
__description__ = "Official Fedora Announcements"
__link__ = "http://fedoraproject.org/"
__docs__ = "http://fedoraproject.org/"
__obj__ = "Announcements"
def subtitle(self, msg, **config):
return msg['msg']['message']
def link(self, msg, **config):
return msg['msg']['link']
def usernames(self, msg, **config):
return set([msg['username']])
|
from fedmsg.meta.base import BaseProcessor
class AnnounceProcessor(BaseProcessor):
__name__ = "announce"
__description__ = "Official Fedora Announcements"
__link__ = "http://fedoraproject.org/"
__docs__ = "http://fedoraproject.org/"
__obj__ = "Announcements"
def subtitle(self, msg, **config):
return msg['msg']['message']
def link(self, msg, **config):
return msg['msg']['link']
def usernames(self, msg, **config):
users = set()
if 'username' in msg:
users.update(set([msg['username']]))
return users
|
Handle the situation where in old message the 'username' key does not exists
|
Handle the situation where in old message the 'username' key does not exists
With this commit processing an old message with fedmsg_meta will not break
if that old message does not have the 'username' key.
|
Python
|
lgpl-2.1
|
chaiku/fedmsg,vivekanand1101/fedmsg,vivekanand1101/fedmsg,cicku/fedmsg,mathstuf/fedmsg,mathstuf/fedmsg,maxamillion/fedmsg,mathstuf/fedmsg,chaiku/fedmsg,fedora-infra/fedmsg,fedora-infra/fedmsg,pombredanne/fedmsg,pombredanne/fedmsg,cicku/fedmsg,maxamillion/fedmsg,chaiku/fedmsg,vivekanand1101/fedmsg,pombredanne/fedmsg,cicku/fedmsg,maxamillion/fedmsg,fedora-infra/fedmsg
|
from fedmsg.meta.base import BaseProcessor
class AnnounceProcessor(BaseProcessor):
__name__ = "announce"
__description__ = "Official Fedora Announcements"
__link__ = "http://fedoraproject.org/"
__docs__ = "http://fedoraproject.org/"
__obj__ = "Announcements"
def subtitle(self, msg, **config):
return msg['msg']['message']
def link(self, msg, **config):
return msg['msg']['link']
def usernames(self, msg, **config):
+ users = set()
+ if 'username' in msg:
- return set([msg['username']])
+ users.update(set([msg['username']]))
+ return users
|
Handle the situation where in old message the 'username' key does not exists
|
## Code Before:
from fedmsg.meta.base import BaseProcessor
class AnnounceProcessor(BaseProcessor):
__name__ = "announce"
__description__ = "Official Fedora Announcements"
__link__ = "http://fedoraproject.org/"
__docs__ = "http://fedoraproject.org/"
__obj__ = "Announcements"
def subtitle(self, msg, **config):
return msg['msg']['message']
def link(self, msg, **config):
return msg['msg']['link']
def usernames(self, msg, **config):
return set([msg['username']])
## Instruction:
Handle the situation where in old message the 'username' key does not exists
## Code After:
from fedmsg.meta.base import BaseProcessor
class AnnounceProcessor(BaseProcessor):
__name__ = "announce"
__description__ = "Official Fedora Announcements"
__link__ = "http://fedoraproject.org/"
__docs__ = "http://fedoraproject.org/"
__obj__ = "Announcements"
def subtitle(self, msg, **config):
return msg['msg']['message']
def link(self, msg, **config):
return msg['msg']['link']
def usernames(self, msg, **config):
users = set()
if 'username' in msg:
users.update(set([msg['username']]))
return users
|
...
def usernames(self, msg, **config):
users = set()
if 'username' in msg:
users.update(set([msg['username']]))
return users
...
|
2430e87f2c44c46863ed47c8b3a55c4010820260
|
frontend/modloop/__init__.py
|
frontend/modloop/__init__.py
|
from flask import render_template, request, send_from_directory
import saliweb.frontend
from saliweb.frontend import get_completed_job
from . import submit
app = saliweb.frontend.make_application(__name__, "##CONFIG##")
@app.route('/')
def index():
return render_template('index.html')
@app.route('/contact')
def contact():
return render_template('contact.html')
@app.route('/help')
def help():
return render_template('help.html')
@app.route('/download')
def download():
return render_template('download.html')
@app.route('/job', methods=['GET', 'POST'])
def job():
if request.method == 'GET':
return saliweb.frontend.render_queue_page()
else:
return submit.handle_new_job()
@app.route('/job/<name>')
def results(name):
job = get_completed_job(name, request.args.get('passwd'))
return render_template('results.html', job=job)
@app.route('/job/<name>/<path:fp>')
def results_file(name, fp):
job = get_completed_job(name, request.args.get('passwd'))
return send_from_directory(job.directory, fp)
|
from flask import render_template, request, send_from_directory
import saliweb.frontend
from saliweb.frontend import get_completed_job, Parameter, FileParameter
from . import submit
parameters=[Parameter("name", "Job name", optional=True),
FileParameter("pdb", "PDB file to be refined"),
Parameter("modkey", "MODELLER license key"),
Parameter("loops", "Loops to be refined")]
app = saliweb.frontend.make_application(__name__, "##CONFIG##", parameters)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/contact')
def contact():
return render_template('contact.html')
@app.route('/help')
def help():
return render_template('help.html')
@app.route('/download')
def download():
return render_template('download.html')
@app.route('/job', methods=['GET', 'POST'])
def job():
if request.method == 'GET':
return saliweb.frontend.render_queue_page()
else:
return submit.handle_new_job()
@app.route('/job/<name>')
def results(name):
job = get_completed_job(name, request.args.get('passwd'))
return saliweb.frontend.render_results_template('results.html', job=job)
@app.route('/job/<name>/<path:fp>')
def results_file(name, fp):
job = get_completed_job(name, request.args.get('passwd'))
return send_from_directory(job.directory, fp)
|
Add basic REST API support
|
Add basic REST API support
|
Python
|
lgpl-2.1
|
salilab/modloop,salilab/modloop
|
from flask import render_template, request, send_from_directory
import saliweb.frontend
- from saliweb.frontend import get_completed_job
+ from saliweb.frontend import get_completed_job, Parameter, FileParameter
from . import submit
+ parameters=[Parameter("name", "Job name", optional=True),
+ FileParameter("pdb", "PDB file to be refined"),
+ Parameter("modkey", "MODELLER license key"),
+ Parameter("loops", "Loops to be refined")]
- app = saliweb.frontend.make_application(__name__, "##CONFIG##")
+ app = saliweb.frontend.make_application(__name__, "##CONFIG##", parameters)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/contact')
def contact():
return render_template('contact.html')
@app.route('/help')
def help():
return render_template('help.html')
@app.route('/download')
def download():
return render_template('download.html')
@app.route('/job', methods=['GET', 'POST'])
def job():
if request.method == 'GET':
return saliweb.frontend.render_queue_page()
else:
return submit.handle_new_job()
@app.route('/job/<name>')
def results(name):
job = get_completed_job(name, request.args.get('passwd'))
- return render_template('results.html', job=job)
+ return saliweb.frontend.render_results_template('results.html', job=job)
@app.route('/job/<name>/<path:fp>')
def results_file(name, fp):
job = get_completed_job(name, request.args.get('passwd'))
return send_from_directory(job.directory, fp)
|
Add basic REST API support
|
## Code Before:
from flask import render_template, request, send_from_directory
import saliweb.frontend
from saliweb.frontend import get_completed_job
from . import submit
app = saliweb.frontend.make_application(__name__, "##CONFIG##")
@app.route('/')
def index():
return render_template('index.html')
@app.route('/contact')
def contact():
return render_template('contact.html')
@app.route('/help')
def help():
return render_template('help.html')
@app.route('/download')
def download():
return render_template('download.html')
@app.route('/job', methods=['GET', 'POST'])
def job():
if request.method == 'GET':
return saliweb.frontend.render_queue_page()
else:
return submit.handle_new_job()
@app.route('/job/<name>')
def results(name):
job = get_completed_job(name, request.args.get('passwd'))
return render_template('results.html', job=job)
@app.route('/job/<name>/<path:fp>')
def results_file(name, fp):
job = get_completed_job(name, request.args.get('passwd'))
return send_from_directory(job.directory, fp)
## Instruction:
Add basic REST API support
## Code After:
from flask import render_template, request, send_from_directory
import saliweb.frontend
from saliweb.frontend import get_completed_job, Parameter, FileParameter
from . import submit
parameters=[Parameter("name", "Job name", optional=True),
FileParameter("pdb", "PDB file to be refined"),
Parameter("modkey", "MODELLER license key"),
Parameter("loops", "Loops to be refined")]
app = saliweb.frontend.make_application(__name__, "##CONFIG##", parameters)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/contact')
def contact():
return render_template('contact.html')
@app.route('/help')
def help():
return render_template('help.html')
@app.route('/download')
def download():
return render_template('download.html')
@app.route('/job', methods=['GET', 'POST'])
def job():
if request.method == 'GET':
return saliweb.frontend.render_queue_page()
else:
return submit.handle_new_job()
@app.route('/job/<name>')
def results(name):
job = get_completed_job(name, request.args.get('passwd'))
return saliweb.frontend.render_results_template('results.html', job=job)
@app.route('/job/<name>/<path:fp>')
def results_file(name, fp):
job = get_completed_job(name, request.args.get('passwd'))
return send_from_directory(job.directory, fp)
|
// ... existing code ...
import saliweb.frontend
from saliweb.frontend import get_completed_job, Parameter, FileParameter
from . import submit
// ... modified code ...
parameters=[Parameter("name", "Job name", optional=True),
FileParameter("pdb", "PDB file to be refined"),
Parameter("modkey", "MODELLER license key"),
Parameter("loops", "Loops to be refined")]
app = saliweb.frontend.make_application(__name__, "##CONFIG##", parameters)
...
job = get_completed_job(name, request.args.get('passwd'))
return saliweb.frontend.render_results_template('results.html', job=job)
// ... rest of the code ...
|
02d1b76067a8c3b2de9abc09cd841fe8b8bd7605
|
example/app/integrations/fps_integration.py
|
example/app/integrations/fps_integration.py
|
from billing.integrations.amazon_fps_integration import AmazonFpsIntegration as Integration
from django.core.urlresolvers import reverse
import urlparse
class FpsIntegration(Integration):
def transaction(self, request):
"""Ideally at this method, you will check the
caller reference against a user id or uniquely
identifiable attribute (if you are already not
using it as the caller reference) and the type
of transaction (either pay, reserve etc). For
the sake of the example, we assume all the users
get charged $100"""
request_url = request.build_absolute_uri()
parsed_url = urlparse.urlparse(request_url)
query = parsed_url.query
dd = dict(map(lambda x: x.split("="), query.split("&")))
resp = self.purchase(100, dd)
return "%s?status=%s" %(reverse("app_offsite_amazon_fps"),
resp["status"])
|
from billing.integrations.amazon_fps_integration import AmazonFpsIntegration as Integration
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
import urlparse
class FpsIntegration(Integration):
def transaction(self, request):
"""Ideally at this method, you will check the
caller reference against a user id or uniquely
identifiable attribute (if you are already not
using it as the caller reference) and the type
of transaction (either pay, reserve etc). For
the sake of the example, we assume all the users
get charged $100"""
request_url = request.build_absolute_uri()
parsed_url = urlparse.urlparse(request_url)
query = parsed_url.query
dd = dict(map(lambda x: x.split("="), query.split("&")))
resp = self.purchase(100, dd)
return HttpResponseRedirect("%s?status=%s" %(reverse("app_offsite_amazon_fps"),
resp["status"]))
|
Use the HttpResponseRedirect for redirection.
|
Use the HttpResponseRedirect for redirection.
|
Python
|
bsd-3-clause
|
biddyweb/merchant,spookylukey/merchant,spookylukey/merchant,digideskio/merchant,mjrulesamrat/merchant,agiliq/merchant,SimpleTax/merchant,mjrulesamrat/merchant,biddyweb/merchant,SimpleTax/merchant,agiliq/merchant,digideskio/merchant
|
from billing.integrations.amazon_fps_integration import AmazonFpsIntegration as Integration
from django.core.urlresolvers import reverse
+ from django.http import HttpResponseRedirect
import urlparse
class FpsIntegration(Integration):
def transaction(self, request):
"""Ideally at this method, you will check the
caller reference against a user id or uniquely
identifiable attribute (if you are already not
using it as the caller reference) and the type
of transaction (either pay, reserve etc). For
the sake of the example, we assume all the users
get charged $100"""
request_url = request.build_absolute_uri()
parsed_url = urlparse.urlparse(request_url)
query = parsed_url.query
dd = dict(map(lambda x: x.split("="), query.split("&")))
resp = self.purchase(100, dd)
- return "%s?status=%s" %(reverse("app_offsite_amazon_fps"),
+ return HttpResponseRedirect("%s?status=%s" %(reverse("app_offsite_amazon_fps"),
- resp["status"])
+ resp["status"]))
|
Use the HttpResponseRedirect for redirection.
|
## Code Before:
from billing.integrations.amazon_fps_integration import AmazonFpsIntegration as Integration
from django.core.urlresolvers import reverse
import urlparse
class FpsIntegration(Integration):
def transaction(self, request):
"""Ideally at this method, you will check the
caller reference against a user id or uniquely
identifiable attribute (if you are already not
using it as the caller reference) and the type
of transaction (either pay, reserve etc). For
the sake of the example, we assume all the users
get charged $100"""
request_url = request.build_absolute_uri()
parsed_url = urlparse.urlparse(request_url)
query = parsed_url.query
dd = dict(map(lambda x: x.split("="), query.split("&")))
resp = self.purchase(100, dd)
return "%s?status=%s" %(reverse("app_offsite_amazon_fps"),
resp["status"])
## Instruction:
Use the HttpResponseRedirect for redirection.
## Code After:
from billing.integrations.amazon_fps_integration import AmazonFpsIntegration as Integration
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
import urlparse
class FpsIntegration(Integration):
def transaction(self, request):
"""Ideally at this method, you will check the
caller reference against a user id or uniquely
identifiable attribute (if you are already not
using it as the caller reference) and the type
of transaction (either pay, reserve etc). For
the sake of the example, we assume all the users
get charged $100"""
request_url = request.build_absolute_uri()
parsed_url = urlparse.urlparse(request_url)
query = parsed_url.query
dd = dict(map(lambda x: x.split("="), query.split("&")))
resp = self.purchase(100, dd)
return HttpResponseRedirect("%s?status=%s" %(reverse("app_offsite_amazon_fps"),
resp["status"]))
|
...
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
import urlparse
...
resp = self.purchase(100, dd)
return HttpResponseRedirect("%s?status=%s" %(reverse("app_offsite_amazon_fps"),
resp["status"]))
...
|
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'
|
# ... existing code ...
CAPAPI_API_KEY = '12345'
# ... rest of the code ...
|
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)
|
...
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)
...
|
025c3f6b73c97fdb58b1a492efcb6efe44cfdab0
|
twisted/plugins/caldav.py
|
twisted/plugins/caldav.py
|
from zope.interface import implements
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker
from twisted.python import reflect
def serviceMakerProperty(propname):
def getProperty(self):
return getattr(reflect.namedClass(self.serviceMakerClass), propname)
return property(getProperty)
class TAP(object):
implements(IPlugin, IServiceMaker)
def __init__(self, serviceMakerClass):
self.serviceMakerClass = serviceMakerClass
self._serviceMaker = None
options = serviceMakerProperty("options")
tapname = serviceMakerProperty("tapname")
description = serviceMakerProperty("description")
def makeService(self, options):
if self._serviceMaker is None:
self._serviceMaker = reflect.namedClass(self.serviceMakerClass)()
return self._serviceMaker.makeService(options)
TwistedCalDAV = TAP("calendarserver.tap.caldav.CalDAVServiceMaker")
CalDAVNotifier = TAP("twistedcaldav.notify.NotificationServiceMaker")
CalDAVMailGateway = TAP("twistedcaldav.mail.MailGatewayServiceMaker")
|
from zope.interface import implements
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker
from twisted.python import reflect
from twisted.internet.protocol import Factory
Factory.noisy = False
def serviceMakerProperty(propname):
def getProperty(self):
return getattr(reflect.namedClass(self.serviceMakerClass), propname)
return property(getProperty)
class TAP(object):
implements(IPlugin, IServiceMaker)
def __init__(self, serviceMakerClass):
self.serviceMakerClass = serviceMakerClass
self._serviceMaker = None
options = serviceMakerProperty("options")
tapname = serviceMakerProperty("tapname")
description = serviceMakerProperty("description")
def makeService(self, options):
if self._serviceMaker is None:
self._serviceMaker = reflect.namedClass(self.serviceMakerClass)()
return self._serviceMaker.makeService(options)
TwistedCalDAV = TAP("calendarserver.tap.caldav.CalDAVServiceMaker")
CalDAVNotifier = TAP("twistedcaldav.notify.NotificationServiceMaker")
CalDAVMailGateway = TAP("twistedcaldav.mail.MailGatewayServiceMaker")
|
Set Factory.noisy to False by default
|
Set Factory.noisy to False by default
git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@3933 e27351fd-9f3e-4f54-a53b-843176b1656c
|
Python
|
apache-2.0
|
trevor/calendarserver,trevor/calendarserver,trevor/calendarserver
|
from zope.interface import implements
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker
from twisted.python import reflect
+
+ from twisted.internet.protocol import Factory
+ Factory.noisy = False
+
def serviceMakerProperty(propname):
def getProperty(self):
return getattr(reflect.namedClass(self.serviceMakerClass), propname)
return property(getProperty)
class TAP(object):
implements(IPlugin, IServiceMaker)
+
def __init__(self, serviceMakerClass):
self.serviceMakerClass = serviceMakerClass
self._serviceMaker = None
- options = serviceMakerProperty("options")
+ options = serviceMakerProperty("options")
- tapname = serviceMakerProperty("tapname")
+ tapname = serviceMakerProperty("tapname")
description = serviceMakerProperty("description")
def makeService(self, options):
if self._serviceMaker is None:
self._serviceMaker = reflect.namedClass(self.serviceMakerClass)()
return self._serviceMaker.makeService(options)
TwistedCalDAV = TAP("calendarserver.tap.caldav.CalDAVServiceMaker")
CalDAVNotifier = TAP("twistedcaldav.notify.NotificationServiceMaker")
CalDAVMailGateway = TAP("twistedcaldav.mail.MailGatewayServiceMaker")
|
Set Factory.noisy to False by default
|
## Code Before:
from zope.interface import implements
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker
from twisted.python import reflect
def serviceMakerProperty(propname):
def getProperty(self):
return getattr(reflect.namedClass(self.serviceMakerClass), propname)
return property(getProperty)
class TAP(object):
implements(IPlugin, IServiceMaker)
def __init__(self, serviceMakerClass):
self.serviceMakerClass = serviceMakerClass
self._serviceMaker = None
options = serviceMakerProperty("options")
tapname = serviceMakerProperty("tapname")
description = serviceMakerProperty("description")
def makeService(self, options):
if self._serviceMaker is None:
self._serviceMaker = reflect.namedClass(self.serviceMakerClass)()
return self._serviceMaker.makeService(options)
TwistedCalDAV = TAP("calendarserver.tap.caldav.CalDAVServiceMaker")
CalDAVNotifier = TAP("twistedcaldav.notify.NotificationServiceMaker")
CalDAVMailGateway = TAP("twistedcaldav.mail.MailGatewayServiceMaker")
## Instruction:
Set Factory.noisy to False by default
## Code After:
from zope.interface import implements
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker
from twisted.python import reflect
from twisted.internet.protocol import Factory
Factory.noisy = False
def serviceMakerProperty(propname):
def getProperty(self):
return getattr(reflect.namedClass(self.serviceMakerClass), propname)
return property(getProperty)
class TAP(object):
implements(IPlugin, IServiceMaker)
def __init__(self, serviceMakerClass):
self.serviceMakerClass = serviceMakerClass
self._serviceMaker = None
options = serviceMakerProperty("options")
tapname = serviceMakerProperty("tapname")
description = serviceMakerProperty("description")
def makeService(self, options):
if self._serviceMaker is None:
self._serviceMaker = reflect.namedClass(self.serviceMakerClass)()
return self._serviceMaker.makeService(options)
TwistedCalDAV = TAP("calendarserver.tap.caldav.CalDAVServiceMaker")
CalDAVNotifier = TAP("twistedcaldav.notify.NotificationServiceMaker")
CalDAVMailGateway = TAP("twistedcaldav.mail.MailGatewayServiceMaker")
|
// ... existing code ...
from twisted.python import reflect
from twisted.internet.protocol import Factory
Factory.noisy = False
// ... modified code ...
implements(IPlugin, IServiceMaker)
def __init__(self, serviceMakerClass):
...
options = serviceMakerProperty("options")
tapname = serviceMakerProperty("tapname")
description = serviceMakerProperty("description")
// ... rest of the code ...
|
c745a6807a26173033bdbea8387e9c10275bb88d
|
step_stool/content.py
|
step_stool/content.py
|
__author__ = 'Chris Krycho'
__copyright__ = '2013 Chris Krycho'
from logging import error
from os import path, walk
from sys import exit
try:
from markdown import Markdown
from mixins import DictAsMember
except ImportError as import_error:
error(import_error)
exit()
def convert_source(config):
'''
Convert all Markdown pages to HTML and metadata pairs. Pairs are keyed to
file names slugs (without the original file extension).
'''
md = Markdown(extensions=config.markdown_extensions, output_format='html5')
converted = {}
for root, dirs, file_names in walk(config.site.content.source):
for file_name in file_names:
file_path = path.join(root, file_name)
plain_slug, extension = path.splitext(file_name)
with open(file_path) as file:
md_text = file.read()
content = md.convert(md_text)
converted[plain_slug] = {'content': content, 'meta': md.Meta}
return DictAsMember(converted)
|
__author__ = 'Chris Krycho'
__copyright__ = '2013 Chris Krycho'
from logging import error
from os import path, walk
from sys import exit
try:
from markdown import Markdown
from mixins import DictAsMember
except ImportError as import_error:
error(import_error)
exit()
def convert_source(config):
'''
Convert all Markdown pages to HTML and metadata pairs. Pairs are keyed to
file names slugs (without the original file extension).
'''
md = Markdown(extensions=config.markdown_extensions, output_format='html5')
converted = {}
for root, dirs, file_names in walk(config.site.content.source):
for file_name in file_names:
file_path = path.join(root, file_name)
plain_slug, extension = path.splitext(file_name)
with open(file_path) as file:
md_text = file.read()
content = md.convert(md_text)
converted[plain_slug] = {'content': content, 'meta': md.Meta}
md.reset()
return DictAsMember(converted)
|
Call the reset() method in the Markdown object to clear extensions (e.g. metadata) between processing each file.
|
Call the reset() method in the Markdown object to clear extensions (e.g. metadata) between processing each file.
|
Python
|
mit
|
chriskrycho/step-stool,chriskrycho/step-stool
|
__author__ = 'Chris Krycho'
__copyright__ = '2013 Chris Krycho'
from logging import error
from os import path, walk
from sys import exit
try:
from markdown import Markdown
from mixins import DictAsMember
except ImportError as import_error:
error(import_error)
exit()
def convert_source(config):
'''
Convert all Markdown pages to HTML and metadata pairs. Pairs are keyed to
file names slugs (without the original file extension).
'''
md = Markdown(extensions=config.markdown_extensions, output_format='html5')
converted = {}
for root, dirs, file_names in walk(config.site.content.source):
for file_name in file_names:
file_path = path.join(root, file_name)
plain_slug, extension = path.splitext(file_name)
with open(file_path) as file:
md_text = file.read()
content = md.convert(md_text)
converted[plain_slug] = {'content': content, 'meta': md.Meta}
+ md.reset()
return DictAsMember(converted)
|
Call the reset() method in the Markdown object to clear extensions (e.g. metadata) between processing each file.
|
## Code Before:
__author__ = 'Chris Krycho'
__copyright__ = '2013 Chris Krycho'
from logging import error
from os import path, walk
from sys import exit
try:
from markdown import Markdown
from mixins import DictAsMember
except ImportError as import_error:
error(import_error)
exit()
def convert_source(config):
'''
Convert all Markdown pages to HTML and metadata pairs. Pairs are keyed to
file names slugs (without the original file extension).
'''
md = Markdown(extensions=config.markdown_extensions, output_format='html5')
converted = {}
for root, dirs, file_names in walk(config.site.content.source):
for file_name in file_names:
file_path = path.join(root, file_name)
plain_slug, extension = path.splitext(file_name)
with open(file_path) as file:
md_text = file.read()
content = md.convert(md_text)
converted[plain_slug] = {'content': content, 'meta': md.Meta}
return DictAsMember(converted)
## Instruction:
Call the reset() method in the Markdown object to clear extensions (e.g. metadata) between processing each file.
## Code After:
__author__ = 'Chris Krycho'
__copyright__ = '2013 Chris Krycho'
from logging import error
from os import path, walk
from sys import exit
try:
from markdown import Markdown
from mixins import DictAsMember
except ImportError as import_error:
error(import_error)
exit()
def convert_source(config):
'''
Convert all Markdown pages to HTML and metadata pairs. Pairs are keyed to
file names slugs (without the original file extension).
'''
md = Markdown(extensions=config.markdown_extensions, output_format='html5')
converted = {}
for root, dirs, file_names in walk(config.site.content.source):
for file_name in file_names:
file_path = path.join(root, file_name)
plain_slug, extension = path.splitext(file_name)
with open(file_path) as file:
md_text = file.read()
content = md.convert(md_text)
converted[plain_slug] = {'content': content, 'meta': md.Meta}
md.reset()
return DictAsMember(converted)
|
// ... existing code ...
converted[plain_slug] = {'content': content, 'meta': md.Meta}
md.reset()
// ... rest of the code ...
|
b344d63ad3ff7abff0772a744e951d5d5c8438f3
|
carepoint/models/address_mixin.py
|
carepoint/models/address_mixin.py
|
from sqlalchemy import (Column,
Integer,
DateTime,
)
class AddressMixin(object):
""" This is a mixin for Address Many2Many bindings """
addr_id = Column(Integer, primary_key=True)
priority = Column(Integer)
addr_type_cn = Column(Integer)
app_flags = Column(Integer)
timestmp = Column(DateTime)
|
from sqlalchemy import (Column,
Integer,
DateTime,
ForeignKey
)
class AddressMixin(object):
""" This is a mixin for Address Many2Many bindings """
addr_id = Column(
Integer,
ForeignKey('csaddr.addr_id'),
primary_key=True,
)
priority = Column(Integer)
addr_type_cn = Column(Integer)
app_flags = Column(Integer)
timestmp = Column(DateTime)
|
Add ForeignKey on addr_id in carepoint cph address model
|
Add ForeignKey on addr_id in carepoint cph address model
|
Python
|
mit
|
laslabs/Python-Carepoint
|
from sqlalchemy import (Column,
Integer,
DateTime,
+ ForeignKey
)
class AddressMixin(object):
""" This is a mixin for Address Many2Many bindings """
- addr_id = Column(Integer, primary_key=True)
+ addr_id = Column(
+ Integer,
+ ForeignKey('csaddr.addr_id'),
+ primary_key=True,
+ )
priority = Column(Integer)
addr_type_cn = Column(Integer)
app_flags = Column(Integer)
timestmp = Column(DateTime)
|
Add ForeignKey on addr_id in carepoint cph address model
|
## Code Before:
from sqlalchemy import (Column,
Integer,
DateTime,
)
class AddressMixin(object):
""" This is a mixin for Address Many2Many bindings """
addr_id = Column(Integer, primary_key=True)
priority = Column(Integer)
addr_type_cn = Column(Integer)
app_flags = Column(Integer)
timestmp = Column(DateTime)
## Instruction:
Add ForeignKey on addr_id in carepoint cph address model
## Code After:
from sqlalchemy import (Column,
Integer,
DateTime,
ForeignKey
)
class AddressMixin(object):
""" This is a mixin for Address Many2Many bindings """
addr_id = Column(
Integer,
ForeignKey('csaddr.addr_id'),
primary_key=True,
)
priority = Column(Integer)
addr_type_cn = Column(Integer)
app_flags = Column(Integer)
timestmp = Column(DateTime)
|
...
DateTime,
ForeignKey
)
...
addr_id = Column(
Integer,
ForeignKey('csaddr.addr_id'),
primary_key=True,
)
priority = Column(Integer)
...
|
ac2b01e9177d04a6446b770639745010770cb317
|
nuage_neutron/plugins/nuage_ml2/nuage_subnet_ext_driver.py
|
nuage_neutron/plugins/nuage_ml2/nuage_subnet_ext_driver.py
|
from oslo_log import log as logging
from neutron.plugins.ml2 import driver_api as api
LOG = logging.getLogger(__name__)
class NuageSubnetExtensionDriver(api.ExtensionDriver):
_supported_extension_alias = 'nuage-subnet'
def initialize(self):
pass
@property
def extension_alias(self):
return self._supported_extension_alias
def process_create_subnet(self, plugin_context, data, result):
result['net_partition'] = data['net_partition']
result['nuagenet'] = data['nuagenet']
def extend_subnet_dict(self, session, db_data, result):
return result
|
from oslo_log import log as logging
from neutron.plugins.ml2 import driver_api as api
from nuage_neutron.plugins.common import nuagedb
LOG = logging.getLogger(__name__)
class NuageSubnetExtensionDriver(api.ExtensionDriver):
_supported_extension_alias = 'nuage-subnet'
def initialize(self):
pass
@property
def extension_alias(self):
return self._supported_extension_alias
def process_create_subnet(self, plugin_context, data, result):
result['net_partition'] = data['net_partition']
result['nuagenet'] = data['nuagenet']
def extend_subnet_dict(self, session, db_data, result):
subnet_mapping = nuagedb.get_subnet_l2dom_by_id(session, result['id'])
if subnet_mapping:
result['vsd_managed'] = subnet_mapping['nuage_managed_subnet']
else:
result['vsd_managed'] = False
return result
|
Add 'vsd_managed' to the GET subnet response for ML2
|
Add 'vsd_managed' to the GET subnet response for ML2
This commit looks up the related nuage_subnet_l2dom_mapping in the database
and uses the nuage_managed_subnet field to fill in 'vsd_managed'. False by
default.
Change-Id: I68957fe3754dc9f1ccf2b6a2b09a762fccd17a89
Closes-Bug: OPENSTACK-1504
|
Python
|
apache-2.0
|
nuagenetworks/nuage-openstack-neutron,naveensan1/nuage-openstack-neutron,naveensan1/nuage-openstack-neutron,nuagenetworks/nuage-openstack-neutron
|
from oslo_log import log as logging
from neutron.plugins.ml2 import driver_api as api
+ from nuage_neutron.plugins.common import nuagedb
LOG = logging.getLogger(__name__)
class NuageSubnetExtensionDriver(api.ExtensionDriver):
_supported_extension_alias = 'nuage-subnet'
def initialize(self):
pass
@property
def extension_alias(self):
return self._supported_extension_alias
def process_create_subnet(self, plugin_context, data, result):
result['net_partition'] = data['net_partition']
result['nuagenet'] = data['nuagenet']
def extend_subnet_dict(self, session, db_data, result):
+ subnet_mapping = nuagedb.get_subnet_l2dom_by_id(session, result['id'])
+ if subnet_mapping:
+ result['vsd_managed'] = subnet_mapping['nuage_managed_subnet']
+ else:
+ result['vsd_managed'] = False
return result
|
Add 'vsd_managed' to the GET subnet response for ML2
|
## Code Before:
from oslo_log import log as logging
from neutron.plugins.ml2 import driver_api as api
LOG = logging.getLogger(__name__)
class NuageSubnetExtensionDriver(api.ExtensionDriver):
_supported_extension_alias = 'nuage-subnet'
def initialize(self):
pass
@property
def extension_alias(self):
return self._supported_extension_alias
def process_create_subnet(self, plugin_context, data, result):
result['net_partition'] = data['net_partition']
result['nuagenet'] = data['nuagenet']
def extend_subnet_dict(self, session, db_data, result):
return result
## Instruction:
Add 'vsd_managed' to the GET subnet response for ML2
## Code After:
from oslo_log import log as logging
from neutron.plugins.ml2 import driver_api as api
from nuage_neutron.plugins.common import nuagedb
LOG = logging.getLogger(__name__)
class NuageSubnetExtensionDriver(api.ExtensionDriver):
_supported_extension_alias = 'nuage-subnet'
def initialize(self):
pass
@property
def extension_alias(self):
return self._supported_extension_alias
def process_create_subnet(self, plugin_context, data, result):
result['net_partition'] = data['net_partition']
result['nuagenet'] = data['nuagenet']
def extend_subnet_dict(self, session, db_data, result):
subnet_mapping = nuagedb.get_subnet_l2dom_by_id(session, result['id'])
if subnet_mapping:
result['vsd_managed'] = subnet_mapping['nuage_managed_subnet']
else:
result['vsd_managed'] = False
return result
|
# ... existing code ...
from neutron.plugins.ml2 import driver_api as api
from nuage_neutron.plugins.common import nuagedb
# ... modified code ...
def extend_subnet_dict(self, session, db_data, result):
subnet_mapping = nuagedb.get_subnet_l2dom_by_id(session, result['id'])
if subnet_mapping:
result['vsd_managed'] = subnet_mapping['nuage_managed_subnet']
else:
result['vsd_managed'] = False
return result
# ... rest of the code ...
|
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)
|
# ... existing code ...
from ._callable import CallableBackend
from ._autograd import AutogradBackend
from ._pytorch import PyTorchBackend
from ._theano import TheanoBackend
from ._tensorflow import TensorflowBackend
class Function(object):
# ... rest of the code ...
|
421e811242b737a7b1bf27814d70f719f345131b
|
watchlist/utils.py
|
watchlist/utils.py
|
from .models import ShiftSlot, weekday_loc
from website.settings import WORKSHOP_OPEN_DAYS
def get_shift_weekview_rows():
'''Returns a dictionary of shifts for each timeslot, for each weekday'''
slots = ShiftSlot.objects.all()
if not slots:
return None
# Could be troublesome wrt. sorting of dictionary keys. Doesn't *seem* to be an issue right now but it *technically* already is!
rows = {}
for slot in slots:
row_header = '{} -\n{}'.format(slot.start.strftime('%H:%M'), slot.end.strftime('%H:%M'))
if row_header not in rows:
rows[row_header] = []
rows[row_header].append(slot)
# Sort each list in the dict by weekday
for time in rows.keys():
rows[time].sort(key=lambda slot: slot.weekday)
return rows
def get_shift_weekview_columns():
'''Returns a list of weekday name column headers to populate a weekview table with'''
slots = ShiftSlot.objects.all()
if not slots:
return None
cols = []
for slot in slots:
col_header = slot.get_weekday_name()
if col_header not in cols:
cols.append(col_header)
return cols
|
from .models import ShiftSlot, weekday_loc
from website.settings import WORKSHOP_OPEN_DAYS
def get_shift_weekview_rows():
'''Returns a dictionary of shifts for each timeslot, for each weekday'''
slots = ShiftSlot.objects.all()
if not slots:
return None
# Could be troublesome wrt. sorting of dictionary keys. Doesn't *seem* to be an issue right now but it *technically* already is!
rows = {}
for slot in slots:
row_header = '{} -\n{}'.format(slot.start.strftime('%H:%M'), slot.end.strftime('%H:%M'))
if row_header not in rows:
rows[row_header] = []
rows[row_header].append(slot)
# Sort each list in the dict by weekday
for time in rows.keys():
rows[time].sort(key=lambda slot: slot.weekday)
return rows
def get_shift_weekview_columns():
'''Returns a list of weekday name column headers to populate a weekview table with'''
slots = ShiftSlot.objects.all().order_by('weekday')
if not slots:
return None
cols = []
for slot in slots:
col_header = slot.get_weekday_name()
if col_header not in cols:
cols.append(col_header)
return cols
|
Order weekday columns in watchlist
|
Order weekday columns in watchlist
|
Python
|
mit
|
hackerspace-ntnu/website,hackerspace-ntnu/website,hackerspace-ntnu/website
|
from .models import ShiftSlot, weekday_loc
from website.settings import WORKSHOP_OPEN_DAYS
def get_shift_weekview_rows():
'''Returns a dictionary of shifts for each timeslot, for each weekday'''
slots = ShiftSlot.objects.all()
if not slots:
return None
# Could be troublesome wrt. sorting of dictionary keys. Doesn't *seem* to be an issue right now but it *technically* already is!
rows = {}
for slot in slots:
row_header = '{} -\n{}'.format(slot.start.strftime('%H:%M'), slot.end.strftime('%H:%M'))
if row_header not in rows:
rows[row_header] = []
rows[row_header].append(slot)
# Sort each list in the dict by weekday
for time in rows.keys():
rows[time].sort(key=lambda slot: slot.weekday)
return rows
def get_shift_weekview_columns():
'''Returns a list of weekday name column headers to populate a weekview table with'''
- slots = ShiftSlot.objects.all()
+ slots = ShiftSlot.objects.all().order_by('weekday')
if not slots:
return None
cols = []
for slot in slots:
col_header = slot.get_weekday_name()
if col_header not in cols:
cols.append(col_header)
return cols
|
Order weekday columns in watchlist
|
## Code Before:
from .models import ShiftSlot, weekday_loc
from website.settings import WORKSHOP_OPEN_DAYS
def get_shift_weekview_rows():
'''Returns a dictionary of shifts for each timeslot, for each weekday'''
slots = ShiftSlot.objects.all()
if not slots:
return None
# Could be troublesome wrt. sorting of dictionary keys. Doesn't *seem* to be an issue right now but it *technically* already is!
rows = {}
for slot in slots:
row_header = '{} -\n{}'.format(slot.start.strftime('%H:%M'), slot.end.strftime('%H:%M'))
if row_header not in rows:
rows[row_header] = []
rows[row_header].append(slot)
# Sort each list in the dict by weekday
for time in rows.keys():
rows[time].sort(key=lambda slot: slot.weekday)
return rows
def get_shift_weekview_columns():
'''Returns a list of weekday name column headers to populate a weekview table with'''
slots = ShiftSlot.objects.all()
if not slots:
return None
cols = []
for slot in slots:
col_header = slot.get_weekday_name()
if col_header not in cols:
cols.append(col_header)
return cols
## Instruction:
Order weekday columns in watchlist
## Code After:
from .models import ShiftSlot, weekday_loc
from website.settings import WORKSHOP_OPEN_DAYS
def get_shift_weekview_rows():
'''Returns a dictionary of shifts for each timeslot, for each weekday'''
slots = ShiftSlot.objects.all()
if not slots:
return None
# Could be troublesome wrt. sorting of dictionary keys. Doesn't *seem* to be an issue right now but it *technically* already is!
rows = {}
for slot in slots:
row_header = '{} -\n{}'.format(slot.start.strftime('%H:%M'), slot.end.strftime('%H:%M'))
if row_header not in rows:
rows[row_header] = []
rows[row_header].append(slot)
# Sort each list in the dict by weekday
for time in rows.keys():
rows[time].sort(key=lambda slot: slot.weekday)
return rows
def get_shift_weekview_columns():
'''Returns a list of weekday name column headers to populate a weekview table with'''
slots = ShiftSlot.objects.all().order_by('weekday')
if not slots:
return None
cols = []
for slot in slots:
col_header = slot.get_weekday_name()
if col_header not in cols:
cols.append(col_header)
return cols
|
// ... existing code ...
'''Returns a list of weekday name column headers to populate a weekview table with'''
slots = ShiftSlot.objects.all().order_by('weekday')
if not slots:
// ... rest of the code ...
|
7b3f1edc1e9ba120a2718d0001135aa45c7a6753
|
personnel/views.py
|
personnel/views.py
|
'''This app contains the views for the personnel app.
'''
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from personnel.models import Person, JobPosting
class LaboratoryPersonnelList(ListView):
'''This class generates the view for current laboratory personnel located at **/personnel**.
This is filtered based on whether the ::class:`Personnel` object is marked as current_lab_member = True.
'''
queryset = Person.objects.filter(current_lab_member=True)
template_name = "personnel_list.html"
context_object_name = 'personnel'
def get_context_data(self, **kwargs):
'''This method adds to the context the personnel-type = current.'''
context = super(LaboratoryPersonnelList, self).get_context_data(**kwargs)
context['personnel-type'] = "current"
context['postings'] = JobPosting.objects.filter(active=True)
return context
class LaboratoryPersonnelDetail(DetailView):
'''This class generates the view for personnel-details located at **/personnel/<name_slug>**.
'''
model = Person
slug_field = "name_slug"
slug_url_kwarg = "name_slug"
template_name = "personnel_detail.html"
context_object_name = 'person'
|
'''This app contains the views for the personnel app.
'''
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from personnel.models import Person, JobPosting
class LaboratoryPersonnelList(ListView):
'''This class generates the view for current laboratory personnel located at **/personnel**.
This is filtered based on whether the ::class:`Personnel` object is marked as current_lab_member = True.
'''
queryset = Person.objects.filter(current_lab_member=True).order_by('created')
template_name = "personnel_list.html"
context_object_name = 'personnel'
def get_context_data(self, **kwargs):
'''This method adds to the context the personnel-type = current.'''
context = super(LaboratoryPersonnelList, self).get_context_data(**kwargs)
context['personnel-type'] = "current"
context['postings'] = JobPosting.objects.filter(active=True)
return context
class LaboratoryPersonnelDetail(DetailView):
'''This class generates the view for personnel-details located at **/personnel/<name_slug>**.
'''
model = Person
slug_field = "name_slug"
slug_url_kwarg = "name_slug"
template_name = "personnel_detail.html"
context_object_name = 'person'
|
Reset personnel page back to ordering by creation date.
|
Reset personnel page back to ordering by creation date.
|
Python
|
mit
|
davebridges/Lab-Website,davebridges/Lab-Website,davebridges/Lab-Website
|
'''This app contains the views for the personnel app.
'''
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from personnel.models import Person, JobPosting
class LaboratoryPersonnelList(ListView):
'''This class generates the view for current laboratory personnel located at **/personnel**.
This is filtered based on whether the ::class:`Personnel` object is marked as current_lab_member = True.
'''
- queryset = Person.objects.filter(current_lab_member=True)
+ queryset = Person.objects.filter(current_lab_member=True).order_by('created')
template_name = "personnel_list.html"
context_object_name = 'personnel'
def get_context_data(self, **kwargs):
'''This method adds to the context the personnel-type = current.'''
context = super(LaboratoryPersonnelList, self).get_context_data(**kwargs)
context['personnel-type'] = "current"
context['postings'] = JobPosting.objects.filter(active=True)
return context
class LaboratoryPersonnelDetail(DetailView):
'''This class generates the view for personnel-details located at **/personnel/<name_slug>**.
'''
model = Person
slug_field = "name_slug"
slug_url_kwarg = "name_slug"
template_name = "personnel_detail.html"
context_object_name = 'person'
|
Reset personnel page back to ordering by creation date.
|
## Code Before:
'''This app contains the views for the personnel app.
'''
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from personnel.models import Person, JobPosting
class LaboratoryPersonnelList(ListView):
'''This class generates the view for current laboratory personnel located at **/personnel**.
This is filtered based on whether the ::class:`Personnel` object is marked as current_lab_member = True.
'''
queryset = Person.objects.filter(current_lab_member=True)
template_name = "personnel_list.html"
context_object_name = 'personnel'
def get_context_data(self, **kwargs):
'''This method adds to the context the personnel-type = current.'''
context = super(LaboratoryPersonnelList, self).get_context_data(**kwargs)
context['personnel-type'] = "current"
context['postings'] = JobPosting.objects.filter(active=True)
return context
class LaboratoryPersonnelDetail(DetailView):
'''This class generates the view for personnel-details located at **/personnel/<name_slug>**.
'''
model = Person
slug_field = "name_slug"
slug_url_kwarg = "name_slug"
template_name = "personnel_detail.html"
context_object_name = 'person'
## Instruction:
Reset personnel page back to ordering by creation date.
## Code After:
'''This app contains the views for the personnel app.
'''
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from personnel.models import Person, JobPosting
class LaboratoryPersonnelList(ListView):
'''This class generates the view for current laboratory personnel located at **/personnel**.
This is filtered based on whether the ::class:`Personnel` object is marked as current_lab_member = True.
'''
queryset = Person.objects.filter(current_lab_member=True).order_by('created')
template_name = "personnel_list.html"
context_object_name = 'personnel'
def get_context_data(self, **kwargs):
'''This method adds to the context the personnel-type = current.'''
context = super(LaboratoryPersonnelList, self).get_context_data(**kwargs)
context['personnel-type'] = "current"
context['postings'] = JobPosting.objects.filter(active=True)
return context
class LaboratoryPersonnelDetail(DetailView):
'''This class generates the view for personnel-details located at **/personnel/<name_slug>**.
'''
model = Person
slug_field = "name_slug"
slug_url_kwarg = "name_slug"
template_name = "personnel_detail.html"
context_object_name = 'person'
|
# ... existing code ...
'''
queryset = Person.objects.filter(current_lab_member=True).order_by('created')
template_name = "personnel_list.html"
# ... rest of the code ...
|
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()
# -------------------------------------------------------
|
# ... existing code ...
import json
import numpy as np
from scipy.spatial.transform import Rotation as R
# ... modified code ...
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:
...
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))
# ... rest of the code ...
|
c10afc4ebd4d7ec8571c0685c0d87f76b25b3af9
|
scipy/special/_precompute/utils.py
|
scipy/special/_precompute/utils.py
|
try:
import mpmath as mp
except ImportError:
pass
try:
from sympy.abc import x # type: ignore[import]
except ImportError:
pass
def lagrange_inversion(a):
"""Given a series
f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
use the Lagrange inversion formula to compute a series
g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
necessarily b[0] = 0 too.
The algorithm is naive and could be improved, but speed isn't an
issue here and it's easy to read.
"""
n = len(a)
f = sum(a[i]*x**i for i in range(len(a)))
h = (x/f).series(x, 0, n).removeO()
hpower = [h**0]
for k in range(n):
hpower.append((hpower[-1]*h).expand())
b = [mp.mpf(0)]
for k in range(1, n):
b.append(hpower[k].coeff(x, k - 1)/k)
b = map(lambda x: mp.mpf(x), b)
return b
|
try:
import mpmath as mp
except ImportError:
pass
try:
from sympy.abc import x # type: ignore[import]
except ImportError:
pass
def lagrange_inversion(a):
"""Given a series
f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
use the Lagrange inversion formula to compute a series
g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
necessarily b[0] = 0 too.
The algorithm is naive and could be improved, but speed isn't an
issue here and it's easy to read.
"""
n = len(a)
f = sum(a[i]*x**i for i in range(len(a)))
h = (x/f).series(x, 0, n).removeO()
hpower = [h**0]
for k in range(n):
hpower.append((hpower[-1]*h).expand())
b = [mp.mpf(0)]
for k in range(1, n):
b.append(hpower[k].coeff(x, k - 1)/k)
b = [mp.mpf(x) for x in b]
return b
|
Use list comprehension instead of lambda function
|
Use list comprehension instead of lambda function
|
Python
|
bsd-3-clause
|
grlee77/scipy,WarrenWeckesser/scipy,vigna/scipy,endolith/scipy,andyfaff/scipy,rgommers/scipy,scipy/scipy,grlee77/scipy,mdhaber/scipy,Stefan-Endres/scipy,zerothi/scipy,rgommers/scipy,andyfaff/scipy,scipy/scipy,zerothi/scipy,tylerjereddy/scipy,endolith/scipy,mdhaber/scipy,endolith/scipy,rgommers/scipy,mdhaber/scipy,endolith/scipy,e-q/scipy,WarrenWeckesser/scipy,ilayn/scipy,matthew-brett/scipy,anntzer/scipy,scipy/scipy,tylerjereddy/scipy,Eric89GXL/scipy,vigna/scipy,WarrenWeckesser/scipy,perimosocordiae/scipy,andyfaff/scipy,perimosocordiae/scipy,e-q/scipy,andyfaff/scipy,WarrenWeckesser/scipy,tylerjereddy/scipy,grlee77/scipy,tylerjereddy/scipy,anntzer/scipy,matthew-brett/scipy,tylerjereddy/scipy,rgommers/scipy,WarrenWeckesser/scipy,vigna/scipy,matthew-brett/scipy,zerothi/scipy,Stefan-Endres/scipy,endolith/scipy,vigna/scipy,ilayn/scipy,ilayn/scipy,zerothi/scipy,mdhaber/scipy,perimosocordiae/scipy,WarrenWeckesser/scipy,anntzer/scipy,zerothi/scipy,perimosocordiae/scipy,zerothi/scipy,andyfaff/scipy,scipy/scipy,vigna/scipy,anntzer/scipy,e-q/scipy,scipy/scipy,perimosocordiae/scipy,matthew-brett/scipy,Eric89GXL/scipy,grlee77/scipy,mdhaber/scipy,anntzer/scipy,ilayn/scipy,ilayn/scipy,matthew-brett/scipy,anntzer/scipy,grlee77/scipy,Stefan-Endres/scipy,e-q/scipy,ilayn/scipy,scipy/scipy,Eric89GXL/scipy,mdhaber/scipy,endolith/scipy,Eric89GXL/scipy,rgommers/scipy,Eric89GXL/scipy,andyfaff/scipy,Eric89GXL/scipy,Stefan-Endres/scipy,Stefan-Endres/scipy,Stefan-Endres/scipy,perimosocordiae/scipy,e-q/scipy
|
try:
import mpmath as mp
except ImportError:
pass
try:
from sympy.abc import x # type: ignore[import]
except ImportError:
pass
def lagrange_inversion(a):
"""Given a series
f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
use the Lagrange inversion formula to compute a series
g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
necessarily b[0] = 0 too.
The algorithm is naive and could be improved, but speed isn't an
issue here and it's easy to read.
"""
n = len(a)
f = sum(a[i]*x**i for i in range(len(a)))
h = (x/f).series(x, 0, n).removeO()
hpower = [h**0]
for k in range(n):
hpower.append((hpower[-1]*h).expand())
b = [mp.mpf(0)]
for k in range(1, n):
b.append(hpower[k].coeff(x, k - 1)/k)
- b = map(lambda x: mp.mpf(x), b)
+ b = [mp.mpf(x) for x in b]
return b
|
Use list comprehension instead of lambda function
|
## Code Before:
try:
import mpmath as mp
except ImportError:
pass
try:
from sympy.abc import x # type: ignore[import]
except ImportError:
pass
def lagrange_inversion(a):
"""Given a series
f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
use the Lagrange inversion formula to compute a series
g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
necessarily b[0] = 0 too.
The algorithm is naive and could be improved, but speed isn't an
issue here and it's easy to read.
"""
n = len(a)
f = sum(a[i]*x**i for i in range(len(a)))
h = (x/f).series(x, 0, n).removeO()
hpower = [h**0]
for k in range(n):
hpower.append((hpower[-1]*h).expand())
b = [mp.mpf(0)]
for k in range(1, n):
b.append(hpower[k].coeff(x, k - 1)/k)
b = map(lambda x: mp.mpf(x), b)
return b
## Instruction:
Use list comprehension instead of lambda function
## Code After:
try:
import mpmath as mp
except ImportError:
pass
try:
from sympy.abc import x # type: ignore[import]
except ImportError:
pass
def lagrange_inversion(a):
"""Given a series
f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
use the Lagrange inversion formula to compute a series
g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
necessarily b[0] = 0 too.
The algorithm is naive and could be improved, but speed isn't an
issue here and it's easy to read.
"""
n = len(a)
f = sum(a[i]*x**i for i in range(len(a)))
h = (x/f).series(x, 0, n).removeO()
hpower = [h**0]
for k in range(n):
hpower.append((hpower[-1]*h).expand())
b = [mp.mpf(0)]
for k in range(1, n):
b.append(hpower[k].coeff(x, k - 1)/k)
b = [mp.mpf(x) for x in b]
return b
|
// ... existing code ...
b.append(hpower[k].coeff(x, k - 1)/k)
b = [mp.mpf(x) for x in b]
return b
// ... rest of the code ...
|
4e876b59745a67cf1fbcbaacf1ca1675c3e1946a
|
onetime/models.py
|
onetime/models.py
|
from django.db import models
from django.contrib.auth.models import User
class Key(models.Model):
user = models.ForeignKey(User)
key = models.CharField(max_length=40)
created = models.DateTimeField(auto_now_add=True)
usage_left = models.IntegerField(null=True, default=1)
expires = models.DateTimeField(null=True)
next = models.CharField(null=True, max_length=200)
|
from datetime import datetime
from django.db import models
from django.contrib.auth.models import User
class Key(models.Model):
user = models.ForeignKey(User)
key = models.CharField(max_length=40)
created = models.DateTimeField(auto_now_add=True)
usage_left = models.IntegerField(null=True, default=1)
expires = models.DateTimeField(null=True)
next = models.CharField(null=True, max_length=200)
def __unicode__(self):
return '%s (%s)' % (self.key, self.user.username)
def is_valid(self):
if self.usage_left is not None and self.usage_left <= 0:
return False
if self.expires is not None and self.expires < datetime.now():
return False
return True
def update_usage(self):
if self.usage_left is not None:
self.usage_left -= 1
self.save()
|
Add validation and usage logics into the model
|
Add validation and usage logics into the model
|
Python
|
agpl-3.0
|
ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,uploadcare/django-loginurl,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,fajran/django-loginurl,vanschelven/cmsplugin-journal,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website
|
+ from datetime import datetime
+
from django.db import models
from django.contrib.auth.models import User
class Key(models.Model):
user = models.ForeignKey(User)
key = models.CharField(max_length=40)
created = models.DateTimeField(auto_now_add=True)
usage_left = models.IntegerField(null=True, default=1)
expires = models.DateTimeField(null=True)
next = models.CharField(null=True, max_length=200)
+ def __unicode__(self):
+ return '%s (%s)' % (self.key, self.user.username)
+ def is_valid(self):
+ if self.usage_left is not None and self.usage_left <= 0:
+ return False
+ if self.expires is not None and self.expires < datetime.now():
+ return False
+ return True
+
+ def update_usage(self):
+ if self.usage_left is not None:
+ self.usage_left -= 1
+ self.save()
+
+
|
Add validation and usage logics into the model
|
## Code Before:
from django.db import models
from django.contrib.auth.models import User
class Key(models.Model):
user = models.ForeignKey(User)
key = models.CharField(max_length=40)
created = models.DateTimeField(auto_now_add=True)
usage_left = models.IntegerField(null=True, default=1)
expires = models.DateTimeField(null=True)
next = models.CharField(null=True, max_length=200)
## Instruction:
Add validation and usage logics into the model
## Code After:
from datetime import datetime
from django.db import models
from django.contrib.auth.models import User
class Key(models.Model):
user = models.ForeignKey(User)
key = models.CharField(max_length=40)
created = models.DateTimeField(auto_now_add=True)
usage_left = models.IntegerField(null=True, default=1)
expires = models.DateTimeField(null=True)
next = models.CharField(null=True, max_length=200)
def __unicode__(self):
return '%s (%s)' % (self.key, self.user.username)
def is_valid(self):
if self.usage_left is not None and self.usage_left <= 0:
return False
if self.expires is not None and self.expires < datetime.now():
return False
return True
def update_usage(self):
if self.usage_left is not None:
self.usage_left -= 1
self.save()
|
# ... existing code ...
from datetime import datetime
from django.db import models
# ... modified code ...
def __unicode__(self):
return '%s (%s)' % (self.key, self.user.username)
def is_valid(self):
if self.usage_left is not None and self.usage_left <= 0:
return False
if self.expires is not None and self.expires < datetime.now():
return False
return True
def update_usage(self):
if self.usage_left is not None:
self.usage_left -= 1
self.save()
# ... rest of the code ...
|
00c87d7b169119c8d9e5972d47ec9293870f313f
|
gui.py
|
gui.py
|
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class MainWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Text Playing Game")
self.set_border_width(10)
self.set_size_request(500, 400)
win = MainWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
|
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class MainWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Text Playing Game")
self.set_border_width(10)
self.set_size_request(400, 350)
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=20)
box.set_homogeneous(False)
vboxUp = Gtk.Box(spacing=20)
vboxUp.set_homogeneous(False)
vboxBot = Gtk.Box(spacing=20)
vboxBot.set_homogeneous(False)
hboxLeft = Gtk.Box(spacing=20)
hboxLeft.set_homogeneous(False)
hboxRight = Gtk.Box(spacing=20)
hboxRight.set_homogeneous(False)
box.pack_start(vboxUp, True, True, 0)
box.pack_start(vboxBot, True, True, 0)
vboxBot.pack_start(hboxLeft, True, True, 0)
vboxBot.pack_start(hboxRight, True, True, 0)
label = Gtk.Label()
label.set_text("What is your name brave soul?")
label.set_justify(Gtk.Justification.FILL)
vboxUp.pack_start(label, True, True, 0)
self.entry = Gtk.Entry()
hboxLeft.pack_start(self.entry, True, True, 0)
self.button = Gtk.Button(label="Next")
self.button.connect("clicked", self.button_clicked)
hboxRight.pack_start(self.button, True, True, 0)
self.add(box)
def button_clicked(self, widget):
print("Hello")
win = MainWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
|
Set up beginning template - definitely requires changes
|
Set up beginning template -
definitely requires changes
|
Python
|
mit
|
Giovanni21M/Text-Playing-Game
|
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class MainWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Text Playing Game")
self.set_border_width(10)
- self.set_size_request(500, 400)
+ self.set_size_request(400, 350)
+ box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=20)
+ box.set_homogeneous(False)
+
+ vboxUp = Gtk.Box(spacing=20)
+ vboxUp.set_homogeneous(False)
+ vboxBot = Gtk.Box(spacing=20)
+ vboxBot.set_homogeneous(False)
+
+ hboxLeft = Gtk.Box(spacing=20)
+ hboxLeft.set_homogeneous(False)
+ hboxRight = Gtk.Box(spacing=20)
+ hboxRight.set_homogeneous(False)
+
+ box.pack_start(vboxUp, True, True, 0)
+ box.pack_start(vboxBot, True, True, 0)
+
+ vboxBot.pack_start(hboxLeft, True, True, 0)
+ vboxBot.pack_start(hboxRight, True, True, 0)
+
+ label = Gtk.Label()
+ label.set_text("What is your name brave soul?")
+ label.set_justify(Gtk.Justification.FILL)
+ vboxUp.pack_start(label, True, True, 0)
+
+ self.entry = Gtk.Entry()
+ hboxLeft.pack_start(self.entry, True, True, 0)
+
+ self.button = Gtk.Button(label="Next")
+ self.button.connect("clicked", self.button_clicked)
+ hboxRight.pack_start(self.button, True, True, 0)
+
+ self.add(box)
+
+ def button_clicked(self, widget):
+ print("Hello")
+
win = MainWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
|
Set up beginning template - definitely requires changes
|
## Code Before:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class MainWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Text Playing Game")
self.set_border_width(10)
self.set_size_request(500, 400)
win = MainWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
## Instruction:
Set up beginning template - definitely requires changes
## Code After:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class MainWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Text Playing Game")
self.set_border_width(10)
self.set_size_request(400, 350)
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=20)
box.set_homogeneous(False)
vboxUp = Gtk.Box(spacing=20)
vboxUp.set_homogeneous(False)
vboxBot = Gtk.Box(spacing=20)
vboxBot.set_homogeneous(False)
hboxLeft = Gtk.Box(spacing=20)
hboxLeft.set_homogeneous(False)
hboxRight = Gtk.Box(spacing=20)
hboxRight.set_homogeneous(False)
box.pack_start(vboxUp, True, True, 0)
box.pack_start(vboxBot, True, True, 0)
vboxBot.pack_start(hboxLeft, True, True, 0)
vboxBot.pack_start(hboxRight, True, True, 0)
label = Gtk.Label()
label.set_text("What is your name brave soul?")
label.set_justify(Gtk.Justification.FILL)
vboxUp.pack_start(label, True, True, 0)
self.entry = Gtk.Entry()
hboxLeft.pack_start(self.entry, True, True, 0)
self.button = Gtk.Button(label="Next")
self.button.connect("clicked", self.button_clicked)
hboxRight.pack_start(self.button, True, True, 0)
self.add(box)
def button_clicked(self, widget):
print("Hello")
win = MainWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
|
...
self.set_border_width(10)
self.set_size_request(400, 350)
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=20)
box.set_homogeneous(False)
vboxUp = Gtk.Box(spacing=20)
vboxUp.set_homogeneous(False)
vboxBot = Gtk.Box(spacing=20)
vboxBot.set_homogeneous(False)
hboxLeft = Gtk.Box(spacing=20)
hboxLeft.set_homogeneous(False)
hboxRight = Gtk.Box(spacing=20)
hboxRight.set_homogeneous(False)
box.pack_start(vboxUp, True, True, 0)
box.pack_start(vboxBot, True, True, 0)
vboxBot.pack_start(hboxLeft, True, True, 0)
vboxBot.pack_start(hboxRight, True, True, 0)
label = Gtk.Label()
label.set_text("What is your name brave soul?")
label.set_justify(Gtk.Justification.FILL)
vboxUp.pack_start(label, True, True, 0)
self.entry = Gtk.Entry()
hboxLeft.pack_start(self.entry, True, True, 0)
self.button = Gtk.Button(label="Next")
self.button.connect("clicked", self.button_clicked)
hboxRight.pack_start(self.button, True, True, 0)
self.add(box)
def button_clicked(self, widget):
print("Hello")
...
|
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)
|
...
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)
...
|
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'
|
# ... existing code ...
# ... modified code ...
from bae.core import const
import bae_secrets
DATABASES = {
# ... rest of the code ...
|
d6929fa152bb8149fa9b4033135441030dd71260
|
authentic2/idp/idp_openid/context_processors.py
|
authentic2/idp/idp_openid/context_processors.py
|
def get_url():
return reverse('openid-provider-xrds')
def openid_meta(request):
context = {
'openid_server': context['request'].build_absolute_uri(get_url())
}
content = '''<meta http-equiv="X-XRDS-Location" content="%(openid_server)s"/>
<meta http-equiv="X-YADIS-Location" content="%(openid_server)s" />
''' % context
return { 'openid_meta': context }
|
from django.core.urlresolvers import reverse
def get_url():
return reverse('openid-provider-xrds')
def openid_meta(request):
context = {
'openid_server': request.build_absolute_uri(get_url())
}
content = '''<meta http-equiv="X-XRDS-Location" content="%(openid_server)s"/>
<meta http-equiv="X-YADIS-Location" content="%(openid_server)s" />
''' % context
return { 'openid_meta': content }
|
Remove dependency on openid in the base template (bis)
|
Remove dependency on openid in the base template (bis)
Fixes #1357
|
Python
|
agpl-3.0
|
BryceLohr/authentic,BryceLohr/authentic,incuna/authentic,incuna/authentic,adieu/authentic2,incuna/authentic,adieu/authentic2,adieu/authentic2,BryceLohr/authentic,pu239ppy/authentic2,adieu/authentic2,pu239ppy/authentic2,BryceLohr/authentic,pu239ppy/authentic2,incuna/authentic,pu239ppy/authentic2,incuna/authentic
|
+ from django.core.urlresolvers import reverse
+
def get_url():
return reverse('openid-provider-xrds')
def openid_meta(request):
context = {
- 'openid_server': context['request'].build_absolute_uri(get_url())
+ 'openid_server': request.build_absolute_uri(get_url())
}
content = '''<meta http-equiv="X-XRDS-Location" content="%(openid_server)s"/>
<meta http-equiv="X-YADIS-Location" content="%(openid_server)s" />
''' % context
- return { 'openid_meta': context }
+ return { 'openid_meta': content }
|
Remove dependency on openid in the base template (bis)
|
## Code Before:
def get_url():
return reverse('openid-provider-xrds')
def openid_meta(request):
context = {
'openid_server': context['request'].build_absolute_uri(get_url())
}
content = '''<meta http-equiv="X-XRDS-Location" content="%(openid_server)s"/>
<meta http-equiv="X-YADIS-Location" content="%(openid_server)s" />
''' % context
return { 'openid_meta': context }
## Instruction:
Remove dependency on openid in the base template (bis)
## Code After:
from django.core.urlresolvers import reverse
def get_url():
return reverse('openid-provider-xrds')
def openid_meta(request):
context = {
'openid_server': request.build_absolute_uri(get_url())
}
content = '''<meta http-equiv="X-XRDS-Location" content="%(openid_server)s"/>
<meta http-equiv="X-YADIS-Location" content="%(openid_server)s" />
''' % context
return { 'openid_meta': content }
|
...
from django.core.urlresolvers import reverse
def get_url():
...
context = {
'openid_server': request.build_absolute_uri(get_url())
}
...
''' % context
return { 'openid_meta': content }
...
|
62bbc01940e85e6017b4b5d4e757437b05c81f71
|
evaluation_system/reports/views.py
|
evaluation_system/reports/views.py
|
from django.shortcuts import render
from django.views.generic import TemplateView
from django.shortcuts import redirect
from ..evaluation.models import Evaluation, Group_User
class showProfessorReport(TemplateView):
template_name= "report/professorReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "professor":
return redirect("/")
context = self.get_context_data(**kwargs)
context["evaluations"] = Evaluation.objects.filter(course__professor = request.user)
return self.render_to_response(context)
class showStudentReport(TemplateView):
template_name= "report/studentReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "student":
return redirect("/")
context = self.get_context_data(**kwargs)
group = Group_User.objects.filter(student = request.user)
context["group"] = group
if not group:
context['error'] = "You're not assigned to any courses"
return self.render_to_response(context)
|
from django.shortcuts import render
from django.views.generic import TemplateView
from django.shortcuts import redirect
from ..evaluation.models import Evaluation, Group_User
class showProfessorReport(TemplateView):
template_name= "report/professorReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "professor":
return redirect("/")
context = self.get_context_data(**kwargs)
context["evaluations"] = Evaluation.objects.filter(course__professor = request.user, created_by = request.user.id)
return self.render_to_response(context)
class showStudentReport(TemplateView):
template_name= "report/studentReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "student":
return redirect("/")
context = self.get_context_data(**kwargs)
group = Group_User.objects.filter(student = request.user)
context["group"] = group
if not group:
context['error'] = "You're not assigned to any courses"
return self.render_to_response(context)
|
Fix evaluation query on report
|
Fix evaluation query on report
|
Python
|
mit
|
carlosa54/evaluation_system,carlosa54/evaluation_system,carlosa54/evaluation_system
|
from django.shortcuts import render
from django.views.generic import TemplateView
from django.shortcuts import redirect
from ..evaluation.models import Evaluation, Group_User
class showProfessorReport(TemplateView):
template_name= "report/professorReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "professor":
return redirect("/")
context = self.get_context_data(**kwargs)
- context["evaluations"] = Evaluation.objects.filter(course__professor = request.user)
+ context["evaluations"] = Evaluation.objects.filter(course__professor = request.user, created_by = request.user.id)
return self.render_to_response(context)
class showStudentReport(TemplateView):
template_name= "report/studentReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "student":
return redirect("/")
context = self.get_context_data(**kwargs)
group = Group_User.objects.filter(student = request.user)
context["group"] = group
if not group:
context['error'] = "You're not assigned to any courses"
return self.render_to_response(context)
|
Fix evaluation query on report
|
## Code Before:
from django.shortcuts import render
from django.views.generic import TemplateView
from django.shortcuts import redirect
from ..evaluation.models import Evaluation, Group_User
class showProfessorReport(TemplateView):
template_name= "report/professorReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "professor":
return redirect("/")
context = self.get_context_data(**kwargs)
context["evaluations"] = Evaluation.objects.filter(course__professor = request.user)
return self.render_to_response(context)
class showStudentReport(TemplateView):
template_name= "report/studentReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "student":
return redirect("/")
context = self.get_context_data(**kwargs)
group = Group_User.objects.filter(student = request.user)
context["group"] = group
if not group:
context['error'] = "You're not assigned to any courses"
return self.render_to_response(context)
## Instruction:
Fix evaluation query on report
## Code After:
from django.shortcuts import render
from django.views.generic import TemplateView
from django.shortcuts import redirect
from ..evaluation.models import Evaluation, Group_User
class showProfessorReport(TemplateView):
template_name= "report/professorReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "professor":
return redirect("/")
context = self.get_context_data(**kwargs)
context["evaluations"] = Evaluation.objects.filter(course__professor = request.user, created_by = request.user.id)
return self.render_to_response(context)
class showStudentReport(TemplateView):
template_name= "report/studentReport.html"
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated():
return redirect("/login")
if not request.user.type == "student":
return redirect("/")
context = self.get_context_data(**kwargs)
group = Group_User.objects.filter(student = request.user)
context["group"] = group
if not group:
context['error'] = "You're not assigned to any courses"
return self.render_to_response(context)
|
# ... existing code ...
context["evaluations"] = Evaluation.objects.filter(course__professor = request.user, created_by = request.user.id)
# ... rest of the code ...
|
389ca2213c2ba3c86c783372e3e933a12f90506e
|
ckanext/requestdata/controllers/admin.py
|
ckanext/requestdata/controllers/admin.py
|
from ckan.lib import base
from ckan import logic
from ckan.plugins import toolkit
get_action = logic.get_action
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
redirect = base.redirect
abort = base.abort
BaseController = base.BaseController
class AdminController(BaseController):
def email(self):
'''Email template admin tab.
:param :
:type
'''
return toolkit.render('admin/email.html')
def requests_data(self):
'''
Return all of the data requests in admin panel
:return:
'''
return toolkit.render('admin/all_requests_data.html')
|
from ckan.lib import base
from ckan import logic
from ckan.plugins import toolkit
from ckan.controllers.admin import AdminController
get_action = logic.get_action
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
redirect = base.redirect
abort = base.abort
BaseController = base.BaseController
class AdminController(AdminController):
def email(self):
'''Email template admin tab.
:param :
:type
'''
return toolkit.render('admin/email.html')
def requests_data(self):
'''
Return all of the data requests in admin panel
:return:
'''
return toolkit.render('admin/all_requests_data.html')
|
Extend Admin instead of Base controller
|
Extend Admin instead of Base controller
|
Python
|
agpl-3.0
|
ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata
|
from ckan.lib import base
from ckan import logic
from ckan.plugins import toolkit
+ from ckan.controllers.admin import AdminController
get_action = logic.get_action
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
redirect = base.redirect
abort = base.abort
BaseController = base.BaseController
- class AdminController(BaseController):
+ class AdminController(AdminController):
def email(self):
'''Email template admin tab.
:param :
:type
'''
return toolkit.render('admin/email.html')
def requests_data(self):
'''
Return all of the data requests in admin panel
:return:
'''
return toolkit.render('admin/all_requests_data.html')
|
Extend Admin instead of Base controller
|
## Code Before:
from ckan.lib import base
from ckan import logic
from ckan.plugins import toolkit
get_action = logic.get_action
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
redirect = base.redirect
abort = base.abort
BaseController = base.BaseController
class AdminController(BaseController):
def email(self):
'''Email template admin tab.
:param :
:type
'''
return toolkit.render('admin/email.html')
def requests_data(self):
'''
Return all of the data requests in admin panel
:return:
'''
return toolkit.render('admin/all_requests_data.html')
## Instruction:
Extend Admin instead of Base controller
## Code After:
from ckan.lib import base
from ckan import logic
from ckan.plugins import toolkit
from ckan.controllers.admin import AdminController
get_action = logic.get_action
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
redirect = base.redirect
abort = base.abort
BaseController = base.BaseController
class AdminController(AdminController):
def email(self):
'''Email template admin tab.
:param :
:type
'''
return toolkit.render('admin/email.html')
def requests_data(self):
'''
Return all of the data requests in admin panel
:return:
'''
return toolkit.render('admin/all_requests_data.html')
|
...
from ckan.plugins import toolkit
from ckan.controllers.admin import AdminController
...
class AdminController(AdminController):
...
|
b4578d34adaa641dab5082f9d2bffe14c69649c5
|
detour/__init__.py
|
detour/__init__.py
|
from __future__ import absolute_import
from __future__ import unicode_literals
__version_info__ = '0.1.0'
__version__ = '0.1.0'
version = '0.1.0'
VERSION = '0.1.0'
def get_version():
return version # pragma: no cover
|
from __future__ import absolute_import
from __future__ import unicode_literals
__version_info__ = '0.1.0'
__version__ = '0.1.0'
version = '0.1.0'
VERSION = '0.1.0'
def get_version():
return version # pragma: no cover
class DetourException(NotImplementedError):
pass
|
Add a root exception for use if necessary.
|
Add a root exception for use if necessary.
|
Python
|
bsd-2-clause
|
kezabelle/wsgi-detour
|
from __future__ import absolute_import
from __future__ import unicode_literals
__version_info__ = '0.1.0'
__version__ = '0.1.0'
version = '0.1.0'
VERSION = '0.1.0'
def get_version():
return version # pragma: no cover
+
+ class DetourException(NotImplementedError):
+ pass
+
|
Add a root exception for use if necessary.
|
## Code Before:
from __future__ import absolute_import
from __future__ import unicode_literals
__version_info__ = '0.1.0'
__version__ = '0.1.0'
version = '0.1.0'
VERSION = '0.1.0'
def get_version():
return version # pragma: no cover
## Instruction:
Add a root exception for use if necessary.
## Code After:
from __future__ import absolute_import
from __future__ import unicode_literals
__version_info__ = '0.1.0'
__version__ = '0.1.0'
version = '0.1.0'
VERSION = '0.1.0'
def get_version():
return version # pragma: no cover
class DetourException(NotImplementedError):
pass
|
...
return version # pragma: no cover
class DetourException(NotImplementedError):
pass
...
|
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'),
)
|
# ... existing code ...
from rest_frmaework_nested import routers
from authentication_app.views import AccountViewSet
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
# ... modified code ...
urlpatterns = patterns('',
# APIendpoints
url(r'^api/v1/', include(router.urls)),
url('^.*$', IndexView.as_view(), name='index'),
)
# ... rest of the code ...
|
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")]
|
# ... existing code ...
class GVG_104:
def OWN_CARD_PLAYED(self, card):
if card.type == CardType.MINION and card.atk == 1:
return [Buff(card, "GVG_104a")]
# ... rest of the code ...
|
e0b7217caaf4b94c879f43f2ee95584c469687db
|
csrv/model/read_o8d.py
|
csrv/model/read_o8d.py
|
from xml.etree import ElementTree
def read_file(filename):
filedata = open(filename).read()
return read(filedata)
def read(filedata):
root = ElementTree.fromstring(filedata)
identity = []
cards = []
for section in root.getchildren():
if len(section) == 1:
dest = identity
else:
dest = cards
for card in section.getchildren():
for i in range(int(card.get('qty'))):
dest.append(card.text)
return (identity[0], cards)
|
from xml.etree import ElementTree
def read_file(filename):
filedata = open(filename).read()
return read(filedata)
def read(filedata):
root = ElementTree.fromstring(filedata)
identity = []
cards = []
for section in root.getchildren():
if len(section) == 1:
dest = identity
else:
dest = cards
for card in section.getchildren():
for i in range(int(card.get('qty'))):
# Read the last 5 digits of card#id
dest.append("Card{}".format(card.get('id')[-5:]))
return (identity[0], cards)
|
Fix o8d importer to read card IDs to make the sanitized cards
|
Fix o8d importer to read card IDs to make the sanitized cards
|
Python
|
apache-2.0
|
mrroach/CentralServer,mrroach/CentralServer,mrroach/CentralServer
|
from xml.etree import ElementTree
def read_file(filename):
filedata = open(filename).read()
return read(filedata)
def read(filedata):
root = ElementTree.fromstring(filedata)
identity = []
cards = []
for section in root.getchildren():
if len(section) == 1:
dest = identity
else:
dest = cards
for card in section.getchildren():
for i in range(int(card.get('qty'))):
- dest.append(card.text)
+ # Read the last 5 digits of card#id
+ dest.append("Card{}".format(card.get('id')[-5:]))
return (identity[0], cards)
|
Fix o8d importer to read card IDs to make the sanitized cards
|
## Code Before:
from xml.etree import ElementTree
def read_file(filename):
filedata = open(filename).read()
return read(filedata)
def read(filedata):
root = ElementTree.fromstring(filedata)
identity = []
cards = []
for section in root.getchildren():
if len(section) == 1:
dest = identity
else:
dest = cards
for card in section.getchildren():
for i in range(int(card.get('qty'))):
dest.append(card.text)
return (identity[0], cards)
## Instruction:
Fix o8d importer to read card IDs to make the sanitized cards
## Code After:
from xml.etree import ElementTree
def read_file(filename):
filedata = open(filename).read()
return read(filedata)
def read(filedata):
root = ElementTree.fromstring(filedata)
identity = []
cards = []
for section in root.getchildren():
if len(section) == 1:
dest = identity
else:
dest = cards
for card in section.getchildren():
for i in range(int(card.get('qty'))):
# Read the last 5 digits of card#id
dest.append("Card{}".format(card.get('id')[-5:]))
return (identity[0], cards)
|
// ... existing code ...
for i in range(int(card.get('qty'))):
# Read the last 5 digits of card#id
dest.append("Card{}".format(card.get('id')[-5:]))
return (identity[0], cards)
// ... rest of the code ...
|
a5ff4c247030559c83a06976fcda062c0c42d810
|
django_fixmystreet/fixmystreet/tests/__init__.py
|
django_fixmystreet/fixmystreet/tests/__init__.py
|
import shutil
import os
from django.core.files.storage import default_storage
from django.test import TestCase
class SampleFilesTestCase(TestCase):
fixtures = ['sample']
@classmethod
def setUpClass(cls):
default_storage.location = 'media' # force using source media folder to avoid real data erasing
# @classmethod
# def setUpClass(cls):
# shutil.copytree('media', 'media-tmp')
# default_storage.location = 'media-tmp'
#
# @classmethod
# def tearDownClass(self):
# shutil.rmtree('media-tmp')
def _fixture_setup(self):
if os.path.exists('media/photos'):
shutil.rmtree('media/photos')
shutil.copytree('media/photos-sample', 'media/photos')
super(SampleFilesTestCase, self)._fixture_setup()
def tearDown(self):
shutil.rmtree('media/photos')
from django_fixmystreet.fixmystreet.tests.views import *
from django_fixmystreet.fixmystreet.tests.reports import *
from django_fixmystreet.fixmystreet.tests.users import *
from django_fixmystreet.fixmystreet.tests.organisation_entity import *
from django_fixmystreet.fixmystreet.tests.mail import *
# from django_fixmystreet.fixmystreet.tests.api import *
|
import shutil
import os
from django.core.files.storage import default_storage
from django.test import TestCase
class SampleFilesTestCase(TestCase):
fixtures = ['sample']
@classmethod
def setUpClass(cls):
default_storage.location = 'media' # force using source media folder to avoid real data erasing
# @classmethod
# def setUpClass(cls):
# shutil.copytree('media', 'media-tmp')
# default_storage.location = 'media-tmp'
#
# @classmethod
# def tearDownClass(self):
# shutil.rmtree('media-tmp')
def _fixture_setup(self):
if os.path.exists('media/photos'):
shutil.rmtree('media/photos')
shutil.copytree('media/photos-sample', 'media/photos')
super(SampleFilesTestCase, self)._fixture_setup()
from django_fixmystreet.fixmystreet.tests.views import *
from django_fixmystreet.fixmystreet.tests.reports import *
from django_fixmystreet.fixmystreet.tests.users import *
from django_fixmystreet.fixmystreet.tests.organisation_entity import *
from django_fixmystreet.fixmystreet.tests.mail import *
# from django_fixmystreet.fixmystreet.tests.api import *
|
Fix unit test fixtures files
|
Fix unit test fixtures files
|
Python
|
agpl-3.0
|
IMIO/django-fixmystreet,IMIO/django-fixmystreet,IMIO/django-fixmystreet,IMIO/django-fixmystreet
|
import shutil
import os
from django.core.files.storage import default_storage
from django.test import TestCase
class SampleFilesTestCase(TestCase):
fixtures = ['sample']
@classmethod
def setUpClass(cls):
default_storage.location = 'media' # force using source media folder to avoid real data erasing
# @classmethod
# def setUpClass(cls):
# shutil.copytree('media', 'media-tmp')
# default_storage.location = 'media-tmp'
#
# @classmethod
# def tearDownClass(self):
# shutil.rmtree('media-tmp')
def _fixture_setup(self):
if os.path.exists('media/photos'):
shutil.rmtree('media/photos')
shutil.copytree('media/photos-sample', 'media/photos')
super(SampleFilesTestCase, self)._fixture_setup()
- def tearDown(self):
- shutil.rmtree('media/photos')
from django_fixmystreet.fixmystreet.tests.views import *
from django_fixmystreet.fixmystreet.tests.reports import *
from django_fixmystreet.fixmystreet.tests.users import *
from django_fixmystreet.fixmystreet.tests.organisation_entity import *
from django_fixmystreet.fixmystreet.tests.mail import *
# from django_fixmystreet.fixmystreet.tests.api import *
|
Fix unit test fixtures files
|
## Code Before:
import shutil
import os
from django.core.files.storage import default_storage
from django.test import TestCase
class SampleFilesTestCase(TestCase):
fixtures = ['sample']
@classmethod
def setUpClass(cls):
default_storage.location = 'media' # force using source media folder to avoid real data erasing
# @classmethod
# def setUpClass(cls):
# shutil.copytree('media', 'media-tmp')
# default_storage.location = 'media-tmp'
#
# @classmethod
# def tearDownClass(self):
# shutil.rmtree('media-tmp')
def _fixture_setup(self):
if os.path.exists('media/photos'):
shutil.rmtree('media/photos')
shutil.copytree('media/photos-sample', 'media/photos')
super(SampleFilesTestCase, self)._fixture_setup()
def tearDown(self):
shutil.rmtree('media/photos')
from django_fixmystreet.fixmystreet.tests.views import *
from django_fixmystreet.fixmystreet.tests.reports import *
from django_fixmystreet.fixmystreet.tests.users import *
from django_fixmystreet.fixmystreet.tests.organisation_entity import *
from django_fixmystreet.fixmystreet.tests.mail import *
# from django_fixmystreet.fixmystreet.tests.api import *
## Instruction:
Fix unit test fixtures files
## Code After:
import shutil
import os
from django.core.files.storage import default_storage
from django.test import TestCase
class SampleFilesTestCase(TestCase):
fixtures = ['sample']
@classmethod
def setUpClass(cls):
default_storage.location = 'media' # force using source media folder to avoid real data erasing
# @classmethod
# def setUpClass(cls):
# shutil.copytree('media', 'media-tmp')
# default_storage.location = 'media-tmp'
#
# @classmethod
# def tearDownClass(self):
# shutil.rmtree('media-tmp')
def _fixture_setup(self):
if os.path.exists('media/photos'):
shutil.rmtree('media/photos')
shutil.copytree('media/photos-sample', 'media/photos')
super(SampleFilesTestCase, self)._fixture_setup()
from django_fixmystreet.fixmystreet.tests.views import *
from django_fixmystreet.fixmystreet.tests.reports import *
from django_fixmystreet.fixmystreet.tests.users import *
from django_fixmystreet.fixmystreet.tests.organisation_entity import *
from django_fixmystreet.fixmystreet.tests.mail import *
# from django_fixmystreet.fixmystreet.tests.api import *
|
...
...
|
8c1b7f8a5a7403e464938aa0aa6876557ec6a2b3
|
daphne/server.py
|
daphne/server.py
|
import time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
class Server(object):
def __init__(self, channel_layer, host="127.0.0.1", port=8000):
self.channel_layer = channel_layer
self.host = host
self.port = port
def run(self):
self.factory = HTTPFactory(self.channel_layer)
reactor.listenTCP(self.port, self.factory, interface=self.host)
reactor.callInThread(self.backend_reader)
reactor.run()
def backend_reader(self):
"""
Run in a separate thread; reads messages from the backend.
"""
while True:
channels = self.factory.reply_channels()
# Quit if reactor is stopping
if not reactor.running:
return
# Don't do anything if there's no channels to listen on
if channels:
channel, message = self.channel_layer.receive_many(channels, block=True)
else:
time.sleep(0.1)
continue
# Wait around if there's nothing received
if channel is None:
time.sleep(0.05)
continue
# Deal with the message
self.factory.dispatch_reply(channel, message)
|
import time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
class Server(object):
def __init__(self, channel_layer, host="127.0.0.1", port=8000, signal_handlers=True):
self.channel_layer = channel_layer
self.host = host
self.port = port
self.signal_handlers = signal_handlers
def run(self):
self.factory = HTTPFactory(self.channel_layer)
reactor.listenTCP(self.port, self.factory, interface=self.host)
reactor.callInThread(self.backend_reader)
reactor.run(installSignalHandlers=self.signal_handlers)
def backend_reader(self):
"""
Run in a separate thread; reads messages from the backend.
"""
while True:
channels = self.factory.reply_channels()
# Quit if reactor is stopping
if not reactor.running:
return
# Don't do anything if there's no channels to listen on
if channels:
channel, message = self.channel_layer.receive_many(channels, block=True)
else:
time.sleep(0.1)
continue
# Wait around if there's nothing received
if channel is None:
time.sleep(0.05)
continue
# Deal with the message
self.factory.dispatch_reply(channel, message)
|
Allow signal handlers to be disabled to run in subthread
|
Allow signal handlers to be disabled to run in subthread
|
Python
|
bsd-3-clause
|
django/daphne,maikhoepfel/daphne
|
import time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
class Server(object):
- def __init__(self, channel_layer, host="127.0.0.1", port=8000):
+ def __init__(self, channel_layer, host="127.0.0.1", port=8000, signal_handlers=True):
self.channel_layer = channel_layer
self.host = host
self.port = port
+ self.signal_handlers = signal_handlers
def run(self):
self.factory = HTTPFactory(self.channel_layer)
reactor.listenTCP(self.port, self.factory, interface=self.host)
reactor.callInThread(self.backend_reader)
- reactor.run()
+ reactor.run(installSignalHandlers=self.signal_handlers)
def backend_reader(self):
"""
Run in a separate thread; reads messages from the backend.
"""
while True:
channels = self.factory.reply_channels()
# Quit if reactor is stopping
if not reactor.running:
return
# Don't do anything if there's no channels to listen on
if channels:
channel, message = self.channel_layer.receive_many(channels, block=True)
else:
time.sleep(0.1)
continue
# Wait around if there's nothing received
if channel is None:
time.sleep(0.05)
continue
# Deal with the message
self.factory.dispatch_reply(channel, message)
|
Allow signal handlers to be disabled to run in subthread
|
## Code Before:
import time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
class Server(object):
def __init__(self, channel_layer, host="127.0.0.1", port=8000):
self.channel_layer = channel_layer
self.host = host
self.port = port
def run(self):
self.factory = HTTPFactory(self.channel_layer)
reactor.listenTCP(self.port, self.factory, interface=self.host)
reactor.callInThread(self.backend_reader)
reactor.run()
def backend_reader(self):
"""
Run in a separate thread; reads messages from the backend.
"""
while True:
channels = self.factory.reply_channels()
# Quit if reactor is stopping
if not reactor.running:
return
# Don't do anything if there's no channels to listen on
if channels:
channel, message = self.channel_layer.receive_many(channels, block=True)
else:
time.sleep(0.1)
continue
# Wait around if there's nothing received
if channel is None:
time.sleep(0.05)
continue
# Deal with the message
self.factory.dispatch_reply(channel, message)
## Instruction:
Allow signal handlers to be disabled to run in subthread
## Code After:
import time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
class Server(object):
def __init__(self, channel_layer, host="127.0.0.1", port=8000, signal_handlers=True):
self.channel_layer = channel_layer
self.host = host
self.port = port
self.signal_handlers = signal_handlers
def run(self):
self.factory = HTTPFactory(self.channel_layer)
reactor.listenTCP(self.port, self.factory, interface=self.host)
reactor.callInThread(self.backend_reader)
reactor.run(installSignalHandlers=self.signal_handlers)
def backend_reader(self):
"""
Run in a separate thread; reads messages from the backend.
"""
while True:
channels = self.factory.reply_channels()
# Quit if reactor is stopping
if not reactor.running:
return
# Don't do anything if there's no channels to listen on
if channels:
channel, message = self.channel_layer.receive_many(channels, block=True)
else:
time.sleep(0.1)
continue
# Wait around if there's nothing received
if channel is None:
time.sleep(0.05)
continue
# Deal with the message
self.factory.dispatch_reply(channel, message)
|
...
def __init__(self, channel_layer, host="127.0.0.1", port=8000, signal_handlers=True):
self.channel_layer = channel_layer
...
self.port = port
self.signal_handlers = signal_handlers
...
reactor.callInThread(self.backend_reader)
reactor.run(installSignalHandlers=self.signal_handlers)
...
|
75615b2328e521b6bb37321d1cd7dc75c4d3bfef
|
hecate/core/topology/border.py
|
hecate/core/topology/border.py
|
from hecate.core.topology.mixins import DimensionsMixin
class Border(DimensionsMixin):
"""
Base class for all types of borders.
"""
def __init__(self):
self.topology = None
class TorusBorder(Border):
supported_dimensions = list(range(1, 100))
def wrap_coords(self, coord_prefix):
code = ""
for i in range(self.dimensions):
code += "{x}{i} %= {w}{i};\n".format(
x=coord_prefix, i=i,
w=self.topology.lattice.width_prefix
)
return code
|
from hecate.core.topology.mixins import DimensionsMixin
class Border(DimensionsMixin):
"""
Base class for all types of borders.
"""
def __init__(self):
self.topology = None
class TorusBorder(Border):
supported_dimensions = list(range(1, 100))
def wrap_coords(self, coord_prefix):
code = ""
for i in range(self.dimensions):
code += "{x}{i} = ({x}{i} + {w}{i}) % {w}{i};\n".format(
x=coord_prefix, i=i,
w=self.topology.lattice.width_prefix
)
return code
|
Fix incorrect TorusBorder wrapping in negative direction
|
Fix incorrect TorusBorder wrapping in negative direction
|
Python
|
mit
|
a5kin/hecate,a5kin/hecate
|
from hecate.core.topology.mixins import DimensionsMixin
class Border(DimensionsMixin):
"""
Base class for all types of borders.
"""
def __init__(self):
self.topology = None
class TorusBorder(Border):
supported_dimensions = list(range(1, 100))
def wrap_coords(self, coord_prefix):
code = ""
for i in range(self.dimensions):
- code += "{x}{i} %= {w}{i};\n".format(
+ code += "{x}{i} = ({x}{i} + {w}{i}) % {w}{i};\n".format(
x=coord_prefix, i=i,
w=self.topology.lattice.width_prefix
)
return code
|
Fix incorrect TorusBorder wrapping in negative direction
|
## Code Before:
from hecate.core.topology.mixins import DimensionsMixin
class Border(DimensionsMixin):
"""
Base class for all types of borders.
"""
def __init__(self):
self.topology = None
class TorusBorder(Border):
supported_dimensions = list(range(1, 100))
def wrap_coords(self, coord_prefix):
code = ""
for i in range(self.dimensions):
code += "{x}{i} %= {w}{i};\n".format(
x=coord_prefix, i=i,
w=self.topology.lattice.width_prefix
)
return code
## Instruction:
Fix incorrect TorusBorder wrapping in negative direction
## Code After:
from hecate.core.topology.mixins import DimensionsMixin
class Border(DimensionsMixin):
"""
Base class for all types of borders.
"""
def __init__(self):
self.topology = None
class TorusBorder(Border):
supported_dimensions = list(range(1, 100))
def wrap_coords(self, coord_prefix):
code = ""
for i in range(self.dimensions):
code += "{x}{i} = ({x}{i} + {w}{i}) % {w}{i};\n".format(
x=coord_prefix, i=i,
w=self.topology.lattice.width_prefix
)
return code
|
// ... existing code ...
for i in range(self.dimensions):
code += "{x}{i} = ({x}{i} + {w}{i}) % {w}{i};\n".format(
x=coord_prefix, i=i,
// ... rest of the code ...
|
0e7be2adf1101ae842dddb3db3217957a8e5957f
|
iati/core/rulesets.py
|
iati/core/rulesets.py
|
"""A module containg a core representation of IATI Rulesets."""
class Ruleset(object):
"""Representation of a Ruleset as defined within the IATI SSOT."""
pass
class Rule(object):
"""Representation of a Rule contained within a Ruleset.
Acts as a base class for specific types of Rule that actually do something.
"""
pass
class NoMoreThanOne(Rule):
"""Representation of a Rule that checks that there is no more than one Element matching a given XPath."""
pass
|
class Ruleset(object):
"""Representation of a Ruleset as defined within the IATI SSOT."""
pass
class Rule(object):
"""Representation of a Rule contained within a Ruleset.
Acts as a base class for specific types of Rule that actually do something.
"""
pass
class NoMoreThanOne(Rule):
"""Representation of a Rule that checks that there is no more than one Element matching a given XPath."""
pass
|
Add a ruleset module TODO
|
Add a ruleset module TODO
|
Python
|
mit
|
IATI/iati.core,IATI/iati.core
|
- """A module containg a core representation of IATI Rulesets."""
class Ruleset(object):
"""Representation of a Ruleset as defined within the IATI SSOT."""
pass
class Rule(object):
"""Representation of a Rule contained within a Ruleset.
Acts as a base class for specific types of Rule that actually do something.
"""
pass
class NoMoreThanOne(Rule):
"""Representation of a Rule that checks that there is no more than one Element matching a given XPath."""
pass
|
Add a ruleset module TODO
|
## Code Before:
"""A module containg a core representation of IATI Rulesets."""
class Ruleset(object):
"""Representation of a Ruleset as defined within the IATI SSOT."""
pass
class Rule(object):
"""Representation of a Rule contained within a Ruleset.
Acts as a base class for specific types of Rule that actually do something.
"""
pass
class NoMoreThanOne(Rule):
"""Representation of a Rule that checks that there is no more than one Element matching a given XPath."""
pass
## Instruction:
Add a ruleset module TODO
## Code After:
class Ruleset(object):
"""Representation of a Ruleset as defined within the IATI SSOT."""
pass
class Rule(object):
"""Representation of a Rule contained within a Ruleset.
Acts as a base class for specific types of Rule that actually do something.
"""
pass
class NoMoreThanOne(Rule):
"""Representation of a Rule that checks that there is no more than one Element matching a given XPath."""
pass
|
...
...
|
6a68ef52ab9e762860087f701eee15e11786ca71
|
k3d/__init__.py
|
k3d/__init__.py
|
from ipywidgets import DOMWidget
from IPython.display import display
from traitlets import Unicode, Bytes, Dict
from .objects import Objects
from .factory import Factory
import base64, json, zlib
class K3D(DOMWidget, Factory):
_view_module = Unicode('nbextensions/k3d_widget/view', sync=True)
_view_name = Unicode('K3DView', sync=True)
_model_module = Unicode('nbextensions/k3d_widget/model', sync=True)
_model_name = Unicode('K3DModel', sync=True)
COMPRESSION_LEVEL = 1
data = Bytes(sync=True)
parameters = Dict(sync=True)
def __init__(self, antialias=False, background_color=0xFFFFFF, height=512):
super(K3D, self).__init__()
self.__objects = Objects(self.__show)
self.on_displayed(lambda x: self.__objects.flush())
self.parameters = {
'antialias': antialias,
'backgroundColor': background_color,
'height': height,
}
def __add__(self, obj):
self.__objects.add(obj)
return self
def display(self):
display(self)
def __show(self, obj):
self.data = base64.b64encode(zlib.compress(json.dumps(obj, separators=(',', ':')), self.COMPRESSION_LEVEL))
|
from ipywidgets import DOMWidget
from IPython.display import display
from traitlets import Unicode, Bytes, Dict
from .objects import Objects
from .factory import Factory
import base64, json, zlib
class K3D(DOMWidget, Factory):
_view_module = Unicode('nbextensions/k3d_widget/view', sync=True)
_view_name = Unicode('K3DView', sync=True)
_model_module = Unicode('nbextensions/k3d_widget/model', sync=True)
_model_name = Unicode('K3DModel', sync=True)
COMPRESSION_LEVEL = 1
data = Bytes(sync=True)
parameters = Dict(sync=True)
def __init__(self, antialias=False, background_color=0xFFFFFF, height=512):
super(K3D, self).__init__()
self.__objects = Objects(self.__show)
self.__display_strategy = self.__display
self.on_displayed(lambda x: self.__objects.flush())
self.parameters = {
'antialias': antialias,
'backgroundColor': background_color,
'height': height,
}
def __add__(self, obj):
self.__objects.add(obj)
return self
def display(self):
self.__display_strategy()
def __display(self):
display(self)
self.__display_strategy = self.__pass
def __show(self, obj):
self.data = base64.b64encode(zlib.compress(json.dumps(obj, separators=(',', ':')), self.COMPRESSION_LEVEL))
def __pass(self):
pass
|
Fix calling "display" method multiple times
|
Fix calling "display" method multiple times
|
Python
|
mit
|
K3D-tools/K3D-jupyter,K3D-tools/K3D-jupyter,K3D-tools/K3D-jupyter,K3D-tools/K3D-jupyter
|
from ipywidgets import DOMWidget
from IPython.display import display
from traitlets import Unicode, Bytes, Dict
from .objects import Objects
from .factory import Factory
import base64, json, zlib
class K3D(DOMWidget, Factory):
_view_module = Unicode('nbextensions/k3d_widget/view', sync=True)
_view_name = Unicode('K3DView', sync=True)
_model_module = Unicode('nbextensions/k3d_widget/model', sync=True)
_model_name = Unicode('K3DModel', sync=True)
COMPRESSION_LEVEL = 1
data = Bytes(sync=True)
parameters = Dict(sync=True)
def __init__(self, antialias=False, background_color=0xFFFFFF, height=512):
super(K3D, self).__init__()
self.__objects = Objects(self.__show)
+ self.__display_strategy = self.__display
self.on_displayed(lambda x: self.__objects.flush())
self.parameters = {
'antialias': antialias,
'backgroundColor': background_color,
'height': height,
}
def __add__(self, obj):
self.__objects.add(obj)
return self
def display(self):
+ self.__display_strategy()
+
+ def __display(self):
display(self)
+ self.__display_strategy = self.__pass
def __show(self, obj):
self.data = base64.b64encode(zlib.compress(json.dumps(obj, separators=(',', ':')), self.COMPRESSION_LEVEL))
+ def __pass(self):
+ pass
+
|
Fix calling "display" method multiple times
|
## Code Before:
from ipywidgets import DOMWidget
from IPython.display import display
from traitlets import Unicode, Bytes, Dict
from .objects import Objects
from .factory import Factory
import base64, json, zlib
class K3D(DOMWidget, Factory):
_view_module = Unicode('nbextensions/k3d_widget/view', sync=True)
_view_name = Unicode('K3DView', sync=True)
_model_module = Unicode('nbextensions/k3d_widget/model', sync=True)
_model_name = Unicode('K3DModel', sync=True)
COMPRESSION_LEVEL = 1
data = Bytes(sync=True)
parameters = Dict(sync=True)
def __init__(self, antialias=False, background_color=0xFFFFFF, height=512):
super(K3D, self).__init__()
self.__objects = Objects(self.__show)
self.on_displayed(lambda x: self.__objects.flush())
self.parameters = {
'antialias': antialias,
'backgroundColor': background_color,
'height': height,
}
def __add__(self, obj):
self.__objects.add(obj)
return self
def display(self):
display(self)
def __show(self, obj):
self.data = base64.b64encode(zlib.compress(json.dumps(obj, separators=(',', ':')), self.COMPRESSION_LEVEL))
## Instruction:
Fix calling "display" method multiple times
## Code After:
from ipywidgets import DOMWidget
from IPython.display import display
from traitlets import Unicode, Bytes, Dict
from .objects import Objects
from .factory import Factory
import base64, json, zlib
class K3D(DOMWidget, Factory):
_view_module = Unicode('nbextensions/k3d_widget/view', sync=True)
_view_name = Unicode('K3DView', sync=True)
_model_module = Unicode('nbextensions/k3d_widget/model', sync=True)
_model_name = Unicode('K3DModel', sync=True)
COMPRESSION_LEVEL = 1
data = Bytes(sync=True)
parameters = Dict(sync=True)
def __init__(self, antialias=False, background_color=0xFFFFFF, height=512):
super(K3D, self).__init__()
self.__objects = Objects(self.__show)
self.__display_strategy = self.__display
self.on_displayed(lambda x: self.__objects.flush())
self.parameters = {
'antialias': antialias,
'backgroundColor': background_color,
'height': height,
}
def __add__(self, obj):
self.__objects.add(obj)
return self
def display(self):
self.__display_strategy()
def __display(self):
display(self)
self.__display_strategy = self.__pass
def __show(self, obj):
self.data = base64.b64encode(zlib.compress(json.dumps(obj, separators=(',', ':')), self.COMPRESSION_LEVEL))
def __pass(self):
pass
|
# ... existing code ...
self.__objects = Objects(self.__show)
self.__display_strategy = self.__display
self.on_displayed(lambda x: self.__objects.flush())
# ... modified code ...
def display(self):
self.__display_strategy()
def __display(self):
display(self)
self.__display_strategy = self.__pass
...
self.data = base64.b64encode(zlib.compress(json.dumps(obj, separators=(',', ':')), self.COMPRESSION_LEVEL))
def __pass(self):
pass
# ... rest of the code ...
|
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
...
P = etiquette.photodb.PhotoDB()
...
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:])
...
|
7b9ee45c0791d8368a0bb8af52652d3fcd482c79
|
qubesadmin/__init__.py
|
qubesadmin/__init__.py
|
'''Qubes OS management client.'''
import os
import qubesadmin.config
import qubesadmin.base
import qubesadmin.app
DEFAULT = qubesadmin.base.DEFAULT
if os.path.exists(qubesadmin.config.QUBESD_SOCKET):
Qubes = qubesadmin.app.QubesLocal
else:
Qubes = qubesadmin.app.QubesRemote
|
'''Qubes OS management client.'''
import os
import qubesadmin.config
import qubesadmin.base
import qubesadmin.app
DEFAULT = qubesadmin.base.DEFAULT
if os.path.exists('/etc/qubes-release'):
Qubes = qubesadmin.app.QubesLocal
else:
Qubes = qubesadmin.app.QubesRemote
|
Choose QubesLocal or QubesRemote based on /etc/qubes-release presence
|
Choose QubesLocal or QubesRemote based on /etc/qubes-release presence
Do not check for qubesd socket (at module import time), because if not
running at this precise time, it will lead to wrong choice. And a weird
error message in consequence (looking for qrexec-client-vm in dom0).
Fixes QubesOS/qubes-issues#2917
|
Python
|
lgpl-2.1
|
marmarek/qubes-core-mgmt-client,marmarek/qubes-core-mgmt-client,marmarek/qubes-core-mgmt-client
|
'''Qubes OS management client.'''
import os
import qubesadmin.config
import qubesadmin.base
import qubesadmin.app
DEFAULT = qubesadmin.base.DEFAULT
- if os.path.exists(qubesadmin.config.QUBESD_SOCKET):
+ if os.path.exists('/etc/qubes-release'):
Qubes = qubesadmin.app.QubesLocal
else:
Qubes = qubesadmin.app.QubesRemote
|
Choose QubesLocal or QubesRemote based on /etc/qubes-release presence
|
## Code Before:
'''Qubes OS management client.'''
import os
import qubesadmin.config
import qubesadmin.base
import qubesadmin.app
DEFAULT = qubesadmin.base.DEFAULT
if os.path.exists(qubesadmin.config.QUBESD_SOCKET):
Qubes = qubesadmin.app.QubesLocal
else:
Qubes = qubesadmin.app.QubesRemote
## Instruction:
Choose QubesLocal or QubesRemote based on /etc/qubes-release presence
## Code After:
'''Qubes OS management client.'''
import os
import qubesadmin.config
import qubesadmin.base
import qubesadmin.app
DEFAULT = qubesadmin.base.DEFAULT
if os.path.exists('/etc/qubes-release'):
Qubes = qubesadmin.app.QubesLocal
else:
Qubes = qubesadmin.app.QubesRemote
|
...
if os.path.exists('/etc/qubes-release'):
Qubes = qubesadmin.app.QubesLocal
...
|
60bdc3cb6d503e675f029a6d2bbf4941267a2087
|
pysswords/__main__.py
|
pysswords/__main__.py
|
import os
import argparse
def default_db():
return os.path.join(os.path.expanduser("~"), "~/.pysswords")
def parse_args(args):
parser = argparse.ArgumentParser(prog="Pysswords")
group_init = parser.add_argument_group("Init options")
group_init.add_argument("-I", "--init", action="store_true")
group_init.add_argument("-D", "--database", default=default_db())
group_cred = parser.add_argument_group("Credential options")
group_cred.add_argument("-a", "--add", action="store_true")
group_cred.add_argument("-g", "--get")
group_cred.add_argument("-u", "--update")
group_cred.add_argument("-r", "--remove")
group_cred.add_argument("-s", "--search")
return parser.parse_args(args)
|
import os
import argparse
def default_db():
return os.path.join(os.path.expanduser("~"), "~/.pysswords")
def parse_args(args):
parser = argparse.ArgumentParser(prog="Pysswords")
group_db = parser.add_argument_group("Databse options")
group_db.add_argument("-I", "--init", action="store_true")
group_db.add_argument("-D", "--database", default=default_db())
group_cred = parser.add_argument_group("Credential options")
group_cred.add_argument("-a", "--add", action="store_true")
group_cred.add_argument("-g", "--get")
group_cred.add_argument("-u", "--update")
group_cred.add_argument("-r", "--remove")
group_cred.add_argument("-s", "--search")
return parser.parse_args(args)
|
Refactor parse args db options
|
Refactor parse args db options
|
Python
|
mit
|
scorphus/passpie,eiginn/passpie,marcwebbie/passpie,marcwebbie/pysswords,eiginn/passpie,scorphus/passpie,marcwebbie/passpie
|
import os
import argparse
def default_db():
return os.path.join(os.path.expanduser("~"), "~/.pysswords")
def parse_args(args):
parser = argparse.ArgumentParser(prog="Pysswords")
- group_init = parser.add_argument_group("Init options")
+ group_db = parser.add_argument_group("Databse options")
- group_init.add_argument("-I", "--init", action="store_true")
+ group_db.add_argument("-I", "--init", action="store_true")
- group_init.add_argument("-D", "--database", default=default_db())
+ group_db.add_argument("-D", "--database", default=default_db())
group_cred = parser.add_argument_group("Credential options")
group_cred.add_argument("-a", "--add", action="store_true")
group_cred.add_argument("-g", "--get")
group_cred.add_argument("-u", "--update")
group_cred.add_argument("-r", "--remove")
group_cred.add_argument("-s", "--search")
return parser.parse_args(args)
|
Refactor parse args db options
|
## Code Before:
import os
import argparse
def default_db():
return os.path.join(os.path.expanduser("~"), "~/.pysswords")
def parse_args(args):
parser = argparse.ArgumentParser(prog="Pysswords")
group_init = parser.add_argument_group("Init options")
group_init.add_argument("-I", "--init", action="store_true")
group_init.add_argument("-D", "--database", default=default_db())
group_cred = parser.add_argument_group("Credential options")
group_cred.add_argument("-a", "--add", action="store_true")
group_cred.add_argument("-g", "--get")
group_cred.add_argument("-u", "--update")
group_cred.add_argument("-r", "--remove")
group_cred.add_argument("-s", "--search")
return parser.parse_args(args)
## Instruction:
Refactor parse args db options
## Code After:
import os
import argparse
def default_db():
return os.path.join(os.path.expanduser("~"), "~/.pysswords")
def parse_args(args):
parser = argparse.ArgumentParser(prog="Pysswords")
group_db = parser.add_argument_group("Databse options")
group_db.add_argument("-I", "--init", action="store_true")
group_db.add_argument("-D", "--database", default=default_db())
group_cred = parser.add_argument_group("Credential options")
group_cred.add_argument("-a", "--add", action="store_true")
group_cred.add_argument("-g", "--get")
group_cred.add_argument("-u", "--update")
group_cred.add_argument("-r", "--remove")
group_cred.add_argument("-s", "--search")
return parser.parse_args(args)
|
# ... existing code ...
group_db = parser.add_argument_group("Databse options")
group_db.add_argument("-I", "--init", action="store_true")
group_db.add_argument("-D", "--database", default=default_db())
# ... rest of the code ...
|
12e35b703f548df5e57e44446ddd8739f96aef95
|
tartpy/tools.py
|
tartpy/tools.py
|
import time
from .runtime import behavior, Actor, exception_message, Runtime
from .eventloop import EventLoop
class Wait(object):
"""A synchronizing object.
Convenience object to wait for results outside actors.
Use as::
w = Wait()
wait = runtime.create(w.wait_beh)
# now use `wait` as a customer
msg = w.join()
`msg` will be the message sent back to the customer.
"""
POLL_TIME = 0.01 # seconds
def __init__(self):
self.state = None
@behavior
def wait_beh(self, this, message):
self.state = message
def join(self):
while self.state is None:
time.sleep(self.POLL_TIME)
return self.state
def later(actor, t, msg):
EventLoop().later(t, lambda: actor << msg)
@behavior
def log_beh(self, message):
print('LOG:', message)
|
from collections.abc import Mapping, Sequence
import time
from .runtime import behavior, Actor, exception_message, Runtime
from .eventloop import EventLoop
class Wait(object):
"""A synchronizing object.
Convenience object to wait for results outside actors.
Use as::
w = Wait()
wait = runtime.create(w.wait_beh)
# now use `wait` as a customer
msg = w.join()
`msg` will be the message sent back to the customer.
"""
POLL_TIME = 0.01 # seconds
def __init__(self):
self.state = None
@behavior
def wait_beh(self, this, message):
self.state = message
def join(self):
while self.state is None:
time.sleep(self.POLL_TIME)
return self.state
def later(actor, t, msg):
EventLoop().later(t, lambda: actor << msg)
@behavior
def log_beh(self, message):
print('LOG:', message)
def actor_map(f, message):
"""Map a function f:{Actor} -> B to a message."""
if isinstance(message, Actor):
return f(message)
if isinstance(message, Mapping):
return {actor_map(f, key): actor_map(f, value)
for key, value in message.items()}
if isinstance(message, str):
return message
if isinstance(message, Sequence):
return [actor_map(f, value) for value in message]
return message
|
Add a map function over messages
|
Add a map function over messages
|
Python
|
mit
|
waltermoreira/tartpy
|
+ from collections.abc import Mapping, Sequence
import time
from .runtime import behavior, Actor, exception_message, Runtime
from .eventloop import EventLoop
class Wait(object):
"""A synchronizing object.
Convenience object to wait for results outside actors.
Use as::
w = Wait()
wait = runtime.create(w.wait_beh)
# now use `wait` as a customer
msg = w.join()
`msg` will be the message sent back to the customer.
"""
POLL_TIME = 0.01 # seconds
def __init__(self):
self.state = None
@behavior
def wait_beh(self, this, message):
self.state = message
def join(self):
while self.state is None:
time.sleep(self.POLL_TIME)
return self.state
def later(actor, t, msg):
EventLoop().later(t, lambda: actor << msg)
@behavior
def log_beh(self, message):
print('LOG:', message)
+ def actor_map(f, message):
+ """Map a function f:{Actor} -> B to a message."""
+
+ if isinstance(message, Actor):
+ return f(message)
+ if isinstance(message, Mapping):
+ return {actor_map(f, key): actor_map(f, value)
+ for key, value in message.items()}
+ if isinstance(message, str):
+ return message
+ if isinstance(message, Sequence):
+ return [actor_map(f, value) for value in message]
+ return message
+
|
Add a map function over messages
|
## Code Before:
import time
from .runtime import behavior, Actor, exception_message, Runtime
from .eventloop import EventLoop
class Wait(object):
"""A synchronizing object.
Convenience object to wait for results outside actors.
Use as::
w = Wait()
wait = runtime.create(w.wait_beh)
# now use `wait` as a customer
msg = w.join()
`msg` will be the message sent back to the customer.
"""
POLL_TIME = 0.01 # seconds
def __init__(self):
self.state = None
@behavior
def wait_beh(self, this, message):
self.state = message
def join(self):
while self.state is None:
time.sleep(self.POLL_TIME)
return self.state
def later(actor, t, msg):
EventLoop().later(t, lambda: actor << msg)
@behavior
def log_beh(self, message):
print('LOG:', message)
## Instruction:
Add a map function over messages
## Code After:
from collections.abc import Mapping, Sequence
import time
from .runtime import behavior, Actor, exception_message, Runtime
from .eventloop import EventLoop
class Wait(object):
"""A synchronizing object.
Convenience object to wait for results outside actors.
Use as::
w = Wait()
wait = runtime.create(w.wait_beh)
# now use `wait` as a customer
msg = w.join()
`msg` will be the message sent back to the customer.
"""
POLL_TIME = 0.01 # seconds
def __init__(self):
self.state = None
@behavior
def wait_beh(self, this, message):
self.state = message
def join(self):
while self.state is None:
time.sleep(self.POLL_TIME)
return self.state
def later(actor, t, msg):
EventLoop().later(t, lambda: actor << msg)
@behavior
def log_beh(self, message):
print('LOG:', message)
def actor_map(f, message):
"""Map a function f:{Actor} -> B to a message."""
if isinstance(message, Actor):
return f(message)
if isinstance(message, Mapping):
return {actor_map(f, key): actor_map(f, value)
for key, value in message.items()}
if isinstance(message, str):
return message
if isinstance(message, Sequence):
return [actor_map(f, value) for value in message]
return message
|
# ... existing code ...
from collections.abc import Mapping, Sequence
import time
# ... modified code ...
def actor_map(f, message):
"""Map a function f:{Actor} -> B to a message."""
if isinstance(message, Actor):
return f(message)
if isinstance(message, Mapping):
return {actor_map(f, key): actor_map(f, value)
for key, value in message.items()}
if isinstance(message, str):
return message
if isinstance(message, Sequence):
return [actor_map(f, value) for value in message]
return message
# ... rest of the code ...
|
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()
|
...
import json
import logging
...
# Import napalm-logs pkgs
from napalm_logs.exceptions import BindException
from napalm_logs.transport.base import TransportBase
log = logging.getLogger(__name__)
...
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)
...
|
7ee5692a98a6dfc714a05f1add8e72b09c52929e
|
students/psbriant/final_project/clean_data.py
|
students/psbriant/final_project/clean_data.py
|
import pandas
from datetime import datetime
# Change source to smaller file.
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
# print(data["Date Text"].head())
first_date = data["Date Text"].values[0]
print(first_date)
# datetime.strptime(first_date, "%Y-%m-%d")
# datetime(2012, 3, 10, 0, 0)
# data.date = data.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d"))
# print(data.date.head())
# data.index = data.date
# print(data)
# print(data.ix[datetime(2012, 8, 19)])
# Remove date column
# data = data.drop(["date"], axis=1)
# print(data.columns)
# Determine what values are missing
# empty = data.apply(lambda col: pandas.isnull(col))
|
import pandas
from datetime import datetime
# Change source to smaller file.
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv",
parse_dates=[0], infer_datetime_format=True)
temp = pandas.DatetimeIndex(data["Date_Text"])
data["Month"] = temp.month
data["Year"] = temp.year
print(data)
# print(data["Date Text"].head())
# first_date = data["Date Text"].values[0]
# print(first_date)
# datetime.strptime(first_date, "%b-%Y")
# datetime(2012, 3, 10, 0, 0)
# data.date = data["Date Text"].apply(lambda d: datetime.strptime(d, "%b-%Y"))
# print(data.date.head())
# data.index = data.date
# print(data)
# print(data.ix[datetime(2012, 8, 19)])
# Remove date column
# data = data.drop(["date"], axis=1)
# print(data.columns)
# Determine what values are missing
# empty = data.apply(lambda col: pandas.isnull(col))
|
Add code to split month and year into new columns.
|
Add code to split month and year into new columns.
|
Python
|
unlicense
|
UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016
|
import pandas
from datetime import datetime
# Change source to smaller file.
- data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
+ data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv",
+ parse_dates=[0], infer_datetime_format=True)
+ temp = pandas.DatetimeIndex(data["Date_Text"])
+ data["Month"] = temp.month
+ data["Year"] = temp.year
+ print(data)
# print(data["Date Text"].head())
- first_date = data["Date Text"].values[0]
+ # first_date = data["Date Text"].values[0]
- print(first_date)
+ # print(first_date)
- # datetime.strptime(first_date, "%Y-%m-%d")
+ # datetime.strptime(first_date, "%b-%Y")
+
# datetime(2012, 3, 10, 0, 0)
- # data.date = data.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d"))
+ # data.date = data["Date Text"].apply(lambda d: datetime.strptime(d, "%b-%Y"))
# print(data.date.head())
# data.index = data.date
# print(data)
# print(data.ix[datetime(2012, 8, 19)])
# Remove date column
# data = data.drop(["date"], axis=1)
# print(data.columns)
# Determine what values are missing
# empty = data.apply(lambda col: pandas.isnull(col))
|
Add code to split month and year into new columns.
|
## Code Before:
import pandas
from datetime import datetime
# Change source to smaller file.
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
# print(data["Date Text"].head())
first_date = data["Date Text"].values[0]
print(first_date)
# datetime.strptime(first_date, "%Y-%m-%d")
# datetime(2012, 3, 10, 0, 0)
# data.date = data.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d"))
# print(data.date.head())
# data.index = data.date
# print(data)
# print(data.ix[datetime(2012, 8, 19)])
# Remove date column
# data = data.drop(["date"], axis=1)
# print(data.columns)
# Determine what values are missing
# empty = data.apply(lambda col: pandas.isnull(col))
## Instruction:
Add code to split month and year into new columns.
## Code After:
import pandas
from datetime import datetime
# Change source to smaller file.
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv",
parse_dates=[0], infer_datetime_format=True)
temp = pandas.DatetimeIndex(data["Date_Text"])
data["Month"] = temp.month
data["Year"] = temp.year
print(data)
# print(data["Date Text"].head())
# first_date = data["Date Text"].values[0]
# print(first_date)
# datetime.strptime(first_date, "%b-%Y")
# datetime(2012, 3, 10, 0, 0)
# data.date = data["Date Text"].apply(lambda d: datetime.strptime(d, "%b-%Y"))
# print(data.date.head())
# data.index = data.date
# print(data)
# print(data.ix[datetime(2012, 8, 19)])
# Remove date column
# data = data.drop(["date"], axis=1)
# print(data.columns)
# Determine what values are missing
# empty = data.apply(lambda col: pandas.isnull(col))
|
// ... existing code ...
# Change source to smaller file.
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv",
parse_dates=[0], infer_datetime_format=True)
temp = pandas.DatetimeIndex(data["Date_Text"])
data["Month"] = temp.month
data["Year"] = temp.year
print(data)
// ... modified code ...
# first_date = data["Date Text"].values[0]
# print(first_date)
# datetime.strptime(first_date, "%b-%Y")
# datetime(2012, 3, 10, 0, 0)
...
# data.date = data["Date Text"].apply(lambda d: datetime.strptime(d, "%b-%Y"))
# print(data.date.head())
// ... rest of the code ...
|
146e35f48774173c2000b8a9790cdbe6925ba94a
|
opps/contrib/multisite/admin.py
|
opps/contrib/multisite/admin.py
|
from django.contrib import admin
from .models import SitePermission
admin.site.register(SitePermission)
|
from django.contrib import admin
from django.utils import timezone
from .models import SitePermission
class AdminViewPermission(admin.ModelAdmin):
def queryset(self, request):
queryset = super(AdminViewPermission, self).queryset(request)
try:
sitepermission = SitePermission.objects.get(
user=request.user,
date_available__lte=timezone.now(),
published=True)
return queryset.filter(site_iid=sitepermission.site_iid)
except SitePermission.DoesNotExist:
pass
return queryset
admin.site.register(SitePermission)
|
Create AdminViewPermission on contrib multisite
|
Create AdminViewPermission on contrib multisite
|
Python
|
mit
|
opps/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,opps/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,YACOWS/opps,opps/opps,jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,williamroot/opps
|
from django.contrib import admin
+ from django.utils import timezone
+
from .models import SitePermission
+
+
+ class AdminViewPermission(admin.ModelAdmin):
+
+ def queryset(self, request):
+ queryset = super(AdminViewPermission, self).queryset(request)
+ try:
+ sitepermission = SitePermission.objects.get(
+ user=request.user,
+ date_available__lte=timezone.now(),
+ published=True)
+ return queryset.filter(site_iid=sitepermission.site_iid)
+ except SitePermission.DoesNotExist:
+ pass
+ return queryset
admin.site.register(SitePermission)
|
Create AdminViewPermission on contrib multisite
|
## Code Before:
from django.contrib import admin
from .models import SitePermission
admin.site.register(SitePermission)
## Instruction:
Create AdminViewPermission on contrib multisite
## Code After:
from django.contrib import admin
from django.utils import timezone
from .models import SitePermission
class AdminViewPermission(admin.ModelAdmin):
def queryset(self, request):
queryset = super(AdminViewPermission, self).queryset(request)
try:
sitepermission = SitePermission.objects.get(
user=request.user,
date_available__lte=timezone.now(),
published=True)
return queryset.filter(site_iid=sitepermission.site_iid)
except SitePermission.DoesNotExist:
pass
return queryset
admin.site.register(SitePermission)
|
...
from django.contrib import admin
from django.utils import timezone
from .models import SitePermission
...
class AdminViewPermission(admin.ModelAdmin):
def queryset(self, request):
queryset = super(AdminViewPermission, self).queryset(request)
try:
sitepermission = SitePermission.objects.get(
user=request.user,
date_available__lte=timezone.now(),
published=True)
return queryset.filter(site_iid=sitepermission.site_iid)
except SitePermission.DoesNotExist:
pass
return queryset
admin.site.register(SitePermission)
...
|
709b9e57d8ea664715fd9bb89729f99324c3e0c2
|
libs/utils.py
|
libs/utils.py
|
from django.core.cache import cache
#get the cache key for storage
def cache_get_key(*args, **kwargs):
import hashlib
serialise = []
for arg in args:
serialise.append(str(arg))
for key,arg in kwargs.items():
if key == "clear_cache":
continue
serialise.append(str(key))
serialise.append(str(arg))
key = hashlib.md5("".join(serialise)).hexdigest()
return key
#decorator for caching functions
def cache_for(time):
def decorator(fn):
def wrapper(*args, **kwargs):
key = cache_get_key(fn.__name__, *args, **kwargs)
result = cache.get(key)
if not result or "clear_cache" in kwargs and kwargs["clear_cache"]:
result = fn(*args, **kwargs)
cache.set(key, result, time)
return result
return wrapper
return decorator
|
from django.core.cache import cache
def cache_get_key(*args, **kwargs):
"""Get the cache key for storage"""
import hashlib
serialise = []
for arg in args:
serialise.append(str(arg))
for key,arg in kwargs.items():
if key == "clear_cache":
continue
serialise.append(str(key))
serialise.append(str(arg))
key = hashlib.md5("".join(serialise)).hexdigest()
return key
def cache_for(time):
"""Decorator for caching functions"""
def decorator(fn):
def wrapper(*args, **kwargs):
key = cache_get_key(fn.__name__, *args, **kwargs)
result = cache.get(key)
if not result or "clear_cache" in kwargs and kwargs["clear_cache"]:
cache.delete(key)
result = fn(*args, **kwargs)
cache.set(key, result, time)
return result
return wrapper
return decorator
|
Delete cache first before setting new value
|
Delete cache first before setting new value
|
Python
|
mit
|
daigotanaka/kawaraban,daigotanaka/kawaraban,daigotanaka/kawaraban,daigotanaka/kawaraban
|
from django.core.cache import cache
- #get the cache key for storage
+
def cache_get_key(*args, **kwargs):
+ """Get the cache key for storage"""
import hashlib
serialise = []
for arg in args:
serialise.append(str(arg))
for key,arg in kwargs.items():
if key == "clear_cache":
continue
serialise.append(str(key))
serialise.append(str(arg))
key = hashlib.md5("".join(serialise)).hexdigest()
return key
- #decorator for caching functions
+
def cache_for(time):
+ """Decorator for caching functions"""
def decorator(fn):
def wrapper(*args, **kwargs):
key = cache_get_key(fn.__name__, *args, **kwargs)
result = cache.get(key)
if not result or "clear_cache" in kwargs and kwargs["clear_cache"]:
+ cache.delete(key)
result = fn(*args, **kwargs)
cache.set(key, result, time)
return result
return wrapper
return decorator
|
Delete cache first before setting new value
|
## Code Before:
from django.core.cache import cache
#get the cache key for storage
def cache_get_key(*args, **kwargs):
import hashlib
serialise = []
for arg in args:
serialise.append(str(arg))
for key,arg in kwargs.items():
if key == "clear_cache":
continue
serialise.append(str(key))
serialise.append(str(arg))
key = hashlib.md5("".join(serialise)).hexdigest()
return key
#decorator for caching functions
def cache_for(time):
def decorator(fn):
def wrapper(*args, **kwargs):
key = cache_get_key(fn.__name__, *args, **kwargs)
result = cache.get(key)
if not result or "clear_cache" in kwargs and kwargs["clear_cache"]:
result = fn(*args, **kwargs)
cache.set(key, result, time)
return result
return wrapper
return decorator
## Instruction:
Delete cache first before setting new value
## Code After:
from django.core.cache import cache
def cache_get_key(*args, **kwargs):
"""Get the cache key for storage"""
import hashlib
serialise = []
for arg in args:
serialise.append(str(arg))
for key,arg in kwargs.items():
if key == "clear_cache":
continue
serialise.append(str(key))
serialise.append(str(arg))
key = hashlib.md5("".join(serialise)).hexdigest()
return key
def cache_for(time):
"""Decorator for caching functions"""
def decorator(fn):
def wrapper(*args, **kwargs):
key = cache_get_key(fn.__name__, *args, **kwargs)
result = cache.get(key)
if not result or "clear_cache" in kwargs and kwargs["clear_cache"]:
cache.delete(key)
result = fn(*args, **kwargs)
cache.set(key, result, time)
return result
return wrapper
return decorator
|
// ... existing code ...
def cache_get_key(*args, **kwargs):
"""Get the cache key for storage"""
import hashlib
// ... modified code ...
def cache_for(time):
"""Decorator for caching functions"""
def decorator(fn):
...
if not result or "clear_cache" in kwargs and kwargs["clear_cache"]:
cache.delete(key)
result = fn(*args, **kwargs)
// ... rest of the code ...
|
53a442ac37bf58bca16dee2ad0787bdf2df98555
|
nltk/test/gluesemantics_malt_fixt.py
|
nltk/test/gluesemantics_malt_fixt.py
|
from __future__ import absolute_import
def setup_module(module):
from nose import SkipTest
from nltk.parse.malt import MaltParser
try:
depparser = MaltParser()
except LookupError:
raise SkipTest("MaltParser is not available")
|
from __future__ import absolute_import
def setup_module(module):
from nose import SkipTest
from nltk.parse.malt import MaltParser
try:
depparser = MaltParser('maltparser-1.7.2')
except LookupError:
raise SkipTest("MaltParser is not available")
|
Add the malt parser directory name in the unittest
|
Add the malt parser directory name in the unittest
Fixes https://nltk.ci.cloudbees.com/job/nltk/TOXENV=py34-jenkins,jdk=jdk8latestOnlineInstall/lastCompletedBuild/testReport/%3Cnose/suite/ContextSuite_context_gluesemantics_malt_fixt__setup/
|
Python
|
apache-2.0
|
nltk/nltk,nltk/nltk,nltk/nltk
|
from __future__ import absolute_import
def setup_module(module):
from nose import SkipTest
from nltk.parse.malt import MaltParser
try:
- depparser = MaltParser()
+ depparser = MaltParser('maltparser-1.7.2')
except LookupError:
raise SkipTest("MaltParser is not available")
|
Add the malt parser directory name in the unittest
|
## Code Before:
from __future__ import absolute_import
def setup_module(module):
from nose import SkipTest
from nltk.parse.malt import MaltParser
try:
depparser = MaltParser()
except LookupError:
raise SkipTest("MaltParser is not available")
## Instruction:
Add the malt parser directory name in the unittest
## Code After:
from __future__ import absolute_import
def setup_module(module):
from nose import SkipTest
from nltk.parse.malt import MaltParser
try:
depparser = MaltParser('maltparser-1.7.2')
except LookupError:
raise SkipTest("MaltParser is not available")
|
// ... existing code ...
try:
depparser = MaltParser('maltparser-1.7.2')
except LookupError:
// ... rest of the code ...
|
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)
|
...
items = []
for v1, n1 in zip(self, self.n):
try:
s = v1.latex()
except:
s = str(v1)
if n1 == 0:
...
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)
...
|
aed9b3066f9d796e5c89e38d833c87e130a421c3
|
auth0/v2/blacklists.py
|
auth0/v2/blacklists.py
|
from .rest import RestClient
class Blacklists(object):
def __init__(self, domain, jwt_token):
url = 'https://%s/api/v2/blacklists/tokens' % domain
self.client = RestClient(endpoint=url, jwt=jwt_token)
def get(self, aud=None):
params = {
'aud': aud
}
return self.client.get(params=params)
def create(self, jti, aud=''):
return self.client.post(data={'jti': jti, 'aud': aud})
|
from .rest import RestClient
class Blacklists(object):
def __init__(self, domain, jwt_token):
self.url = 'https://%s/api/v2/blacklists/tokens' % domain
self.client = RestClient(jwt=jwt_token)
def get(self, aud=None):
params = {
'aud': aud
}
return self.client.get(self.url, params=params)
def create(self, jti, aud=''):
return self.client.post(self.url, data={'jti': jti, 'aud': aud})
|
Fix Blacklists usage of RestClient
|
Fix Blacklists usage of RestClient
|
Python
|
mit
|
auth0/auth0-python,auth0/auth0-python
|
from .rest import RestClient
class Blacklists(object):
def __init__(self, domain, jwt_token):
- url = 'https://%s/api/v2/blacklists/tokens' % domain
+ self.url = 'https://%s/api/v2/blacklists/tokens' % domain
-
- self.client = RestClient(endpoint=url, jwt=jwt_token)
+ self.client = RestClient(jwt=jwt_token)
def get(self, aud=None):
params = {
'aud': aud
}
- return self.client.get(params=params)
+ return self.client.get(self.url, params=params)
def create(self, jti, aud=''):
- return self.client.post(data={'jti': jti, 'aud': aud})
+ return self.client.post(self.url, data={'jti': jti, 'aud': aud})
|
Fix Blacklists usage of RestClient
|
## Code Before:
from .rest import RestClient
class Blacklists(object):
def __init__(self, domain, jwt_token):
url = 'https://%s/api/v2/blacklists/tokens' % domain
self.client = RestClient(endpoint=url, jwt=jwt_token)
def get(self, aud=None):
params = {
'aud': aud
}
return self.client.get(params=params)
def create(self, jti, aud=''):
return self.client.post(data={'jti': jti, 'aud': aud})
## Instruction:
Fix Blacklists usage of RestClient
## Code After:
from .rest import RestClient
class Blacklists(object):
def __init__(self, domain, jwt_token):
self.url = 'https://%s/api/v2/blacklists/tokens' % domain
self.client = RestClient(jwt=jwt_token)
def get(self, aud=None):
params = {
'aud': aud
}
return self.client.get(self.url, params=params)
def create(self, jti, aud=''):
return self.client.post(self.url, data={'jti': jti, 'aud': aud})
|
...
def __init__(self, domain, jwt_token):
self.url = 'https://%s/api/v2/blacklists/tokens' % domain
self.client = RestClient(jwt=jwt_token)
...
return self.client.get(self.url, params=params)
...
def create(self, jti, aud=''):
return self.client.post(self.url, data={'jti': jti, 'aud': aud})
...
|
9c3d24083be5969ca84c1625dbc0d368acdc51f8
|
tg/tests/test_util.py
|
tg/tests/test_util.py
|
import tg
from tg.util import *
from nose.tools import eq_
import os
path = None
def setup():
global path
path = os.curdir
os.chdir(os.path.abspath(os.path.dirname(os.path.dirname(tg.__file__))))
def teardown():
global path
os.chdir(path)
# These tests aren't reliable if the package in question has
# entry points.
def test_get_package_name():
eq_(get_package_name(), 'tg')
def test_get_project_name():
eq_(get_project_name(), 'TurboGears2')
def test_get_project_meta():
eq_(get_project_meta('requires.txt'), os.path.join('TurboGears2.egg-info', 'requires.txt'))
def test_get_model():
eq_(get_model(), None)
|
import tg
from tg.util import *
from nose.tools import eq_
import os
path = None
def setup():
global path
path = os.curdir
os.chdir(os.path.abspath(os.path.dirname(os.path.dirname(tg.__file__))))
def teardown():
global path
os.chdir(path)
def test_get_partial_dict():
eq_(get_partial_dict('prefix', {'prefix.xyz':1, 'prefix.zyx':2, 'xy':3}),
{'xyz':1,'zyx':2})
# These tests aren't reliable if the package in question has
# entry points.
def test_get_package_name():
eq_(get_package_name(), 'tg')
def test_get_project_name():
eq_(get_project_name(), 'TurboGears2')
def test_get_project_meta():
eq_(get_project_meta('requires.txt'), os.path.join('TurboGears2.egg-info', 'requires.txt'))
def test_get_model():
eq_(get_model(), None)
|
Add a test_get_partial_dict unit test, which currently fails
|
Add a test_get_partial_dict unit test, which currently fails
|
Python
|
mit
|
lucius-feng/tg2,lucius-feng/tg2
|
import tg
from tg.util import *
from nose.tools import eq_
import os
path = None
def setup():
global path
path = os.curdir
os.chdir(os.path.abspath(os.path.dirname(os.path.dirname(tg.__file__))))
def teardown():
global path
os.chdir(path)
+ def test_get_partial_dict():
+ eq_(get_partial_dict('prefix', {'prefix.xyz':1, 'prefix.zyx':2, 'xy':3}),
+ {'xyz':1,'zyx':2})
+
# These tests aren't reliable if the package in question has
# entry points.
def test_get_package_name():
eq_(get_package_name(), 'tg')
def test_get_project_name():
eq_(get_project_name(), 'TurboGears2')
def test_get_project_meta():
eq_(get_project_meta('requires.txt'), os.path.join('TurboGears2.egg-info', 'requires.txt'))
def test_get_model():
eq_(get_model(), None)
+
|
Add a test_get_partial_dict unit test, which currently fails
|
## Code Before:
import tg
from tg.util import *
from nose.tools import eq_
import os
path = None
def setup():
global path
path = os.curdir
os.chdir(os.path.abspath(os.path.dirname(os.path.dirname(tg.__file__))))
def teardown():
global path
os.chdir(path)
# These tests aren't reliable if the package in question has
# entry points.
def test_get_package_name():
eq_(get_package_name(), 'tg')
def test_get_project_name():
eq_(get_project_name(), 'TurboGears2')
def test_get_project_meta():
eq_(get_project_meta('requires.txt'), os.path.join('TurboGears2.egg-info', 'requires.txt'))
def test_get_model():
eq_(get_model(), None)
## Instruction:
Add a test_get_partial_dict unit test, which currently fails
## Code After:
import tg
from tg.util import *
from nose.tools import eq_
import os
path = None
def setup():
global path
path = os.curdir
os.chdir(os.path.abspath(os.path.dirname(os.path.dirname(tg.__file__))))
def teardown():
global path
os.chdir(path)
def test_get_partial_dict():
eq_(get_partial_dict('prefix', {'prefix.xyz':1, 'prefix.zyx':2, 'xy':3}),
{'xyz':1,'zyx':2})
# These tests aren't reliable if the package in question has
# entry points.
def test_get_package_name():
eq_(get_package_name(), 'tg')
def test_get_project_name():
eq_(get_project_name(), 'TurboGears2')
def test_get_project_meta():
eq_(get_project_meta('requires.txt'), os.path.join('TurboGears2.egg-info', 'requires.txt'))
def test_get_model():
eq_(get_model(), None)
|
...
def test_get_partial_dict():
eq_(get_partial_dict('prefix', {'prefix.xyz':1, 'prefix.zyx':2, 'xy':3}),
{'xyz':1,'zyx':2})
# These tests aren't reliable if the package in question has
...
|
762147b8660a507ac5db8d0408162e8463b2fe8e
|
daiquiri/registry/serializers.py
|
daiquiri/registry/serializers.py
|
from rest_framework import serializers
from daiquiri.core.serializers import JSONListField, JSONDictField
class DublincoreSerializer(serializers.Serializer):
identifier = serializers.ReadOnlyField()
title = serializers.ReadOnlyField()
description = serializers.SerializerMethodField()
publisher = serializers.SerializerMethodField()
subjects = serializers.ReadOnlyField()
def get_description(self, obj):
return obj['content']['description']
def get_publisher(self, obj):
return obj['curation']['publisher']
class VoresourceSerializer(serializers.Serializer):
identifier = serializers.ReadOnlyField()
title = serializers.ReadOnlyField()
created = serializers.ReadOnlyField()
updated = serializers.ReadOnlyField()
voresource_status = serializers.ReadOnlyField(default='active')
curation = JSONDictField(default={})
content = JSONDictField(default={})
capabilities = JSONListField(default=[])
tableset = JSONListField(default=[])
managed_authority = serializers.ReadOnlyField(default=None)
managing_org = serializers.ReadOnlyField(default=None)
type = serializers.ReadOnlyField()
|
from rest_framework import serializers
from daiquiri.core.serializers import JSONDictField, JSONListField
class DublincoreSerializer(serializers.Serializer):
identifier = serializers.ReadOnlyField()
title = serializers.ReadOnlyField()
description = serializers.SerializerMethodField()
publisher = serializers.SerializerMethodField()
subjects = serializers.ReadOnlyField()
def get_description(self, obj):
return obj['content']['description']
def get_publisher(self, obj):
return obj['curation']['publisher']
class VoresourceSerializer(serializers.Serializer):
identifier = serializers.ReadOnlyField()
title = serializers.ReadOnlyField()
created = serializers.ReadOnlyField()
updated = serializers.ReadOnlyField()
type = serializers.ReadOnlyField()
status = serializers.ReadOnlyField()
curation = JSONDictField(default={})
content = JSONDictField(default={})
capabilities = JSONListField(default=[])
tableset = JSONListField(default=[])
managed_authority = serializers.ReadOnlyField(default=None)
managing_org = serializers.ReadOnlyField(default=None)
|
Fix status field in OAI-PMH
|
Fix status field in OAI-PMH
|
Python
|
apache-2.0
|
aipescience/django-daiquiri,aipescience/django-daiquiri,aipescience/django-daiquiri
|
from rest_framework import serializers
- from daiquiri.core.serializers import JSONListField, JSONDictField
+ from daiquiri.core.serializers import JSONDictField, JSONListField
class DublincoreSerializer(serializers.Serializer):
identifier = serializers.ReadOnlyField()
title = serializers.ReadOnlyField()
description = serializers.SerializerMethodField()
publisher = serializers.SerializerMethodField()
subjects = serializers.ReadOnlyField()
def get_description(self, obj):
return obj['content']['description']
def get_publisher(self, obj):
return obj['curation']['publisher']
class VoresourceSerializer(serializers.Serializer):
identifier = serializers.ReadOnlyField()
title = serializers.ReadOnlyField()
created = serializers.ReadOnlyField()
updated = serializers.ReadOnlyField()
- voresource_status = serializers.ReadOnlyField(default='active')
+ type = serializers.ReadOnlyField()
+ status = serializers.ReadOnlyField()
curation = JSONDictField(default={})
content = JSONDictField(default={})
capabilities = JSONListField(default=[])
tableset = JSONListField(default=[])
managed_authority = serializers.ReadOnlyField(default=None)
managing_org = serializers.ReadOnlyField(default=None)
- type = serializers.ReadOnlyField()
|
Fix status field in OAI-PMH
|
## Code Before:
from rest_framework import serializers
from daiquiri.core.serializers import JSONListField, JSONDictField
class DublincoreSerializer(serializers.Serializer):
identifier = serializers.ReadOnlyField()
title = serializers.ReadOnlyField()
description = serializers.SerializerMethodField()
publisher = serializers.SerializerMethodField()
subjects = serializers.ReadOnlyField()
def get_description(self, obj):
return obj['content']['description']
def get_publisher(self, obj):
return obj['curation']['publisher']
class VoresourceSerializer(serializers.Serializer):
identifier = serializers.ReadOnlyField()
title = serializers.ReadOnlyField()
created = serializers.ReadOnlyField()
updated = serializers.ReadOnlyField()
voresource_status = serializers.ReadOnlyField(default='active')
curation = JSONDictField(default={})
content = JSONDictField(default={})
capabilities = JSONListField(default=[])
tableset = JSONListField(default=[])
managed_authority = serializers.ReadOnlyField(default=None)
managing_org = serializers.ReadOnlyField(default=None)
type = serializers.ReadOnlyField()
## Instruction:
Fix status field in OAI-PMH
## Code After:
from rest_framework import serializers
from daiquiri.core.serializers import JSONDictField, JSONListField
class DublincoreSerializer(serializers.Serializer):
identifier = serializers.ReadOnlyField()
title = serializers.ReadOnlyField()
description = serializers.SerializerMethodField()
publisher = serializers.SerializerMethodField()
subjects = serializers.ReadOnlyField()
def get_description(self, obj):
return obj['content']['description']
def get_publisher(self, obj):
return obj['curation']['publisher']
class VoresourceSerializer(serializers.Serializer):
identifier = serializers.ReadOnlyField()
title = serializers.ReadOnlyField()
created = serializers.ReadOnlyField()
updated = serializers.ReadOnlyField()
type = serializers.ReadOnlyField()
status = serializers.ReadOnlyField()
curation = JSONDictField(default={})
content = JSONDictField(default={})
capabilities = JSONListField(default=[])
tableset = JSONListField(default=[])
managed_authority = serializers.ReadOnlyField(default=None)
managing_org = serializers.ReadOnlyField(default=None)
|
// ... existing code ...
from daiquiri.core.serializers import JSONDictField, JSONListField
// ... modified code ...
updated = serializers.ReadOnlyField()
type = serializers.ReadOnlyField()
status = serializers.ReadOnlyField()
...
managing_org = serializers.ReadOnlyField(default=None)
// ... rest of the code ...
|
d391f6fe8371b045cd684841da59984e5b28b1b3
|
plata/product/producer/models.py
|
plata/product/producer/models.py
|
from datetime import datetime
from django.db import models
from django.db.models import Sum, signals
from django.utils.translation import ugettext_lazy as _
from plata.product.models import Product
class ProducerManager(models.Manager):
def active(self):
return self.filter(is_active=True)
class Producer(models.Model):
is_active = models.BooleanField(_('is active'), default=True)
name = models.CharField(_('name'), max_length=100)
slug = models.SlugField(_('slug'), unique=True)
ordering = models.PositiveIntegerField(_('ordering'), default=0)
description = models.TextField(_('description'), blank=True)
class Meta:
app_label = 'product'
ordering = ['ordering', 'name']
verbose_name = _('producer')
verbose_name_plural = _('producers')
def __unicode__(self):
return self.name
Product.add_to_class('producer', models.ForeignKey(Producer,
related_name='products', verbose_name=_('producer')))
|
from datetime import datetime
from django.db import models
from django.db.models import Sum, signals
from django.utils.translation import ugettext_lazy as _
from plata.product.models import Product
class ProducerManager(models.Manager):
def active(self):
return self.filter(is_active=True)
class Producer(models.Model):
is_active = models.BooleanField(_('is active'), default=True)
name = models.CharField(_('name'), max_length=100)
slug = models.SlugField(_('slug'), unique=True)
ordering = models.PositiveIntegerField(_('ordering'), default=0)
description = models.TextField(_('description'), blank=True)
class Meta:
app_label = 'product'
ordering = ['ordering', 'name']
verbose_name = _('producer')
verbose_name_plural = _('producers')
def __unicode__(self):
return self.name
Product.add_to_class('producer', models.ForeignKey(Producer, blank=True, null=True,
related_name='products', verbose_name=_('producer')))
|
Revert "It shouldn't be that hard to define a producer, really"
|
Revert "It shouldn't be that hard to define a producer, really"
Sometimes it is.
This reverts commit 883c518d8844bd006d6abc783b315aea01d59b69.
|
Python
|
bsd-3-clause
|
allink/plata,armicron/plata,stefanklug/plata,armicron/plata,armicron/plata
|
from datetime import datetime
from django.db import models
from django.db.models import Sum, signals
from django.utils.translation import ugettext_lazy as _
from plata.product.models import Product
class ProducerManager(models.Manager):
def active(self):
return self.filter(is_active=True)
class Producer(models.Model):
is_active = models.BooleanField(_('is active'), default=True)
name = models.CharField(_('name'), max_length=100)
slug = models.SlugField(_('slug'), unique=True)
ordering = models.PositiveIntegerField(_('ordering'), default=0)
description = models.TextField(_('description'), blank=True)
class Meta:
app_label = 'product'
ordering = ['ordering', 'name']
verbose_name = _('producer')
verbose_name_plural = _('producers')
def __unicode__(self):
return self.name
- Product.add_to_class('producer', models.ForeignKey(Producer,
+ Product.add_to_class('producer', models.ForeignKey(Producer, blank=True, null=True,
related_name='products', verbose_name=_('producer')))
|
Revert "It shouldn't be that hard to define a producer, really"
|
## Code Before:
from datetime import datetime
from django.db import models
from django.db.models import Sum, signals
from django.utils.translation import ugettext_lazy as _
from plata.product.models import Product
class ProducerManager(models.Manager):
def active(self):
return self.filter(is_active=True)
class Producer(models.Model):
is_active = models.BooleanField(_('is active'), default=True)
name = models.CharField(_('name'), max_length=100)
slug = models.SlugField(_('slug'), unique=True)
ordering = models.PositiveIntegerField(_('ordering'), default=0)
description = models.TextField(_('description'), blank=True)
class Meta:
app_label = 'product'
ordering = ['ordering', 'name']
verbose_name = _('producer')
verbose_name_plural = _('producers')
def __unicode__(self):
return self.name
Product.add_to_class('producer', models.ForeignKey(Producer,
related_name='products', verbose_name=_('producer')))
## Instruction:
Revert "It shouldn't be that hard to define a producer, really"
## Code After:
from datetime import datetime
from django.db import models
from django.db.models import Sum, signals
from django.utils.translation import ugettext_lazy as _
from plata.product.models import Product
class ProducerManager(models.Manager):
def active(self):
return self.filter(is_active=True)
class Producer(models.Model):
is_active = models.BooleanField(_('is active'), default=True)
name = models.CharField(_('name'), max_length=100)
slug = models.SlugField(_('slug'), unique=True)
ordering = models.PositiveIntegerField(_('ordering'), default=0)
description = models.TextField(_('description'), blank=True)
class Meta:
app_label = 'product'
ordering = ['ordering', 'name']
verbose_name = _('producer')
verbose_name_plural = _('producers')
def __unicode__(self):
return self.name
Product.add_to_class('producer', models.ForeignKey(Producer, blank=True, null=True,
related_name='products', verbose_name=_('producer')))
|
...
Product.add_to_class('producer', models.ForeignKey(Producer, blank=True, null=True,
related_name='products', verbose_name=_('producer')))
...
|
08331a081713f880d5eca4fb7b18f4c61e360132
|
tests/skipif_markers.py
|
tests/skipif_markers.py
|
import pytest
import os
try:
os.environ[u'TRAVIS']
except KeyError:
travis = False
else:
travis = True
try:
os.environ[u'DISABLE_NETWORK_TESTS']
except KeyError:
no_network = False
else:
no_network = True
# For some reason pytest incorrectly uses the first reason text regardless of
# which condition matches. Using a unified message for now
# travis_reason = 'Works locally with tox but fails on Travis.'
# no_network_reason = 'Needs a network connection to GitHub.'
reason = (
'Fails on Travis or else there is no network connection to '
'GitHub/Bitbucket.'
)
skipif_travis = pytest.mark.skipif(travis, reason=reason)
skipif_no_network = pytest.mark.skipif(no_network, reason=reason)
|
import pytest
import os
try:
os.environ[u'TRAVIS']
except KeyError:
travis = False
else:
travis = True
try:
os.environ[u'DISABLE_NETWORK_TESTS']
except KeyError:
no_network = False
else:
no_network = True
skipif_travis = pytest.mark.skipif(
travis, reason='Works locally with tox but fails on Travis.'
)
skipif_no_network = pytest.mark.skipif(
no_network, reason='Needs a network connection to GitHub/Bitbucket.'
)
|
Revert skipif markers to use correct reasons (bug fixed in pytest)
|
Revert skipif markers to use correct reasons (bug fixed in pytest)
|
Python
|
bsd-3-clause
|
hackebrot/cookiecutter,michaeljoseph/cookiecutter,willingc/cookiecutter,stevepiercy/cookiecutter,pjbull/cookiecutter,stevepiercy/cookiecutter,audreyr/cookiecutter,terryjbates/cookiecutter,luzfcb/cookiecutter,dajose/cookiecutter,dajose/cookiecutter,michaeljoseph/cookiecutter,Springerle/cookiecutter,terryjbates/cookiecutter,willingc/cookiecutter,pjbull/cookiecutter,luzfcb/cookiecutter,audreyr/cookiecutter,Springerle/cookiecutter,hackebrot/cookiecutter
|
import pytest
import os
try:
os.environ[u'TRAVIS']
except KeyError:
travis = False
else:
travis = True
try:
os.environ[u'DISABLE_NETWORK_TESTS']
except KeyError:
no_network = False
else:
no_network = True
+ skipif_travis = pytest.mark.skipif(
- # For some reason pytest incorrectly uses the first reason text regardless of
- # which condition matches. Using a unified message for now
- # travis_reason = 'Works locally with tox but fails on Travis.'
+ travis, reason='Works locally with tox but fails on Travis.'
- # no_network_reason = 'Needs a network connection to GitHub.'
- reason = (
- 'Fails on Travis or else there is no network connection to '
- 'GitHub/Bitbucket.'
)
- skipif_travis = pytest.mark.skipif(travis, reason=reason)
- skipif_no_network = pytest.mark.skipif(no_network, reason=reason)
+ skipif_no_network = pytest.mark.skipif(
+ no_network, reason='Needs a network connection to GitHub/Bitbucket.'
+ )
|
Revert skipif markers to use correct reasons (bug fixed in pytest)
|
## Code Before:
import pytest
import os
try:
os.environ[u'TRAVIS']
except KeyError:
travis = False
else:
travis = True
try:
os.environ[u'DISABLE_NETWORK_TESTS']
except KeyError:
no_network = False
else:
no_network = True
# For some reason pytest incorrectly uses the first reason text regardless of
# which condition matches. Using a unified message for now
# travis_reason = 'Works locally with tox but fails on Travis.'
# no_network_reason = 'Needs a network connection to GitHub.'
reason = (
'Fails on Travis or else there is no network connection to '
'GitHub/Bitbucket.'
)
skipif_travis = pytest.mark.skipif(travis, reason=reason)
skipif_no_network = pytest.mark.skipif(no_network, reason=reason)
## Instruction:
Revert skipif markers to use correct reasons (bug fixed in pytest)
## Code After:
import pytest
import os
try:
os.environ[u'TRAVIS']
except KeyError:
travis = False
else:
travis = True
try:
os.environ[u'DISABLE_NETWORK_TESTS']
except KeyError:
no_network = False
else:
no_network = True
skipif_travis = pytest.mark.skipif(
travis, reason='Works locally with tox but fails on Travis.'
)
skipif_no_network = pytest.mark.skipif(
no_network, reason='Needs a network connection to GitHub/Bitbucket.'
)
|
// ... existing code ...
skipif_travis = pytest.mark.skipif(
travis, reason='Works locally with tox but fails on Travis.'
)
// ... modified code ...
skipif_no_network = pytest.mark.skipif(
no_network, reason='Needs a network connection to GitHub/Bitbucket.'
)
// ... rest of the code ...
|
50a88c05c605f5157eebadb26e30f418dc3251b6
|
tests/teamscale_client_test.py
|
tests/teamscale_client_test.py
|
import requests
import responses
from teamscale_client.teamscale_client import TeamscaleClient
def get_client():
return TeamscaleClient("http://localhost:8080", "admin", "admin", "foo")
@responses.activate
def test_put():
responses.add(responses.PUT, 'http://localhost:8080',
body='success', status=200)
resp = get_client().put("http://localhost:8080", "[]", {})
assert resp.text == "success"
|
import requests
import responses
import re
from teamscale_client.teamscale_client import TeamscaleClient
URL = "http://localhost:8080"
def get_client():
return TeamscaleClient(URL, "admin", "admin", "foo")
def get_project_service_mock(service_id):
return re.compile(r'%s/p/foo/%s/.*' % (URL, service_id))
def get_global_service_mock(service_id):
return re.compile(r'%s/%s/.*' % (URL, service_id))
@responses.activate
def test_put():
responses.add(responses.PUT, 'http://localhost:8080',
body='success', status=200)
resp = get_client().put("http://localhost:8080", "[]", {})
assert resp.text == "success"
@responses.activate
def test_upload_findings():
responses.add(responses.PUT, get_project_service_mock('add-external-findings'),
body='success', status=200)
resp = get_client().upload_findings([], 18073649127634, "Test message", "partition-name")
assert resp.text == "success"
@responses.activate
def test_upload_metrics():
responses.add(responses.PUT, get_project_service_mock('add-external-metrics'),
body='success', status=200)
resp = get_client().upload_metrics([], 18073649127634, "Test message", "partition-name")
assert resp.text == "success"
@responses.activate
def test_upload_metric_description():
responses.add(responses.PUT, get_global_service_mock('add-external-metric-description'),
body='success', status=200)
resp = get_client().upload_metric_definitions([])
assert resp.text == "success"
|
Add basic execution tests for upload methods
|
Add basic execution tests for upload methods
|
Python
|
apache-2.0
|
cqse/teamscale-client-python
|
import requests
import responses
+ import re
from teamscale_client.teamscale_client import TeamscaleClient
+ URL = "http://localhost:8080"
+
def get_client():
- return TeamscaleClient("http://localhost:8080", "admin", "admin", "foo")
+ return TeamscaleClient(URL, "admin", "admin", "foo")
+
+ def get_project_service_mock(service_id):
+ return re.compile(r'%s/p/foo/%s/.*' % (URL, service_id))
+
+ def get_global_service_mock(service_id):
+ return re.compile(r'%s/%s/.*' % (URL, service_id))
@responses.activate
def test_put():
responses.add(responses.PUT, 'http://localhost:8080',
body='success', status=200)
resp = get_client().put("http://localhost:8080", "[]", {})
assert resp.text == "success"
+ @responses.activate
+ def test_upload_findings():
+ responses.add(responses.PUT, get_project_service_mock('add-external-findings'),
+ body='success', status=200)
+ resp = get_client().upload_findings([], 18073649127634, "Test message", "partition-name")
+ assert resp.text == "success"
+
+ @responses.activate
+ def test_upload_metrics():
+ responses.add(responses.PUT, get_project_service_mock('add-external-metrics'),
+ body='success', status=200)
+ resp = get_client().upload_metrics([], 18073649127634, "Test message", "partition-name")
+ assert resp.text == "success"
+
+ @responses.activate
+ def test_upload_metric_description():
+ responses.add(responses.PUT, get_global_service_mock('add-external-metric-description'),
+ body='success', status=200)
+ resp = get_client().upload_metric_definitions([])
+ assert resp.text == "success"
+
+
|
Add basic execution tests for upload methods
|
## Code Before:
import requests
import responses
from teamscale_client.teamscale_client import TeamscaleClient
def get_client():
return TeamscaleClient("http://localhost:8080", "admin", "admin", "foo")
@responses.activate
def test_put():
responses.add(responses.PUT, 'http://localhost:8080',
body='success', status=200)
resp = get_client().put("http://localhost:8080", "[]", {})
assert resp.text == "success"
## Instruction:
Add basic execution tests for upload methods
## Code After:
import requests
import responses
import re
from teamscale_client.teamscale_client import TeamscaleClient
URL = "http://localhost:8080"
def get_client():
return TeamscaleClient(URL, "admin", "admin", "foo")
def get_project_service_mock(service_id):
return re.compile(r'%s/p/foo/%s/.*' % (URL, service_id))
def get_global_service_mock(service_id):
return re.compile(r'%s/%s/.*' % (URL, service_id))
@responses.activate
def test_put():
responses.add(responses.PUT, 'http://localhost:8080',
body='success', status=200)
resp = get_client().put("http://localhost:8080", "[]", {})
assert resp.text == "success"
@responses.activate
def test_upload_findings():
responses.add(responses.PUT, get_project_service_mock('add-external-findings'),
body='success', status=200)
resp = get_client().upload_findings([], 18073649127634, "Test message", "partition-name")
assert resp.text == "success"
@responses.activate
def test_upload_metrics():
responses.add(responses.PUT, get_project_service_mock('add-external-metrics'),
body='success', status=200)
resp = get_client().upload_metrics([], 18073649127634, "Test message", "partition-name")
assert resp.text == "success"
@responses.activate
def test_upload_metric_description():
responses.add(responses.PUT, get_global_service_mock('add-external-metric-description'),
body='success', status=200)
resp = get_client().upload_metric_definitions([])
assert resp.text == "success"
|
# ... existing code ...
import responses
import re
from teamscale_client.teamscale_client import TeamscaleClient
# ... modified code ...
URL = "http://localhost:8080"
def get_client():
return TeamscaleClient(URL, "admin", "admin", "foo")
def get_project_service_mock(service_id):
return re.compile(r'%s/p/foo/%s/.*' % (URL, service_id))
def get_global_service_mock(service_id):
return re.compile(r'%s/%s/.*' % (URL, service_id))
...
assert resp.text == "success"
@responses.activate
def test_upload_findings():
responses.add(responses.PUT, get_project_service_mock('add-external-findings'),
body='success', status=200)
resp = get_client().upload_findings([], 18073649127634, "Test message", "partition-name")
assert resp.text == "success"
@responses.activate
def test_upload_metrics():
responses.add(responses.PUT, get_project_service_mock('add-external-metrics'),
body='success', status=200)
resp = get_client().upload_metrics([], 18073649127634, "Test message", "partition-name")
assert resp.text == "success"
@responses.activate
def test_upload_metric_description():
responses.add(responses.PUT, get_global_service_mock('add-external-metric-description'),
body='success', status=200)
resp = get_client().upload_metric_definitions([])
assert resp.text == "success"
# ... rest of the code ...
|
35d80ac6af0a546f138f6db31511e9dade7aae8e
|
feder/es_search/queries.py
|
feder/es_search/queries.py
|
from elasticsearch_dsl import Search, Index
from elasticsearch_dsl.query import MultiMatch, Match, Q, MoreLikeThis
from elasticsearch_dsl.connections import get_connection, connections
from .documents import LetterDocument
def serialize_document(doc):
return {
"_id": doc.__dict__["meta"]["id"],
"_index": doc.__dict__["meta"]["index"],
}
def search_keywords(query):
q = MultiMatch(query=query, fields=["title", "body", "content"])
return LetterDocument.search().query(q).execute()
def more_like_this(doc):
like = serialize_document(doc)
q = MoreLikeThis(like=like, fields=["title", "body"],)
query = LetterDocument.search().query(q)
print(query.to_dict())
x = query.execute()
print(x)
return x
|
from elasticsearch_dsl import Search, Index
from elasticsearch_dsl.query import MultiMatch, Match, Q, MoreLikeThis
from elasticsearch_dsl.connections import get_connection, connections
from .documents import LetterDocument
def serialize_document(doc):
return {
"_id": doc.__dict__["meta"]["id"],
"_index": doc.__dict__["meta"]["index"],
}
def search_keywords(query):
q = MultiMatch(query=query, fields=["title", "body", "content"])
return LetterDocument.search().query(q).execute()
def more_like_this(doc):
like = serialize_document(doc)
q = MoreLikeThis(like=like, fields=["title", "body"],)
query = LetterDocument.search().query(q)
# print(query.to_dict())
return query.execute()
|
Reduce debug logging in more_like_this
|
Reduce debug logging in more_like_this
|
Python
|
mit
|
watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder
|
from elasticsearch_dsl import Search, Index
from elasticsearch_dsl.query import MultiMatch, Match, Q, MoreLikeThis
from elasticsearch_dsl.connections import get_connection, connections
from .documents import LetterDocument
def serialize_document(doc):
return {
"_id": doc.__dict__["meta"]["id"],
"_index": doc.__dict__["meta"]["index"],
}
def search_keywords(query):
q = MultiMatch(query=query, fields=["title", "body", "content"])
return LetterDocument.search().query(q).execute()
def more_like_this(doc):
like = serialize_document(doc)
q = MoreLikeThis(like=like, fields=["title", "body"],)
query = LetterDocument.search().query(q)
- print(query.to_dict())
+ # print(query.to_dict())
- x = query.execute()
+ return query.execute()
- print(x)
- return x
|
Reduce debug logging in more_like_this
|
## Code Before:
from elasticsearch_dsl import Search, Index
from elasticsearch_dsl.query import MultiMatch, Match, Q, MoreLikeThis
from elasticsearch_dsl.connections import get_connection, connections
from .documents import LetterDocument
def serialize_document(doc):
return {
"_id": doc.__dict__["meta"]["id"],
"_index": doc.__dict__["meta"]["index"],
}
def search_keywords(query):
q = MultiMatch(query=query, fields=["title", "body", "content"])
return LetterDocument.search().query(q).execute()
def more_like_this(doc):
like = serialize_document(doc)
q = MoreLikeThis(like=like, fields=["title", "body"],)
query = LetterDocument.search().query(q)
print(query.to_dict())
x = query.execute()
print(x)
return x
## Instruction:
Reduce debug logging in more_like_this
## Code After:
from elasticsearch_dsl import Search, Index
from elasticsearch_dsl.query import MultiMatch, Match, Q, MoreLikeThis
from elasticsearch_dsl.connections import get_connection, connections
from .documents import LetterDocument
def serialize_document(doc):
return {
"_id": doc.__dict__["meta"]["id"],
"_index": doc.__dict__["meta"]["index"],
}
def search_keywords(query):
q = MultiMatch(query=query, fields=["title", "body", "content"])
return LetterDocument.search().query(q).execute()
def more_like_this(doc):
like = serialize_document(doc)
q = MoreLikeThis(like=like, fields=["title", "body"],)
query = LetterDocument.search().query(q)
# print(query.to_dict())
return query.execute()
|
...
query = LetterDocument.search().query(q)
# print(query.to_dict())
return query.execute()
...
|
f9698eb96ca0c69a9d41a2d19a56af83e74da949
|
examples/advanced/extend_python.py
|
examples/advanced/extend_python.py
|
from lark.lark import Lark
from python_parser import PythonIndenter
GRAMMAR = r"""
%import python (compound_stmt, single_input, file_input, eval_input, test, suite, _NEWLINE, _INDENT, _DEDENT, COMMENT)
%extend compound_stmt: match_stmt
match_stmt: "match" test ":" cases
cases: _NEWLINE _INDENT case+ _DEDENT
case: "case" test ":" suite // test is not quite correct.
%ignore /[\t \f]+/ // WS
%ignore /\\[\t \f]*\r?\n/ // LINE_CONT
%ignore COMMENT
"""
parser = Lark(GRAMMAR, parser='lalr', start=['single_input', 'file_input', 'eval_input'], postlex=PythonIndenter())
tree = parser.parse(r"""
def name(n):
match n:
case 1:
print("one")
case 2:
print("two")
case _:
print("number is too big")
""", start='file_input')
# Remove the 'python3__' prefix that was added to the implicitly imported rules.
for t in tree.iter_subtrees():
t.data = t.data.rsplit('__', 1)[-1]
print(tree.pretty())
|
from lark.lark import Lark
from lark.indenter import PythonIndenter
GRAMMAR = r"""
%import python (compound_stmt, single_input, file_input, eval_input, test, suite, _NEWLINE, _INDENT, _DEDENT, COMMENT)
%extend compound_stmt: match_stmt
match_stmt: "match" test ":" cases
cases: _NEWLINE _INDENT case+ _DEDENT
case: "case" test ":" suite // test is not quite correct.
%ignore /[\t \f]+/ // WS
%ignore /\\[\t \f]*\r?\n/ // LINE_CONT
%ignore COMMENT
"""
parser = Lark(GRAMMAR, parser='lalr', start=['single_input', 'file_input', 'eval_input'], postlex=PythonIndenter())
tree = parser.parse(r"""
def name(n):
match n:
case 1:
print("one")
case 2:
print("two")
case _:
print("number is too big")
""", start='file_input')
# Remove the 'python3__' prefix that was added to the implicitly imported rules.
for t in tree.iter_subtrees():
t.data = t.data.rsplit('__', 1)[-1]
print(tree.pretty())
|
Fix confusing import (no change in functionality)
|
Fix confusing import (no change in functionality)
|
Python
|
mit
|
lark-parser/lark
|
from lark.lark import Lark
- from python_parser import PythonIndenter
+ from lark.indenter import PythonIndenter
GRAMMAR = r"""
%import python (compound_stmt, single_input, file_input, eval_input, test, suite, _NEWLINE, _INDENT, _DEDENT, COMMENT)
%extend compound_stmt: match_stmt
match_stmt: "match" test ":" cases
cases: _NEWLINE _INDENT case+ _DEDENT
case: "case" test ":" suite // test is not quite correct.
%ignore /[\t \f]+/ // WS
%ignore /\\[\t \f]*\r?\n/ // LINE_CONT
%ignore COMMENT
"""
parser = Lark(GRAMMAR, parser='lalr', start=['single_input', 'file_input', 'eval_input'], postlex=PythonIndenter())
tree = parser.parse(r"""
def name(n):
match n:
case 1:
print("one")
case 2:
print("two")
case _:
print("number is too big")
""", start='file_input')
# Remove the 'python3__' prefix that was added to the implicitly imported rules.
for t in tree.iter_subtrees():
t.data = t.data.rsplit('__', 1)[-1]
print(tree.pretty())
|
Fix confusing import (no change in functionality)
|
## Code Before:
from lark.lark import Lark
from python_parser import PythonIndenter
GRAMMAR = r"""
%import python (compound_stmt, single_input, file_input, eval_input, test, suite, _NEWLINE, _INDENT, _DEDENT, COMMENT)
%extend compound_stmt: match_stmt
match_stmt: "match" test ":" cases
cases: _NEWLINE _INDENT case+ _DEDENT
case: "case" test ":" suite // test is not quite correct.
%ignore /[\t \f]+/ // WS
%ignore /\\[\t \f]*\r?\n/ // LINE_CONT
%ignore COMMENT
"""
parser = Lark(GRAMMAR, parser='lalr', start=['single_input', 'file_input', 'eval_input'], postlex=PythonIndenter())
tree = parser.parse(r"""
def name(n):
match n:
case 1:
print("one")
case 2:
print("two")
case _:
print("number is too big")
""", start='file_input')
# Remove the 'python3__' prefix that was added to the implicitly imported rules.
for t in tree.iter_subtrees():
t.data = t.data.rsplit('__', 1)[-1]
print(tree.pretty())
## Instruction:
Fix confusing import (no change in functionality)
## Code After:
from lark.lark import Lark
from lark.indenter import PythonIndenter
GRAMMAR = r"""
%import python (compound_stmt, single_input, file_input, eval_input, test, suite, _NEWLINE, _INDENT, _DEDENT, COMMENT)
%extend compound_stmt: match_stmt
match_stmt: "match" test ":" cases
cases: _NEWLINE _INDENT case+ _DEDENT
case: "case" test ":" suite // test is not quite correct.
%ignore /[\t \f]+/ // WS
%ignore /\\[\t \f]*\r?\n/ // LINE_CONT
%ignore COMMENT
"""
parser = Lark(GRAMMAR, parser='lalr', start=['single_input', 'file_input', 'eval_input'], postlex=PythonIndenter())
tree = parser.parse(r"""
def name(n):
match n:
case 1:
print("one")
case 2:
print("two")
case _:
print("number is too big")
""", start='file_input')
# Remove the 'python3__' prefix that was added to the implicitly imported rules.
for t in tree.iter_subtrees():
t.data = t.data.rsplit('__', 1)[-1]
print(tree.pretty())
|
# ... existing code ...
from lark.lark import Lark
from lark.indenter import PythonIndenter
# ... rest of the code ...
|
e6e0d96790d71caccb3f00487bfeeddccdc78139
|
app/raw/tasks.py
|
app/raw/tasks.py
|
from __future__ import absolute_import
from celery import shared_task
from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy import log, signals
from scrapy.utils.project import get_project_settings
import os
from raw.scraper.spiders.legco_library import LibraryAgendaSpider
from raw.scraper.spiders.members import LibraryMemberSpider
@shared_task
def run_scraper():
output_name = 'foo.jl'
spider = LibraryAgendaSpider()
settings = get_project_settings()
url_path = os.path.join(settings.get('DATA_DIR_BASE'), 'scrapes', output_name)
settings.overrides['FEED_URI'] = url_path
crawler = Crawler(settings)
crawler.signals.connect(reactor.stop, signal=signals.spider_closed)
crawler.configure()
crawler.crawl(spider)
crawler.start()
log.start(loglevel=log.INFO, logstdout=True)
reactor.run()
return output_name
|
from __future__ import absolute_import
from celery import shared_task
from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy import log, signals
from scrapy.utils.project import get_project_settings
import os
from raw.scraper.spiders.legco_library import LibraryAgendaSpider
from raw.scraper.spiders.members import LibraryMemberSpider
@shared_task
def run_scraper():
output_name = 'foo.jl'
spider = LibraryAgendaSpider()
settings = get_project_settings()
output_path = os.path.join(settings.get('DATA_DIR_BASE'), 'scrapes', output_name)
settings.overrides['FEED_URI'] = output_path
crawler = Crawler(settings)
crawler.signals.connect(reactor.stop, signal=signals.spider_closed)
crawler.configure()
crawler.crawl(spider)
crawler.start()
log.start(loglevel=log.INFO, logstdout=True)
reactor.run()
return output_path
|
Fix variable and return value
|
Fix variable and return value
|
Python
|
mit
|
legco-watch/legco-watch,comsaint/legco-watch,comsaint/legco-watch,legco-watch/legco-watch,comsaint/legco-watch,legco-watch/legco-watch,comsaint/legco-watch,legco-watch/legco-watch
|
from __future__ import absolute_import
from celery import shared_task
from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy import log, signals
from scrapy.utils.project import get_project_settings
import os
from raw.scraper.spiders.legco_library import LibraryAgendaSpider
from raw.scraper.spiders.members import LibraryMemberSpider
@shared_task
def run_scraper():
output_name = 'foo.jl'
spider = LibraryAgendaSpider()
settings = get_project_settings()
- url_path = os.path.join(settings.get('DATA_DIR_BASE'), 'scrapes', output_name)
+ output_path = os.path.join(settings.get('DATA_DIR_BASE'), 'scrapes', output_name)
- settings.overrides['FEED_URI'] = url_path
+ settings.overrides['FEED_URI'] = output_path
crawler = Crawler(settings)
crawler.signals.connect(reactor.stop, signal=signals.spider_closed)
crawler.configure()
crawler.crawl(spider)
crawler.start()
log.start(loglevel=log.INFO, logstdout=True)
reactor.run()
- return output_name
+ return output_path
|
Fix variable and return value
|
## Code Before:
from __future__ import absolute_import
from celery import shared_task
from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy import log, signals
from scrapy.utils.project import get_project_settings
import os
from raw.scraper.spiders.legco_library import LibraryAgendaSpider
from raw.scraper.spiders.members import LibraryMemberSpider
@shared_task
def run_scraper():
output_name = 'foo.jl'
spider = LibraryAgendaSpider()
settings = get_project_settings()
url_path = os.path.join(settings.get('DATA_DIR_BASE'), 'scrapes', output_name)
settings.overrides['FEED_URI'] = url_path
crawler = Crawler(settings)
crawler.signals.connect(reactor.stop, signal=signals.spider_closed)
crawler.configure()
crawler.crawl(spider)
crawler.start()
log.start(loglevel=log.INFO, logstdout=True)
reactor.run()
return output_name
## Instruction:
Fix variable and return value
## Code After:
from __future__ import absolute_import
from celery import shared_task
from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy import log, signals
from scrapy.utils.project import get_project_settings
import os
from raw.scraper.spiders.legco_library import LibraryAgendaSpider
from raw.scraper.spiders.members import LibraryMemberSpider
@shared_task
def run_scraper():
output_name = 'foo.jl'
spider = LibraryAgendaSpider()
settings = get_project_settings()
output_path = os.path.join(settings.get('DATA_DIR_BASE'), 'scrapes', output_name)
settings.overrides['FEED_URI'] = output_path
crawler = Crawler(settings)
crawler.signals.connect(reactor.stop, signal=signals.spider_closed)
crawler.configure()
crawler.crawl(spider)
crawler.start()
log.start(loglevel=log.INFO, logstdout=True)
reactor.run()
return output_path
|
# ... existing code ...
settings = get_project_settings()
output_path = os.path.join(settings.get('DATA_DIR_BASE'), 'scrapes', output_name)
settings.overrides['FEED_URI'] = output_path
# ... modified code ...
reactor.run()
return output_path
# ... rest of the code ...
|
a65eea671a605bdeef70160e2d967a59888fcd1b
|
molml/features.py
|
molml/features.py
|
from .atom import * # NOQA
from .molecule import * # NOQA
|
from .atom import * # NOQA
from .molecule import * # NOQA
from .crystal import * # NOQA
from .kernel import * # NOQA
|
Add default import for crystal and kernel
|
Add default import for crystal and kernel
|
Python
|
mit
|
crcollins/molml
|
from .atom import * # NOQA
from .molecule import * # NOQA
+ from .crystal import * # NOQA
+ from .kernel import * # NOQA
|
Add default import for crystal and kernel
|
## Code Before:
from .atom import * # NOQA
from .molecule import * # NOQA
## Instruction:
Add default import for crystal and kernel
## Code After:
from .atom import * # NOQA
from .molecule import * # NOQA
from .crystal import * # NOQA
from .kernel import * # NOQA
|
...
from .molecule import * # NOQA
from .crystal import * # NOQA
from .kernel import * # NOQA
...
|
74d7c55ab6584daef444923c888e6905d8c9ccf1
|
expense/admin.py
|
expense/admin.py
|
from django.contrib import admin
from expense.models import ExpenseNote
class ExpenseNoteAdmin(admin.ModelAdmin):
list_display = ['date', 'save_in_ledger', 'details', 'contact', 'credit_account', 'debit_account', 'amount']
list_filter = ['date', 'save_in_ledger']
readonly_fields = ['amount']
fields = ('date', 'contact', 'number', 'details', 'credit_account', 'debit_account', 'amount', 'save_in_ledger')
admin.site.register(ExpenseNote, ExpenseNoteAdmin)
|
from django.contrib import admin
from expense.models import ExpenseNote
class ExpenseNoteAdmin(admin.ModelAdmin):
list_display = ['date', 'save_in_ledger', 'details', 'contact', 'credit_account', 'debit_account', 'amount']
list_filter = ['date', 'save_in_ledger']
fields = ('date', 'contact', 'number', 'details', 'credit_account', 'debit_account', 'amount', 'save_in_ledger')
admin.site.register(ExpenseNote, ExpenseNoteAdmin)
|
Allow editing amount field in expensenote
|
Allow editing amount field in expensenote
|
Python
|
mpl-2.0
|
jackbravo/condorest-django,jackbravo/condorest-django,jackbravo/condorest-django
|
from django.contrib import admin
from expense.models import ExpenseNote
class ExpenseNoteAdmin(admin.ModelAdmin):
list_display = ['date', 'save_in_ledger', 'details', 'contact', 'credit_account', 'debit_account', 'amount']
list_filter = ['date', 'save_in_ledger']
- readonly_fields = ['amount']
fields = ('date', 'contact', 'number', 'details', 'credit_account', 'debit_account', 'amount', 'save_in_ledger')
admin.site.register(ExpenseNote, ExpenseNoteAdmin)
|
Allow editing amount field in expensenote
|
## Code Before:
from django.contrib import admin
from expense.models import ExpenseNote
class ExpenseNoteAdmin(admin.ModelAdmin):
list_display = ['date', 'save_in_ledger', 'details', 'contact', 'credit_account', 'debit_account', 'amount']
list_filter = ['date', 'save_in_ledger']
readonly_fields = ['amount']
fields = ('date', 'contact', 'number', 'details', 'credit_account', 'debit_account', 'amount', 'save_in_ledger')
admin.site.register(ExpenseNote, ExpenseNoteAdmin)
## Instruction:
Allow editing amount field in expensenote
## Code After:
from django.contrib import admin
from expense.models import ExpenseNote
class ExpenseNoteAdmin(admin.ModelAdmin):
list_display = ['date', 'save_in_ledger', 'details', 'contact', 'credit_account', 'debit_account', 'amount']
list_filter = ['date', 'save_in_ledger']
fields = ('date', 'contact', 'number', 'details', 'credit_account', 'debit_account', 'amount', 'save_in_ledger')
admin.site.register(ExpenseNote, ExpenseNoteAdmin)
|
...
list_filter = ['date', 'save_in_ledger']
fields = ('date', 'contact', 'number', 'details', 'credit_account', 'debit_account', 'amount', 'save_in_ledger')
...
|
29bf7ef7de9e0a5c66876b126f4df7ef279e30b6
|
mediacloud/mediawords/db/exceptions/handler.py
|
mediacloud/mediawords/db/exceptions/handler.py
|
class McDatabaseHandlerException(Exception):
"""Database handler exception."""
pass
class McConnectException(McDatabaseHandlerException):
"""__connect() exception."""
pass
class McSchemaIsUpToDateException(McDatabaseHandlerException):
"""schema_is_up_to_date() exception."""
pass
class McQueryException(McDatabaseHandlerException):
"""query() exception."""
pass
class McPrimaryKeyColumnException(McDatabaseHandlerException):
"""primary_key_column() exception."""
pass
class McFindByIDException(McDatabaseHandlerException):
"""find_by_id() exception."""
pass
class McRequireByIDException(McDatabaseHandlerException):
"""require_by_id() exception."""
pass
class McUpdateByIDException(McDatabaseHandlerException):
"""update_by_id() exception."""
pass
class McDeleteByIDException(McDatabaseHandlerException):
"""delete_by_id() exception."""
pass
class McCreateException(McDatabaseHandlerException):
"""create() exception."""
pass
class McSelectException(McDatabaseHandlerException):
"""select() exception."""
pass
class McFindOrCreateException(McDatabaseHandlerException):
"""find_or_create() exception."""
pass
class McQuoteException(McDatabaseHandlerException):
"""quote() exception."""
pass
class McPrepareException(McDatabaseHandlerException):
"""prepare() exception."""
pass
class McQueryPagedHashesException(McDatabaseHandlerException):
"""query_paged_hashes() exception."""
pass
class McTransactionException(McDatabaseHandlerException):
"""Exception thrown on transaction problems."""
pass
class McBeginException(McTransactionException):
"""begin() exception."""
pass
|
class McDatabaseHandlerException(Exception):
"""Database handler exception."""
pass
class McConnectException(McDatabaseHandlerException):
"""__connect() exception."""
pass
class McSchemaIsUpToDateException(McDatabaseHandlerException):
"""schema_is_up_to_date() exception."""
pass
class McQueryException(McDatabaseHandlerException):
"""query() exception."""
pass
class McPrimaryKeyColumnException(McDatabaseHandlerException):
"""primary_key_column() exception."""
pass
class McFindByIDException(McDatabaseHandlerException):
"""find_by_id() exception."""
pass
class McRequireByIDException(McDatabaseHandlerException):
"""require_by_id() exception."""
pass
class McUpdateByIDException(McDatabaseHandlerException):
"""update_by_id() exception."""
pass
class McDeleteByIDException(McDatabaseHandlerException):
"""delete_by_id() exception."""
pass
class McCreateException(McDatabaseHandlerException):
"""create() exception."""
pass
class McFindOrCreateException(McDatabaseHandlerException):
"""find_or_create() exception."""
pass
class McQuoteException(McDatabaseHandlerException):
"""quote() exception."""
pass
class McPrepareException(McDatabaseHandlerException):
"""prepare() exception."""
pass
class McQueryPagedHashesException(McDatabaseHandlerException):
"""query_paged_hashes() exception."""
pass
class McTransactionException(McDatabaseHandlerException):
"""Exception thrown on transaction problems."""
pass
class McBeginException(McTransactionException):
"""begin() exception."""
pass
|
Revert "Add exception to be thrown by select()"
|
Revert "Add exception to be thrown by select()"
This reverts commit 1009bd3b5e5941aff2f7b3852494ee19f085dcce.
|
Python
|
agpl-3.0
|
berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud
|
class McDatabaseHandlerException(Exception):
"""Database handler exception."""
pass
class McConnectException(McDatabaseHandlerException):
"""__connect() exception."""
pass
class McSchemaIsUpToDateException(McDatabaseHandlerException):
"""schema_is_up_to_date() exception."""
pass
class McQueryException(McDatabaseHandlerException):
"""query() exception."""
pass
class McPrimaryKeyColumnException(McDatabaseHandlerException):
"""primary_key_column() exception."""
pass
class McFindByIDException(McDatabaseHandlerException):
"""find_by_id() exception."""
pass
class McRequireByIDException(McDatabaseHandlerException):
"""require_by_id() exception."""
pass
class McUpdateByIDException(McDatabaseHandlerException):
"""update_by_id() exception."""
pass
class McDeleteByIDException(McDatabaseHandlerException):
"""delete_by_id() exception."""
pass
class McCreateException(McDatabaseHandlerException):
"""create() exception."""
pass
- class McSelectException(McDatabaseHandlerException):
- """select() exception."""
- pass
-
-
class McFindOrCreateException(McDatabaseHandlerException):
"""find_or_create() exception."""
pass
class McQuoteException(McDatabaseHandlerException):
"""quote() exception."""
pass
class McPrepareException(McDatabaseHandlerException):
"""prepare() exception."""
pass
class McQueryPagedHashesException(McDatabaseHandlerException):
"""query_paged_hashes() exception."""
pass
class McTransactionException(McDatabaseHandlerException):
"""Exception thrown on transaction problems."""
pass
class McBeginException(McTransactionException):
"""begin() exception."""
pass
|
Revert "Add exception to be thrown by select()"
|
## Code Before:
class McDatabaseHandlerException(Exception):
"""Database handler exception."""
pass
class McConnectException(McDatabaseHandlerException):
"""__connect() exception."""
pass
class McSchemaIsUpToDateException(McDatabaseHandlerException):
"""schema_is_up_to_date() exception."""
pass
class McQueryException(McDatabaseHandlerException):
"""query() exception."""
pass
class McPrimaryKeyColumnException(McDatabaseHandlerException):
"""primary_key_column() exception."""
pass
class McFindByIDException(McDatabaseHandlerException):
"""find_by_id() exception."""
pass
class McRequireByIDException(McDatabaseHandlerException):
"""require_by_id() exception."""
pass
class McUpdateByIDException(McDatabaseHandlerException):
"""update_by_id() exception."""
pass
class McDeleteByIDException(McDatabaseHandlerException):
"""delete_by_id() exception."""
pass
class McCreateException(McDatabaseHandlerException):
"""create() exception."""
pass
class McSelectException(McDatabaseHandlerException):
"""select() exception."""
pass
class McFindOrCreateException(McDatabaseHandlerException):
"""find_or_create() exception."""
pass
class McQuoteException(McDatabaseHandlerException):
"""quote() exception."""
pass
class McPrepareException(McDatabaseHandlerException):
"""prepare() exception."""
pass
class McQueryPagedHashesException(McDatabaseHandlerException):
"""query_paged_hashes() exception."""
pass
class McTransactionException(McDatabaseHandlerException):
"""Exception thrown on transaction problems."""
pass
class McBeginException(McTransactionException):
"""begin() exception."""
pass
## Instruction:
Revert "Add exception to be thrown by select()"
## Code After:
class McDatabaseHandlerException(Exception):
"""Database handler exception."""
pass
class McConnectException(McDatabaseHandlerException):
"""__connect() exception."""
pass
class McSchemaIsUpToDateException(McDatabaseHandlerException):
"""schema_is_up_to_date() exception."""
pass
class McQueryException(McDatabaseHandlerException):
"""query() exception."""
pass
class McPrimaryKeyColumnException(McDatabaseHandlerException):
"""primary_key_column() exception."""
pass
class McFindByIDException(McDatabaseHandlerException):
"""find_by_id() exception."""
pass
class McRequireByIDException(McDatabaseHandlerException):
"""require_by_id() exception."""
pass
class McUpdateByIDException(McDatabaseHandlerException):
"""update_by_id() exception."""
pass
class McDeleteByIDException(McDatabaseHandlerException):
"""delete_by_id() exception."""
pass
class McCreateException(McDatabaseHandlerException):
"""create() exception."""
pass
class McFindOrCreateException(McDatabaseHandlerException):
"""find_or_create() exception."""
pass
class McQuoteException(McDatabaseHandlerException):
"""quote() exception."""
pass
class McPrepareException(McDatabaseHandlerException):
"""prepare() exception."""
pass
class McQueryPagedHashesException(McDatabaseHandlerException):
"""query_paged_hashes() exception."""
pass
class McTransactionException(McDatabaseHandlerException):
"""Exception thrown on transaction problems."""
pass
class McBeginException(McTransactionException):
"""begin() exception."""
pass
|
# ... existing code ...
class McFindOrCreateException(McDatabaseHandlerException):
# ... rest of the code ...
|
d538e4fd59d714b7a7826937c50b66ec3f697b05
|
mygpo/api/backend.py
|
mygpo/api/backend.py
|
import uuid
from django.db import transaction, IntegrityError
from mygpo.users.settings import STORE_UA
from mygpo.users.models import Client
import logging
logger = logging.getLogger(__name__)
def get_device(user, uid, user_agent, undelete=True):
"""
Loads or creates the device indicated by user, uid.
If the device has been deleted and undelete=True, it is undeleted.
"""
store_ua = user.profile.settings.get_wksetting(STORE_UA)
# list of fields to update -- empty list = no update
update_fields = []
try:
with transaction.atomic():
client = Client(id=uuid.uuid1(), user=user, uid=uid)
client.full_clean()
client.save()
except IntegrityError:
client = Client.objects.get(user=user, uid=uid)
if client.deleted and undelete:
client.deleted = False
update_fields.append('deleted')
if store_ua and user_agent and client.user_agent != user_agent:
client.user_agent = user_agent
update_fields.append('user_agent')
if update_fields:
client.save(update_fields=update_fields)
return client
|
import uuid
from django.db import transaction, IntegrityError
from mygpo.users.settings import STORE_UA
from mygpo.users.models import Client
import logging
logger = logging.getLogger(__name__)
def get_device(user, uid, user_agent, undelete=True):
"""
Loads or creates the device indicated by user, uid.
If the device has been deleted and undelete=True, it is undeleted.
"""
store_ua = user.profile.settings.get_wksetting(STORE_UA)
# list of fields to update -- empty list = no update
update_fields = []
try:
with transaction.atomic():
client = Client(id=uuid.uuid1(), user=user, uid=uid)
client.clean_fields()
client.clean()
client.save()
except IntegrityError:
client = Client.objects.get(user=user, uid=uid)
if client.deleted and undelete:
client.deleted = False
update_fields.append('deleted')
if store_ua and user_agent and client.user_agent != user_agent:
client.user_agent = user_agent
update_fields.append('user_agent')
if update_fields:
client.save(update_fields=update_fields)
return client
|
Fix validation of Client objects
|
Fix validation of Client objects
|
Python
|
agpl-3.0
|
gpodder/mygpo,gpodder/mygpo,gpodder/mygpo,gpodder/mygpo
|
import uuid
from django.db import transaction, IntegrityError
from mygpo.users.settings import STORE_UA
from mygpo.users.models import Client
import logging
logger = logging.getLogger(__name__)
def get_device(user, uid, user_agent, undelete=True):
"""
Loads or creates the device indicated by user, uid.
If the device has been deleted and undelete=True, it is undeleted.
"""
store_ua = user.profile.settings.get_wksetting(STORE_UA)
# list of fields to update -- empty list = no update
update_fields = []
try:
with transaction.atomic():
client = Client(id=uuid.uuid1(), user=user, uid=uid)
+ client.clean_fields()
- client.full_clean()
+ client.clean()
client.save()
except IntegrityError:
client = Client.objects.get(user=user, uid=uid)
if client.deleted and undelete:
client.deleted = False
update_fields.append('deleted')
if store_ua and user_agent and client.user_agent != user_agent:
client.user_agent = user_agent
update_fields.append('user_agent')
if update_fields:
client.save(update_fields=update_fields)
return client
|
Fix validation of Client objects
|
## Code Before:
import uuid
from django.db import transaction, IntegrityError
from mygpo.users.settings import STORE_UA
from mygpo.users.models import Client
import logging
logger = logging.getLogger(__name__)
def get_device(user, uid, user_agent, undelete=True):
"""
Loads or creates the device indicated by user, uid.
If the device has been deleted and undelete=True, it is undeleted.
"""
store_ua = user.profile.settings.get_wksetting(STORE_UA)
# list of fields to update -- empty list = no update
update_fields = []
try:
with transaction.atomic():
client = Client(id=uuid.uuid1(), user=user, uid=uid)
client.full_clean()
client.save()
except IntegrityError:
client = Client.objects.get(user=user, uid=uid)
if client.deleted and undelete:
client.deleted = False
update_fields.append('deleted')
if store_ua and user_agent and client.user_agent != user_agent:
client.user_agent = user_agent
update_fields.append('user_agent')
if update_fields:
client.save(update_fields=update_fields)
return client
## Instruction:
Fix validation of Client objects
## Code After:
import uuid
from django.db import transaction, IntegrityError
from mygpo.users.settings import STORE_UA
from mygpo.users.models import Client
import logging
logger = logging.getLogger(__name__)
def get_device(user, uid, user_agent, undelete=True):
"""
Loads or creates the device indicated by user, uid.
If the device has been deleted and undelete=True, it is undeleted.
"""
store_ua = user.profile.settings.get_wksetting(STORE_UA)
# list of fields to update -- empty list = no update
update_fields = []
try:
with transaction.atomic():
client = Client(id=uuid.uuid1(), user=user, uid=uid)
client.clean_fields()
client.clean()
client.save()
except IntegrityError:
client = Client.objects.get(user=user, uid=uid)
if client.deleted and undelete:
client.deleted = False
update_fields.append('deleted')
if store_ua and user_agent and client.user_agent != user_agent:
client.user_agent = user_agent
update_fields.append('user_agent')
if update_fields:
client.save(update_fields=update_fields)
return client
|
# ... existing code ...
client = Client(id=uuid.uuid1(), user=user, uid=uid)
client.clean_fields()
client.clean()
client.save()
# ... rest of the code ...
|
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))
|
...
sock.connect(server_address)
sock.sendall(json.dumps(result))
print (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
|
...
raise RuntimeError("{platform} is not supported.".format(platform=platform))
except (RuntimeError, ImportError) as e:
import warnings
...
|
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),
]
|
# ... existing code ...
urlpatterns = [
url(r'^$', views.index),
url(r'^personal/$', views.personal_data),
# ... rest of the code ...
|
db13de154fa44f3ef0bf1e365d2ee0d7a6951700
|
cellcounter/accounts/urls.py
|
cellcounter/accounts/urls.py
|
from django.conf.urls import patterns, url
from cellcounter.accounts import views
urlpatterns = patterns('',
url('^new/$', views.RegistrationView.as_view(), name='register'),
url('^(?P<pk>[0-9]+)/$', views.UserDetailView.as_view(), name='user-detail'),
url('^(?P<pk>[0-9]+)/delete/$', views.UserDeleteView.as_view(), name='user-delete'),
url('^(?P<pk>[0-9]+)/edit/$', views.UserUpdateView.as_view(), name='user-update'),
url('^password/reset/$', views.PasswordResetView.as_view(),
name='password-reset'),
url('^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[\d\w\-]+)/$',
views.PasswordResetConfirmView.as_view(),
name='password-reset-confirm'),
url('^password/change/$', views.PasswordChangeView.as_view(), name='change-password'),
)
|
from django.conf.urls import patterns, url
from cellcounter.accounts import views
urlpatterns = patterns('',
url('^new/$', views.RegistrationView.as_view(), name='register'),
url('^(?P<pk>[0-9]+)/$', views.UserDetailView.as_view(), name='user-detail'),
url('^(?P<pk>[0-9]+)/delete/$', views.UserDeleteView.as_view(), name='user-delete'),
url('^(?P<pk>[0-9]+)/edit/$', views.UserUpdateView.as_view(), name='user-update'),
url('^password/reset/$', views.PasswordResetView.as_view(),
name='password-reset'),
url('^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
views.PasswordResetConfirmView.as_view(),
name='password-reset-confirm'),
url('^password/change/$', views.PasswordChangeView.as_view(), name='change-password'),
)
|
Use URL regex as per main Django project
|
Use URL regex as per main Django project
|
Python
|
mit
|
cellcounter/cellcounter,haematologic/cellcounter,haematologic/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,haematologic/cellcounter
|
from django.conf.urls import patterns, url
from cellcounter.accounts import views
urlpatterns = patterns('',
url('^new/$', views.RegistrationView.as_view(), name='register'),
url('^(?P<pk>[0-9]+)/$', views.UserDetailView.as_view(), name='user-detail'),
url('^(?P<pk>[0-9]+)/delete/$', views.UserDeleteView.as_view(), name='user-delete'),
url('^(?P<pk>[0-9]+)/edit/$', views.UserUpdateView.as_view(), name='user-update'),
url('^password/reset/$', views.PasswordResetView.as_view(),
name='password-reset'),
- url('^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[\d\w\-]+)/$',
+ url('^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
views.PasswordResetConfirmView.as_view(),
name='password-reset-confirm'),
url('^password/change/$', views.PasswordChangeView.as_view(), name='change-password'),
)
|
Use URL regex as per main Django project
|
## Code Before:
from django.conf.urls import patterns, url
from cellcounter.accounts import views
urlpatterns = patterns('',
url('^new/$', views.RegistrationView.as_view(), name='register'),
url('^(?P<pk>[0-9]+)/$', views.UserDetailView.as_view(), name='user-detail'),
url('^(?P<pk>[0-9]+)/delete/$', views.UserDeleteView.as_view(), name='user-delete'),
url('^(?P<pk>[0-9]+)/edit/$', views.UserUpdateView.as_view(), name='user-update'),
url('^password/reset/$', views.PasswordResetView.as_view(),
name='password-reset'),
url('^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[\d\w\-]+)/$',
views.PasswordResetConfirmView.as_view(),
name='password-reset-confirm'),
url('^password/change/$', views.PasswordChangeView.as_view(), name='change-password'),
)
## Instruction:
Use URL regex as per main Django project
## Code After:
from django.conf.urls import patterns, url
from cellcounter.accounts import views
urlpatterns = patterns('',
url('^new/$', views.RegistrationView.as_view(), name='register'),
url('^(?P<pk>[0-9]+)/$', views.UserDetailView.as_view(), name='user-detail'),
url('^(?P<pk>[0-9]+)/delete/$', views.UserDeleteView.as_view(), name='user-delete'),
url('^(?P<pk>[0-9]+)/edit/$', views.UserUpdateView.as_view(), name='user-update'),
url('^password/reset/$', views.PasswordResetView.as_view(),
name='password-reset'),
url('^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
views.PasswordResetConfirmView.as_view(),
name='password-reset-confirm'),
url('^password/change/$', views.PasswordChangeView.as_view(), name='change-password'),
)
|
# ... existing code ...
name='password-reset'),
url('^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
views.PasswordResetConfirmView.as_view(),
# ... rest of the code ...
|
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
|
# ... existing code ...
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)
# ... rest of the code ...
|
cfeaf5b01b6c822b2351a556e48a1a68aa2bce88
|
glue_vispy_viewers/volume/tests/test_glue_viewer.py
|
glue_vispy_viewers/volume/tests/test_glue_viewer.py
|
import operator
import numpy as np
from glue.qt import get_qapp
from glue.core.data import Data
from glue.core.data_collection import DataCollection
from glue.app.qt.application import GlueApplication
from glue.core.subset import InequalitySubsetState
# from glue.core.tests.util import simple_session
from ..vol_glue_viewer import GlueVispyViewer
def test_viewer():
app = get_qapp()
data = Data(x=np.arange(1000).reshape((10, 10, 10)) / 1000.)
dc = DataCollection([data])
app = GlueApplication(dc)
app.new_data_viewer(GlueVispyViewer, data=data)
subset_state1 = InequalitySubsetState(data.find_component_id('x'), 2/3., operator.gt)
dc.new_subset_group(label='test_subset1', subset_state=subset_state1)
subset_state2 = InequalitySubsetState(data.find_component_id('x'), 1/3., operator.lt)
dc.new_subset_group(label='test_subset2', subset_state=subset_state2)
app.show()
|
import operator
import numpy as np
from glue.qt import get_qapp
from glue.core.data import Data
from glue.core.data_collection import DataCollection
try:
from glue.app.qt.application import GlueApplication
except:
from glue.qt.glue_application import GlueApplication
from glue.core.subset import InequalitySubsetState
# from glue.core.tests.util import simple_session
from ..vol_glue_viewer import GlueVispyViewer
def test_viewer():
app = get_qapp()
data = Data(x=np.arange(1000).reshape((10, 10, 10)) / 1000.)
dc = DataCollection([data])
app = GlueApplication(dc)
app.new_data_viewer(GlueVispyViewer, data=data)
subset_state1 = InequalitySubsetState(data.find_component_id('x'), 2/3., operator.gt)
dc.new_subset_group(label='test_subset1', subset_state=subset_state1)
subset_state2 = InequalitySubsetState(data.find_component_id('x'), 1/3., operator.lt)
dc.new_subset_group(label='test_subset2', subset_state=subset_state2)
app.show()
|
Fix compatibility with latest stable glue version
|
Fix compatibility with latest stable glue version
|
Python
|
bsd-2-clause
|
PennyQ/astro-vispy,PennyQ/glue-3d-viewer,astrofrog/glue-vispy-viewers,glue-viz/glue-3d-viewer,glue-viz/glue-vispy-viewers,astrofrog/glue-3d-viewer
|
import operator
import numpy as np
from glue.qt import get_qapp
from glue.core.data import Data
from glue.core.data_collection import DataCollection
+
+ try:
- from glue.app.qt.application import GlueApplication
+ from glue.app.qt.application import GlueApplication
+ except:
+ from glue.qt.glue_application import GlueApplication
+
from glue.core.subset import InequalitySubsetState
# from glue.core.tests.util import simple_session
from ..vol_glue_viewer import GlueVispyViewer
def test_viewer():
app = get_qapp()
data = Data(x=np.arange(1000).reshape((10, 10, 10)) / 1000.)
dc = DataCollection([data])
app = GlueApplication(dc)
app.new_data_viewer(GlueVispyViewer, data=data)
subset_state1 = InequalitySubsetState(data.find_component_id('x'), 2/3., operator.gt)
dc.new_subset_group(label='test_subset1', subset_state=subset_state1)
subset_state2 = InequalitySubsetState(data.find_component_id('x'), 1/3., operator.lt)
dc.new_subset_group(label='test_subset2', subset_state=subset_state2)
app.show()
|
Fix compatibility with latest stable glue version
|
## Code Before:
import operator
import numpy as np
from glue.qt import get_qapp
from glue.core.data import Data
from glue.core.data_collection import DataCollection
from glue.app.qt.application import GlueApplication
from glue.core.subset import InequalitySubsetState
# from glue.core.tests.util import simple_session
from ..vol_glue_viewer import GlueVispyViewer
def test_viewer():
app = get_qapp()
data = Data(x=np.arange(1000).reshape((10, 10, 10)) / 1000.)
dc = DataCollection([data])
app = GlueApplication(dc)
app.new_data_viewer(GlueVispyViewer, data=data)
subset_state1 = InequalitySubsetState(data.find_component_id('x'), 2/3., operator.gt)
dc.new_subset_group(label='test_subset1', subset_state=subset_state1)
subset_state2 = InequalitySubsetState(data.find_component_id('x'), 1/3., operator.lt)
dc.new_subset_group(label='test_subset2', subset_state=subset_state2)
app.show()
## Instruction:
Fix compatibility with latest stable glue version
## Code After:
import operator
import numpy as np
from glue.qt import get_qapp
from glue.core.data import Data
from glue.core.data_collection import DataCollection
try:
from glue.app.qt.application import GlueApplication
except:
from glue.qt.glue_application import GlueApplication
from glue.core.subset import InequalitySubsetState
# from glue.core.tests.util import simple_session
from ..vol_glue_viewer import GlueVispyViewer
def test_viewer():
app = get_qapp()
data = Data(x=np.arange(1000).reshape((10, 10, 10)) / 1000.)
dc = DataCollection([data])
app = GlueApplication(dc)
app.new_data_viewer(GlueVispyViewer, data=data)
subset_state1 = InequalitySubsetState(data.find_component_id('x'), 2/3., operator.gt)
dc.new_subset_group(label='test_subset1', subset_state=subset_state1)
subset_state2 = InequalitySubsetState(data.find_component_id('x'), 1/3., operator.lt)
dc.new_subset_group(label='test_subset2', subset_state=subset_state2)
app.show()
|
...
from glue.core.data_collection import DataCollection
try:
from glue.app.qt.application import GlueApplication
except:
from glue.qt.glue_application import GlueApplication
from glue.core.subset import InequalitySubsetState
...
|
99b1edfcc317dbb71b8dad9ad501aaa21f8044f9
|
zorp/__init__.py
|
zorp/__init__.py
|
from zorp.client import Client
from zorp.decorator import remote_method
from zorp.server import Server
|
from zorp.client import Client, TriesExceededException
from zorp.decorator import remote_method
from zorp.server import Server
|
Add TriesExceededException to the base package
|
Add TriesExceededException to the base package
|
Python
|
mit
|
proxama/zorp
|
- from zorp.client import Client
+ from zorp.client import Client, TriesExceededException
from zorp.decorator import remote_method
from zorp.server import Server
|
Add TriesExceededException to the base package
|
## Code Before:
from zorp.client import Client
from zorp.decorator import remote_method
from zorp.server import Server
## Instruction:
Add TriesExceededException to the base package
## Code After:
from zorp.client import Client, TriesExceededException
from zorp.decorator import remote_method
from zorp.server import Server
|
// ... existing code ...
from zorp.client import Client, TriesExceededException
from zorp.decorator import remote_method
// ... rest of the code ...
|
a6fda9344461424d9da4f70772443a2a283a8da1
|
test/test_client.py
|
test/test_client.py
|
import unittest
import delighted
class ClientTest(unittest.TestCase):
def test_instantiating_client_requires_api_key(self):
self.assertRaises(ValueError, lambda: delighted.Client())
delighted.Client(api_key='abc123')
|
import unittest
import delighted
class ClientTest(unittest.TestCase):
def test_instantiating_client_requires_api_key(self):
original_api_key = delighted.api_key
try:
delighted.api_key = None
self.assertRaises(ValueError, lambda: delighted.Client())
delighted.Client(api_key='abc123')
except:
delighted.api_key = original_api_key
|
Make no-api-key test more reliable
|
Make no-api-key test more reliable
|
Python
|
mit
|
mkdynamic/delighted-python,delighted/delighted-python,kaeawc/delighted-python
|
import unittest
import delighted
class ClientTest(unittest.TestCase):
def test_instantiating_client_requires_api_key(self):
+ original_api_key = delighted.api_key
+ try:
+ delighted.api_key = None
- self.assertRaises(ValueError, lambda: delighted.Client())
+ self.assertRaises(ValueError, lambda: delighted.Client())
- delighted.Client(api_key='abc123')
+ delighted.Client(api_key='abc123')
+ except:
+ delighted.api_key = original_api_key
|
Make no-api-key test more reliable
|
## Code Before:
import unittest
import delighted
class ClientTest(unittest.TestCase):
def test_instantiating_client_requires_api_key(self):
self.assertRaises(ValueError, lambda: delighted.Client())
delighted.Client(api_key='abc123')
## Instruction:
Make no-api-key test more reliable
## Code After:
import unittest
import delighted
class ClientTest(unittest.TestCase):
def test_instantiating_client_requires_api_key(self):
original_api_key = delighted.api_key
try:
delighted.api_key = None
self.assertRaises(ValueError, lambda: delighted.Client())
delighted.Client(api_key='abc123')
except:
delighted.api_key = original_api_key
|
# ... existing code ...
def test_instantiating_client_requires_api_key(self):
original_api_key = delighted.api_key
try:
delighted.api_key = None
self.assertRaises(ValueError, lambda: delighted.Client())
delighted.Client(api_key='abc123')
except:
delighted.api_key = original_api_key
# ... rest of the code ...
|
37c63e6ea5c14a0c7aae11581ae32f24eaaa9641
|
test/layers_test.py
|
test/layers_test.py
|
import theanets
import numpy as np
class TestLayer:
def test_build(self):
layer = theanets.layers.build('feedforward', nin=2, nout=4)
assert isinstance(layer, theanets.layers.Layer)
class TestFeedforward:
def test_create(self):
l = theanets.layers.Feedforward(nin=2, nout=4)
assert l.reset() == 12
class TestTied:
def test_create(self):
l0 = theanets.layers.Feedforward(nin=2, nout=4)
l = theanets.layers.Tied(partner=l0)
assert l.reset() == 2
class TestClassifier:
def test_create(self):
l = theanets.layers.Classifier(nin=2, nout=4)
assert l.reset() == 12
class TestRecurrent:
def test_create(self):
l = theanets.layers.Recurrent(nin=2, nout=4)
assert l.reset() == 28
class TestMRNN:
def test_create(self):
l = theanets.layers.MRNN(nin=2, nout=4, factors=3)
assert l.reset() == 42
class TestLSTM:
def test_create(self):
l = theanets.layers.LSTM(nin=2, nout=4)
assert l.reset() == 124
|
import theanets
import numpy as np
class TestLayer:
def test_build(self):
layer = theanets.layers.build('feedforward', nin=2, nout=4)
assert isinstance(layer, theanets.layers.Layer)
class TestFeedforward:
def test_create(self):
l = theanets.layers.Feedforward(nin=2, nout=4)
assert l.reset() == 12
class TestTied:
def test_create(self):
l0 = theanets.layers.Feedforward(nin=2, nout=4)
l = theanets.layers.Tied(partner=l0)
assert l.reset() == 2
class TestClassifier:
def test_create(self):
l = theanets.layers.Classifier(nin=2, nout=4)
assert l.reset() == 12
class TestRNN:
def test_create(self):
l = theanets.layers.RNN(nin=2, nout=4)
assert l.reset() == 28
class TestMRNN:
def test_create(self):
l = theanets.layers.MRNN(nin=2, nout=4, factors=3)
assert l.reset() == 42
class TestLSTM:
def test_create(self):
l = theanets.layers.LSTM(nin=2, nout=4)
assert l.reset() == 124
|
Update layers test for RNN change.
|
Update layers test for RNN change.
|
Python
|
mit
|
devdoer/theanets,chrinide/theanets,lmjohns3/theanets
|
import theanets
import numpy as np
class TestLayer:
def test_build(self):
layer = theanets.layers.build('feedforward', nin=2, nout=4)
assert isinstance(layer, theanets.layers.Layer)
class TestFeedforward:
def test_create(self):
l = theanets.layers.Feedforward(nin=2, nout=4)
assert l.reset() == 12
class TestTied:
def test_create(self):
l0 = theanets.layers.Feedforward(nin=2, nout=4)
l = theanets.layers.Tied(partner=l0)
assert l.reset() == 2
class TestClassifier:
def test_create(self):
l = theanets.layers.Classifier(nin=2, nout=4)
assert l.reset() == 12
- class TestRecurrent:
+ class TestRNN:
def test_create(self):
- l = theanets.layers.Recurrent(nin=2, nout=4)
+ l = theanets.layers.RNN(nin=2, nout=4)
assert l.reset() == 28
class TestMRNN:
def test_create(self):
l = theanets.layers.MRNN(nin=2, nout=4, factors=3)
assert l.reset() == 42
class TestLSTM:
def test_create(self):
l = theanets.layers.LSTM(nin=2, nout=4)
assert l.reset() == 124
|
Update layers test for RNN change.
|
## Code Before:
import theanets
import numpy as np
class TestLayer:
def test_build(self):
layer = theanets.layers.build('feedforward', nin=2, nout=4)
assert isinstance(layer, theanets.layers.Layer)
class TestFeedforward:
def test_create(self):
l = theanets.layers.Feedforward(nin=2, nout=4)
assert l.reset() == 12
class TestTied:
def test_create(self):
l0 = theanets.layers.Feedforward(nin=2, nout=4)
l = theanets.layers.Tied(partner=l0)
assert l.reset() == 2
class TestClassifier:
def test_create(self):
l = theanets.layers.Classifier(nin=2, nout=4)
assert l.reset() == 12
class TestRecurrent:
def test_create(self):
l = theanets.layers.Recurrent(nin=2, nout=4)
assert l.reset() == 28
class TestMRNN:
def test_create(self):
l = theanets.layers.MRNN(nin=2, nout=4, factors=3)
assert l.reset() == 42
class TestLSTM:
def test_create(self):
l = theanets.layers.LSTM(nin=2, nout=4)
assert l.reset() == 124
## Instruction:
Update layers test for RNN change.
## Code After:
import theanets
import numpy as np
class TestLayer:
def test_build(self):
layer = theanets.layers.build('feedforward', nin=2, nout=4)
assert isinstance(layer, theanets.layers.Layer)
class TestFeedforward:
def test_create(self):
l = theanets.layers.Feedforward(nin=2, nout=4)
assert l.reset() == 12
class TestTied:
def test_create(self):
l0 = theanets.layers.Feedforward(nin=2, nout=4)
l = theanets.layers.Tied(partner=l0)
assert l.reset() == 2
class TestClassifier:
def test_create(self):
l = theanets.layers.Classifier(nin=2, nout=4)
assert l.reset() == 12
class TestRNN:
def test_create(self):
l = theanets.layers.RNN(nin=2, nout=4)
assert l.reset() == 28
class TestMRNN:
def test_create(self):
l = theanets.layers.MRNN(nin=2, nout=4, factors=3)
assert l.reset() == 42
class TestLSTM:
def test_create(self):
l = theanets.layers.LSTM(nin=2, nout=4)
assert l.reset() == 124
|
...
class TestRNN:
def test_create(self):
l = theanets.layers.RNN(nin=2, nout=4)
assert l.reset() == 28
...
|
c916ea93fc4bcd0383ae7a95ae73f2418e122e1f
|
Orange/tests/__init__.py
|
Orange/tests/__init__.py
|
import os
import unittest
def suite():
test_dir = os.path.dirname(__file__)
return unittest.TestLoader().discover(test_dir, )
test_suite = suite()
if __name__ == '__main__':
unittest.main(defaultTest='suite')
|
import os
import unittest
from Orange.widgets.tests import test_settings, test_setting_provider
def suite():
test_dir = os.path.dirname(__file__)
return unittest.TestSuite([
unittest.TestLoader().discover(test_dir),
unittest.TestLoader().loadTestsFromModule(test_settings),
unittest.TestLoader().loadTestsFromModule(test_setting_provider),
])
test_suite = suite()
if __name__ == '__main__':
unittest.main(defaultTest='suite')
|
Test settings when setup.py test is run.
|
Test settings when setup.py test is run.
|
Python
|
bsd-2-clause
|
marinkaz/orange3,marinkaz/orange3,qPCR4vir/orange3,qusp/orange3,cheral/orange3,kwikadi/orange3,cheral/orange3,cheral/orange3,marinkaz/orange3,marinkaz/orange3,kwikadi/orange3,qusp/orange3,qPCR4vir/orange3,kwikadi/orange3,kwikadi/orange3,qPCR4vir/orange3,kwikadi/orange3,kwikadi/orange3,qPCR4vir/orange3,marinkaz/orange3,cheral/orange3,qPCR4vir/orange3,qusp/orange3,qusp/orange3,marinkaz/orange3,cheral/orange3,cheral/orange3,qPCR4vir/orange3
|
import os
import unittest
+
+ from Orange.widgets.tests import test_settings, test_setting_provider
def suite():
test_dir = os.path.dirname(__file__)
+ return unittest.TestSuite([
- return unittest.TestLoader().discover(test_dir, )
+ unittest.TestLoader().discover(test_dir),
+ unittest.TestLoader().loadTestsFromModule(test_settings),
+ unittest.TestLoader().loadTestsFromModule(test_setting_provider),
+ ])
+
test_suite = suite()
if __name__ == '__main__':
unittest.main(defaultTest='suite')
|
Test settings when setup.py test is run.
|
## Code Before:
import os
import unittest
def suite():
test_dir = os.path.dirname(__file__)
return unittest.TestLoader().discover(test_dir, )
test_suite = suite()
if __name__ == '__main__':
unittest.main(defaultTest='suite')
## Instruction:
Test settings when setup.py test is run.
## Code After:
import os
import unittest
from Orange.widgets.tests import test_settings, test_setting_provider
def suite():
test_dir = os.path.dirname(__file__)
return unittest.TestSuite([
unittest.TestLoader().discover(test_dir),
unittest.TestLoader().loadTestsFromModule(test_settings),
unittest.TestLoader().loadTestsFromModule(test_setting_provider),
])
test_suite = suite()
if __name__ == '__main__':
unittest.main(defaultTest='suite')
|
// ... existing code ...
import unittest
from Orange.widgets.tests import test_settings, test_setting_provider
// ... modified code ...
test_dir = os.path.dirname(__file__)
return unittest.TestSuite([
unittest.TestLoader().discover(test_dir),
unittest.TestLoader().loadTestsFromModule(test_settings),
unittest.TestLoader().loadTestsFromModule(test_setting_provider),
])
// ... rest of the code ...
|
059cc7ec7cd7c8b078b896be67a2041eaa3ea8da
|
accounts/backends.py
|
accounts/backends.py
|
from django.contrib.auth import get_user_model
from django.conf import settings
from django.contrib.auth.models import check_password
from django.core.validators import validate_email
from django.forms import ValidationError
User = get_user_model()
class EmailOrUsernameAuthBackend():
"""
A custom authentication backend. Allows users to log in using their email address or username.
"""
def _lookup_user(self, username_or_email):
try:
validate_email(username_or_email)
except ValidationError:
# not an email
using_email = False
else:
# looks like an email!
using_email = True
try:
if using_email:
user = User.objects.get(email__iexact=username_or_email)
else:
user = User.objects.get(username__iexact=username_or_email)
except User.DoesNotExist:
return None
return user
def authenticate(self, username=None, password=None):
"""
Authentication method - username here is actually "username_or_email",
but named as such to fit Django convention
"""
user = self._lookup_user(username)
if user:
if user.check_password(password):
return user
return None
def get_user(self, user_id):
try:
user = User.objects.get(pk=user_id)
if user.is_active:
return user
return None
except User.DoesNotExist:
return None
|
from django.contrib.auth import get_user_model
from django.conf import settings
from django.contrib.auth.models import check_password
from django.core.validators import validate_email
from django.forms import ValidationError
User = get_user_model()
class EmailOrUsernameAuthBackend():
"""
A custom authentication backend. Allows users to log in using their email address or username.
"""
def _lookup_user(self, username_or_email):
try:
validate_email(username_or_email)
except ValidationError:
# not an email
using_email = False
else:
# looks like an email!
using_email = True
try:
if using_email:
user = User.objects.get(email__iexact=username_or_email)
else:
user = User.objects.get(username__iexact=username_or_email)
except User.DoesNotExist:
return None
else:
return user
def authenticate(self, username=None, password=None):
"""
Authentication method - username here is actually "username_or_email",
but named as such to fit Django convention
"""
user = self._lookup_user(username)
if user:
if user.check_password(password):
return user
return None
def get_user(self, user_id):
try:
user = User.objects.get(pk=user_id)
if user.is_active:
return user
return None
except User.DoesNotExist:
return None
|
Move return statement in _lookup_user into except/else flow
|
Move return statement in _lookup_user into except/else flow
|
Python
|
bsd-2-clause
|
ScottyMJacobson/django-email-or-username
|
from django.contrib.auth import get_user_model
from django.conf import settings
from django.contrib.auth.models import check_password
from django.core.validators import validate_email
from django.forms import ValidationError
User = get_user_model()
class EmailOrUsernameAuthBackend():
"""
A custom authentication backend. Allows users to log in using their email address or username.
"""
def _lookup_user(self, username_or_email):
try:
validate_email(username_or_email)
except ValidationError:
# not an email
using_email = False
else:
# looks like an email!
using_email = True
try:
if using_email:
user = User.objects.get(email__iexact=username_or_email)
else:
user = User.objects.get(username__iexact=username_or_email)
except User.DoesNotExist:
return None
-
+ else:
- return user
+ return user
def authenticate(self, username=None, password=None):
"""
Authentication method - username here is actually "username_or_email",
but named as such to fit Django convention
"""
user = self._lookup_user(username)
if user:
if user.check_password(password):
return user
return None
def get_user(self, user_id):
try:
user = User.objects.get(pk=user_id)
if user.is_active:
return user
return None
except User.DoesNotExist:
return None
|
Move return statement in _lookup_user into except/else flow
|
## Code Before:
from django.contrib.auth import get_user_model
from django.conf import settings
from django.contrib.auth.models import check_password
from django.core.validators import validate_email
from django.forms import ValidationError
User = get_user_model()
class EmailOrUsernameAuthBackend():
"""
A custom authentication backend. Allows users to log in using their email address or username.
"""
def _lookup_user(self, username_or_email):
try:
validate_email(username_or_email)
except ValidationError:
# not an email
using_email = False
else:
# looks like an email!
using_email = True
try:
if using_email:
user = User.objects.get(email__iexact=username_or_email)
else:
user = User.objects.get(username__iexact=username_or_email)
except User.DoesNotExist:
return None
return user
def authenticate(self, username=None, password=None):
"""
Authentication method - username here is actually "username_or_email",
but named as such to fit Django convention
"""
user = self._lookup_user(username)
if user:
if user.check_password(password):
return user
return None
def get_user(self, user_id):
try:
user = User.objects.get(pk=user_id)
if user.is_active:
return user
return None
except User.DoesNotExist:
return None
## Instruction:
Move return statement in _lookup_user into except/else flow
## Code After:
from django.contrib.auth import get_user_model
from django.conf import settings
from django.contrib.auth.models import check_password
from django.core.validators import validate_email
from django.forms import ValidationError
User = get_user_model()
class EmailOrUsernameAuthBackend():
"""
A custom authentication backend. Allows users to log in using their email address or username.
"""
def _lookup_user(self, username_or_email):
try:
validate_email(username_or_email)
except ValidationError:
# not an email
using_email = False
else:
# looks like an email!
using_email = True
try:
if using_email:
user = User.objects.get(email__iexact=username_or_email)
else:
user = User.objects.get(username__iexact=username_or_email)
except User.DoesNotExist:
return None
else:
return user
def authenticate(self, username=None, password=None):
"""
Authentication method - username here is actually "username_or_email",
but named as such to fit Django convention
"""
user = self._lookup_user(username)
if user:
if user.check_password(password):
return user
return None
def get_user(self, user_id):
try:
user = User.objects.get(pk=user_id)
if user.is_active:
return user
return None
except User.DoesNotExist:
return None
|
# ... existing code ...
return None
else:
return user
# ... rest of the code ...
|
7bd82f6feb1a34dd7b855cfe2f421232229e19db
|
pages/search_indexes.py
|
pages/search_indexes.py
|
"""Django haystack `SearchIndex` module."""
from pages.models import Page
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(document=True, use_template=True)
publication_date = DateTimeField(model_attr='publication_date')
def get_queryset(self):
"""Used when the entire index for model is updated."""
return Page.objects.published()
site.register(Page, PageIndex)
|
"""Django haystack `SearchIndex` module."""
from pages.models import Page
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(document=True, use_template=True)
title = CharField(model_attr='title')
publication_date = DateTimeField(model_attr='publication_date')
def get_queryset(self):
"""Used when the entire index for model is updated."""
return Page.objects.published()
site.register(Page, PageIndex)
|
Add a title attribute to the SearchIndex for pages.
|
Add a title attribute to the SearchIndex for pages.
This is useful when displaying a list of search results because we
can display the title of the result without hitting the database to
actually pull the page.
|
Python
|
bsd-3-clause
|
remik/django-page-cms,pombredanne/django-page-cms-1,oliciv/django-page-cms,remik/django-page-cms,remik/django-page-cms,batiste/django-page-cms,oliciv/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,remik/django-page-cms,akaihola/django-page-cms,pombredanne/django-page-cms-1,oliciv/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,pombredanne/django-page-cms-1
|
"""Django haystack `SearchIndex` module."""
from pages.models import Page
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(document=True, use_template=True)
+ title = CharField(model_attr='title')
publication_date = DateTimeField(model_attr='publication_date')
def get_queryset(self):
"""Used when the entire index for model is updated."""
return Page.objects.published()
site.register(Page, PageIndex)
|
Add a title attribute to the SearchIndex for pages.
|
## Code Before:
"""Django haystack `SearchIndex` module."""
from pages.models import Page
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(document=True, use_template=True)
publication_date = DateTimeField(model_attr='publication_date')
def get_queryset(self):
"""Used when the entire index for model is updated."""
return Page.objects.published()
site.register(Page, PageIndex)
## Instruction:
Add a title attribute to the SearchIndex for pages.
## Code After:
"""Django haystack `SearchIndex` module."""
from pages.models import Page
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(document=True, use_template=True)
title = CharField(model_attr='title')
publication_date = DateTimeField(model_attr='publication_date')
def get_queryset(self):
"""Used when the entire index for model is updated."""
return Page.objects.published()
site.register(Page, PageIndex)
|
// ... existing code ...
text = CharField(document=True, use_template=True)
title = CharField(model_attr='title')
publication_date = DateTimeField(model_attr='publication_date')
// ... rest of the code ...
|
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
|
# ... existing code ...
# ... modified code ...
def total_after(num):
total = 0
for i in range(1, num+1):
total += on_square(i)
return total
# ... rest of the code ...
|
c86d5c928cdefd09aca102b2a5c37f662e1426a6
|
{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/users/tests/factories.py
|
{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/users/tests/factories.py
|
from feder.users import models
import factory
class UserFactory(factory.django.DjangoModelFactory):
username = factory.Sequence(lambda n: 'user-{0}'.format(n))
email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n))
password = factory.PosteGnerationMethodCall('set_password', 'password')
class Meta:
model = models.User
django_get_or_create = ('username', )
|
import factory
class UserFactory(factory.django.DjangoModelFactory):
username = factory.Sequence(lambda n: 'user-{0}'.format(n))
email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n))
password = factory.PostGenerationMethodCall('set_password', 'password')
class Meta:
model = 'users.User'
django_get_or_create = ('username', )
|
Fix typo & import in UserFactory
|
Fix typo & import in UserFactory
|
Python
|
bsd-3-clause
|
andresgz/cookiecutter-django,gappsexperts/cookiecutter-django,asyncee/cookiecutter-django,gappsexperts/cookiecutter-django,calculuscowboy/cookiecutter-django,aleprovencio/cookiecutter-django,ddiazpinto/cookiecutter-django,asyncee/cookiecutter-django,drxos/cookiecutter-django-dokku,thisjustin/cookiecutter-django,aleprovencio/cookiecutter-django,mjhea0/cookiecutter-django,schacki/cookiecutter-django,aeikenberry/cookiecutter-django-rest-babel,ovidner/cookiecutter-django,thisjustin/cookiecutter-django,schacki/cookiecutter-django,Parbhat/cookiecutter-django-foundation,aleprovencio/cookiecutter-django,nunchaks/cookiecutter-django,Parbhat/cookiecutter-django-foundation,ad-m/cookiecutter-django,hairychris/cookiecutter-django,ingenioustechie/cookiecutter-django-openshift,pydanny/cookiecutter-django,gappsexperts/cookiecutter-django,kappataumu/cookiecutter-django,calculuscowboy/cookiecutter-django,ryankanno/cookiecutter-django,hairychris/cookiecutter-django,hairychris/cookiecutter-django,kappataumu/cookiecutter-django,ingenioustechie/cookiecutter-django-openshift,kappataumu/cookiecutter-django,HandyCodeJob/hcj-django-temp,Parbhat/cookiecutter-django-foundation,ryankanno/cookiecutter-django,bopo/cookiecutter-django,HandyCodeJob/hcj-django-temp,aeikenberry/cookiecutter-django-rest-babel,schacki/cookiecutter-django,nunchaks/cookiecutter-django,webyneter/cookiecutter-django,crdoconnor/cookiecutter-django,webspired/cookiecutter-django,ingenioustechie/cookiecutter-django-openshift,drxos/cookiecutter-django-dokku,crdoconnor/cookiecutter-django,luzfcb/cookiecutter-django,pydanny/cookiecutter-django,jondelmil/cookiecutter-django,ad-m/cookiecutter-django,kappataumu/cookiecutter-django,hackebrot/cookiecutter-django,pydanny/cookiecutter-django,ad-m/cookiecutter-django,topwebmaster/cookiecutter-django,ryankanno/cookiecutter-django,gappsexperts/cookiecutter-django,HandyCodeJob/hcj-django-temp,hairychris/cookiecutter-django,webspired/cookiecutter-django,hackebrot/cookiecutter-django,topwebmaster/cookiecutter-django,calculuscowboy/cookiecutter-django,jondelmil/cookiecutter-django,mistalaba/cookiecutter-django,trungdong/cookiecutter-django,ovidner/cookiecutter-django,Parbhat/cookiecutter-django-foundation,aeikenberry/cookiecutter-django-rest-babel,jondelmil/cookiecutter-django,ddiazpinto/cookiecutter-django,mjhea0/cookiecutter-django,webspired/cookiecutter-django,nunchaks/cookiecutter-django,andresgz/cookiecutter-django,ad-m/cookiecutter-django,ovidner/cookiecutter-django,mistalaba/cookiecutter-django,bopo/cookiecutter-django,bopo/cookiecutter-django,HandyCodeJob/hcj-django-temp,ddiazpinto/cookiecutter-django,calculuscowboy/cookiecutter-django,ovidner/cookiecutter-django,thisjustin/cookiecutter-django,schacki/cookiecutter-django,webyneter/cookiecutter-django,pydanny/cookiecutter-django,trungdong/cookiecutter-django,asyncee/cookiecutter-django,ingenioustechie/cookiecutter-django-openshift,crdoconnor/cookiecutter-django,nunchaks/cookiecutter-django,aeikenberry/cookiecutter-django-rest-babel,hackebrot/cookiecutter-django,asyncee/cookiecutter-django,aleprovencio/cookiecutter-django,crdoconnor/cookiecutter-django,luzfcb/cookiecutter-django,mistalaba/cookiecutter-django,luzfcb/cookiecutter-django,topwebmaster/cookiecutter-django,drxos/cookiecutter-django-dokku,ddiazpinto/cookiecutter-django,mjhea0/cookiecutter-django,hackebrot/cookiecutter-django,trungdong/cookiecutter-django,topwebmaster/cookiecutter-django,ryankanno/cookiecutter-django,trungdong/cookiecutter-django,luzfcb/cookiecutter-django,mistalaba/cookiecutter-django,andresgz/cookiecutter-django,webyneter/cookiecutter-django,webyneter/cookiecutter-django,andresgz/cookiecutter-django,thisjustin/cookiecutter-django,mjhea0/cookiecutter-django,drxos/cookiecutter-django-dokku,jondelmil/cookiecutter-django,bopo/cookiecutter-django,webspired/cookiecutter-django
|
- from feder.users import models
import factory
class UserFactory(factory.django.DjangoModelFactory):
username = factory.Sequence(lambda n: 'user-{0}'.format(n))
email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n))
- password = factory.PosteGnerationMethodCall('set_password', 'password')
+ password = factory.PostGenerationMethodCall('set_password', 'password')
class Meta:
- model = models.User
+ model = 'users.User'
django_get_or_create = ('username', )
|
Fix typo & import in UserFactory
|
## Code Before:
from feder.users import models
import factory
class UserFactory(factory.django.DjangoModelFactory):
username = factory.Sequence(lambda n: 'user-{0}'.format(n))
email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n))
password = factory.PosteGnerationMethodCall('set_password', 'password')
class Meta:
model = models.User
django_get_or_create = ('username', )
## Instruction:
Fix typo & import in UserFactory
## Code After:
import factory
class UserFactory(factory.django.DjangoModelFactory):
username = factory.Sequence(lambda n: 'user-{0}'.format(n))
email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n))
password = factory.PostGenerationMethodCall('set_password', 'password')
class Meta:
model = 'users.User'
django_get_or_create = ('username', )
|
// ... existing code ...
import factory
// ... modified code ...
email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n))
password = factory.PostGenerationMethodCall('set_password', 'password')
...
class Meta:
model = 'users.User'
django_get_or_create = ('username', )
// ... rest of the code ...
|
f98ff54c363fc2f2b0885464afffcb92cdea8cfe
|
ubersmith/calls/device.py
|
ubersmith/calls/device.py
|
from ubersmith.calls import BaseCall, GroupCall
from ubersmith.utils import prepend_base
__all__ = [
'GetCall',
'ListCall',
]
_ = prepend_base(__name__.split('.')[-1])
class GetCall(BaseCall):
method = _('get')
required_fields = ['device_id']
class ListCall(GroupCall):
method = _('list')
rename_fields = {'clientid': 'client_id'}
int_fields = ['client_id']
class ModuleGraphCall(FileCall):
method = _('module_graph')
|
from ubersmith.calls import BaseCall, GroupCall, FileCall
from ubersmith.utils import prepend_base
__all__ = [
'GetCall',
'ListCall',
'ModuleGraphCall',
]
_ = prepend_base(__name__.split('.')[-1])
class GetCall(BaseCall):
method = _('get')
required_fields = ['device_id']
class ListCall(GroupCall):
method = _('list')
rename_fields = {'clientid': 'client_id'}
int_fields = ['client_id']
class ModuleGraphCall(FileCall):
method = _('module_graph')
|
Make module graph call return a file.
|
Make module graph call return a file.
|
Python
|
mit
|
hivelocity/python-ubersmith,jasonkeene/python-ubersmith,hivelocity/python-ubersmith,jasonkeene/python-ubersmith
|
- from ubersmith.calls import BaseCall, GroupCall
+ from ubersmith.calls import BaseCall, GroupCall, FileCall
from ubersmith.utils import prepend_base
__all__ = [
'GetCall',
'ListCall',
+ 'ModuleGraphCall',
]
_ = prepend_base(__name__.split('.')[-1])
class GetCall(BaseCall):
method = _('get')
required_fields = ['device_id']
class ListCall(GroupCall):
method = _('list')
rename_fields = {'clientid': 'client_id'}
int_fields = ['client_id']
class ModuleGraphCall(FileCall):
method = _('module_graph')
|
Make module graph call return a file.
|
## Code Before:
from ubersmith.calls import BaseCall, GroupCall
from ubersmith.utils import prepend_base
__all__ = [
'GetCall',
'ListCall',
]
_ = prepend_base(__name__.split('.')[-1])
class GetCall(BaseCall):
method = _('get')
required_fields = ['device_id']
class ListCall(GroupCall):
method = _('list')
rename_fields = {'clientid': 'client_id'}
int_fields = ['client_id']
class ModuleGraphCall(FileCall):
method = _('module_graph')
## Instruction:
Make module graph call return a file.
## Code After:
from ubersmith.calls import BaseCall, GroupCall, FileCall
from ubersmith.utils import prepend_base
__all__ = [
'GetCall',
'ListCall',
'ModuleGraphCall',
]
_ = prepend_base(__name__.split('.')[-1])
class GetCall(BaseCall):
method = _('get')
required_fields = ['device_id']
class ListCall(GroupCall):
method = _('list')
rename_fields = {'clientid': 'client_id'}
int_fields = ['client_id']
class ModuleGraphCall(FileCall):
method = _('module_graph')
|
// ... existing code ...
from ubersmith.calls import BaseCall, GroupCall, FileCall
from ubersmith.utils import prepend_base
// ... modified code ...
'ListCall',
'ModuleGraphCall',
]
// ... rest of the code ...
|
af1df841b3d0c013c0678fa6fb9821b61a9eb87c
|
policy_evaluation/deterministic.py
|
policy_evaluation/deterministic.py
|
from torch.autograd import Variable
class DeterministicPolicy(object):
def __init__(self, policy):
"""Assumes policy returns an autograd.Variable"""
self.name = "DP"
self.policy = policy
self.cuda = next(policy.parameters()).is_cuda
def get_action(self, state):
""" Takes best action based on estimated state-action values."""
state = state.cuda() if self.cuda else state
q_val, argmax_a = self.policy(
Variable(state, volatile=True)).data.max(1)
"""
result = self.policy(Variable(state_batch, volatile=True))
print(result)
"""
return (q_val[0], argmax_a[0])
|
from torch.autograd import Variable
class DeterministicPolicy(object):
def __init__(self, policy):
"""Assumes policy returns an autograd.Variable"""
self.name = "DP"
self.policy = policy
self.cuda = next(policy.parameters()).is_cuda
def get_action(self, state):
""" Takes best action based on estimated state-action values."""
state = state.cuda() if self.cuda else state
q_val, argmax_a = self.policy(
Variable(state, volatile=True)).data.max(1)
"""
result = self.policy(Variable(state_batch, volatile=True))
print(result)
"""
return (q_val.squeeze()[0], argmax_a.squeeze()[0])
|
Make DQN backward compatible with pytorch 0.1.2.
|
Make DQN backward compatible with pytorch 0.1.2.
|
Python
|
mit
|
floringogianu/categorical-dqn
|
from torch.autograd import Variable
class DeterministicPolicy(object):
def __init__(self, policy):
"""Assumes policy returns an autograd.Variable"""
self.name = "DP"
self.policy = policy
self.cuda = next(policy.parameters()).is_cuda
def get_action(self, state):
""" Takes best action based on estimated state-action values."""
state = state.cuda() if self.cuda else state
q_val, argmax_a = self.policy(
Variable(state, volatile=True)).data.max(1)
"""
result = self.policy(Variable(state_batch, volatile=True))
print(result)
"""
- return (q_val[0], argmax_a[0])
+ return (q_val.squeeze()[0], argmax_a.squeeze()[0])
|
Make DQN backward compatible with pytorch 0.1.2.
|
## Code Before:
from torch.autograd import Variable
class DeterministicPolicy(object):
def __init__(self, policy):
"""Assumes policy returns an autograd.Variable"""
self.name = "DP"
self.policy = policy
self.cuda = next(policy.parameters()).is_cuda
def get_action(self, state):
""" Takes best action based on estimated state-action values."""
state = state.cuda() if self.cuda else state
q_val, argmax_a = self.policy(
Variable(state, volatile=True)).data.max(1)
"""
result = self.policy(Variable(state_batch, volatile=True))
print(result)
"""
return (q_val[0], argmax_a[0])
## Instruction:
Make DQN backward compatible with pytorch 0.1.2.
## Code After:
from torch.autograd import Variable
class DeterministicPolicy(object):
def __init__(self, policy):
"""Assumes policy returns an autograd.Variable"""
self.name = "DP"
self.policy = policy
self.cuda = next(policy.parameters()).is_cuda
def get_action(self, state):
""" Takes best action based on estimated state-action values."""
state = state.cuda() if self.cuda else state
q_val, argmax_a = self.policy(
Variable(state, volatile=True)).data.max(1)
"""
result = self.policy(Variable(state_batch, volatile=True))
print(result)
"""
return (q_val.squeeze()[0], argmax_a.squeeze()[0])
|
# ... existing code ...
"""
return (q_val.squeeze()[0], argmax_a.squeeze()[0])
# ... rest of the code ...
|
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)
|
// ... existing code ...
def strategy(redirect_uri=None, load_strategy=load_strategy):
def decorator(func):
// ... rest of the code ...
|
05ec1e93e04b829b8a71f6837409de1b5c8ead5d
|
bndl/compute/tests/__init__.py
|
bndl/compute/tests/__init__.py
|
import unittest
from bndl.compute.run import create_ctx
from bndl.util.conf import Config
class ComputeTest(unittest.TestCase):
worker_count = 3
@classmethod
def setUpClass(cls):
config = Config()
config['bndl.compute.worker_count'] = cls.worker_count
config['bndl.net.listen_addresses'] = 'tcp://127.0.0.11:5000'
cls.ctx = create_ctx(config, daemon=True)
cls.ctx.await_workers(cls.worker_count)
@classmethod
def tearDownClass(cls):
cls.ctx.stop()
class DatasetTest(ComputeTest):
pass
|
import sys
import unittest
from bndl.compute.run import create_ctx
from bndl.util.conf import Config
class ComputeTest(unittest.TestCase):
worker_count = 3
@classmethod
def setUpClass(cls):
# Increase switching interval to lure out race conditions a bit ...
cls._old_switchinterval = sys.getswitchinterval()
sys.setswitchinterval(1e-6)
config = Config()
config['bndl.compute.worker_count'] = cls.worker_count
config['bndl.net.listen_addresses'] = 'tcp://127.0.0.11:5000'
cls.ctx = create_ctx(config, daemon=True)
cls.ctx.await_workers(cls.worker_count)
@classmethod
def tearDownClass(cls):
cls.ctx.stop()
sys.setswitchinterval(cls._old_switchinterval)
class DatasetTest(ComputeTest):
pass
|
Increase switching interval to lure out race conditions a bit ...
|
Increase switching interval to lure out race conditions a bit ...
|
Python
|
apache-2.0
|
bndl/bndl,bndl/bndl
|
+ import sys
import unittest
from bndl.compute.run import create_ctx
from bndl.util.conf import Config
class ComputeTest(unittest.TestCase):
worker_count = 3
@classmethod
def setUpClass(cls):
+ # Increase switching interval to lure out race conditions a bit ...
+ cls._old_switchinterval = sys.getswitchinterval()
+ sys.setswitchinterval(1e-6)
+
config = Config()
config['bndl.compute.worker_count'] = cls.worker_count
config['bndl.net.listen_addresses'] = 'tcp://127.0.0.11:5000'
cls.ctx = create_ctx(config, daemon=True)
cls.ctx.await_workers(cls.worker_count)
@classmethod
def tearDownClass(cls):
cls.ctx.stop()
+ sys.setswitchinterval(cls._old_switchinterval)
class DatasetTest(ComputeTest):
pass
|
Increase switching interval to lure out race conditions a bit ...
|
## Code Before:
import unittest
from bndl.compute.run import create_ctx
from bndl.util.conf import Config
class ComputeTest(unittest.TestCase):
worker_count = 3
@classmethod
def setUpClass(cls):
config = Config()
config['bndl.compute.worker_count'] = cls.worker_count
config['bndl.net.listen_addresses'] = 'tcp://127.0.0.11:5000'
cls.ctx = create_ctx(config, daemon=True)
cls.ctx.await_workers(cls.worker_count)
@classmethod
def tearDownClass(cls):
cls.ctx.stop()
class DatasetTest(ComputeTest):
pass
## Instruction:
Increase switching interval to lure out race conditions a bit ...
## Code After:
import sys
import unittest
from bndl.compute.run import create_ctx
from bndl.util.conf import Config
class ComputeTest(unittest.TestCase):
worker_count = 3
@classmethod
def setUpClass(cls):
# Increase switching interval to lure out race conditions a bit ...
cls._old_switchinterval = sys.getswitchinterval()
sys.setswitchinterval(1e-6)
config = Config()
config['bndl.compute.worker_count'] = cls.worker_count
config['bndl.net.listen_addresses'] = 'tcp://127.0.0.11:5000'
cls.ctx = create_ctx(config, daemon=True)
cls.ctx.await_workers(cls.worker_count)
@classmethod
def tearDownClass(cls):
cls.ctx.stop()
sys.setswitchinterval(cls._old_switchinterval)
class DatasetTest(ComputeTest):
pass
|
# ... existing code ...
import sys
import unittest
# ... modified code ...
def setUpClass(cls):
# Increase switching interval to lure out race conditions a bit ...
cls._old_switchinterval = sys.getswitchinterval()
sys.setswitchinterval(1e-6)
config = Config()
...
cls.ctx.stop()
sys.setswitchinterval(cls._old_switchinterval)
# ... rest of the code ...
|
691dae3963d049664605084438714b2850bd0933
|
linter.py
|
linter.py
|
"""This module exports the AnsibleLint plugin class."""
from SublimeLinter.lint import Linter, util
class AnsibleLint(Linter):
"""Provides an interface to ansible-lint."""
# ansbile-lint verison requirements check
version_args = '--version'
version_re = r'(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 3.0.1'
# linter settings
cmd = ('ansible-lint', '${args}', '${file}')
regex = r'.+:(?P<line>\d+): \[(?P<error>.z+)\] (?P<message>.+)'
# -p generate non-multi-line, pep8 compatible output
multiline = False
# ansible-lint does not support column number
word_re = False
line_col_base = (1, 1)
tempfile_suffix = 'yml'
error_stream = util.STREAM_STDOUT
defaults = {
'selector': 'source.ansible',
'args': '-p'
}
|
"""This module exports the AnsibleLint plugin class."""
from SublimeLinter.lint import Linter, util
class AnsibleLint(Linter):
"""Provides an interface to ansible-lint."""
# ansbile-lint verison requirements check
version_args = '--version'
version_re = r'(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 3.0.1'
# linter settings
cmd = ('ansible-lint', '${args}', '@')
regex = r'^.+:(?P<line>\d+): \[.(?P<error>.+)\] (?P<message>.+)'
# -p generate non-multi-line, pep8 compatible output
multiline = False
# ansible-lint does not support column number
word_re = False
line_col_base = (1, 1)
tempfile_suffix = 'yml'
error_stream = util.STREAM_STDOUT
defaults = {
'selector': 'source.ansible',
'args': '--nocolor -p',
'--exclude= +': ['.galaxy'],
}
inline_overrides = ['exclude']
|
Update to support SublimeLinter 4
|
Update to support SublimeLinter 4
|
Python
|
mit
|
mliljedahl/SublimeLinter-contrib-ansible-lint
|
"""This module exports the AnsibleLint plugin class."""
from SublimeLinter.lint import Linter, util
class AnsibleLint(Linter):
"""Provides an interface to ansible-lint."""
# ansbile-lint verison requirements check
version_args = '--version'
version_re = r'(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 3.0.1'
# linter settings
- cmd = ('ansible-lint', '${args}', '${file}')
+ cmd = ('ansible-lint', '${args}', '@')
- regex = r'.+:(?P<line>\d+): \[(?P<error>.z+)\] (?P<message>.+)'
+ regex = r'^.+:(?P<line>\d+): \[.(?P<error>.+)\] (?P<message>.+)'
# -p generate non-multi-line, pep8 compatible output
multiline = False
# ansible-lint does not support column number
word_re = False
line_col_base = (1, 1)
tempfile_suffix = 'yml'
error_stream = util.STREAM_STDOUT
+
defaults = {
'selector': 'source.ansible',
- 'args': '-p'
+ 'args': '--nocolor -p',
+ '--exclude= +': ['.galaxy'],
}
+ inline_overrides = ['exclude']
|
Update to support SublimeLinter 4
|
## Code Before:
"""This module exports the AnsibleLint plugin class."""
from SublimeLinter.lint import Linter, util
class AnsibleLint(Linter):
"""Provides an interface to ansible-lint."""
# ansbile-lint verison requirements check
version_args = '--version'
version_re = r'(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 3.0.1'
# linter settings
cmd = ('ansible-lint', '${args}', '${file}')
regex = r'.+:(?P<line>\d+): \[(?P<error>.z+)\] (?P<message>.+)'
# -p generate non-multi-line, pep8 compatible output
multiline = False
# ansible-lint does not support column number
word_re = False
line_col_base = (1, 1)
tempfile_suffix = 'yml'
error_stream = util.STREAM_STDOUT
defaults = {
'selector': 'source.ansible',
'args': '-p'
}
## Instruction:
Update to support SublimeLinter 4
## Code After:
"""This module exports the AnsibleLint plugin class."""
from SublimeLinter.lint import Linter, util
class AnsibleLint(Linter):
"""Provides an interface to ansible-lint."""
# ansbile-lint verison requirements check
version_args = '--version'
version_re = r'(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 3.0.1'
# linter settings
cmd = ('ansible-lint', '${args}', '@')
regex = r'^.+:(?P<line>\d+): \[.(?P<error>.+)\] (?P<message>.+)'
# -p generate non-multi-line, pep8 compatible output
multiline = False
# ansible-lint does not support column number
word_re = False
line_col_base = (1, 1)
tempfile_suffix = 'yml'
error_stream = util.STREAM_STDOUT
defaults = {
'selector': 'source.ansible',
'args': '--nocolor -p',
'--exclude= +': ['.galaxy'],
}
inline_overrides = ['exclude']
|
...
# linter settings
cmd = ('ansible-lint', '${args}', '@')
regex = r'^.+:(?P<line>\d+): \[.(?P<error>.+)\] (?P<message>.+)'
# -p generate non-multi-line, pep8 compatible output
...
error_stream = util.STREAM_STDOUT
defaults = {
...
'selector': 'source.ansible',
'args': '--nocolor -p',
'--exclude= +': ['.galaxy'],
}
inline_overrides = ['exclude']
...
|
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)
|
...
if cont:
try:
comic_id = int(cont[0])
comic = await get_by_id(comic_id)
return await print_comic(comic)
except ValueError:
pass
...
|
f1eb55a147c4cc160decbfbcde190b7e8a2d3be6
|
clot/torrent/backbone.py
|
clot/torrent/backbone.py
|
"""This module implements the torrent's underlying storage."""
from .. import bencode
class Backbone: # pylint: disable=too-few-public-methods
"""Torrent file low-level contents."""
def __init__(self, raw_bytes, file_path=None):
"""Initialize self."""
self.raw_bytes = raw_bytes
self.data = bencode.decode(raw_bytes, keytostr=True)
if not isinstance(self.data, dict):
raise ValueError(f'expected top-level dictionary instead of {type(self.data)}')
self.file_path = file_path
def save_as(self, file_path, *, overwrite=False):
"""Write the torrent to a file and remember the new path and contents on success."""
raw_bytes = bencode.encode(self.data)
with open(file_path, 'wb' if overwrite else 'xb') as file:
file.write(raw_bytes)
self.raw_bytes = raw_bytes
self.file_path = file_path
def save(self):
"""Write the torrent to the file from which it was previously loaded or saved to."""
if self.file_path is None:
raise Exception('expected a torrent loaded from file')
raw_bytes = bencode.encode(self.data)
with open(self.file_path, 'wb') as file:
file.write(raw_bytes)
self.raw_bytes = raw_bytes
|
"""This module implements the torrent's underlying storage."""
from .. import bencode
class Backbone:
"""Torrent file low-level contents."""
def __init__(self, raw_bytes, file_path=None):
"""Initialize self."""
self.raw_bytes = raw_bytes
self.data = bencode.decode(raw_bytes, keytostr=True)
if not isinstance(self.data, dict):
raise ValueError(f'expected top-level dictionary instead of {type(self.data)}')
self.file_path = file_path
def save_as(self, file_path, *, overwrite=False):
"""Write the torrent to a file and remember the new path and contents on success."""
raw_bytes = bencode.encode(self.data)
with open(file_path, 'wb' if overwrite else 'xb') as file:
file.write(raw_bytes)
self.raw_bytes = raw_bytes
self.file_path = file_path
def save(self):
"""Write the torrent to the file from which it was previously loaded or saved to."""
if self.file_path is None:
raise Exception('expected a torrent loaded from file')
raw_bytes = bencode.encode(self.data)
with open(self.file_path, 'wb') as file:
file.write(raw_bytes)
self.raw_bytes = raw_bytes
|
Remove no longer needed pylint pragma
|
Remove no longer needed pylint pragma
|
Python
|
mit
|
elliptical/bencode
|
"""This module implements the torrent's underlying storage."""
from .. import bencode
- class Backbone: # pylint: disable=too-few-public-methods
+ class Backbone:
"""Torrent file low-level contents."""
def __init__(self, raw_bytes, file_path=None):
"""Initialize self."""
self.raw_bytes = raw_bytes
self.data = bencode.decode(raw_bytes, keytostr=True)
if not isinstance(self.data, dict):
raise ValueError(f'expected top-level dictionary instead of {type(self.data)}')
self.file_path = file_path
def save_as(self, file_path, *, overwrite=False):
"""Write the torrent to a file and remember the new path and contents on success."""
raw_bytes = bencode.encode(self.data)
with open(file_path, 'wb' if overwrite else 'xb') as file:
file.write(raw_bytes)
self.raw_bytes = raw_bytes
self.file_path = file_path
def save(self):
"""Write the torrent to the file from which it was previously loaded or saved to."""
if self.file_path is None:
raise Exception('expected a torrent loaded from file')
raw_bytes = bencode.encode(self.data)
with open(self.file_path, 'wb') as file:
file.write(raw_bytes)
self.raw_bytes = raw_bytes
|
Remove no longer needed pylint pragma
|
## Code Before:
"""This module implements the torrent's underlying storage."""
from .. import bencode
class Backbone: # pylint: disable=too-few-public-methods
"""Torrent file low-level contents."""
def __init__(self, raw_bytes, file_path=None):
"""Initialize self."""
self.raw_bytes = raw_bytes
self.data = bencode.decode(raw_bytes, keytostr=True)
if not isinstance(self.data, dict):
raise ValueError(f'expected top-level dictionary instead of {type(self.data)}')
self.file_path = file_path
def save_as(self, file_path, *, overwrite=False):
"""Write the torrent to a file and remember the new path and contents on success."""
raw_bytes = bencode.encode(self.data)
with open(file_path, 'wb' if overwrite else 'xb') as file:
file.write(raw_bytes)
self.raw_bytes = raw_bytes
self.file_path = file_path
def save(self):
"""Write the torrent to the file from which it was previously loaded or saved to."""
if self.file_path is None:
raise Exception('expected a torrent loaded from file')
raw_bytes = bencode.encode(self.data)
with open(self.file_path, 'wb') as file:
file.write(raw_bytes)
self.raw_bytes = raw_bytes
## Instruction:
Remove no longer needed pylint pragma
## Code After:
"""This module implements the torrent's underlying storage."""
from .. import bencode
class Backbone:
"""Torrent file low-level contents."""
def __init__(self, raw_bytes, file_path=None):
"""Initialize self."""
self.raw_bytes = raw_bytes
self.data = bencode.decode(raw_bytes, keytostr=True)
if not isinstance(self.data, dict):
raise ValueError(f'expected top-level dictionary instead of {type(self.data)}')
self.file_path = file_path
def save_as(self, file_path, *, overwrite=False):
"""Write the torrent to a file and remember the new path and contents on success."""
raw_bytes = bencode.encode(self.data)
with open(file_path, 'wb' if overwrite else 'xb') as file:
file.write(raw_bytes)
self.raw_bytes = raw_bytes
self.file_path = file_path
def save(self):
"""Write the torrent to the file from which it was previously loaded or saved to."""
if self.file_path is None:
raise Exception('expected a torrent loaded from file')
raw_bytes = bencode.encode(self.data)
with open(self.file_path, 'wb') as file:
file.write(raw_bytes)
self.raw_bytes = raw_bytes
|
# ... existing code ...
class Backbone:
"""Torrent file low-level contents."""
# ... rest of the code ...
|
ae3d8fd826647c8d853247b069726a26f4ae462d
|
exterminal.py
|
exterminal.py
|
import sublime, sublime_plugin
import os
def wrapped_exec(self, *args, **kwargs):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
if settings.get('enabled') and kwargs.get('use_exterminal', True):
wrapper = settings.get('exec_wrapper')
try:
shell_cmd = kwargs.get('shell_cmd', '')
shell_cmd = wrapper % shell_cmd.replace('"','\\"')
kwargs['shell_cmd'] = shell_cmd
except KeyError: pass
try:
cmd = ' '.join(kwargs.get('cmd'))
kwargs['shell_cmd'] = wrapper % cmd.replace('"','\\"')
except KeyError: pass
return self.run_cached_by_exterminal(*args, **kwargs)
def plugin_loaded():
exec_cls = [cls for cls in sublime_plugin.window_command_classes \
if cls.__qualname__=='ExecCommand'][0]
if hasattr(exec_cls(None), 'run_cached_by_exterminal'):
exec_cls.run = exec_cls.run_cached_by_exterminal
exec_cls.run_cached_by_exterminal = None
exec_cls.run_cached_by_exterminal = exec_cls.run
exec_cls.run = wrapped_exec
class StartExterminalCommand(sublime_plugin.WindowCommand):
def run(self, *args):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
cmd = settings.get('start_exterminal', '')
os.popen(cmd)
|
import sublime, sublime_plugin
import os
def wrapped_exec(self, *args, **kwargs):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
if settings.get('enabled') and kwargs.get('use_exterminal', True):
wrapper = settings.get('exec_wrapper')
try:
shell_cmd = kwargs.get('shell_cmd')
shell_cmd = wrapper % shell_cmd.replace('"','\\"')
kwargs['shell_cmd'] = shell_cmd
except KeyError: pass
try:
cmd = ' '.join(kwargs.get('cmd'))
kwargs['shell_cmd'] = wrapper % cmd.replace('"','\\"')
except KeyError: pass
return self.run_cached_by_exterminal(*args, **kwargs)
def plugin_loaded():
exec_cls = [cls for cls in sublime_plugin.window_command_classes \
if cls.__qualname__=='ExecCommand'][0]
if hasattr(exec_cls(None), 'run_cached_by_exterminal'):
exec_cls.run = exec_cls.run_cached_by_exterminal
exec_cls.run_cached_by_exterminal = None
exec_cls.run_cached_by_exterminal = exec_cls.run
exec_cls.run = wrapped_exec
class StartExterminalCommand(sublime_plugin.WindowCommand):
def run(self, *args):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
cmd = settings.get('start_exterminal', '')
os.popen(cmd)
|
Fix dangling default in kwargs 'shell_cmd'
|
Fix dangling default in kwargs 'shell_cmd'
|
Python
|
mit
|
jemc/SublimeExterminal,jemc/SublimeExterminal
|
import sublime, sublime_plugin
import os
def wrapped_exec(self, *args, **kwargs):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
if settings.get('enabled') and kwargs.get('use_exterminal', True):
wrapper = settings.get('exec_wrapper')
try:
- shell_cmd = kwargs.get('shell_cmd', '')
+ shell_cmd = kwargs.get('shell_cmd')
shell_cmd = wrapper % shell_cmd.replace('"','\\"')
kwargs['shell_cmd'] = shell_cmd
except KeyError: pass
try:
cmd = ' '.join(kwargs.get('cmd'))
kwargs['shell_cmd'] = wrapper % cmd.replace('"','\\"')
except KeyError: pass
-
return self.run_cached_by_exterminal(*args, **kwargs)
def plugin_loaded():
exec_cls = [cls for cls in sublime_plugin.window_command_classes \
if cls.__qualname__=='ExecCommand'][0]
if hasattr(exec_cls(None), 'run_cached_by_exterminal'):
exec_cls.run = exec_cls.run_cached_by_exterminal
exec_cls.run_cached_by_exterminal = None
exec_cls.run_cached_by_exterminal = exec_cls.run
exec_cls.run = wrapped_exec
class StartExterminalCommand(sublime_plugin.WindowCommand):
def run(self, *args):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
cmd = settings.get('start_exterminal', '')
os.popen(cmd)
|
Fix dangling default in kwargs 'shell_cmd'
|
## Code Before:
import sublime, sublime_plugin
import os
def wrapped_exec(self, *args, **kwargs):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
if settings.get('enabled') and kwargs.get('use_exterminal', True):
wrapper = settings.get('exec_wrapper')
try:
shell_cmd = kwargs.get('shell_cmd', '')
shell_cmd = wrapper % shell_cmd.replace('"','\\"')
kwargs['shell_cmd'] = shell_cmd
except KeyError: pass
try:
cmd = ' '.join(kwargs.get('cmd'))
kwargs['shell_cmd'] = wrapper % cmd.replace('"','\\"')
except KeyError: pass
return self.run_cached_by_exterminal(*args, **kwargs)
def plugin_loaded():
exec_cls = [cls for cls in sublime_plugin.window_command_classes \
if cls.__qualname__=='ExecCommand'][0]
if hasattr(exec_cls(None), 'run_cached_by_exterminal'):
exec_cls.run = exec_cls.run_cached_by_exterminal
exec_cls.run_cached_by_exterminal = None
exec_cls.run_cached_by_exterminal = exec_cls.run
exec_cls.run = wrapped_exec
class StartExterminalCommand(sublime_plugin.WindowCommand):
def run(self, *args):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
cmd = settings.get('start_exterminal', '')
os.popen(cmd)
## Instruction:
Fix dangling default in kwargs 'shell_cmd'
## Code After:
import sublime, sublime_plugin
import os
def wrapped_exec(self, *args, **kwargs):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
if settings.get('enabled') and kwargs.get('use_exterminal', True):
wrapper = settings.get('exec_wrapper')
try:
shell_cmd = kwargs.get('shell_cmd')
shell_cmd = wrapper % shell_cmd.replace('"','\\"')
kwargs['shell_cmd'] = shell_cmd
except KeyError: pass
try:
cmd = ' '.join(kwargs.get('cmd'))
kwargs['shell_cmd'] = wrapper % cmd.replace('"','\\"')
except KeyError: pass
return self.run_cached_by_exterminal(*args, **kwargs)
def plugin_loaded():
exec_cls = [cls for cls in sublime_plugin.window_command_classes \
if cls.__qualname__=='ExecCommand'][0]
if hasattr(exec_cls(None), 'run_cached_by_exterminal'):
exec_cls.run = exec_cls.run_cached_by_exterminal
exec_cls.run_cached_by_exterminal = None
exec_cls.run_cached_by_exterminal = exec_cls.run
exec_cls.run = wrapped_exec
class StartExterminalCommand(sublime_plugin.WindowCommand):
def run(self, *args):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
cmd = settings.get('start_exterminal', '')
os.popen(cmd)
|
# ... existing code ...
try:
shell_cmd = kwargs.get('shell_cmd')
shell_cmd = wrapper % shell_cmd.replace('"','\\"')
# ... modified code ...
except KeyError: pass
# ... rest of the code ...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.