commit stringlengths 40 40 | old_file stringlengths 4 106 | new_file stringlengths 4 106 | old_contents stringlengths 10 2.94k | new_contents stringlengths 21 2.95k | subject stringlengths 16 444 | message stringlengths 17 2.63k | lang stringclasses 1 value | license stringclasses 13 values | repos stringlengths 7 43k | ndiff stringlengths 52 3.31k | instruction stringlengths 16 444 | content stringlengths 133 4.32k | diff stringlengths 49 3.61k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
50b6778ae43b8945b2073630e351ab759b007a3e | tests/social/youtube/test_tasks.py | tests/social/youtube/test_tasks.py | import pytest
from components.social.youtube.factories import ChannelFactory
from components.social.youtube.models import Video
from components.social.youtube.tasks import (fetch_all_videos,
fetch_latest_videos)
pytestmark = pytest.mark.django_db
def test_fetch_all_videos():
channel = ChannelFactory(username='revyver')
fetch_all_videos(channel)
assert channel.videos.count() > 0
for video in channel.videos.all():
assert isinstance(video, Video)
def test_fetch_latest_videos():
channel = ChannelFactory(username='revyver')
fetch_latest_videos()
assert channel.videos.count() > 0
for video in channel.videos.all():
assert isinstance(video, Video)
| import pytest
from components.social.youtube.factories import ChannelFactory
from components.social.youtube.models import Video
from components.social.youtube.tasks import (fetch_all_videos,
fetch_latest_videos)
pytestmark = pytest.mark.django_db
def test_fetch_all_videos():
channel = ChannelFactory(username='iceymoon')
fetch_all_videos(channel)
assert channel.videos.count() > 0
for video in channel.videos.all():
assert isinstance(video, Video)
def test_fetch_latest_videos():
channel = ChannelFactory(username='iceymoon')
fetch_latest_videos()
assert channel.videos.count() > 0
for video in channel.videos.all():
assert isinstance(video, Video)
| Switch to Jen's channel to (hopefully) make these tests faster. | Switch to Jen's channel to (hopefully) make these tests faster.
| Python | apache-2.0 | hello-base/web,hello-base/web,hello-base/web,hello-base/web | import pytest
from components.social.youtube.factories import ChannelFactory
from components.social.youtube.models import Video
from components.social.youtube.tasks import (fetch_all_videos,
fetch_latest_videos)
pytestmark = pytest.mark.django_db
def test_fetch_all_videos():
- channel = ChannelFactory(username='revyver')
+ channel = ChannelFactory(username='iceymoon')
fetch_all_videos(channel)
assert channel.videos.count() > 0
for video in channel.videos.all():
assert isinstance(video, Video)
def test_fetch_latest_videos():
- channel = ChannelFactory(username='revyver')
+ channel = ChannelFactory(username='iceymoon')
fetch_latest_videos()
assert channel.videos.count() > 0
for video in channel.videos.all():
assert isinstance(video, Video)
| Switch to Jen's channel to (hopefully) make these tests faster. | ## Code Before:
import pytest
from components.social.youtube.factories import ChannelFactory
from components.social.youtube.models import Video
from components.social.youtube.tasks import (fetch_all_videos,
fetch_latest_videos)
pytestmark = pytest.mark.django_db
def test_fetch_all_videos():
channel = ChannelFactory(username='revyver')
fetch_all_videos(channel)
assert channel.videos.count() > 0
for video in channel.videos.all():
assert isinstance(video, Video)
def test_fetch_latest_videos():
channel = ChannelFactory(username='revyver')
fetch_latest_videos()
assert channel.videos.count() > 0
for video in channel.videos.all():
assert isinstance(video, Video)
## Instruction:
Switch to Jen's channel to (hopefully) make these tests faster.
## Code After:
import pytest
from components.social.youtube.factories import ChannelFactory
from components.social.youtube.models import Video
from components.social.youtube.tasks import (fetch_all_videos,
fetch_latest_videos)
pytestmark = pytest.mark.django_db
def test_fetch_all_videos():
channel = ChannelFactory(username='iceymoon')
fetch_all_videos(channel)
assert channel.videos.count() > 0
for video in channel.videos.all():
assert isinstance(video, Video)
def test_fetch_latest_videos():
channel = ChannelFactory(username='iceymoon')
fetch_latest_videos()
assert channel.videos.count() > 0
for video in channel.videos.all():
assert isinstance(video, Video)
| import pytest
from components.social.youtube.factories import ChannelFactory
from components.social.youtube.models import Video
from components.social.youtube.tasks import (fetch_all_videos,
fetch_latest_videos)
pytestmark = pytest.mark.django_db
def test_fetch_all_videos():
- channel = ChannelFactory(username='revyver')
? ^ - ^^^
+ channel = ChannelFactory(username='iceymoon')
? ^^ ^^^^
fetch_all_videos(channel)
assert channel.videos.count() > 0
for video in channel.videos.all():
assert isinstance(video, Video)
def test_fetch_latest_videos():
- channel = ChannelFactory(username='revyver')
? ^ - ^^^
+ channel = ChannelFactory(username='iceymoon')
? ^^ ^^^^
fetch_latest_videos()
assert channel.videos.count() > 0
for video in channel.videos.all():
assert isinstance(video, Video) |
dc1a7bc4d674fd6e7235222612f1d147112d77db | src/nodeconductor_assembly_waldur/packages/migrations/0002_openstack_packages.py | src/nodeconductor_assembly_waldur/packages/migrations/0002_openstack_packages.py | from __future__ import unicode_literals
from django.db import migrations, models
import nodeconductor.core.fields
class Migration(migrations.Migration):
dependencies = [
('openstack', '0022_volume_device'),
('structure', '0037_remove_customer_billing_backend_id'),
('packages', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='OpenStackPackage',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('uuid', nodeconductor.core.fields.UUIDField()),
('service_settings', models.ForeignKey(related_name='+', to='structure.ServiceSettings')),
],
options={
'abstract': False,
},
),
migrations.RemoveField(
model_name='packagetemplate',
name='type',
),
migrations.AddField(
model_name='packagetemplate',
name='service_settings',
field=models.ForeignKey(related_name='+', default=1, to='structure.ServiceSettings'),
preserve_default=False,
),
migrations.AddField(
model_name='openstackpackage',
name='template',
field=models.ForeignKey(related_name='openstack_packages', to='packages.PackageTemplate', help_text='Tenant will be created based on this template.'),
),
migrations.AddField(
model_name='openstackpackage',
name='tenant',
field=models.ForeignKey(related_name='+', to='openstack.Tenant'),
),
]
| from __future__ import unicode_literals
from django.db import migrations, models
import nodeconductor.core.fields
class Migration(migrations.Migration):
dependencies = [
('openstack', '0022_volume_device'),
('structure', '0037_remove_customer_billing_backend_id'),
('packages', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='OpenStackPackage',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('uuid', nodeconductor.core.fields.UUIDField()),
('service_settings', models.ForeignKey(related_name='+', to='structure.ServiceSettings')),
],
options={
'abstract': False,
},
),
migrations.RemoveField(
model_name='packagetemplate',
name='type',
),
migrations.AddField(
model_name='packagetemplate',
name='service_settings',
field=models.ForeignKey(related_name='+', to='structure.ServiceSettings'),
preserve_default=False,
),
migrations.AddField(
model_name='openstackpackage',
name='template',
field=models.ForeignKey(related_name='openstack_packages', to='packages.PackageTemplate', help_text='Tenant will be created based on this template.'),
),
migrations.AddField(
model_name='openstackpackage',
name='tenant',
field=models.ForeignKey(related_name='+', to='openstack.Tenant'),
),
]
| Remove useless default from migration | Remove useless default from migration
- wal-26
| Python | mit | opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind | from __future__ import unicode_literals
from django.db import migrations, models
import nodeconductor.core.fields
class Migration(migrations.Migration):
dependencies = [
('openstack', '0022_volume_device'),
('structure', '0037_remove_customer_billing_backend_id'),
('packages', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='OpenStackPackage',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('uuid', nodeconductor.core.fields.UUIDField()),
('service_settings', models.ForeignKey(related_name='+', to='structure.ServiceSettings')),
],
options={
'abstract': False,
},
),
migrations.RemoveField(
model_name='packagetemplate',
name='type',
),
migrations.AddField(
model_name='packagetemplate',
name='service_settings',
- field=models.ForeignKey(related_name='+', default=1, to='structure.ServiceSettings'),
+ field=models.ForeignKey(related_name='+', to='structure.ServiceSettings'),
preserve_default=False,
),
migrations.AddField(
model_name='openstackpackage',
name='template',
field=models.ForeignKey(related_name='openstack_packages', to='packages.PackageTemplate', help_text='Tenant will be created based on this template.'),
),
migrations.AddField(
model_name='openstackpackage',
name='tenant',
field=models.ForeignKey(related_name='+', to='openstack.Tenant'),
),
]
| Remove useless default from migration | ## Code Before:
from __future__ import unicode_literals
from django.db import migrations, models
import nodeconductor.core.fields
class Migration(migrations.Migration):
dependencies = [
('openstack', '0022_volume_device'),
('structure', '0037_remove_customer_billing_backend_id'),
('packages', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='OpenStackPackage',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('uuid', nodeconductor.core.fields.UUIDField()),
('service_settings', models.ForeignKey(related_name='+', to='structure.ServiceSettings')),
],
options={
'abstract': False,
},
),
migrations.RemoveField(
model_name='packagetemplate',
name='type',
),
migrations.AddField(
model_name='packagetemplate',
name='service_settings',
field=models.ForeignKey(related_name='+', default=1, to='structure.ServiceSettings'),
preserve_default=False,
),
migrations.AddField(
model_name='openstackpackage',
name='template',
field=models.ForeignKey(related_name='openstack_packages', to='packages.PackageTemplate', help_text='Tenant will be created based on this template.'),
),
migrations.AddField(
model_name='openstackpackage',
name='tenant',
field=models.ForeignKey(related_name='+', to='openstack.Tenant'),
),
]
## Instruction:
Remove useless default from migration
## Code After:
from __future__ import unicode_literals
from django.db import migrations, models
import nodeconductor.core.fields
class Migration(migrations.Migration):
dependencies = [
('openstack', '0022_volume_device'),
('structure', '0037_remove_customer_billing_backend_id'),
('packages', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='OpenStackPackage',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('uuid', nodeconductor.core.fields.UUIDField()),
('service_settings', models.ForeignKey(related_name='+', to='structure.ServiceSettings')),
],
options={
'abstract': False,
},
),
migrations.RemoveField(
model_name='packagetemplate',
name='type',
),
migrations.AddField(
model_name='packagetemplate',
name='service_settings',
field=models.ForeignKey(related_name='+', to='structure.ServiceSettings'),
preserve_default=False,
),
migrations.AddField(
model_name='openstackpackage',
name='template',
field=models.ForeignKey(related_name='openstack_packages', to='packages.PackageTemplate', help_text='Tenant will be created based on this template.'),
),
migrations.AddField(
model_name='openstackpackage',
name='tenant',
field=models.ForeignKey(related_name='+', to='openstack.Tenant'),
),
]
| from __future__ import unicode_literals
from django.db import migrations, models
import nodeconductor.core.fields
class Migration(migrations.Migration):
dependencies = [
('openstack', '0022_volume_device'),
('structure', '0037_remove_customer_billing_backend_id'),
('packages', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='OpenStackPackage',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('uuid', nodeconductor.core.fields.UUIDField()),
('service_settings', models.ForeignKey(related_name='+', to='structure.ServiceSettings')),
],
options={
'abstract': False,
},
),
migrations.RemoveField(
model_name='packagetemplate',
name='type',
),
migrations.AddField(
model_name='packagetemplate',
name='service_settings',
- field=models.ForeignKey(related_name='+', default=1, to='structure.ServiceSettings'),
? -----------
+ field=models.ForeignKey(related_name='+', to='structure.ServiceSettings'),
preserve_default=False,
),
migrations.AddField(
model_name='openstackpackage',
name='template',
field=models.ForeignKey(related_name='openstack_packages', to='packages.PackageTemplate', help_text='Tenant will be created based on this template.'),
),
migrations.AddField(
model_name='openstackpackage',
name='tenant',
field=models.ForeignKey(related_name='+', to='openstack.Tenant'),
),
] |
c06e28dae894823c0ae5385e0f9c047ceab8561c | zombies/tests.py | zombies/tests.py | from django.test import TestCase
# Create your tests here.
from django.test import TestCase
from models import Story
class StoryMethodTests(TestCase):
def test_ensure_story_is_inserted(self):
story = Story(name="Zombies on Campus",visits=1,description='Zombies desciption',picture='testpic')
story.save()
self.assertEquals((story.visits==1), True)
self.assertEquals((story.name=='Zombies on Campus'), True)
self.assertEquals((story.description=='Zombies desciption'), True)
self.assertEquals((story.picture=='testpic'), True) | from django.test import TestCase
# Create your tests here.
from django.test import TestCase
from models import Story, StoryPoint
class StoryMethodTests(TestCase):
def test_ensure_story_is_inserted(self):
story = Story(name="Zombies on Campus",visits=1,description='Zombies desciption',picture='testpic')
story.save()
self.assertEquals((story.visits==1), True)
self.assertEquals((story.name=='Zombies on Campus'), True)
self.assertEquals((story.description=='Zombies desciption'), True)
self.assertEquals((story.picture=='testpic'), True)
def test_ensure_storyPoints_is_inserted(self):
storyPoint = StoryPoint(description='You are in the library',choiceText='yes',experience=10,story_type='start',main_story_id_id=5,visits=1,story_point_id=1,picture='testpic2')
storyPoint.save()
self.assertEquals((storyPoint.description=='You are in the library'),True)
self.assertEquals((storyPoint.choiceText=='yes'),True)
self.assertEquals((storyPoint.experience==10),True)
self.assertEquals((storyPoint.story_type=='start'),True)
self.assertEquals((storyPoint.story_point_id==1),True)
self.assertEquals((storyPoint.picture=='testpic2'),True)
self.assertEquals((storyPoint.visits==1),True)
self.assertEquals((storyPoint.main_story_id_id==5),True)
| Test case 2 for table storypoint | Test case 2 for table storypoint
| Python | apache-2.0 | ITLabProject2016/internet_technology_lab_project,ITLabProject2016/internet_technology_lab_project,ITLabProject2016/internet_technology_lab_project | from django.test import TestCase
# Create your tests here.
from django.test import TestCase
- from models import Story
+ from models import Story, StoryPoint
class StoryMethodTests(TestCase):
def test_ensure_story_is_inserted(self):
story = Story(name="Zombies on Campus",visits=1,description='Zombies desciption',picture='testpic')
story.save()
self.assertEquals((story.visits==1), True)
self.assertEquals((story.name=='Zombies on Campus'), True)
self.assertEquals((story.description=='Zombies desciption'), True)
- self.assertEquals((story.picture=='testpic'), True)
+ self.assertEquals((story.picture=='testpic'), True)
+
+
+
+ def test_ensure_storyPoints_is_inserted(self):
+
+ storyPoint = StoryPoint(description='You are in the library',choiceText='yes',experience=10,story_type='start',main_story_id_id=5,visits=1,story_point_id=1,picture='testpic2')
+ storyPoint.save()
+ self.assertEquals((storyPoint.description=='You are in the library'),True)
+ self.assertEquals((storyPoint.choiceText=='yes'),True)
+ self.assertEquals((storyPoint.experience==10),True)
+ self.assertEquals((storyPoint.story_type=='start'),True)
+ self.assertEquals((storyPoint.story_point_id==1),True)
+ self.assertEquals((storyPoint.picture=='testpic2'),True)
+ self.assertEquals((storyPoint.visits==1),True)
+ self.assertEquals((storyPoint.main_story_id_id==5),True)
+ | Test case 2 for table storypoint | ## Code Before:
from django.test import TestCase
# Create your tests here.
from django.test import TestCase
from models import Story
class StoryMethodTests(TestCase):
def test_ensure_story_is_inserted(self):
story = Story(name="Zombies on Campus",visits=1,description='Zombies desciption',picture='testpic')
story.save()
self.assertEquals((story.visits==1), True)
self.assertEquals((story.name=='Zombies on Campus'), True)
self.assertEquals((story.description=='Zombies desciption'), True)
self.assertEquals((story.picture=='testpic'), True)
## Instruction:
Test case 2 for table storypoint
## Code After:
from django.test import TestCase
# Create your tests here.
from django.test import TestCase
from models import Story, StoryPoint
class StoryMethodTests(TestCase):
def test_ensure_story_is_inserted(self):
story = Story(name="Zombies on Campus",visits=1,description='Zombies desciption',picture='testpic')
story.save()
self.assertEquals((story.visits==1), True)
self.assertEquals((story.name=='Zombies on Campus'), True)
self.assertEquals((story.description=='Zombies desciption'), True)
self.assertEquals((story.picture=='testpic'), True)
def test_ensure_storyPoints_is_inserted(self):
storyPoint = StoryPoint(description='You are in the library',choiceText='yes',experience=10,story_type='start',main_story_id_id=5,visits=1,story_point_id=1,picture='testpic2')
storyPoint.save()
self.assertEquals((storyPoint.description=='You are in the library'),True)
self.assertEquals((storyPoint.choiceText=='yes'),True)
self.assertEquals((storyPoint.experience==10),True)
self.assertEquals((storyPoint.story_type=='start'),True)
self.assertEquals((storyPoint.story_point_id==1),True)
self.assertEquals((storyPoint.picture=='testpic2'),True)
self.assertEquals((storyPoint.visits==1),True)
self.assertEquals((storyPoint.main_story_id_id==5),True)
| from django.test import TestCase
# Create your tests here.
from django.test import TestCase
- from models import Story
+ from models import Story, StoryPoint
? ++++++++++++
class StoryMethodTests(TestCase):
def test_ensure_story_is_inserted(self):
story = Story(name="Zombies on Campus",visits=1,description='Zombies desciption',picture='testpic')
story.save()
self.assertEquals((story.visits==1), True)
self.assertEquals((story.name=='Zombies on Campus'), True)
self.assertEquals((story.description=='Zombies desciption'), True)
self.assertEquals((story.picture=='testpic'), True)
+
+
+
+ def test_ensure_storyPoints_is_inserted(self):
+
+ storyPoint = StoryPoint(description='You are in the library',choiceText='yes',experience=10,story_type='start',main_story_id_id=5,visits=1,story_point_id=1,picture='testpic2')
+ storyPoint.save()
+ self.assertEquals((storyPoint.description=='You are in the library'),True)
+ self.assertEquals((storyPoint.choiceText=='yes'),True)
+ self.assertEquals((storyPoint.experience==10),True)
+ self.assertEquals((storyPoint.story_type=='start'),True)
+ self.assertEquals((storyPoint.story_point_id==1),True)
+ self.assertEquals((storyPoint.picture=='testpic2'),True)
+ self.assertEquals((storyPoint.visits==1),True)
+ self.assertEquals((storyPoint.main_story_id_id==5),True) |
cd30723af9f82b7a91d1ad1e2a5b86f88d8f4b17 | harvester/post_processing/dedup_sourceresource.py | harvester/post_processing/dedup_sourceresource.py |
def dedup_sourceresource(doc):
''' Look for duplicate values in the doc['sourceResource'] and
remove.
Values must be *exactly* the same
'''
for key, value in doc['sourceResource'].items():
if not isinstance(value, basestring):
new_list = []
for item in value:
if item not in new_list:
new_list.append(item)
doc['sourceResource'][key] = new_list
return doc
|
def dedup_sourceresource(doc):
''' Look for duplicate values in the doc['sourceResource'] and
remove.
Values must be *exactly* the same
'''
for key, value in doc['sourceResource'].items():
if isinstance(value, list):
# can't use set() because of dict values (non-hashable)
new_list = []
for item in value:
if item not in new_list:
new_list.append(item)
doc['sourceResource'][key] = new_list
return doc
| Make sure dedup item is a list. | Make sure dedup item is a list.
| Python | bsd-3-clause | barbarahui/harvester,ucldc/harvester,ucldc/harvester,mredar/harvester,mredar/harvester,barbarahui/harvester |
def dedup_sourceresource(doc):
''' Look for duplicate values in the doc['sourceResource'] and
remove.
Values must be *exactly* the same
'''
for key, value in doc['sourceResource'].items():
- if not isinstance(value, basestring):
+ if isinstance(value, list):
+ # can't use set() because of dict values (non-hashable)
new_list = []
for item in value:
if item not in new_list:
new_list.append(item)
doc['sourceResource'][key] = new_list
return doc
| Make sure dedup item is a list. | ## Code Before:
def dedup_sourceresource(doc):
''' Look for duplicate values in the doc['sourceResource'] and
remove.
Values must be *exactly* the same
'''
for key, value in doc['sourceResource'].items():
if not isinstance(value, basestring):
new_list = []
for item in value:
if item not in new_list:
new_list.append(item)
doc['sourceResource'][key] = new_list
return doc
## Instruction:
Make sure dedup item is a list.
## Code After:
def dedup_sourceresource(doc):
''' Look for duplicate values in the doc['sourceResource'] and
remove.
Values must be *exactly* the same
'''
for key, value in doc['sourceResource'].items():
if isinstance(value, list):
# can't use set() because of dict values (non-hashable)
new_list = []
for item in value:
if item not in new_list:
new_list.append(item)
doc['sourceResource'][key] = new_list
return doc
|
def dedup_sourceresource(doc):
''' Look for duplicate values in the doc['sourceResource'] and
remove.
Values must be *exactly* the same
'''
for key, value in doc['sourceResource'].items():
- if not isinstance(value, basestring):
? ---- ^^^^ ----
+ if isinstance(value, list):
? ^^
+ # can't use set() because of dict values (non-hashable)
new_list = []
for item in value:
if item not in new_list:
new_list.append(item)
doc['sourceResource'][key] = new_list
return doc |
923c994fe9a7b02e1939b83ebeefc296cd16b607 | lib/proc_query.py | lib/proc_query.py | import re
import snmpy
class proc_query(snmpy.plugin):
def create(self):
for key, val in sorted(self.conf['objects'].items()):
extra = {
'run': self.gather,
'start': val.get('start', 0),
'regex': re.compile(val['regex']),
}
self.data['1.%s' % key] = 'string', val['label']
self.data['2.%s' % key] = val['type'], val.get('start', 0), extra
def gather(self, obj):
text = open('/proc/%s' % self.conf['proc_entry'])
find = self.data[obj:'regex'].findall(text)
if find:
if self.data[obj:'regex'].groups == 0:
self.data[obj] = len(find)
else:
self.data[obj] = find[0].strip()
else:
self.data[obj] = self.data[obj:'start']
| import re
import snmpy
class proc_query(snmpy.plugin):
def create(self):
for key, val in sorted(self.conf['objects'].items()):
extra = {
'run': self.gather,
'start': val.get('start', 0),
'regex': re.compile(val['regex']),
}
self.data['1.%s' % key] = 'string', val['label']
self.data['2.%s' % key] = val['type'], val.get('start', 0), extra
def gather(self, obj):
text = open('/proc/%s' % self.conf['object']).read()
find = self.data[obj:'regex'].findall(text)
if find:
if self.data[obj:'regex'].groups == 0:
self.data[obj] = len(find)
else:
self.data[obj] = find[0].strip()
else:
self.data[obj] = self.data[obj:'start']
| Rename proc object config key from proc_entry to simply object. | Rename proc object config key from proc_entry to simply object.
| Python | mit | mk23/snmpy,mk23/snmpy | import re
import snmpy
class proc_query(snmpy.plugin):
def create(self):
for key, val in sorted(self.conf['objects'].items()):
extra = {
'run': self.gather,
'start': val.get('start', 0),
'regex': re.compile(val['regex']),
}
self.data['1.%s' % key] = 'string', val['label']
self.data['2.%s' % key] = val['type'], val.get('start', 0), extra
def gather(self, obj):
- text = open('/proc/%s' % self.conf['proc_entry'])
+ text = open('/proc/%s' % self.conf['object']).read()
find = self.data[obj:'regex'].findall(text)
if find:
if self.data[obj:'regex'].groups == 0:
self.data[obj] = len(find)
else:
self.data[obj] = find[0].strip()
else:
self.data[obj] = self.data[obj:'start']
| Rename proc object config key from proc_entry to simply object. | ## Code Before:
import re
import snmpy
class proc_query(snmpy.plugin):
def create(self):
for key, val in sorted(self.conf['objects'].items()):
extra = {
'run': self.gather,
'start': val.get('start', 0),
'regex': re.compile(val['regex']),
}
self.data['1.%s' % key] = 'string', val['label']
self.data['2.%s' % key] = val['type'], val.get('start', 0), extra
def gather(self, obj):
text = open('/proc/%s' % self.conf['proc_entry'])
find = self.data[obj:'regex'].findall(text)
if find:
if self.data[obj:'regex'].groups == 0:
self.data[obj] = len(find)
else:
self.data[obj] = find[0].strip()
else:
self.data[obj] = self.data[obj:'start']
## Instruction:
Rename proc object config key from proc_entry to simply object.
## Code After:
import re
import snmpy
class proc_query(snmpy.plugin):
def create(self):
for key, val in sorted(self.conf['objects'].items()):
extra = {
'run': self.gather,
'start': val.get('start', 0),
'regex': re.compile(val['regex']),
}
self.data['1.%s' % key] = 'string', val['label']
self.data['2.%s' % key] = val['type'], val.get('start', 0), extra
def gather(self, obj):
text = open('/proc/%s' % self.conf['object']).read()
find = self.data[obj:'regex'].findall(text)
if find:
if self.data[obj:'regex'].groups == 0:
self.data[obj] = len(find)
else:
self.data[obj] = find[0].strip()
else:
self.data[obj] = self.data[obj:'start']
| import re
import snmpy
class proc_query(snmpy.plugin):
def create(self):
for key, val in sorted(self.conf['objects'].items()):
extra = {
'run': self.gather,
'start': val.get('start', 0),
'regex': re.compile(val['regex']),
}
self.data['1.%s' % key] = 'string', val['label']
self.data['2.%s' % key] = val['type'], val.get('start', 0), extra
def gather(self, obj):
- text = open('/proc/%s' % self.conf['proc_entry'])
? -- --- --
+ text = open('/proc/%s' % self.conf['object']).read()
? +++ +++++++
find = self.data[obj:'regex'].findall(text)
if find:
if self.data[obj:'regex'].groups == 0:
self.data[obj] = len(find)
else:
self.data[obj] = find[0].strip()
else:
self.data[obj] = self.data[obj:'start'] |
ff13cc4b7ef29c4454abb41b8e9a525d12c9ff7d | tailorscad/tests/test_arg_parser.py | tailorscad/tests/test_arg_parser.py |
import unittest
from tailorscad.arg_parser import parse_args
class TestArgParser(unittest.TestCase):
def test_parse_args_none(self):
args = []
argv = []
args = parse_args(argv)
self.assertFalse(args)
def test_parse_args_inknown(self):
args = []
argv = ['-a', 'word']
args = parse_args(argv)
self.assertFalse(args)
def test_parse_args_known(self):
args = []
argv = ['-c', 'test']
args = parse_args(argv)
self.assertTrue(args)
self.assertEqual(args, ['test'])
def test_parse_args_unkown_and_known(self):
args = []
argv = ['-a', 'word', '-c', 'test']
args = parse_args(argv)
self.assertTrue(args)
self.assertEqual(args, ['test'])
|
import unittest
from tailorscad.arg_parser import parse_args
class TestArgParser(unittest.TestCase):
def test_parse_args_none(self):
args = []
argv = []
args = parse_args(argv)
self.assertFalse(args.config)
def test_parse_args_inknown(self):
args = []
argv = ['-a', 'word']
args = parse_args(argv)
self.assertFalse(args.config)
def test_parse_args_known(self):
args = []
argv = ['-c', 'test']
args = parse_args(argv)
self.assertTrue(args)
self.assertEqual(args.config, 'test')
def test_parse_args_unkown_and_known(self):
args = []
argv = ['-a', 'word', '-c', 'test']
args = parse_args(argv)
self.assertTrue(args)
self.assertEqual(args.config, 'test')
| Fix unit tests for arg_parser | Fix unit tests for arg_parser
| Python | mit | savorywatt/tailorSCAD |
import unittest
from tailorscad.arg_parser import parse_args
class TestArgParser(unittest.TestCase):
def test_parse_args_none(self):
args = []
argv = []
args = parse_args(argv)
- self.assertFalse(args)
+ self.assertFalse(args.config)
def test_parse_args_inknown(self):
args = []
argv = ['-a', 'word']
args = parse_args(argv)
- self.assertFalse(args)
+ self.assertFalse(args.config)
def test_parse_args_known(self):
args = []
argv = ['-c', 'test']
args = parse_args(argv)
self.assertTrue(args)
- self.assertEqual(args, ['test'])
+ self.assertEqual(args.config, 'test')
def test_parse_args_unkown_and_known(self):
args = []
argv = ['-a', 'word', '-c', 'test']
args = parse_args(argv)
self.assertTrue(args)
- self.assertEqual(args, ['test'])
+ self.assertEqual(args.config, 'test')
| Fix unit tests for arg_parser | ## Code Before:
import unittest
from tailorscad.arg_parser import parse_args
class TestArgParser(unittest.TestCase):
def test_parse_args_none(self):
args = []
argv = []
args = parse_args(argv)
self.assertFalse(args)
def test_parse_args_inknown(self):
args = []
argv = ['-a', 'word']
args = parse_args(argv)
self.assertFalse(args)
def test_parse_args_known(self):
args = []
argv = ['-c', 'test']
args = parse_args(argv)
self.assertTrue(args)
self.assertEqual(args, ['test'])
def test_parse_args_unkown_and_known(self):
args = []
argv = ['-a', 'word', '-c', 'test']
args = parse_args(argv)
self.assertTrue(args)
self.assertEqual(args, ['test'])
## Instruction:
Fix unit tests for arg_parser
## Code After:
import unittest
from tailorscad.arg_parser import parse_args
class TestArgParser(unittest.TestCase):
def test_parse_args_none(self):
args = []
argv = []
args = parse_args(argv)
self.assertFalse(args.config)
def test_parse_args_inknown(self):
args = []
argv = ['-a', 'word']
args = parse_args(argv)
self.assertFalse(args.config)
def test_parse_args_known(self):
args = []
argv = ['-c', 'test']
args = parse_args(argv)
self.assertTrue(args)
self.assertEqual(args.config, 'test')
def test_parse_args_unkown_and_known(self):
args = []
argv = ['-a', 'word', '-c', 'test']
args = parse_args(argv)
self.assertTrue(args)
self.assertEqual(args.config, 'test')
|
import unittest
from tailorscad.arg_parser import parse_args
class TestArgParser(unittest.TestCase):
def test_parse_args_none(self):
args = []
argv = []
args = parse_args(argv)
- self.assertFalse(args)
+ self.assertFalse(args.config)
? +++++++
def test_parse_args_inknown(self):
args = []
argv = ['-a', 'word']
args = parse_args(argv)
- self.assertFalse(args)
+ self.assertFalse(args.config)
? +++++++
def test_parse_args_known(self):
args = []
argv = ['-c', 'test']
args = parse_args(argv)
self.assertTrue(args)
- self.assertEqual(args, ['test'])
? - -
+ self.assertEqual(args.config, 'test')
? +++++++
def test_parse_args_unkown_and_known(self):
args = []
argv = ['-a', 'word', '-c', 'test']
args = parse_args(argv)
self.assertTrue(args)
- self.assertEqual(args, ['test'])
? - -
+ self.assertEqual(args.config, 'test')
? +++++++
|
88e0ec5ff58f7dabb531749472a410498c8e7827 | py_skiplist/iterators.py | py_skiplist/iterators.py | from itertools import dropwhile, count, cycle
import random
def geometric(p):
return (next(dropwhile(lambda _: random.randint(1, int(1. / p)) == 1, count())) for _ in cycle([1]))
def uniform(n):
"""
Simple deterministic distribution for testing internal of the skiplist
"""
return (n for _ in cycle([1]))
| from itertools import dropwhile, count, repeat
import random
def geometric(p):
return (next(dropwhile(lambda _: random.randint(1, int(1. / p)) == 1, count())) for _ in repeat(1))
# Simple deterministic distribution for testing internals of the skiplist.
uniform = repeat
| Use itertools.repeat over slower alternatives. | Use itertools.repeat over slower alternatives. | Python | mit | ZhukovAlexander/skiplist-python | - from itertools import dropwhile, count, cycle
+ from itertools import dropwhile, count, repeat
import random
def geometric(p):
- return (next(dropwhile(lambda _: random.randint(1, int(1. / p)) == 1, count())) for _ in cycle([1]))
+ return (next(dropwhile(lambda _: random.randint(1, int(1. / p)) == 1, count())) for _ in repeat(1))
- def uniform(n):
- """
- Simple deterministic distribution for testing internal of the skiplist
+ # Simple deterministic distribution for testing internals of the skiplist.
+ uniform = repeat
- """
- return (n for _ in cycle([1]))
| Use itertools.repeat over slower alternatives. | ## Code Before:
from itertools import dropwhile, count, cycle
import random
def geometric(p):
return (next(dropwhile(lambda _: random.randint(1, int(1. / p)) == 1, count())) for _ in cycle([1]))
def uniform(n):
"""
Simple deterministic distribution for testing internal of the skiplist
"""
return (n for _ in cycle([1]))
## Instruction:
Use itertools.repeat over slower alternatives.
## Code After:
from itertools import dropwhile, count, repeat
import random
def geometric(p):
return (next(dropwhile(lambda _: random.randint(1, int(1. / p)) == 1, count())) for _ in repeat(1))
# Simple deterministic distribution for testing internals of the skiplist.
uniform = repeat
| - from itertools import dropwhile, count, cycle
? ^^^^
+ from itertools import dropwhile, count, repeat
? ^ ++++
import random
def geometric(p):
- return (next(dropwhile(lambda _: random.randint(1, int(1. / p)) == 1, count())) for _ in cycle([1]))
? ^^^^ - -
+ return (next(dropwhile(lambda _: random.randint(1, int(1. / p)) == 1, count())) for _ in repeat(1))
? ^ ++++
- def uniform(n):
- """
- Simple deterministic distribution for testing internal of the skiplist
? ^^^
+ # Simple deterministic distribution for testing internals of the skiplist.
? ^ + ++
+ uniform = repeat
- """
- return (n for _ in cycle([1])) |
71646a47c1d9e47c4920fefe754b648c270eace4 | tests/test_cli.py | tests/test_cli.py | import os
import shutil
from click.testing import CliRunner
from gypsy.scripts.cli import cli
from conftest import DATA_DIR
def remove_path_if_exists(*paths):
for path in paths:
try:
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
except OSError:
pass
def test_prep():
input_data_path = os.path.join(DATA_DIR, 'raw_standtable.csv')
expected_output_path = os.path.splitext(input_data_path)[0] + '_prepped.csv'
remove_path_if_exists(expected_output_path)
runner = CliRunner()
result = runner.invoke(cli, ['prep', input_data_path])
assert result.exit_code == 0
assert result.output == ""
assert os.path.exists(expected_output_path)
def test_simulate():
data_path = os.path.join(DATA_DIR, 'raw_standtable_prepped.csv')
expected_output_path = os.path.join(os.getcwd(), 'gypsy-output')
remove_path_if_exists(expected_output_path)
runner = CliRunner()
result = runner.invoke(cli, ['simulate', data_path])
assert result.exit_code == 0
assert result.output == ""
assert os.path.exists(expected_output_path)
| import os
import shutil
from click.testing import CliRunner
from gypsy.scripts.cli import cli
from conftest import DATA_DIR
def remove_path_if_exists(*paths): #pylint: disable=missing-docstring
for path in paths:
try:
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
except OSError:
pass
def test_prep():
input_data_path = os.path.join(DATA_DIR, 'raw_standtable.csv')
expected_output_path = os.path.splitext(input_data_path)[0] + '_prepped.csv'
remove_path_if_exists(expected_output_path)
runner = CliRunner()
result = runner.invoke(cli, ['prep', input_data_path])
assert result.exit_code == 0
assert result.output == ""
assert os.path.exists(expected_output_path)
def test_simulate():
data_path = os.path.join(DATA_DIR, 'raw_standtable_prepped.csv')
expected_output_path = os.path.join(os.getcwd(), 'gypsy-output')
remove_path_if_exists(expected_output_path)
runner = CliRunner()
result = runner.invoke(cli, ['simulate', data_path])
assert result.exit_code == 0
assert result.output == ""
assert os.path.exists(expected_output_path)
def test_cli_config_file(): #pylint: disable=missing-docstring
runner = CliRunner()
result = runner.invoke(cli, ['--config-file', 'configfilepath.txt'])
assert result.exit_code == 0
| Add test that cli accepts config file | Add test that cli accepts config file
| Python | mit | tesera/pygypsy,tesera/pygypsy | import os
import shutil
from click.testing import CliRunner
from gypsy.scripts.cli import cli
from conftest import DATA_DIR
- def remove_path_if_exists(*paths):
+ def remove_path_if_exists(*paths): #pylint: disable=missing-docstring
for path in paths:
try:
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
except OSError:
pass
-
def test_prep():
input_data_path = os.path.join(DATA_DIR, 'raw_standtable.csv')
expected_output_path = os.path.splitext(input_data_path)[0] + '_prepped.csv'
remove_path_if_exists(expected_output_path)
runner = CliRunner()
result = runner.invoke(cli, ['prep', input_data_path])
assert result.exit_code == 0
assert result.output == ""
assert os.path.exists(expected_output_path)
-
def test_simulate():
data_path = os.path.join(DATA_DIR, 'raw_standtable_prepped.csv')
expected_output_path = os.path.join(os.getcwd(), 'gypsy-output')
remove_path_if_exists(expected_output_path)
runner = CliRunner()
result = runner.invoke(cli, ['simulate', data_path])
assert result.exit_code == 0
assert result.output == ""
assert os.path.exists(expected_output_path)
+ def test_cli_config_file(): #pylint: disable=missing-docstring
+ runner = CliRunner()
+ result = runner.invoke(cli, ['--config-file', 'configfilepath.txt'])
+ assert result.exit_code == 0
+ | Add test that cli accepts config file | ## Code Before:
import os
import shutil
from click.testing import CliRunner
from gypsy.scripts.cli import cli
from conftest import DATA_DIR
def remove_path_if_exists(*paths):
for path in paths:
try:
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
except OSError:
pass
def test_prep():
input_data_path = os.path.join(DATA_DIR, 'raw_standtable.csv')
expected_output_path = os.path.splitext(input_data_path)[0] + '_prepped.csv'
remove_path_if_exists(expected_output_path)
runner = CliRunner()
result = runner.invoke(cli, ['prep', input_data_path])
assert result.exit_code == 0
assert result.output == ""
assert os.path.exists(expected_output_path)
def test_simulate():
data_path = os.path.join(DATA_DIR, 'raw_standtable_prepped.csv')
expected_output_path = os.path.join(os.getcwd(), 'gypsy-output')
remove_path_if_exists(expected_output_path)
runner = CliRunner()
result = runner.invoke(cli, ['simulate', data_path])
assert result.exit_code == 0
assert result.output == ""
assert os.path.exists(expected_output_path)
## Instruction:
Add test that cli accepts config file
## Code After:
import os
import shutil
from click.testing import CliRunner
from gypsy.scripts.cli import cli
from conftest import DATA_DIR
def remove_path_if_exists(*paths): #pylint: disable=missing-docstring
for path in paths:
try:
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
except OSError:
pass
def test_prep():
input_data_path = os.path.join(DATA_DIR, 'raw_standtable.csv')
expected_output_path = os.path.splitext(input_data_path)[0] + '_prepped.csv'
remove_path_if_exists(expected_output_path)
runner = CliRunner()
result = runner.invoke(cli, ['prep', input_data_path])
assert result.exit_code == 0
assert result.output == ""
assert os.path.exists(expected_output_path)
def test_simulate():
data_path = os.path.join(DATA_DIR, 'raw_standtable_prepped.csv')
expected_output_path = os.path.join(os.getcwd(), 'gypsy-output')
remove_path_if_exists(expected_output_path)
runner = CliRunner()
result = runner.invoke(cli, ['simulate', data_path])
assert result.exit_code == 0
assert result.output == ""
assert os.path.exists(expected_output_path)
def test_cli_config_file(): #pylint: disable=missing-docstring
runner = CliRunner()
result = runner.invoke(cli, ['--config-file', 'configfilepath.txt'])
assert result.exit_code == 0
| import os
import shutil
from click.testing import CliRunner
from gypsy.scripts.cli import cli
from conftest import DATA_DIR
- def remove_path_if_exists(*paths):
+ def remove_path_if_exists(*paths): #pylint: disable=missing-docstring
for path in paths:
try:
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
except OSError:
pass
-
def test_prep():
input_data_path = os.path.join(DATA_DIR, 'raw_standtable.csv')
expected_output_path = os.path.splitext(input_data_path)[0] + '_prepped.csv'
remove_path_if_exists(expected_output_path)
runner = CliRunner()
result = runner.invoke(cli, ['prep', input_data_path])
assert result.exit_code == 0
assert result.output == ""
assert os.path.exists(expected_output_path)
-
def test_simulate():
data_path = os.path.join(DATA_DIR, 'raw_standtable_prepped.csv')
expected_output_path = os.path.join(os.getcwd(), 'gypsy-output')
remove_path_if_exists(expected_output_path)
runner = CliRunner()
result = runner.invoke(cli, ['simulate', data_path])
assert result.exit_code == 0
assert result.output == ""
assert os.path.exists(expected_output_path)
+
+ def test_cli_config_file(): #pylint: disable=missing-docstring
+ runner = CliRunner()
+ result = runner.invoke(cli, ['--config-file', 'configfilepath.txt'])
+ assert result.exit_code == 0 |
c4feb85d3f1f0151b7a64705a555d98221d6d857 | setup-utils/data_upgrade_from_0.4.py | setup-utils/data_upgrade_from_0.4.py | import argparse, shelve, sys
argumentParser = argparse.ArgumentParser(description="Upgrades txircd's data.db from the 0.4 format to the 0.5 format.")
argumentParser.add_argument("--datafile", dest="datafile", help="The location of the data file (default: data.db)", default="data.db")
args = argumentParser.parse_args()
storage = None
try:
storage = shelve.open(args.datafile)
except Exception as err:
print("Error opening data file: {}".format(err))
sys.exit(1)
# SECTION: Upgrade whowas time format
from datetime import datetime
whowasEntries = storage["whowas"]
for whowasEntryList in whowasEntries.itervalues():
for whowasEntry in whowasEntryList:
when = whowasEntry["when"]
whowasEntry["when"] = datetime.utcfromtimestamp(when)
# SHUTDOWN: Close data.db
storage.close() | import argparse, shelve, sys
argumentParser = argparse.ArgumentParser(description="Upgrades txircd's data.db from the 0.4 format to the 0.5 format.")
argumentParser.add_argument("--datafile", dest="datafile", help="The location of the data file (default: data.db)", default="data.db")
args = argumentParser.parse_args()
storage = None
try:
storage = shelve.open(args.datafile)
except Exception as err:
print("Error opening data file: {}".format(err))
sys.exit(1)
# SECTION: Upgrade whowas time format and add real host and IP keys
from datetime import datetime
whowasEntries = storage["whowas"]
for whowasEntryList in whowasEntries.itervalues():
for whowasEntry in whowasEntryList:
when = whowasEntry["when"]
whowasEntry["when"] = datetime.utcfromtimestamp(when)
whowasEntry["realhost"] = whowasEntry["host"]
whowasEntry["ip"] = "0.0.0.0"
# SHUTDOWN: Close data.db
storage.close() | Add new WHOWAS keys when upgrading the data to 0.5 | Add new WHOWAS keys when upgrading the data to 0.5
| Python | bsd-3-clause | Heufneutje/txircd | import argparse, shelve, sys
argumentParser = argparse.ArgumentParser(description="Upgrades txircd's data.db from the 0.4 format to the 0.5 format.")
argumentParser.add_argument("--datafile", dest="datafile", help="The location of the data file (default: data.db)", default="data.db")
args = argumentParser.parse_args()
storage = None
try:
storage = shelve.open(args.datafile)
except Exception as err:
print("Error opening data file: {}".format(err))
sys.exit(1)
- # SECTION: Upgrade whowas time format
+ # SECTION: Upgrade whowas time format and add real host and IP keys
from datetime import datetime
whowasEntries = storage["whowas"]
for whowasEntryList in whowasEntries.itervalues():
for whowasEntry in whowasEntryList:
when = whowasEntry["when"]
whowasEntry["when"] = datetime.utcfromtimestamp(when)
+ whowasEntry["realhost"] = whowasEntry["host"]
+ whowasEntry["ip"] = "0.0.0.0"
# SHUTDOWN: Close data.db
storage.close() | Add new WHOWAS keys when upgrading the data to 0.5 | ## Code Before:
import argparse, shelve, sys
argumentParser = argparse.ArgumentParser(description="Upgrades txircd's data.db from the 0.4 format to the 0.5 format.")
argumentParser.add_argument("--datafile", dest="datafile", help="The location of the data file (default: data.db)", default="data.db")
args = argumentParser.parse_args()
storage = None
try:
storage = shelve.open(args.datafile)
except Exception as err:
print("Error opening data file: {}".format(err))
sys.exit(1)
# SECTION: Upgrade whowas time format
from datetime import datetime
whowasEntries = storage["whowas"]
for whowasEntryList in whowasEntries.itervalues():
for whowasEntry in whowasEntryList:
when = whowasEntry["when"]
whowasEntry["when"] = datetime.utcfromtimestamp(when)
# SHUTDOWN: Close data.db
storage.close()
## Instruction:
Add new WHOWAS keys when upgrading the data to 0.5
## Code After:
import argparse, shelve, sys
argumentParser = argparse.ArgumentParser(description="Upgrades txircd's data.db from the 0.4 format to the 0.5 format.")
argumentParser.add_argument("--datafile", dest="datafile", help="The location of the data file (default: data.db)", default="data.db")
args = argumentParser.parse_args()
storage = None
try:
storage = shelve.open(args.datafile)
except Exception as err:
print("Error opening data file: {}".format(err))
sys.exit(1)
# SECTION: Upgrade whowas time format and add real host and IP keys
from datetime import datetime
whowasEntries = storage["whowas"]
for whowasEntryList in whowasEntries.itervalues():
for whowasEntry in whowasEntryList:
when = whowasEntry["when"]
whowasEntry["when"] = datetime.utcfromtimestamp(when)
whowasEntry["realhost"] = whowasEntry["host"]
whowasEntry["ip"] = "0.0.0.0"
# SHUTDOWN: Close data.db
storage.close() | import argparse, shelve, sys
argumentParser = argparse.ArgumentParser(description="Upgrades txircd's data.db from the 0.4 format to the 0.5 format.")
argumentParser.add_argument("--datafile", dest="datafile", help="The location of the data file (default: data.db)", default="data.db")
args = argumentParser.parse_args()
storage = None
try:
storage = shelve.open(args.datafile)
except Exception as err:
print("Error opening data file: {}".format(err))
sys.exit(1)
- # SECTION: Upgrade whowas time format
+ # SECTION: Upgrade whowas time format and add real host and IP keys
from datetime import datetime
whowasEntries = storage["whowas"]
for whowasEntryList in whowasEntries.itervalues():
for whowasEntry in whowasEntryList:
when = whowasEntry["when"]
whowasEntry["when"] = datetime.utcfromtimestamp(when)
+ whowasEntry["realhost"] = whowasEntry["host"]
+ whowasEntry["ip"] = "0.0.0.0"
# SHUTDOWN: Close data.db
storage.close() |
f26a59aae33fd1afef919427e0c36e744cb904fc | test/test_normalizedString.py | test/test_normalizedString.py | from rdflib import *
import unittest
class test_normalisedString(unittest.TestCase):
def test1(self):
lit2 = Literal("\two\nw", datatype=XSD.normalizedString)
lit = Literal("\two\nw", datatype=XSD.string)
self.assertEqual(lit == lit2, False)
def test2(self):
lit = Literal("\tBeing a Doctor Is\n\ta Full-Time Job\r", datatype=XSD.normalizedString)
st = Literal(" Being a Doctor Is a Full-Time Job ", datatype=XSD.string)
self.assertFalse(Literal.eq(st,lit))
def test3(self):
lit=Literal("hey\nthere", datatype=XSD.normalizedString).n3()
print(lit)
self.assertTrue(lit=="\"hey there\"^^<http://www.w3.org/2001/XMLSchema#normalizedString>")
if __name__ == "__main__":
unittest.main() | from rdflib import Literal
from rdflib.namespace import XSD
import unittest
class test_normalisedString(unittest.TestCase):
def test1(self):
lit2 = Literal("\two\nw", datatype=XSD.normalizedString)
lit = Literal("\two\nw", datatype=XSD.string)
self.assertEqual(lit == lit2, False)
def test2(self):
lit = Literal("\tBeing a Doctor Is\n\ta Full-Time Job\r", datatype=XSD.normalizedString)
st = Literal(" Being a Doctor Is a Full-Time Job ", datatype=XSD.string)
self.assertFalse(Literal.eq(st,lit))
def test3(self):
lit = Literal("hey\nthere", datatype=XSD.normalizedString).n3()
self.assertTrue(lit=="\"hey there\"^^<http://www.w3.org/2001/XMLSchema#normalizedString>")
def test4(self):
lit = Literal("hey\nthere\ta tab\rcarriage return", datatype=XSD.normalizedString)
expected = Literal("""hey there a tab carriage return""", datatype=XSD.string)
self.assertEqual(str(lit), str(expected))
if __name__ == "__main__":
unittest.main()
| Add a new test to test all chars that are getting replaced | Add a new test to test all chars that are getting replaced
| Python | bsd-3-clause | RDFLib/rdflib,RDFLib/rdflib,RDFLib/rdflib,RDFLib/rdflib | - from rdflib import *
+ from rdflib import Literal
+ from rdflib.namespace import XSD
import unittest
+
class test_normalisedString(unittest.TestCase):
def test1(self):
lit2 = Literal("\two\nw", datatype=XSD.normalizedString)
lit = Literal("\two\nw", datatype=XSD.string)
self.assertEqual(lit == lit2, False)
def test2(self):
lit = Literal("\tBeing a Doctor Is\n\ta Full-Time Job\r", datatype=XSD.normalizedString)
st = Literal(" Being a Doctor Is a Full-Time Job ", datatype=XSD.string)
self.assertFalse(Literal.eq(st,lit))
def test3(self):
- lit=Literal("hey\nthere", datatype=XSD.normalizedString).n3()
+ lit = Literal("hey\nthere", datatype=XSD.normalizedString).n3()
- print(lit)
self.assertTrue(lit=="\"hey there\"^^<http://www.w3.org/2001/XMLSchema#normalizedString>")
+ def test4(self):
+ lit = Literal("hey\nthere\ta tab\rcarriage return", datatype=XSD.normalizedString)
+ expected = Literal("""hey there a tab carriage return""", datatype=XSD.string)
+ self.assertEqual(str(lit), str(expected))
if __name__ == "__main__":
unittest.main()
+ | Add a new test to test all chars that are getting replaced | ## Code Before:
from rdflib import *
import unittest
class test_normalisedString(unittest.TestCase):
def test1(self):
lit2 = Literal("\two\nw", datatype=XSD.normalizedString)
lit = Literal("\two\nw", datatype=XSD.string)
self.assertEqual(lit == lit2, False)
def test2(self):
lit = Literal("\tBeing a Doctor Is\n\ta Full-Time Job\r", datatype=XSD.normalizedString)
st = Literal(" Being a Doctor Is a Full-Time Job ", datatype=XSD.string)
self.assertFalse(Literal.eq(st,lit))
def test3(self):
lit=Literal("hey\nthere", datatype=XSD.normalizedString).n3()
print(lit)
self.assertTrue(lit=="\"hey there\"^^<http://www.w3.org/2001/XMLSchema#normalizedString>")
if __name__ == "__main__":
unittest.main()
## Instruction:
Add a new test to test all chars that are getting replaced
## Code After:
from rdflib import Literal
from rdflib.namespace import XSD
import unittest
class test_normalisedString(unittest.TestCase):
def test1(self):
lit2 = Literal("\two\nw", datatype=XSD.normalizedString)
lit = Literal("\two\nw", datatype=XSD.string)
self.assertEqual(lit == lit2, False)
def test2(self):
lit = Literal("\tBeing a Doctor Is\n\ta Full-Time Job\r", datatype=XSD.normalizedString)
st = Literal(" Being a Doctor Is a Full-Time Job ", datatype=XSD.string)
self.assertFalse(Literal.eq(st,lit))
def test3(self):
lit = Literal("hey\nthere", datatype=XSD.normalizedString).n3()
self.assertTrue(lit=="\"hey there\"^^<http://www.w3.org/2001/XMLSchema#normalizedString>")
def test4(self):
lit = Literal("hey\nthere\ta tab\rcarriage return", datatype=XSD.normalizedString)
expected = Literal("""hey there a tab carriage return""", datatype=XSD.string)
self.assertEqual(str(lit), str(expected))
if __name__ == "__main__":
unittest.main()
| - from rdflib import *
? ^
+ from rdflib import Literal
? ^^^^^^^
+ from rdflib.namespace import XSD
import unittest
+
class test_normalisedString(unittest.TestCase):
def test1(self):
lit2 = Literal("\two\nw", datatype=XSD.normalizedString)
lit = Literal("\two\nw", datatype=XSD.string)
self.assertEqual(lit == lit2, False)
def test2(self):
lit = Literal("\tBeing a Doctor Is\n\ta Full-Time Job\r", datatype=XSD.normalizedString)
st = Literal(" Being a Doctor Is a Full-Time Job ", datatype=XSD.string)
self.assertFalse(Literal.eq(st,lit))
def test3(self):
- lit=Literal("hey\nthere", datatype=XSD.normalizedString).n3()
+ lit = Literal("hey\nthere", datatype=XSD.normalizedString).n3()
? + +
- print(lit)
self.assertTrue(lit=="\"hey there\"^^<http://www.w3.org/2001/XMLSchema#normalizedString>")
+ def test4(self):
+ lit = Literal("hey\nthere\ta tab\rcarriage return", datatype=XSD.normalizedString)
+ expected = Literal("""hey there a tab carriage return""", datatype=XSD.string)
+ self.assertEqual(str(lit), str(expected))
if __name__ == "__main__":
unittest.main() |
a89b6ec1bda46c63c0ff0e0a8bb44eb3eda41c1b | repo_health/gh_issues/serializers/GhIssueStatsSerializer.py | repo_health/gh_issues/serializers/GhIssueStatsSerializer.py |
from rest_framework import serializers as s
from ..models import GhIssueEvent
from repo_health.index.mixins import CountForPastYearMixin
class GhIssueStatsSerializer(s.Serializer, CountForPastYearMixin):
_label_names = None
issues_count = s.SerializerMethodField()
issues_closed_last_year = s.SerializerMethodField()
issues_opened_last_year = s.SerializerMethodField()
merged_count = s.SerializerMethodField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
repo = args[0]
self._label_names = repo.labels.values_list('name', flat=True)
def get_issues_count(self, repo):
return repo.issues_count
def get_issues_closed_last_year(self, repo):
return self.get_count_list_for_year(repo.issues.filter(events__action=GhIssueEvent.CLOSED_ACTION).distinct())
def get_issues_opened_last_year(self, repo):
return self.get_count_list_for_year(repo.issues)
|
from rest_framework import serializers as s
from ..models import GhIssueEvent
from repo_health.index.mixins import CountForPastYearMixin
class GhIssueStatsSerializer(s.Serializer, CountForPastYearMixin):
_label_names = None
issues_count = s.SerializerMethodField()
issues_closed_last_year = s.SerializerMethodField()
issues_opened_last_year = s.SerializerMethodField()
merged_count = s.SerializerMethodField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
repo = args[0]
self._label_names = repo.labels.values_list('name', flat=True)
def get_issues_count(self, repo):
return repo.issues_count
def get_issues_closed_last_year(self, repo):
return self.get_count_list_for_year(repo.issues.filter(events__action=GhIssueEvent.CLOSED_ACTION).distinct())
def get_issues_opened_last_year(self, repo):
return self.get_count_list_for_year(repo.issues)
def get_merged_count(self, repo):
return repo.issues.filter(events__action=GhIssueEvent.MERGED_ACTION).count()
| Add get merged count method. | Add get merged count method.
| Python | mit | jakeharding/repo-health,jakeharding/repo-health,jakeharding/repo-health,jakeharding/repo-health |
from rest_framework import serializers as s
from ..models import GhIssueEvent
from repo_health.index.mixins import CountForPastYearMixin
class GhIssueStatsSerializer(s.Serializer, CountForPastYearMixin):
_label_names = None
issues_count = s.SerializerMethodField()
issues_closed_last_year = s.SerializerMethodField()
issues_opened_last_year = s.SerializerMethodField()
merged_count = s.SerializerMethodField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
repo = args[0]
self._label_names = repo.labels.values_list('name', flat=True)
def get_issues_count(self, repo):
return repo.issues_count
def get_issues_closed_last_year(self, repo):
return self.get_count_list_for_year(repo.issues.filter(events__action=GhIssueEvent.CLOSED_ACTION).distinct())
def get_issues_opened_last_year(self, repo):
return self.get_count_list_for_year(repo.issues)
+ def get_merged_count(self, repo):
+ return repo.issues.filter(events__action=GhIssueEvent.MERGED_ACTION).count()
+ | Add get merged count method. | ## Code Before:
from rest_framework import serializers as s
from ..models import GhIssueEvent
from repo_health.index.mixins import CountForPastYearMixin
class GhIssueStatsSerializer(s.Serializer, CountForPastYearMixin):
_label_names = None
issues_count = s.SerializerMethodField()
issues_closed_last_year = s.SerializerMethodField()
issues_opened_last_year = s.SerializerMethodField()
merged_count = s.SerializerMethodField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
repo = args[0]
self._label_names = repo.labels.values_list('name', flat=True)
def get_issues_count(self, repo):
return repo.issues_count
def get_issues_closed_last_year(self, repo):
return self.get_count_list_for_year(repo.issues.filter(events__action=GhIssueEvent.CLOSED_ACTION).distinct())
def get_issues_opened_last_year(self, repo):
return self.get_count_list_for_year(repo.issues)
## Instruction:
Add get merged count method.
## Code After:
from rest_framework import serializers as s
from ..models import GhIssueEvent
from repo_health.index.mixins import CountForPastYearMixin
class GhIssueStatsSerializer(s.Serializer, CountForPastYearMixin):
_label_names = None
issues_count = s.SerializerMethodField()
issues_closed_last_year = s.SerializerMethodField()
issues_opened_last_year = s.SerializerMethodField()
merged_count = s.SerializerMethodField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
repo = args[0]
self._label_names = repo.labels.values_list('name', flat=True)
def get_issues_count(self, repo):
return repo.issues_count
def get_issues_closed_last_year(self, repo):
return self.get_count_list_for_year(repo.issues.filter(events__action=GhIssueEvent.CLOSED_ACTION).distinct())
def get_issues_opened_last_year(self, repo):
return self.get_count_list_for_year(repo.issues)
def get_merged_count(self, repo):
return repo.issues.filter(events__action=GhIssueEvent.MERGED_ACTION).count()
|
from rest_framework import serializers as s
from ..models import GhIssueEvent
from repo_health.index.mixins import CountForPastYearMixin
class GhIssueStatsSerializer(s.Serializer, CountForPastYearMixin):
_label_names = None
issues_count = s.SerializerMethodField()
issues_closed_last_year = s.SerializerMethodField()
issues_opened_last_year = s.SerializerMethodField()
merged_count = s.SerializerMethodField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
repo = args[0]
self._label_names = repo.labels.values_list('name', flat=True)
def get_issues_count(self, repo):
return repo.issues_count
def get_issues_closed_last_year(self, repo):
return self.get_count_list_for_year(repo.issues.filter(events__action=GhIssueEvent.CLOSED_ACTION).distinct())
def get_issues_opened_last_year(self, repo):
return self.get_count_list_for_year(repo.issues)
+
+ def get_merged_count(self, repo):
+ return repo.issues.filter(events__action=GhIssueEvent.MERGED_ACTION).count() |
6034265dfdfb2a7e1e4881076cc0f011ff0e639d | netbox/extras/migrations/0022_custom_links.py | netbox/extras/migrations/0022_custom_links.py |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('extras', '0021_add_color_comments_changelog_to_tag'),
]
operations = [
migrations.CreateModel(
name='CustomLink',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False)),
('name', models.CharField(max_length=100, unique=True)),
('text', models.CharField(max_length=200)),
('url', models.CharField(max_length=200)),
('weight', models.PositiveSmallIntegerField(default=100)),
('group_name', models.CharField(blank=True, max_length=50)),
('button_class', models.CharField(default='default', max_length=30)),
('new_window', models.BooleanField()),
('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
],
options={
'ordering': ['group_name', 'weight', 'name'],
},
),
]
|
from django.db import migrations, models
import django.db.models.deletion
import extras.models
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('extras', '0021_add_color_comments_changelog_to_tag'),
]
operations = [
migrations.CreateModel(
name='CustomLink',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False)),
('name', models.CharField(max_length=100, unique=True)),
('text', models.CharField(max_length=200)),
('url', models.CharField(max_length=200)),
('weight', models.PositiveSmallIntegerField(default=100)),
('group_name', models.CharField(blank=True, max_length=50)),
('button_class', models.CharField(default='default', max_length=30)),
('new_window', models.BooleanField()),
('content_type', models.ForeignKey(limit_choices_to=extras.models.get_custom_link_models, on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
],
options={
'ordering': ['group_name', 'weight', 'name'],
},
),
]
| Add limit_choices_to to CustomLink.content_type field | Add limit_choices_to to CustomLink.content_type field
| Python | apache-2.0 | lampwins/netbox,lampwins/netbox,digitalocean/netbox,digitalocean/netbox,digitalocean/netbox,lampwins/netbox,lampwins/netbox,digitalocean/netbox |
from django.db import migrations, models
import django.db.models.deletion
+ import extras.models
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('extras', '0021_add_color_comments_changelog_to_tag'),
]
operations = [
migrations.CreateModel(
name='CustomLink',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False)),
('name', models.CharField(max_length=100, unique=True)),
('text', models.CharField(max_length=200)),
('url', models.CharField(max_length=200)),
('weight', models.PositiveSmallIntegerField(default=100)),
('group_name', models.CharField(blank=True, max_length=50)),
('button_class', models.CharField(default='default', max_length=30)),
('new_window', models.BooleanField()),
- ('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
+ ('content_type', models.ForeignKey(limit_choices_to=extras.models.get_custom_link_models, on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
],
options={
'ordering': ['group_name', 'weight', 'name'],
},
),
]
| Add limit_choices_to to CustomLink.content_type field | ## Code Before:
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('extras', '0021_add_color_comments_changelog_to_tag'),
]
operations = [
migrations.CreateModel(
name='CustomLink',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False)),
('name', models.CharField(max_length=100, unique=True)),
('text', models.CharField(max_length=200)),
('url', models.CharField(max_length=200)),
('weight', models.PositiveSmallIntegerField(default=100)),
('group_name', models.CharField(blank=True, max_length=50)),
('button_class', models.CharField(default='default', max_length=30)),
('new_window', models.BooleanField()),
('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
],
options={
'ordering': ['group_name', 'weight', 'name'],
},
),
]
## Instruction:
Add limit_choices_to to CustomLink.content_type field
## Code After:
from django.db import migrations, models
import django.db.models.deletion
import extras.models
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('extras', '0021_add_color_comments_changelog_to_tag'),
]
operations = [
migrations.CreateModel(
name='CustomLink',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False)),
('name', models.CharField(max_length=100, unique=True)),
('text', models.CharField(max_length=200)),
('url', models.CharField(max_length=200)),
('weight', models.PositiveSmallIntegerField(default=100)),
('group_name', models.CharField(blank=True, max_length=50)),
('button_class', models.CharField(default='default', max_length=30)),
('new_window', models.BooleanField()),
('content_type', models.ForeignKey(limit_choices_to=extras.models.get_custom_link_models, on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
],
options={
'ordering': ['group_name', 'weight', 'name'],
},
),
]
|
from django.db import migrations, models
import django.db.models.deletion
+ import extras.models
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('extras', '0021_add_color_comments_changelog_to_tag'),
]
operations = [
migrations.CreateModel(
name='CustomLink',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False)),
('name', models.CharField(max_length=100, unique=True)),
('text', models.CharField(max_length=200)),
('url', models.CharField(max_length=200)),
('weight', models.PositiveSmallIntegerField(default=100)),
('group_name', models.CharField(blank=True, max_length=50)),
('button_class', models.CharField(default='default', max_length=30)),
('new_window', models.BooleanField()),
- ('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
+ ('content_type', models.ForeignKey(limit_choices_to=extras.models.get_custom_link_models, on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
? +++++++++++++++++++++++++++++++++++++++++++++++++++++++
],
options={
'ordering': ['group_name', 'weight', 'name'],
},
),
] |
0e98542f2b703de66dda71fb1b5efb7ae6d5b93d | setup.py | setup.py |
from distutils.core import setup
from vaspy import __version__ as version
maintainer = 'Shao-Zheng-Jiang'
maintainer_email = 'shaozhengjiang@gmail.com'
author = maintainer
author_email = maintainer_email
description = __doc__
requires = [
'numpy',
'matplotlib'
]
license = 'LICENSE'
long_description = file('README.md').read()
name = 'python-vaspy'
packages = [
'vaspy',
'scripts',
'unittest',
]
data_files = []
platforms = ['linux']
url = 'https://github.com/PytLab/VASPy'
download_url = ''
setup(
author=author,
author_email=author_email,
description=description,
license=license,
long_description=long_description,
maintainer=maintainer,
name=name,
packages=packages,
data_files=data_files,
platforms=platforms,
url=url,
download_url=download_url,
version=version,
)
|
from distutils.core import setup
from vaspy import __version__ as version
maintainer = 'Shao-Zheng-Jiang'
maintainer_email = 'shaozhengjiang@gmail.com'
author = maintainer
author_email = maintainer_email
description = __doc__
requires = [
'numpy',
'matplotlib'
]
license = 'LICENSE'
with open("README.md") as f:
long_descriptio = f.read()
name = 'python-vaspy'
packages = [
'vaspy',
'scripts',
'unittest',
]
data_files = []
platforms = ['linux']
url = 'https://github.com/PytLab/VASPy'
download_url = ''
setup(
author=author,
author_email=author_email,
description=description,
license=license,
long_description=long_description,
maintainer=maintainer,
name=name,
packages=packages,
data_files=data_files,
platforms=platforms,
url=url,
download_url=download_url,
version=version,
)
| Fix bug in getting long_description. | Fix bug in getting long_description.
| Python | mit | PytLab/VASPy,PytLab/VASPy |
from distutils.core import setup
from vaspy import __version__ as version
maintainer = 'Shao-Zheng-Jiang'
maintainer_email = 'shaozhengjiang@gmail.com'
author = maintainer
author_email = maintainer_email
description = __doc__
requires = [
'numpy',
'matplotlib'
]
license = 'LICENSE'
- long_description = file('README.md').read()
+ with open("README.md") as f:
+ long_descriptio = f.read()
name = 'python-vaspy'
packages = [
'vaspy',
'scripts',
'unittest',
]
data_files = []
platforms = ['linux']
url = 'https://github.com/PytLab/VASPy'
download_url = ''
setup(
author=author,
author_email=author_email,
description=description,
license=license,
long_description=long_description,
maintainer=maintainer,
name=name,
packages=packages,
data_files=data_files,
platforms=platforms,
url=url,
download_url=download_url,
version=version,
)
| Fix bug in getting long_description. | ## Code Before:
from distutils.core import setup
from vaspy import __version__ as version
maintainer = 'Shao-Zheng-Jiang'
maintainer_email = 'shaozhengjiang@gmail.com'
author = maintainer
author_email = maintainer_email
description = __doc__
requires = [
'numpy',
'matplotlib'
]
license = 'LICENSE'
long_description = file('README.md').read()
name = 'python-vaspy'
packages = [
'vaspy',
'scripts',
'unittest',
]
data_files = []
platforms = ['linux']
url = 'https://github.com/PytLab/VASPy'
download_url = ''
setup(
author=author,
author_email=author_email,
description=description,
license=license,
long_description=long_description,
maintainer=maintainer,
name=name,
packages=packages,
data_files=data_files,
platforms=platforms,
url=url,
download_url=download_url,
version=version,
)
## Instruction:
Fix bug in getting long_description.
## Code After:
from distutils.core import setup
from vaspy import __version__ as version
maintainer = 'Shao-Zheng-Jiang'
maintainer_email = 'shaozhengjiang@gmail.com'
author = maintainer
author_email = maintainer_email
description = __doc__
requires = [
'numpy',
'matplotlib'
]
license = 'LICENSE'
with open("README.md") as f:
long_descriptio = f.read()
name = 'python-vaspy'
packages = [
'vaspy',
'scripts',
'unittest',
]
data_files = []
platforms = ['linux']
url = 'https://github.com/PytLab/VASPy'
download_url = ''
setup(
author=author,
author_email=author_email,
description=description,
license=license,
long_description=long_description,
maintainer=maintainer,
name=name,
packages=packages,
data_files=data_files,
platforms=platforms,
url=url,
download_url=download_url,
version=version,
)
|
from distutils.core import setup
from vaspy import __version__ as version
maintainer = 'Shao-Zheng-Jiang'
maintainer_email = 'shaozhengjiang@gmail.com'
author = maintainer
author_email = maintainer_email
description = __doc__
requires = [
'numpy',
'matplotlib'
]
license = 'LICENSE'
- long_description = file('README.md').read()
+ with open("README.md") as f:
+ long_descriptio = f.read()
name = 'python-vaspy'
packages = [
'vaspy',
'scripts',
'unittest',
]
data_files = []
platforms = ['linux']
url = 'https://github.com/PytLab/VASPy'
download_url = ''
setup(
author=author,
author_email=author_email,
description=description,
license=license,
long_description=long_description,
maintainer=maintainer,
name=name,
packages=packages,
data_files=data_files,
platforms=platforms,
url=url,
download_url=download_url,
version=version,
) |
d7534dc3536ebe035abf063d83aa8d471cdadb16 | python/pyqt_version.py | python/pyqt_version.py | import PySide2.QtCore
# Prints PySide2 version
# e.g. 5.11.1a1
print(PySide2.__version__)
# Gets a tuple with each version component
# e.g. (5, 11, 1, 'a', 1)
print(PySide2.__version_info__)
# Prints the Qt version used to compile PySide2
# e.g. "5.11.2"
print(PySide2.QtCore.__version__)
# Gets a tuple with each version components of Qt used to compile PySide2
# e.g. (5, 11, 2)
print(PySide2.QtCore.__version_info__)
print(PySide2.QtCore.qVersion())
|
'''
PySide2
'''
import sys
try:
import PySide2.QtCore
except ImportError:
print('cannot load module: PySide2.QtCore')
sys.exit(1)
# Prints PySide2 version
# e.g. 5.11.1a1
print(PySide2.__version__)
# Gets a tuple with each version component
# e.g. (5, 11, 1, 'a', 1)
print(PySide2.__version_info__)
# Prints the Qt version used to compile PySide2
# e.g. "5.11.2"
print(PySide2.QtCore.__version__)
# Gets a tuple with each version components of Qt used to compile PySide2
# e.g. (5, 11, 2)
print(PySide2.QtCore.__version_info__)
print(PySide2.QtCore.qVersion())
| ADD try-except to handle import error | ADD try-except to handle import error
| Python | mit | ericosur/myqt,ericosur/myqt,ericosur/myqt,ericosur/myqt,ericosur/myqt,ericosur/myqt | +
+ '''
+ PySide2
+ '''
+
+ import sys
+ try:
- import PySide2.QtCore
+ import PySide2.QtCore
+ except ImportError:
+ print('cannot load module: PySide2.QtCore')
+ sys.exit(1)
# Prints PySide2 version
# e.g. 5.11.1a1
print(PySide2.__version__)
# Gets a tuple with each version component
# e.g. (5, 11, 1, 'a', 1)
print(PySide2.__version_info__)
# Prints the Qt version used to compile PySide2
# e.g. "5.11.2"
print(PySide2.QtCore.__version__)
# Gets a tuple with each version components of Qt used to compile PySide2
# e.g. (5, 11, 2)
print(PySide2.QtCore.__version_info__)
print(PySide2.QtCore.qVersion())
| ADD try-except to handle import error | ## Code Before:
import PySide2.QtCore
# Prints PySide2 version
# e.g. 5.11.1a1
print(PySide2.__version__)
# Gets a tuple with each version component
# e.g. (5, 11, 1, 'a', 1)
print(PySide2.__version_info__)
# Prints the Qt version used to compile PySide2
# e.g. "5.11.2"
print(PySide2.QtCore.__version__)
# Gets a tuple with each version components of Qt used to compile PySide2
# e.g. (5, 11, 2)
print(PySide2.QtCore.__version_info__)
print(PySide2.QtCore.qVersion())
## Instruction:
ADD try-except to handle import error
## Code After:
'''
PySide2
'''
import sys
try:
import PySide2.QtCore
except ImportError:
print('cannot load module: PySide2.QtCore')
sys.exit(1)
# Prints PySide2 version
# e.g. 5.11.1a1
print(PySide2.__version__)
# Gets a tuple with each version component
# e.g. (5, 11, 1, 'a', 1)
print(PySide2.__version_info__)
# Prints the Qt version used to compile PySide2
# e.g. "5.11.2"
print(PySide2.QtCore.__version__)
# Gets a tuple with each version components of Qt used to compile PySide2
# e.g. (5, 11, 2)
print(PySide2.QtCore.__version_info__)
print(PySide2.QtCore.qVersion())
| +
+ '''
+ PySide2
+ '''
+
+ import sys
+ try:
- import PySide2.QtCore
+ import PySide2.QtCore
? ++++
+ except ImportError:
+ print('cannot load module: PySide2.QtCore')
+ sys.exit(1)
# Prints PySide2 version
# e.g. 5.11.1a1
print(PySide2.__version__)
# Gets a tuple with each version component
# e.g. (5, 11, 1, 'a', 1)
print(PySide2.__version_info__)
# Prints the Qt version used to compile PySide2
# e.g. "5.11.2"
print(PySide2.QtCore.__version__)
# Gets a tuple with each version components of Qt used to compile PySide2
# e.g. (5, 11, 2)
print(PySide2.QtCore.__version_info__)
print(PySide2.QtCore.qVersion()) |
d9cf7b736416f942a7bb9c164d99fdb3b4de1b08 | leapday/templatetags/leapday_extras.py | leapday/templatetags/leapday_extras.py | '''
James D. Zoll
4/15/2013
Purpose: Defines template tags for the Leapday Recipedia application.
License: This is a public work.
'''
from django import template
register = template.Library()
@register.filter()
def good_css_name(value):
'''
Returns the lower-case hyphen-replaced display name,
which used as the css class for the good.
Keyword Arguments:
value -> Good. The good to get the css class for.
'''
return value.display_name.lower().replace(' ','-')
@register.filter()
def base_goods_ordered_set(value):
'''
Returns a set of the base goods required for an object's creation,
ordered by the desired order. In this case, that order is value low
to high, with the "Other" good on the end instead of the front.
Additionally, this attempts first to load goods from the
shim_base_ingredients attribute, which is present in some situations
where the attribute has been preloaded to prevent excessive DB IO.
Keyword Arguments:
value -> Good. The good for which to return the list of ingredients.
'''
try:
base_goods = value.shim_base_ingredients
except:
base_goods = value.base_ingredients.all()
ret = sorted(base_goods, key=lambda x: x.ingredient.value)
ret = ret[1:] + [ret[0]]
return ret
| '''
James D. Zoll
4/15/2013
Purpose: Defines template tags for the Leapday Recipedia application.
License: This is a public work.
'''
from django import template
register = template.Library()
@register.filter()
def good_css_name(value):
'''
Returns the lower-case hyphen-replaced display name,
which used as the css class for the good.
Keyword Arguments:
value -> Good. The good to get the css class for.
'''
return value.display_name.lower().replace(' ','-')
@register.filter()
def base_goods_ordered_set(value):
'''
Returns a set of the base goods required for an object's creation,
ordered by the desired order. In this case, that order is value low
to high, with the "Other" good on the end instead of the front.
Additionally, this attempts first to load goods from the
shim_base_ingredients attribute, which is present in some situations
where the attribute has been preloaded to prevent excessive DB IO.
Keyword Arguments:
value -> Good. The good for which to return the list of ingredients.
'''
try:
base_goods = value.shim_base_ingredients
except:
base_goods = value.base_ingredients.all()
ret = sorted(base_goods, key=lambda x: x.ingredient.value)
return ret
| Fix reordering due to removal of Other | Fix reordering due to removal of Other
| Python | mit | Zerack/zoll.me,Zerack/zoll.me | '''
James D. Zoll
4/15/2013
Purpose: Defines template tags for the Leapday Recipedia application.
License: This is a public work.
'''
from django import template
register = template.Library()
@register.filter()
def good_css_name(value):
'''
Returns the lower-case hyphen-replaced display name,
which used as the css class for the good.
Keyword Arguments:
value -> Good. The good to get the css class for.
'''
return value.display_name.lower().replace(' ','-')
@register.filter()
def base_goods_ordered_set(value):
'''
Returns a set of the base goods required for an object's creation,
ordered by the desired order. In this case, that order is value low
to high, with the "Other" good on the end instead of the front.
Additionally, this attempts first to load goods from the
shim_base_ingredients attribute, which is present in some situations
where the attribute has been preloaded to prevent excessive DB IO.
Keyword Arguments:
value -> Good. The good for which to return the list of ingredients.
'''
try:
base_goods = value.shim_base_ingredients
except:
base_goods = value.base_ingredients.all()
ret = sorted(base_goods, key=lambda x: x.ingredient.value)
- ret = ret[1:] + [ret[0]]
return ret
| Fix reordering due to removal of Other | ## Code Before:
'''
James D. Zoll
4/15/2013
Purpose: Defines template tags for the Leapday Recipedia application.
License: This is a public work.
'''
from django import template
register = template.Library()
@register.filter()
def good_css_name(value):
'''
Returns the lower-case hyphen-replaced display name,
which used as the css class for the good.
Keyword Arguments:
value -> Good. The good to get the css class for.
'''
return value.display_name.lower().replace(' ','-')
@register.filter()
def base_goods_ordered_set(value):
'''
Returns a set of the base goods required for an object's creation,
ordered by the desired order. In this case, that order is value low
to high, with the "Other" good on the end instead of the front.
Additionally, this attempts first to load goods from the
shim_base_ingredients attribute, which is present in some situations
where the attribute has been preloaded to prevent excessive DB IO.
Keyword Arguments:
value -> Good. The good for which to return the list of ingredients.
'''
try:
base_goods = value.shim_base_ingredients
except:
base_goods = value.base_ingredients.all()
ret = sorted(base_goods, key=lambda x: x.ingredient.value)
ret = ret[1:] + [ret[0]]
return ret
## Instruction:
Fix reordering due to removal of Other
## Code After:
'''
James D. Zoll
4/15/2013
Purpose: Defines template tags for the Leapday Recipedia application.
License: This is a public work.
'''
from django import template
register = template.Library()
@register.filter()
def good_css_name(value):
'''
Returns the lower-case hyphen-replaced display name,
which used as the css class for the good.
Keyword Arguments:
value -> Good. The good to get the css class for.
'''
return value.display_name.lower().replace(' ','-')
@register.filter()
def base_goods_ordered_set(value):
'''
Returns a set of the base goods required for an object's creation,
ordered by the desired order. In this case, that order is value low
to high, with the "Other" good on the end instead of the front.
Additionally, this attempts first to load goods from the
shim_base_ingredients attribute, which is present in some situations
where the attribute has been preloaded to prevent excessive DB IO.
Keyword Arguments:
value -> Good. The good for which to return the list of ingredients.
'''
try:
base_goods = value.shim_base_ingredients
except:
base_goods = value.base_ingredients.all()
ret = sorted(base_goods, key=lambda x: x.ingredient.value)
return ret
| '''
James D. Zoll
4/15/2013
Purpose: Defines template tags for the Leapday Recipedia application.
License: This is a public work.
'''
from django import template
register = template.Library()
@register.filter()
def good_css_name(value):
'''
Returns the lower-case hyphen-replaced display name,
which used as the css class for the good.
Keyword Arguments:
value -> Good. The good to get the css class for.
'''
return value.display_name.lower().replace(' ','-')
@register.filter()
def base_goods_ordered_set(value):
'''
Returns a set of the base goods required for an object's creation,
ordered by the desired order. In this case, that order is value low
to high, with the "Other" good on the end instead of the front.
Additionally, this attempts first to load goods from the
shim_base_ingredients attribute, which is present in some situations
where the attribute has been preloaded to prevent excessive DB IO.
Keyword Arguments:
value -> Good. The good for which to return the list of ingredients.
'''
try:
base_goods = value.shim_base_ingredients
except:
base_goods = value.base_ingredients.all()
ret = sorted(base_goods, key=lambda x: x.ingredient.value)
- ret = ret[1:] + [ret[0]]
return ret |
da6e9416e12ce71cd3f23ded9bd75dccc62d26fe | fcn/config.py | fcn/config.py | import os.path as osp
def get_data_dir():
this_dir = osp.dirname(osp.abspath(__file__))
return osp.realpath(osp.join(this_dir, '../data'))
def get_logs_dir():
this_dir = osp.dirname(osp.abspath(__file__))
return osp.realpath(osp.join(this_dir, '../logs'))
| import os.path as osp
def get_data_dir():
this_dir = osp.dirname(osp.abspath(__file__))
return osp.realpath(osp.join(this_dir, '_data'))
| Move data directory in package | Move data directory in package
| Python | mit | wkentaro/fcn | import os.path as osp
def get_data_dir():
this_dir = osp.dirname(osp.abspath(__file__))
- return osp.realpath(osp.join(this_dir, '../data'))
+ return osp.realpath(osp.join(this_dir, '_data'))
-
- def get_logs_dir():
- this_dir = osp.dirname(osp.abspath(__file__))
- return osp.realpath(osp.join(this_dir, '../logs'))
- | Move data directory in package | ## Code Before:
import os.path as osp
def get_data_dir():
this_dir = osp.dirname(osp.abspath(__file__))
return osp.realpath(osp.join(this_dir, '../data'))
def get_logs_dir():
this_dir = osp.dirname(osp.abspath(__file__))
return osp.realpath(osp.join(this_dir, '../logs'))
## Instruction:
Move data directory in package
## Code After:
import os.path as osp
def get_data_dir():
this_dir = osp.dirname(osp.abspath(__file__))
return osp.realpath(osp.join(this_dir, '_data'))
| import os.path as osp
def get_data_dir():
this_dir = osp.dirname(osp.abspath(__file__))
- return osp.realpath(osp.join(this_dir, '../data'))
? ^^^
+ return osp.realpath(osp.join(this_dir, '_data'))
? ^
-
-
- def get_logs_dir():
- this_dir = osp.dirname(osp.abspath(__file__))
- return osp.realpath(osp.join(this_dir, '../logs')) |
4625a1ed4115b85ce7d96a0d0ba486e589e9fe6c | runtests.py | runtests.py | import sys
from optparse import OptionParser
from os.path import abspath, dirname
from django.test.simple import DjangoTestSuiteRunner
def runtests(*test_args, **kwargs):
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
test_runner = DjangoTestSuiteRunner(
verbosity=kwargs.get('verbosity', 1),
interactive=kwargs.get('interactive', False),
failfast=kwargs.get('failfast')
)
failures = test_runner.run_tests(test_args)
sys.exit(failures)
if __name__ == '__main__':
parser = OptionParser()
parser.add_option('--failfast', action='store_true', default=False, dest='failfast')
(options, args) = parser.parse_args()
runtests(failfast=options.failfast, *args) | import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
from django.test.utils import get_runner
from django.conf import settings
import django
if django.VERSION >= (1, 7):
django.setup()
def runtests():
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True)
failures = test_runner.run_tests(['tests'])
sys.exit(bool(failures))
if __name__ == '__main__':
runtests()
| Make test runner only run basis tests | Make test runner only run basis tests
and not dependecies tests
| Python | mit | frecar/django-basis | + import os
import sys
- from optparse import OptionParser
- from os.path import abspath, dirname
- from django.test.simple import DjangoTestSuiteRunner
+
+ os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
+
+ from django.test.utils import get_runner
+ from django.conf import settings
+ import django
+
+ if django.VERSION >= (1, 7):
+ django.setup()
+ def runtests():
+ TestRunner = get_runner(settings)
+ test_runner = TestRunner(verbosity=1, interactive=True)
- def runtests(*test_args, **kwargs):
- parent = dirname(abspath(__file__))
- sys.path.insert(0, parent)
- test_runner = DjangoTestSuiteRunner(
- verbosity=kwargs.get('verbosity', 1),
- interactive=kwargs.get('interactive', False),
- failfast=kwargs.get('failfast')
- )
- failures = test_runner.run_tests(test_args)
+ failures = test_runner.run_tests(['tests'])
- sys.exit(failures)
+ sys.exit(bool(failures))
+
if __name__ == '__main__':
+ runtests()
- parser = OptionParser()
- parser.add_option('--failfast', action='store_true', default=False, dest='failfast')
- (options, args) = parser.parse_args()
-
- runtests(failfast=options.failfast, *args) | Make test runner only run basis tests | ## Code Before:
import sys
from optparse import OptionParser
from os.path import abspath, dirname
from django.test.simple import DjangoTestSuiteRunner
def runtests(*test_args, **kwargs):
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
test_runner = DjangoTestSuiteRunner(
verbosity=kwargs.get('verbosity', 1),
interactive=kwargs.get('interactive', False),
failfast=kwargs.get('failfast')
)
failures = test_runner.run_tests(test_args)
sys.exit(failures)
if __name__ == '__main__':
parser = OptionParser()
parser.add_option('--failfast', action='store_true', default=False, dest='failfast')
(options, args) = parser.parse_args()
runtests(failfast=options.failfast, *args)
## Instruction:
Make test runner only run basis tests
## Code After:
import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
from django.test.utils import get_runner
from django.conf import settings
import django
if django.VERSION >= (1, 7):
django.setup()
def runtests():
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True)
failures = test_runner.run_tests(['tests'])
sys.exit(bool(failures))
if __name__ == '__main__':
runtests()
| + import os
import sys
- from optparse import OptionParser
- from os.path import abspath, dirname
- from django.test.simple import DjangoTestSuiteRunner
+
+ os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
+
+ from django.test.utils import get_runner
+ from django.conf import settings
+ import django
+
+ if django.VERSION >= (1, 7):
+ django.setup()
+ def runtests():
+ TestRunner = get_runner(settings)
+ test_runner = TestRunner(verbosity=1, interactive=True)
- def runtests(*test_args, **kwargs):
- parent = dirname(abspath(__file__))
- sys.path.insert(0, parent)
- test_runner = DjangoTestSuiteRunner(
- verbosity=kwargs.get('verbosity', 1),
- interactive=kwargs.get('interactive', False),
- failfast=kwargs.get('failfast')
- )
- failures = test_runner.run_tests(test_args)
? ----
+ failures = test_runner.run_tests(['tests'])
? ++ ++
- sys.exit(failures)
+ sys.exit(bool(failures))
? +++++ +
+
if __name__ == '__main__':
+ runtests()
- parser = OptionParser()
- parser.add_option('--failfast', action='store_true', default=False, dest='failfast')
-
- (options, args) = parser.parse_args()
-
- runtests(failfast=options.failfast, *args) |
62c24f6edaa91834d4a7b2a3f9b99b8b96322230 | nova/policies/hide_server_addresses.py | nova/policies/hide_server_addresses.py |
from oslo_policy import policy
BASE_POLICY_NAME = 'os_compute_api:os-hide-server-addresses'
hide_server_addresses_policies = [
policy.RuleDefault(
name=BASE_POLICY_NAME,
check_str='is_admin:False'),
]
def list_rules():
return hide_server_addresses_policies
|
from nova.policies import base
BASE_POLICY_NAME = 'os_compute_api:os-hide-server-addresses'
hide_server_addresses_policies = [
base.create_rule_default(
BASE_POLICY_NAME,
'is_admin:False',
"""Hide server's 'addresses' key in the server response.
This set the 'addresses' key in the server response to an empty dictionary
when the server is in a specific set of states as defined in
CONF.api.hide_server_address_states.
By default 'addresses' is hidden only when the server is in 'BUILDING'
state.""",
[
{
'method': 'GET',
'path': '/servers/{id}'
},
{
'method': 'GET',
'path': '/servers/detail'
}
]),
]
def list_rules():
return hide_server_addresses_policies
| Add policy description for 'os-hide-server-addresses' | Add policy description for 'os-hide-server-addresses'
This commit adds policy doc for 'os-hide-server-addresses' policies.
Partial implement blueprint policy-docs
Change-Id: I98edbd8579f052c74283bde2ec4f85d301a0807a
| Python | apache-2.0 | rahulunair/nova,gooddata/openstack-nova,mikalstill/nova,mahak/nova,Juniper/nova,mahak/nova,mikalstill/nova,Juniper/nova,rahulunair/nova,gooddata/openstack-nova,vmturbo/nova,openstack/nova,Juniper/nova,jianghuaw/nova,openstack/nova,gooddata/openstack-nova,klmitch/nova,gooddata/openstack-nova,jianghuaw/nova,klmitch/nova,klmitch/nova,mahak/nova,vmturbo/nova,klmitch/nova,jianghuaw/nova,phenoxim/nova,mikalstill/nova,vmturbo/nova,openstack/nova,vmturbo/nova,jianghuaw/nova,rahulunair/nova,phenoxim/nova,Juniper/nova |
+ from nova.policies import base
- from oslo_policy import policy
-
BASE_POLICY_NAME = 'os_compute_api:os-hide-server-addresses'
hide_server_addresses_policies = [
- policy.RuleDefault(
+ base.create_rule_default(
- name=BASE_POLICY_NAME,
+ BASE_POLICY_NAME,
- check_str='is_admin:False'),
+ 'is_admin:False',
+ """Hide server's 'addresses' key in the server response.
+
+ This set the 'addresses' key in the server response to an empty dictionary
+ when the server is in a specific set of states as defined in
+ CONF.api.hide_server_address_states.
+ By default 'addresses' is hidden only when the server is in 'BUILDING'
+ state.""",
+ [
+ {
+ 'method': 'GET',
+ 'path': '/servers/{id}'
+ },
+ {
+ 'method': 'GET',
+ 'path': '/servers/detail'
+ }
+ ]),
]
def list_rules():
return hide_server_addresses_policies
| Add policy description for 'os-hide-server-addresses' | ## Code Before:
from oslo_policy import policy
BASE_POLICY_NAME = 'os_compute_api:os-hide-server-addresses'
hide_server_addresses_policies = [
policy.RuleDefault(
name=BASE_POLICY_NAME,
check_str='is_admin:False'),
]
def list_rules():
return hide_server_addresses_policies
## Instruction:
Add policy description for 'os-hide-server-addresses'
## Code After:
from nova.policies import base
BASE_POLICY_NAME = 'os_compute_api:os-hide-server-addresses'
hide_server_addresses_policies = [
base.create_rule_default(
BASE_POLICY_NAME,
'is_admin:False',
"""Hide server's 'addresses' key in the server response.
This set the 'addresses' key in the server response to an empty dictionary
when the server is in a specific set of states as defined in
CONF.api.hide_server_address_states.
By default 'addresses' is hidden only when the server is in 'BUILDING'
state.""",
[
{
'method': 'GET',
'path': '/servers/{id}'
},
{
'method': 'GET',
'path': '/servers/detail'
}
]),
]
def list_rules():
return hide_server_addresses_policies
|
+ from nova.policies import base
- from oslo_policy import policy
-
BASE_POLICY_NAME = 'os_compute_api:os-hide-server-addresses'
hide_server_addresses_policies = [
- policy.RuleDefault(
+ base.create_rule_default(
- name=BASE_POLICY_NAME,
? -----
+ BASE_POLICY_NAME,
- check_str='is_admin:False'),
? ---------- -
+ 'is_admin:False',
+ """Hide server's 'addresses' key in the server response.
+
+ This set the 'addresses' key in the server response to an empty dictionary
+ when the server is in a specific set of states as defined in
+ CONF.api.hide_server_address_states.
+ By default 'addresses' is hidden only when the server is in 'BUILDING'
+ state.""",
+ [
+ {
+ 'method': 'GET',
+ 'path': '/servers/{id}'
+ },
+ {
+ 'method': 'GET',
+ 'path': '/servers/detail'
+ }
+ ]),
]
def list_rules():
return hide_server_addresses_policies |
b8c724cb141f6b0757d38b826b5cfd841284a37e | kuryr_libnetwork/server.py | kuryr_libnetwork/server.py |
import sys
from oslo_log import log
from six.moves.urllib import parse
from kuryr_libnetwork import app
from kuryr_libnetwork.common import config
from kuryr_libnetwork import controllers
def start():
config.init(sys.argv[1:])
controllers.neutron_client()
controllers.check_for_neutron_ext_support()
controllers.check_for_neutron_ext_tag()
log.setup(config.CONF, 'Kuryr')
kuryr_uri = parse.urlparse(config.CONF.kuryr_uri)
app.run(kuryr_uri.hostname, kuryr_uri.port)
if __name__ == '__main__':
start()
|
import sys
from oslo_log import log
from six.moves.urllib import parse
from kuryr_libnetwork import app
from kuryr_libnetwork.common import config
from kuryr_libnetwork import controllers
def start():
config.init(sys.argv[1:])
log.setup(config.CONF, 'kuryr')
controllers.neutron_client()
controllers.check_for_neutron_ext_support()
controllers.check_for_neutron_ext_tag()
kuryr_uri = parse.urlparse(config.CONF.kuryr_uri)
app.run(kuryr_uri.hostname, kuryr_uri.port)
if __name__ == '__main__':
start()
| Fix no log in /var/log/kuryr/kuryr.log | Fix no log in /var/log/kuryr/kuryr.log
code misuse "Kuryr" in log.setup, it should be "kuryr".
Change-Id: If36c9e03a01dae710ca12cf340abbb0c5647b47f
Closes-bug: #1617863
| Python | apache-2.0 | celebdor/kuryr-libnetwork,celebdor/kuryr-libnetwork,celebdor/kuryr-libnetwork |
import sys
from oslo_log import log
from six.moves.urllib import parse
from kuryr_libnetwork import app
from kuryr_libnetwork.common import config
from kuryr_libnetwork import controllers
def start():
config.init(sys.argv[1:])
+ log.setup(config.CONF, 'kuryr')
controllers.neutron_client()
controllers.check_for_neutron_ext_support()
controllers.check_for_neutron_ext_tag()
- log.setup(config.CONF, 'Kuryr')
kuryr_uri = parse.urlparse(config.CONF.kuryr_uri)
app.run(kuryr_uri.hostname, kuryr_uri.port)
if __name__ == '__main__':
start()
| Fix no log in /var/log/kuryr/kuryr.log | ## Code Before:
import sys
from oslo_log import log
from six.moves.urllib import parse
from kuryr_libnetwork import app
from kuryr_libnetwork.common import config
from kuryr_libnetwork import controllers
def start():
config.init(sys.argv[1:])
controllers.neutron_client()
controllers.check_for_neutron_ext_support()
controllers.check_for_neutron_ext_tag()
log.setup(config.CONF, 'Kuryr')
kuryr_uri = parse.urlparse(config.CONF.kuryr_uri)
app.run(kuryr_uri.hostname, kuryr_uri.port)
if __name__ == '__main__':
start()
## Instruction:
Fix no log in /var/log/kuryr/kuryr.log
## Code After:
import sys
from oslo_log import log
from six.moves.urllib import parse
from kuryr_libnetwork import app
from kuryr_libnetwork.common import config
from kuryr_libnetwork import controllers
def start():
config.init(sys.argv[1:])
log.setup(config.CONF, 'kuryr')
controllers.neutron_client()
controllers.check_for_neutron_ext_support()
controllers.check_for_neutron_ext_tag()
kuryr_uri = parse.urlparse(config.CONF.kuryr_uri)
app.run(kuryr_uri.hostname, kuryr_uri.port)
if __name__ == '__main__':
start()
|
import sys
from oslo_log import log
from six.moves.urllib import parse
from kuryr_libnetwork import app
from kuryr_libnetwork.common import config
from kuryr_libnetwork import controllers
def start():
config.init(sys.argv[1:])
+ log.setup(config.CONF, 'kuryr')
controllers.neutron_client()
controllers.check_for_neutron_ext_support()
controllers.check_for_neutron_ext_tag()
- log.setup(config.CONF, 'Kuryr')
kuryr_uri = parse.urlparse(config.CONF.kuryr_uri)
app.run(kuryr_uri.hostname, kuryr_uri.port)
if __name__ == '__main__':
start() |
caf245e14421472adb0668e57adf5a3e3ae68424 | scuba/utils.py | scuba/utils.py | try:
from shlex import quote as shell_quote
except ImportError:
from pipes import quote as shell_quote
def format_cmdline(args, maxwidth=80):
def lines():
line = ''
for a in (shell_quote(a) for a in args):
if len(line) + len(a) > maxwidth:
yield line
line = ''
line += ' ' + a
return ' \\\n'.join(lines())[1:]
| try:
from shlex import quote as shell_quote
except ImportError:
from pipes import quote as shell_quote
def format_cmdline(args, maxwidth=80):
'''Format args into a shell-quoted command line.
The result will be wrapped to maxwidth characters where possible,
not breaking a single long argument.
'''
# Leave room for the space and backslash at the end of each line
maxwidth -= 2
def lines():
line = ''
for a in (shell_quote(a) for a in args):
# If adding this argument will make the line too long,
# yield the current line, and start a new one.
if len(line) + len(a) + 1 > maxwidth:
yield line
line = ''
# Append this argument to the current line, separating
# it by a space from the existing arguments.
if line:
line += ' ' + a
else:
line = a
yield line
return ' \\\n'.join(lines())
| Fix missing final line from format_cmdline() | Fix missing final line from format_cmdline()
The previous code was missing 'yield line' after the for loop.
This commit fixes that, as well as the extra space at the beginning
of each line. Normally, we'd use str.join() to avoid such a problem,
but this code is accumulating the line manually, so we can't just join
the args together.
This fixes #41.
| Python | mit | JonathonReinhart/scuba,JonathonReinhart/scuba,JonathonReinhart/scuba | try:
from shlex import quote as shell_quote
except ImportError:
from pipes import quote as shell_quote
+
def format_cmdline(args, maxwidth=80):
+ '''Format args into a shell-quoted command line.
+
+ The result will be wrapped to maxwidth characters where possible,
+ not breaking a single long argument.
+ '''
+
+ # Leave room for the space and backslash at the end of each line
+ maxwidth -= 2
+
def lines():
line = ''
for a in (shell_quote(a) for a in args):
+ # If adding this argument will make the line too long,
+ # yield the current line, and start a new one.
- if len(line) + len(a) > maxwidth:
+ if len(line) + len(a) + 1 > maxwidth:
yield line
line = ''
- line += ' ' + a
- return ' \\\n'.join(lines())[1:]
+ # Append this argument to the current line, separating
+ # it by a space from the existing arguments.
+ if line:
+ line += ' ' + a
+ else:
+ line = a
+ yield line
+
+ return ' \\\n'.join(lines())
+ | Fix missing final line from format_cmdline() | ## Code Before:
try:
from shlex import quote as shell_quote
except ImportError:
from pipes import quote as shell_quote
def format_cmdline(args, maxwidth=80):
def lines():
line = ''
for a in (shell_quote(a) for a in args):
if len(line) + len(a) > maxwidth:
yield line
line = ''
line += ' ' + a
return ' \\\n'.join(lines())[1:]
## Instruction:
Fix missing final line from format_cmdline()
## Code After:
try:
from shlex import quote as shell_quote
except ImportError:
from pipes import quote as shell_quote
def format_cmdline(args, maxwidth=80):
'''Format args into a shell-quoted command line.
The result will be wrapped to maxwidth characters where possible,
not breaking a single long argument.
'''
# Leave room for the space and backslash at the end of each line
maxwidth -= 2
def lines():
line = ''
for a in (shell_quote(a) for a in args):
# If adding this argument will make the line too long,
# yield the current line, and start a new one.
if len(line) + len(a) + 1 > maxwidth:
yield line
line = ''
# Append this argument to the current line, separating
# it by a space from the existing arguments.
if line:
line += ' ' + a
else:
line = a
yield line
return ' \\\n'.join(lines())
| try:
from shlex import quote as shell_quote
except ImportError:
from pipes import quote as shell_quote
+
def format_cmdline(args, maxwidth=80):
+ '''Format args into a shell-quoted command line.
+
+ The result will be wrapped to maxwidth characters where possible,
+ not breaking a single long argument.
+ '''
+
+ # Leave room for the space and backslash at the end of each line
+ maxwidth -= 2
+
def lines():
line = ''
for a in (shell_quote(a) for a in args):
+ # If adding this argument will make the line too long,
+ # yield the current line, and start a new one.
- if len(line) + len(a) > maxwidth:
+ if len(line) + len(a) + 1 > maxwidth:
? ++++
yield line
line = ''
- line += ' ' + a
+ # Append this argument to the current line, separating
+ # it by a space from the existing arguments.
+ if line:
+ line += ' ' + a
+ else:
+ line = a
+
+ yield line
+
- return ' \\\n'.join(lines())[1:]
? ----
+ return ' \\\n'.join(lines()) |
9442338d329e7f87d6265e0b0d3728a0df18d945 | viper/lexer/reserved_tokens.py | viper/lexer/reserved_tokens.py | RESERVED_NAMES = {
'def',
'pass',
'return',
'class',
'interface',
'data',
'if',
'elif',
'else',
'or',
'and',
'not',
'for',
'true',
'false',
}
RESERVED_CLASSES = set()
| RESERVED_NAMES = {
'def',
'pass',
'return',
'class',
'interface',
'data',
'static',
'public',
'private',
'protected',
'module',
'if',
'elif',
'else',
'or',
'and',
'not',
'for',
'true',
'false',
}
RESERVED_CLASSES = set()
| Update list of reserved tokens | Update list of reserved tokens
| Python | apache-2.0 | pdarragh/Viper | RESERVED_NAMES = {
'def',
'pass',
'return',
'class',
'interface',
'data',
+ 'static',
+ 'public',
+ 'private',
+ 'protected',
+ 'module',
'if',
'elif',
'else',
'or',
'and',
'not',
'for',
'true',
'false',
}
RESERVED_CLASSES = set()
| Update list of reserved tokens | ## Code Before:
RESERVED_NAMES = {
'def',
'pass',
'return',
'class',
'interface',
'data',
'if',
'elif',
'else',
'or',
'and',
'not',
'for',
'true',
'false',
}
RESERVED_CLASSES = set()
## Instruction:
Update list of reserved tokens
## Code After:
RESERVED_NAMES = {
'def',
'pass',
'return',
'class',
'interface',
'data',
'static',
'public',
'private',
'protected',
'module',
'if',
'elif',
'else',
'or',
'and',
'not',
'for',
'true',
'false',
}
RESERVED_CLASSES = set()
| RESERVED_NAMES = {
'def',
'pass',
'return',
'class',
'interface',
'data',
+ 'static',
+ 'public',
+ 'private',
+ 'protected',
+ 'module',
'if',
'elif',
'else',
'or',
'and',
'not',
'for',
'true',
'false',
}
RESERVED_CLASSES = set() |
69d013b768edabb6bc7dbe78b1f219ea1b49db16 | sqlitebiter/_config.py | sqlitebiter/_config.py |
from __future__ import absolute_import
from __future__ import unicode_literals
import appconfigpy
from ._const import PROGRAM_NAME
class ConfigKey(object):
PROXY_SERVER = "proxy_server"
GS_CREDENTIALS_FILE_PATH = "gs_credentials_file_path"
app_config_manager = appconfigpy.ConfigManager(
config_name=PROGRAM_NAME,
config_item_list=[
appconfigpy.ConfigItem(
name=ConfigKey.PROXY_SERVER,
prompt_text="HTTP/HTTPS proxy server URI",
initial_value="",
),
# appconfigpy.ConfigItem(
# name="gs_credentials_file_path",
# prompt_text="Google Sheets credentials file path",
# initial_value="",
# ),
])
|
from __future__ import absolute_import
from __future__ import unicode_literals
import appconfigpy
from ._const import PROGRAM_NAME
class ConfigKey(object):
DEFAULT_ENCODING = "default_encoding"
PROXY_SERVER = "proxy_server"
GS_CREDENTIALS_FILE_PATH = "gs_credentials_file_path"
app_config_manager = appconfigpy.ConfigManager(
config_name=PROGRAM_NAME,
config_item_list=[
appconfigpy.ConfigItem(
name=ConfigKey.DEFAULT_ENCODING,
prompt_text="Default encoding to load files",
initial_value="utf-8"),
appconfigpy.ConfigItem(
name=ConfigKey.PROXY_SERVER,
prompt_text="HTTP/HTTPS proxy server URI",
initial_value=""),
# appconfigpy.ConfigItem(
# name="gs_credentials_file_path",
# prompt_text="Google Sheets credentials file path",
# initial_value="",
# ),
])
| Add default encoding parameter to configure subcommand | Add default encoding parameter to configure subcommand
| Python | mit | thombashi/sqlitebiter,thombashi/sqlitebiter |
from __future__ import absolute_import
from __future__ import unicode_literals
import appconfigpy
from ._const import PROGRAM_NAME
class ConfigKey(object):
+ DEFAULT_ENCODING = "default_encoding"
PROXY_SERVER = "proxy_server"
GS_CREDENTIALS_FILE_PATH = "gs_credentials_file_path"
app_config_manager = appconfigpy.ConfigManager(
config_name=PROGRAM_NAME,
config_item_list=[
appconfigpy.ConfigItem(
+ name=ConfigKey.DEFAULT_ENCODING,
+ prompt_text="Default encoding to load files",
+ initial_value="utf-8"),
+ appconfigpy.ConfigItem(
name=ConfigKey.PROXY_SERVER,
prompt_text="HTTP/HTTPS proxy server URI",
- initial_value="",
+ initial_value=""),
- ),
# appconfigpy.ConfigItem(
# name="gs_credentials_file_path",
# prompt_text="Google Sheets credentials file path",
# initial_value="",
# ),
])
| Add default encoding parameter to configure subcommand | ## Code Before:
from __future__ import absolute_import
from __future__ import unicode_literals
import appconfigpy
from ._const import PROGRAM_NAME
class ConfigKey(object):
PROXY_SERVER = "proxy_server"
GS_CREDENTIALS_FILE_PATH = "gs_credentials_file_path"
app_config_manager = appconfigpy.ConfigManager(
config_name=PROGRAM_NAME,
config_item_list=[
appconfigpy.ConfigItem(
name=ConfigKey.PROXY_SERVER,
prompt_text="HTTP/HTTPS proxy server URI",
initial_value="",
),
# appconfigpy.ConfigItem(
# name="gs_credentials_file_path",
# prompt_text="Google Sheets credentials file path",
# initial_value="",
# ),
])
## Instruction:
Add default encoding parameter to configure subcommand
## Code After:
from __future__ import absolute_import
from __future__ import unicode_literals
import appconfigpy
from ._const import PROGRAM_NAME
class ConfigKey(object):
DEFAULT_ENCODING = "default_encoding"
PROXY_SERVER = "proxy_server"
GS_CREDENTIALS_FILE_PATH = "gs_credentials_file_path"
app_config_manager = appconfigpy.ConfigManager(
config_name=PROGRAM_NAME,
config_item_list=[
appconfigpy.ConfigItem(
name=ConfigKey.DEFAULT_ENCODING,
prompt_text="Default encoding to load files",
initial_value="utf-8"),
appconfigpy.ConfigItem(
name=ConfigKey.PROXY_SERVER,
prompt_text="HTTP/HTTPS proxy server URI",
initial_value=""),
# appconfigpy.ConfigItem(
# name="gs_credentials_file_path",
# prompt_text="Google Sheets credentials file path",
# initial_value="",
# ),
])
|
from __future__ import absolute_import
from __future__ import unicode_literals
import appconfigpy
from ._const import PROGRAM_NAME
class ConfigKey(object):
+ DEFAULT_ENCODING = "default_encoding"
PROXY_SERVER = "proxy_server"
GS_CREDENTIALS_FILE_PATH = "gs_credentials_file_path"
app_config_manager = appconfigpy.ConfigManager(
config_name=PROGRAM_NAME,
config_item_list=[
appconfigpy.ConfigItem(
+ name=ConfigKey.DEFAULT_ENCODING,
+ prompt_text="Default encoding to load files",
+ initial_value="utf-8"),
+ appconfigpy.ConfigItem(
name=ConfigKey.PROXY_SERVER,
prompt_text="HTTP/HTTPS proxy server URI",
- initial_value="",
+ initial_value=""),
? +
- ),
# appconfigpy.ConfigItem(
# name="gs_credentials_file_path",
# prompt_text="Google Sheets credentials file path",
# initial_value="",
# ),
]) |
f5cd0de26f430f33fa91bfd21bc96914fe9c56b8 | troposphere/cloudwatch.py | troposphere/cloudwatch.py |
from . import AWSObject, AWSProperty
from .validators import integer, positive_integer, boolean
class MetricDimension(AWSProperty):
props = {
'Name': (basestring, True),
'Value': (basestring, True),
}
class Alarm(AWSObject):
type = "AWS::CloudWatch::Alarm"
props = {
'ActionsEnabled': (boolean, False),
'AlarmActions': ([basestring], False),
'AlarmDescription': (basestring, False),
'AlarmName': (basestring, False),
'ComparisonOperator': (basestring, True),
'Dimensions': ([MetricDimension], False),
'EvaluationPeriods': (positive_integer, True),
'InsufficientDataActions': ([basestring], False),
'MetricName': (basestring, True),
'Namespace': (basestring, True),
'OKActions': ([basestring], False),
'Period': (positive_integer, True),
'Statistic': (basestring, True),
'Threshold': (integer, True),
'Unit': (basestring, False),
}
|
from . import AWSObject, AWSProperty, Ref
from .validators import integer, positive_integer, boolean
class MetricDimension(AWSProperty):
props = {
'Name': (basestring, True),
'Value': (basestring, True),
}
class Alarm(AWSObject):
type = "AWS::CloudWatch::Alarm"
props = {
'ActionsEnabled': (boolean, False),
'AlarmActions': ([basestring, Ref], False),
'AlarmDescription': (basestring, False),
'AlarmName': (basestring, False),
'ComparisonOperator': (basestring, True),
'Dimensions': ([MetricDimension], False),
'EvaluationPeriods': (positive_integer, True),
'InsufficientDataActions': ([basestring, Ref], False),
'MetricName': (basestring, True),
'Namespace': (basestring, True),
'OKActions': ([basestring, Ref], False),
'Period': (positive_integer, True),
'Statistic': (basestring, True),
'Threshold': (integer, True),
'Unit': (basestring, False),
}
| Allow Ref's in addition to basestrings | Allow Ref's in addition to basestrings
| Python | bsd-2-clause | jantman/troposphere,Yipit/troposphere,unravelin/troposphere,xxxVxxx/troposphere,alonsodomin/troposphere,Hons/troposphere,inetCatapult/troposphere,ptoraskar/troposphere,johnctitus/troposphere,cryptickp/troposphere,DualSpark/troposphere,dmm92/troposphere,7digital/troposphere,nicolaka/troposphere,ikben/troposphere,WeAreCloudar/troposphere,amosshapira/troposphere,samcrang/troposphere,jdc0589/troposphere,ccortezb/troposphere,dmm92/troposphere,craigbruce/troposphere,mhahn/troposphere,cloudtools/troposphere,garnaat/troposphere,wangqiang8511/troposphere,LouTheBrew/troposphere,pas256/troposphere,horacio3/troposphere,ikben/troposphere,alonsodomin/troposphere,kid/troposphere,cloudtools/troposphere,7digital/troposphere,mannytoledo/troposphere,micahhausler/troposphere,johnctitus/troposphere,iblazevic/troposphere,horacio3/troposphere,pas256/troposphere,yxd-hde/troposphere |
- from . import AWSObject, AWSProperty
+ from . import AWSObject, AWSProperty, Ref
from .validators import integer, positive_integer, boolean
class MetricDimension(AWSProperty):
props = {
'Name': (basestring, True),
'Value': (basestring, True),
}
class Alarm(AWSObject):
type = "AWS::CloudWatch::Alarm"
props = {
'ActionsEnabled': (boolean, False),
- 'AlarmActions': ([basestring], False),
+ 'AlarmActions': ([basestring, Ref], False),
'AlarmDescription': (basestring, False),
'AlarmName': (basestring, False),
'ComparisonOperator': (basestring, True),
'Dimensions': ([MetricDimension], False),
'EvaluationPeriods': (positive_integer, True),
- 'InsufficientDataActions': ([basestring], False),
+ 'InsufficientDataActions': ([basestring, Ref], False),
'MetricName': (basestring, True),
'Namespace': (basestring, True),
- 'OKActions': ([basestring], False),
+ 'OKActions': ([basestring, Ref], False),
'Period': (positive_integer, True),
'Statistic': (basestring, True),
'Threshold': (integer, True),
'Unit': (basestring, False),
}
| Allow Ref's in addition to basestrings | ## Code Before:
from . import AWSObject, AWSProperty
from .validators import integer, positive_integer, boolean
class MetricDimension(AWSProperty):
props = {
'Name': (basestring, True),
'Value': (basestring, True),
}
class Alarm(AWSObject):
type = "AWS::CloudWatch::Alarm"
props = {
'ActionsEnabled': (boolean, False),
'AlarmActions': ([basestring], False),
'AlarmDescription': (basestring, False),
'AlarmName': (basestring, False),
'ComparisonOperator': (basestring, True),
'Dimensions': ([MetricDimension], False),
'EvaluationPeriods': (positive_integer, True),
'InsufficientDataActions': ([basestring], False),
'MetricName': (basestring, True),
'Namespace': (basestring, True),
'OKActions': ([basestring], False),
'Period': (positive_integer, True),
'Statistic': (basestring, True),
'Threshold': (integer, True),
'Unit': (basestring, False),
}
## Instruction:
Allow Ref's in addition to basestrings
## Code After:
from . import AWSObject, AWSProperty, Ref
from .validators import integer, positive_integer, boolean
class MetricDimension(AWSProperty):
props = {
'Name': (basestring, True),
'Value': (basestring, True),
}
class Alarm(AWSObject):
type = "AWS::CloudWatch::Alarm"
props = {
'ActionsEnabled': (boolean, False),
'AlarmActions': ([basestring, Ref], False),
'AlarmDescription': (basestring, False),
'AlarmName': (basestring, False),
'ComparisonOperator': (basestring, True),
'Dimensions': ([MetricDimension], False),
'EvaluationPeriods': (positive_integer, True),
'InsufficientDataActions': ([basestring, Ref], False),
'MetricName': (basestring, True),
'Namespace': (basestring, True),
'OKActions': ([basestring, Ref], False),
'Period': (positive_integer, True),
'Statistic': (basestring, True),
'Threshold': (integer, True),
'Unit': (basestring, False),
}
|
- from . import AWSObject, AWSProperty
+ from . import AWSObject, AWSProperty, Ref
? +++++
from .validators import integer, positive_integer, boolean
class MetricDimension(AWSProperty):
props = {
'Name': (basestring, True),
'Value': (basestring, True),
}
class Alarm(AWSObject):
type = "AWS::CloudWatch::Alarm"
props = {
'ActionsEnabled': (boolean, False),
- 'AlarmActions': ([basestring], False),
+ 'AlarmActions': ([basestring, Ref], False),
? +++++
'AlarmDescription': (basestring, False),
'AlarmName': (basestring, False),
'ComparisonOperator': (basestring, True),
'Dimensions': ([MetricDimension], False),
'EvaluationPeriods': (positive_integer, True),
- 'InsufficientDataActions': ([basestring], False),
+ 'InsufficientDataActions': ([basestring, Ref], False),
? +++++
'MetricName': (basestring, True),
'Namespace': (basestring, True),
- 'OKActions': ([basestring], False),
+ 'OKActions': ([basestring, Ref], False),
? +++++
'Period': (positive_integer, True),
'Statistic': (basestring, True),
'Threshold': (integer, True),
'Unit': (basestring, False),
} |
6f1dc606b4c4f2702e0a5b48338488ac2eec197c | scripts/utils.py | scripts/utils.py | """Utility functions shared among all the scripts."""
from collections import OrderedDict
import json
import os
json_load_params = {
'object_pairs_hook': OrderedDict
}
def patch_files_filter(files):
"""Filters all file names that can not be among the content of a patch."""
for i in files:
if i != 'files.js':
yield i
json_dump_params = {
'ensure_ascii': False,
'indent': '\t',
'separators': (',', ': '),
'sort_keys': True
}
# Default parameters for JSON input and output
def json_load(fn, json_kwargs=json_load_params):
with open(fn, 'r', encoding='utf-8') as file:
return json.load(file, **json_kwargs)
def json_store(fn, obj, dirs=[''], json_kwargs=json_dump_params):
"""Saves the JSON object [obj] to [fn], creating all necessary
directories in the process. If [dirs] is given, the function is
executed for every root directory in the array."""
for i in dirs:
full_fn = os.path.join(i, fn)
os.makedirs(os.path.dirname(full_fn), exist_ok=True)
with open(full_fn, 'w', encoding='utf-8') as file:
json.dump(obj, file, **json_kwargs)
file.write('\n')
| """Utility functions shared among all the scripts."""
from collections import OrderedDict
import json
import os
json_load_params = {
'object_pairs_hook': OrderedDict
}
def patch_files_filter(files):
"""Filters all file names that can not be among the content of a patch."""
for i in files:
if i != 'files.js':
yield i
json_dump_params = {
'ensure_ascii': False,
'indent': '\t',
'separators': (',', ': '),
'sort_keys': True
}
# Default parameters for JSON input and output
def json_load(fn, json_kwargs=json_load_params):
with open(fn, 'r', encoding='utf-8') as file:
return json.load(file, **json_kwargs)
def json_store(fn, obj, dirs=[''], json_kwargs=json_dump_params):
"""Saves the JSON object [obj] to [fn], creating all necessary
directories in the process. If [dirs] is given, the function is
executed for every root directory in the array."""
for i in dirs:
full_fn = os.path.join(i, fn)
os.makedirs(os.path.dirname(full_fn), exist_ok=True)
with open(full_fn, 'w', newline='\n', encoding='utf-8') as file:
json.dump(obj, file, **json_kwargs)
file.write('\n')
| Enforce Unix newlines when writing JSON files. | scripts: Enforce Unix newlines when writing JSON files.
| Python | unlicense | VBChunguk/thcrap,thpatch/thcrap,thpatch/thcrap,thpatch/thcrap,VBChunguk/thcrap,VBChunguk/thcrap,thpatch/thcrap,thpatch/thcrap | """Utility functions shared among all the scripts."""
from collections import OrderedDict
import json
import os
json_load_params = {
'object_pairs_hook': OrderedDict
}
def patch_files_filter(files):
"""Filters all file names that can not be among the content of a patch."""
for i in files:
if i != 'files.js':
yield i
json_dump_params = {
'ensure_ascii': False,
'indent': '\t',
'separators': (',', ': '),
'sort_keys': True
}
# Default parameters for JSON input and output
def json_load(fn, json_kwargs=json_load_params):
with open(fn, 'r', encoding='utf-8') as file:
return json.load(file, **json_kwargs)
def json_store(fn, obj, dirs=[''], json_kwargs=json_dump_params):
"""Saves the JSON object [obj] to [fn], creating all necessary
directories in the process. If [dirs] is given, the function is
executed for every root directory in the array."""
for i in dirs:
full_fn = os.path.join(i, fn)
os.makedirs(os.path.dirname(full_fn), exist_ok=True)
- with open(full_fn, 'w', encoding='utf-8') as file:
+ with open(full_fn, 'w', newline='\n', encoding='utf-8') as file:
json.dump(obj, file, **json_kwargs)
file.write('\n')
| Enforce Unix newlines when writing JSON files. | ## Code Before:
"""Utility functions shared among all the scripts."""
from collections import OrderedDict
import json
import os
json_load_params = {
'object_pairs_hook': OrderedDict
}
def patch_files_filter(files):
"""Filters all file names that can not be among the content of a patch."""
for i in files:
if i != 'files.js':
yield i
json_dump_params = {
'ensure_ascii': False,
'indent': '\t',
'separators': (',', ': '),
'sort_keys': True
}
# Default parameters for JSON input and output
def json_load(fn, json_kwargs=json_load_params):
with open(fn, 'r', encoding='utf-8') as file:
return json.load(file, **json_kwargs)
def json_store(fn, obj, dirs=[''], json_kwargs=json_dump_params):
"""Saves the JSON object [obj] to [fn], creating all necessary
directories in the process. If [dirs] is given, the function is
executed for every root directory in the array."""
for i in dirs:
full_fn = os.path.join(i, fn)
os.makedirs(os.path.dirname(full_fn), exist_ok=True)
with open(full_fn, 'w', encoding='utf-8') as file:
json.dump(obj, file, **json_kwargs)
file.write('\n')
## Instruction:
Enforce Unix newlines when writing JSON files.
## Code After:
"""Utility functions shared among all the scripts."""
from collections import OrderedDict
import json
import os
json_load_params = {
'object_pairs_hook': OrderedDict
}
def patch_files_filter(files):
"""Filters all file names that can not be among the content of a patch."""
for i in files:
if i != 'files.js':
yield i
json_dump_params = {
'ensure_ascii': False,
'indent': '\t',
'separators': (',', ': '),
'sort_keys': True
}
# Default parameters for JSON input and output
def json_load(fn, json_kwargs=json_load_params):
with open(fn, 'r', encoding='utf-8') as file:
return json.load(file, **json_kwargs)
def json_store(fn, obj, dirs=[''], json_kwargs=json_dump_params):
"""Saves the JSON object [obj] to [fn], creating all necessary
directories in the process. If [dirs] is given, the function is
executed for every root directory in the array."""
for i in dirs:
full_fn = os.path.join(i, fn)
os.makedirs(os.path.dirname(full_fn), exist_ok=True)
with open(full_fn, 'w', newline='\n', encoding='utf-8') as file:
json.dump(obj, file, **json_kwargs)
file.write('\n')
| """Utility functions shared among all the scripts."""
from collections import OrderedDict
import json
import os
json_load_params = {
'object_pairs_hook': OrderedDict
}
def patch_files_filter(files):
"""Filters all file names that can not be among the content of a patch."""
for i in files:
if i != 'files.js':
yield i
json_dump_params = {
'ensure_ascii': False,
'indent': '\t',
'separators': (',', ': '),
'sort_keys': True
}
# Default parameters for JSON input and output
def json_load(fn, json_kwargs=json_load_params):
with open(fn, 'r', encoding='utf-8') as file:
return json.load(file, **json_kwargs)
def json_store(fn, obj, dirs=[''], json_kwargs=json_dump_params):
"""Saves the JSON object [obj] to [fn], creating all necessary
directories in the process. If [dirs] is given, the function is
executed for every root directory in the array."""
for i in dirs:
full_fn = os.path.join(i, fn)
os.makedirs(os.path.dirname(full_fn), exist_ok=True)
- with open(full_fn, 'w', encoding='utf-8') as file:
+ with open(full_fn, 'w', newline='\n', encoding='utf-8') as file:
? ++++++++++++++
json.dump(obj, file, **json_kwargs)
file.write('\n') |
74fde273d79248d4ad1c0cfd47d2861c83b50cbd | kolibri/auth/migrations/0007_auto_20171226_1125.py | kolibri/auth/migrations/0007_auto_20171226_1125.py | from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kolibriauth', '0006_auto_20171206_1207'),
]
operations = [
migrations.AlterField(
model_name='facilitydataset',
name='preset',
field=models.CharField(choices=[('informal', 'Informal and personal use'), ('nonformal', 'Self-managed'), ('formal', 'Admin-managed')], default='nonformal', max_length=50),
),
migrations.AlterUniqueTogether(
name='facilityuser',
unique_together=set([]),
),
]
| from __future__ import unicode_literals
from django.db import migrations, models
# This is necessary because:
# 1. The list generator has an unpredictable order, and when items swap places
# then this would be picked up as a change in Django if we had used
# 2. These choices can be changed in facility_configuration_presets.json
# and such change should not warrant warnings that models are inconsistent
# as it has no impact.
# Notice: The 'choices' property of a field does NOT have any impact on DB
# See: https://github.com/learningequality/kolibri/pull/3180
from ..constants.facility_presets import choices as facility_choices
class Migration(migrations.Migration):
dependencies = [
('kolibriauth', '0006_auto_20171206_1207'),
]
operations = [
migrations.AlterField(
model_name='facilitydataset',
name='preset',
field=models.CharField(choices=facility_choices, default='nonformal', max_length=50),
),
migrations.AlterUniqueTogether(
name='facilityuser',
unique_together=set([]),
),
]
| Fix for dynamic value of FacilityDataset.preset.choices causing migration inconsistencies | Fix for dynamic value of FacilityDataset.preset.choices causing migration inconsistencies
| Python | mit | christianmemije/kolibri,christianmemije/kolibri,indirectlylit/kolibri,benjaoming/kolibri,lyw07/kolibri,learningequality/kolibri,mrpau/kolibri,mrpau/kolibri,lyw07/kolibri,indirectlylit/kolibri,christianmemije/kolibri,jonboiser/kolibri,jonboiser/kolibri,DXCanas/kolibri,lyw07/kolibri,mrpau/kolibri,mrpau/kolibri,benjaoming/kolibri,indirectlylit/kolibri,christianmemije/kolibri,jonboiser/kolibri,learningequality/kolibri,DXCanas/kolibri,lyw07/kolibri,learningequality/kolibri,benjaoming/kolibri,DXCanas/kolibri,DXCanas/kolibri,learningequality/kolibri,jonboiser/kolibri,indirectlylit/kolibri,benjaoming/kolibri | from __future__ import unicode_literals
from django.db import migrations, models
+
+ # This is necessary because:
+ # 1. The list generator has an unpredictable order, and when items swap places
+ # then this would be picked up as a change in Django if we had used
+ # 2. These choices can be changed in facility_configuration_presets.json
+ # and such change should not warrant warnings that models are inconsistent
+ # as it has no impact.
+ # Notice: The 'choices' property of a field does NOT have any impact on DB
+ # See: https://github.com/learningequality/kolibri/pull/3180
+ from ..constants.facility_presets import choices as facility_choices
class Migration(migrations.Migration):
dependencies = [
('kolibriauth', '0006_auto_20171206_1207'),
]
operations = [
migrations.AlterField(
model_name='facilitydataset',
name='preset',
- field=models.CharField(choices=[('informal', 'Informal and personal use'), ('nonformal', 'Self-managed'), ('formal', 'Admin-managed')], default='nonformal', max_length=50),
+ field=models.CharField(choices=facility_choices, default='nonformal', max_length=50),
),
migrations.AlterUniqueTogether(
name='facilityuser',
unique_together=set([]),
),
]
| Fix for dynamic value of FacilityDataset.preset.choices causing migration inconsistencies | ## Code Before:
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kolibriauth', '0006_auto_20171206_1207'),
]
operations = [
migrations.AlterField(
model_name='facilitydataset',
name='preset',
field=models.CharField(choices=[('informal', 'Informal and personal use'), ('nonformal', 'Self-managed'), ('formal', 'Admin-managed')], default='nonformal', max_length=50),
),
migrations.AlterUniqueTogether(
name='facilityuser',
unique_together=set([]),
),
]
## Instruction:
Fix for dynamic value of FacilityDataset.preset.choices causing migration inconsistencies
## Code After:
from __future__ import unicode_literals
from django.db import migrations, models
# This is necessary because:
# 1. The list generator has an unpredictable order, and when items swap places
# then this would be picked up as a change in Django if we had used
# 2. These choices can be changed in facility_configuration_presets.json
# and such change should not warrant warnings that models are inconsistent
# as it has no impact.
# Notice: The 'choices' property of a field does NOT have any impact on DB
# See: https://github.com/learningequality/kolibri/pull/3180
from ..constants.facility_presets import choices as facility_choices
class Migration(migrations.Migration):
dependencies = [
('kolibriauth', '0006_auto_20171206_1207'),
]
operations = [
migrations.AlterField(
model_name='facilitydataset',
name='preset',
field=models.CharField(choices=facility_choices, default='nonformal', max_length=50),
),
migrations.AlterUniqueTogether(
name='facilityuser',
unique_together=set([]),
),
]
| from __future__ import unicode_literals
from django.db import migrations, models
+
+ # This is necessary because:
+ # 1. The list generator has an unpredictable order, and when items swap places
+ # then this would be picked up as a change in Django if we had used
+ # 2. These choices can be changed in facility_configuration_presets.json
+ # and such change should not warrant warnings that models are inconsistent
+ # as it has no impact.
+ # Notice: The 'choices' property of a field does NOT have any impact on DB
+ # See: https://github.com/learningequality/kolibri/pull/3180
+ from ..constants.facility_presets import choices as facility_choices
class Migration(migrations.Migration):
dependencies = [
('kolibriauth', '0006_auto_20171206_1207'),
]
operations = [
migrations.AlterField(
model_name='facilitydataset',
name='preset',
- field=models.CharField(choices=[('informal', 'Informal and personal use'), ('nonformal', 'Self-managed'), ('formal', 'Admin-managed')], default='nonformal', max_length=50),
+ field=models.CharField(choices=facility_choices, default='nonformal', max_length=50),
),
migrations.AlterUniqueTogether(
name='facilityuser',
unique_together=set([]),
),
] |
b85751e356c091d2dffe8366a94fbb42bfcad34e | src/SMESH_SWIG/SMESH_GroupLyingOnGeom.py | src/SMESH_SWIG/SMESH_GroupLyingOnGeom.py | import SMESH
def BuildGroupLyingOn(theMesh, theElemType, theName, theShape):
aMeshGen = salome.lcc.FindOrLoadComponent("FactoryServer", "SMESH")
aFilterMgr = aMeshGen.CreateFilterManager()
aFilter = aFilterMgr.CreateFilter()
aLyingOnGeom = aFilterMgr.CreateLyingOnGeom()
aLyingOnGeom.SetGeom(theShape)
aLyingOnGeom.SetElementType(theElemType)
aFilter.SetPredicate(aLyingOnGeom)
anIds = aFilter.GetElementsId(theMesh)
aGroup = theMesh.CreateGroup(theElemType, theName)
aGroup.Add(anIds)
#Example
## from SMESH_test1 import *
## smesh.Compute(mesh, box)
## BuildGroupLyingOn(mesh, SMESH.FACE, "Group of faces lying on edge", edge )
## salome.sg.updateObjBrowser(1);
| from meshpy import *
def BuildGroupLyingOn(theMesh, theElemType, theName, theShape):
aFilterMgr = smesh.CreateFilterManager()
aFilter = aFilterMgr.CreateFilter()
aLyingOnGeom = aFilterMgr.CreateLyingOnGeom()
aLyingOnGeom.SetGeom(theShape)
aLyingOnGeom.SetElementType(theElemType)
aFilter.SetPredicate(aLyingOnGeom)
anIds = aFilter.GetElementsId(theMesh)
aGroup = theMesh.CreateGroup(theElemType, theName)
aGroup.Add(anIds)
#Example
## from SMESH_test1 import *
## smesh.Compute(mesh, box)
## BuildGroupLyingOn(mesh, SMESH.FACE, "Group of faces lying on edge", edge )
## salome.sg.updateObjBrowser(1);
| Fix a bug - salome.py is not imported here and this causes run-time Python exception | Fix a bug - salome.py is not imported here and this causes run-time Python exception
| Python | lgpl-2.1 | FedoraScientific/salome-smesh,FedoraScientific/salome-smesh,FedoraScientific/salome-smesh,FedoraScientific/salome-smesh | - import SMESH
+ from meshpy import *
def BuildGroupLyingOn(theMesh, theElemType, theName, theShape):
- aMeshGen = salome.lcc.FindOrLoadComponent("FactoryServer", "SMESH")
-
- aFilterMgr = aMeshGen.CreateFilterManager()
+ aFilterMgr = smesh.CreateFilterManager()
aFilter = aFilterMgr.CreateFilter()
aLyingOnGeom = aFilterMgr.CreateLyingOnGeom()
aLyingOnGeom.SetGeom(theShape)
aLyingOnGeom.SetElementType(theElemType)
aFilter.SetPredicate(aLyingOnGeom)
anIds = aFilter.GetElementsId(theMesh)
aGroup = theMesh.CreateGroup(theElemType, theName)
aGroup.Add(anIds)
#Example
## from SMESH_test1 import *
## smesh.Compute(mesh, box)
## BuildGroupLyingOn(mesh, SMESH.FACE, "Group of faces lying on edge", edge )
## salome.sg.updateObjBrowser(1);
| Fix a bug - salome.py is not imported here and this causes run-time Python exception | ## Code Before:
import SMESH
def BuildGroupLyingOn(theMesh, theElemType, theName, theShape):
aMeshGen = salome.lcc.FindOrLoadComponent("FactoryServer", "SMESH")
aFilterMgr = aMeshGen.CreateFilterManager()
aFilter = aFilterMgr.CreateFilter()
aLyingOnGeom = aFilterMgr.CreateLyingOnGeom()
aLyingOnGeom.SetGeom(theShape)
aLyingOnGeom.SetElementType(theElemType)
aFilter.SetPredicate(aLyingOnGeom)
anIds = aFilter.GetElementsId(theMesh)
aGroup = theMesh.CreateGroup(theElemType, theName)
aGroup.Add(anIds)
#Example
## from SMESH_test1 import *
## smesh.Compute(mesh, box)
## BuildGroupLyingOn(mesh, SMESH.FACE, "Group of faces lying on edge", edge )
## salome.sg.updateObjBrowser(1);
## Instruction:
Fix a bug - salome.py is not imported here and this causes run-time Python exception
## Code After:
from meshpy import *
def BuildGroupLyingOn(theMesh, theElemType, theName, theShape):
aFilterMgr = smesh.CreateFilterManager()
aFilter = aFilterMgr.CreateFilter()
aLyingOnGeom = aFilterMgr.CreateLyingOnGeom()
aLyingOnGeom.SetGeom(theShape)
aLyingOnGeom.SetElementType(theElemType)
aFilter.SetPredicate(aLyingOnGeom)
anIds = aFilter.GetElementsId(theMesh)
aGroup = theMesh.CreateGroup(theElemType, theName)
aGroup.Add(anIds)
#Example
## from SMESH_test1 import *
## smesh.Compute(mesh, box)
## BuildGroupLyingOn(mesh, SMESH.FACE, "Group of faces lying on edge", edge )
## salome.sg.updateObjBrowser(1);
| - import SMESH
+ from meshpy import *
def BuildGroupLyingOn(theMesh, theElemType, theName, theShape):
- aMeshGen = salome.lcc.FindOrLoadComponent("FactoryServer", "SMESH")
-
- aFilterMgr = aMeshGen.CreateFilterManager()
? ^^ ---
+ aFilterMgr = smesh.CreateFilterManager()
? ^^
aFilter = aFilterMgr.CreateFilter()
aLyingOnGeom = aFilterMgr.CreateLyingOnGeom()
aLyingOnGeom.SetGeom(theShape)
aLyingOnGeom.SetElementType(theElemType)
aFilter.SetPredicate(aLyingOnGeom)
anIds = aFilter.GetElementsId(theMesh)
aGroup = theMesh.CreateGroup(theElemType, theName)
aGroup.Add(anIds)
#Example
## from SMESH_test1 import *
## smesh.Compute(mesh, box)
## BuildGroupLyingOn(mesh, SMESH.FACE, "Group of faces lying on edge", edge )
## salome.sg.updateObjBrowser(1); |
80857a9f30b3e6773a658bf8ce93809c0881f80a | plugins/liquid_tags/liquid_tags.py | plugins/liquid_tags/liquid_tags.py | from pelican import signals
from .mdx_liquid_tags import LiquidTags, LT_CONFIG
def addLiquidTags(gen):
if not gen.settings.get('MD_EXTENSIONS'):
from pelican.settings import DEFAULT_CONFIG
gen.settings['MD_EXTENSIONS'] = DEFAULT_CONFIG['MD_EXTENSIONS']
if LiquidTags not in gen.settings['MD_EXTENSIONS']:
configs = dict()
for key,value in LT_CONFIG.items():
configs[key]=value
for key,value in gen.settings.items():
if key in LT_CONFIG:
configs[key]=value
gen.settings['MD_EXTENSIONS'].append(LiquidTags(configs))
def register():
signals.initialized.connect(addLiquidTags)
| from pelican import signals
from .mdx_liquid_tags import LiquidTags, LT_CONFIG
def addLiquidTags(gen):
if not gen.settings.get('MARKDOWN'):
from pelican.settings import DEFAULT_CONFIG
gen.settings['MARKDOWN'] = DEFAULT_CONFIG['MARKDOWN']
if LiquidTags not in gen.settings['MARKDOWN']:
configs = dict()
for key,value in LT_CONFIG.items():
configs[key]=value
for key,value in gen.settings.items():
if key in LT_CONFIG:
configs[key]=value
gen.settings['MARKDOWN'].setdefault(
'extensions', []
).append(
LiquidTags(configs)
)
def register():
signals.initialized.connect(addLiquidTags)
| Update to new markdown settings | Update to new markdown settings
| Python | apache-2.0 | danielfrg/danielfrg.github.io-source,danielfrg/danielfrg.github.io-source,danielfrg/danielfrg.github.io-source | from pelican import signals
from .mdx_liquid_tags import LiquidTags, LT_CONFIG
def addLiquidTags(gen):
- if not gen.settings.get('MD_EXTENSIONS'):
+ if not gen.settings.get('MARKDOWN'):
from pelican.settings import DEFAULT_CONFIG
- gen.settings['MD_EXTENSIONS'] = DEFAULT_CONFIG['MD_EXTENSIONS']
+ gen.settings['MARKDOWN'] = DEFAULT_CONFIG['MARKDOWN']
- if LiquidTags not in gen.settings['MD_EXTENSIONS']:
+ if LiquidTags not in gen.settings['MARKDOWN']:
configs = dict()
for key,value in LT_CONFIG.items():
configs[key]=value
for key,value in gen.settings.items():
if key in LT_CONFIG:
configs[key]=value
- gen.settings['MD_EXTENSIONS'].append(LiquidTags(configs))
+ gen.settings['MARKDOWN'].setdefault(
+ 'extensions', []
+ ).append(
+ LiquidTags(configs)
+ )
+
def register():
signals.initialized.connect(addLiquidTags)
| Update to new markdown settings | ## Code Before:
from pelican import signals
from .mdx_liquid_tags import LiquidTags, LT_CONFIG
def addLiquidTags(gen):
if not gen.settings.get('MD_EXTENSIONS'):
from pelican.settings import DEFAULT_CONFIG
gen.settings['MD_EXTENSIONS'] = DEFAULT_CONFIG['MD_EXTENSIONS']
if LiquidTags not in gen.settings['MD_EXTENSIONS']:
configs = dict()
for key,value in LT_CONFIG.items():
configs[key]=value
for key,value in gen.settings.items():
if key in LT_CONFIG:
configs[key]=value
gen.settings['MD_EXTENSIONS'].append(LiquidTags(configs))
def register():
signals.initialized.connect(addLiquidTags)
## Instruction:
Update to new markdown settings
## Code After:
from pelican import signals
from .mdx_liquid_tags import LiquidTags, LT_CONFIG
def addLiquidTags(gen):
if not gen.settings.get('MARKDOWN'):
from pelican.settings import DEFAULT_CONFIG
gen.settings['MARKDOWN'] = DEFAULT_CONFIG['MARKDOWN']
if LiquidTags not in gen.settings['MARKDOWN']:
configs = dict()
for key,value in LT_CONFIG.items():
configs[key]=value
for key,value in gen.settings.items():
if key in LT_CONFIG:
configs[key]=value
gen.settings['MARKDOWN'].setdefault(
'extensions', []
).append(
LiquidTags(configs)
)
def register():
signals.initialized.connect(addLiquidTags)
| from pelican import signals
from .mdx_liquid_tags import LiquidTags, LT_CONFIG
def addLiquidTags(gen):
- if not gen.settings.get('MD_EXTENSIONS'):
? ^^^^^ -----
+ if not gen.settings.get('MARKDOWN'):
? +++ ^^
from pelican.settings import DEFAULT_CONFIG
- gen.settings['MD_EXTENSIONS'] = DEFAULT_CONFIG['MD_EXTENSIONS']
? ^^^^^ ----- ^^^^^ -----
+ gen.settings['MARKDOWN'] = DEFAULT_CONFIG['MARKDOWN']
? +++ ^^ +++ ^^
- if LiquidTags not in gen.settings['MD_EXTENSIONS']:
? ^^^^^ -----
+ if LiquidTags not in gen.settings['MARKDOWN']:
? +++ ^^
configs = dict()
for key,value in LT_CONFIG.items():
configs[key]=value
for key,value in gen.settings.items():
if key in LT_CONFIG:
configs[key]=value
- gen.settings['MD_EXTENSIONS'].append(LiquidTags(configs))
+ gen.settings['MARKDOWN'].setdefault(
+ 'extensions', []
+ ).append(
+ LiquidTags(configs)
+ )
+
def register():
signals.initialized.connect(addLiquidTags) |
b9d1dcf614faa949975bc5296be451abd2594835 | repository/presenter.py | repository/presenter.py | import logger
import datetime
def out(counter, argv, elapsed_time = None):
sum_lines = sum(counter.values())
blue = '\033[94m'
grey = '\033[0m'
endcolor = '\033[0m'
italic = '\x1B[3m'
eitalic = '\x1B[23m'
template = '{0:>7.2%} {3}{2}{4}'
if argv.show_absolute > 0:
template = '{0:>7.2%} {3}{2}{4} ({1})'
top_n = argv.top_n if argv.top_n > 0 else None
sorted_counter = counter.most_common(top_n)
if argv.alphabetically:
sorted_counter = sorted(sorted_counter)
if argv.reverse:
sorted_counter = reversed(sorted_counter)
for author, contributions in sorted_counter:
relative = float(contributions) / float(sum_lines)
output = template.format(relative, contributions, author, blue,
endcolor, italic, eitalic)
print(output)
n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter))
elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time))
logger.instance.info(n_contributors)
logger.instance.info(elapsed)
| import logger
import datetime
def out(counter, argv, elapsed_time = None):
sum_lines = sum(counter.values())
blue = '\033[94m'
grey = '\033[0m'
endcolor = '\033[0m'
italic = '\x1B[3m'
eitalic = '\x1B[23m'
template = '{0:>7.2%} {3}{2}{4}'
if argv.show_absolute > 0:
template = '{0:>7.2%} {3}{2}{4} ({1})'
top_n = argv.top_n
if top_n < 0 or top_n > len(counter):
top_n = len(counter)
sorted_counter = counter.most_common(top_n)
if argv.alphabetically:
sorted_counter = sorted(sorted_counter)
if argv.reverse:
sorted_counter = reversed(sorted_counter)
for author, contributions in sorted_counter:
relative = float(contributions) / float(sum_lines)
output = template.format(relative, contributions, author, blue,
endcolor, italic, eitalic)
print(output)
n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter))
elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time))
logger.instance.info(n_contributors)
logger.instance.info(elapsed)
| Fix small issue with `--top-n` command switch | Fix small issue with `--top-n` command switch
| Python | mit | moacirosa/git-current-contributors,moacirosa/git-current-contributors | import logger
import datetime
def out(counter, argv, elapsed_time = None):
sum_lines = sum(counter.values())
blue = '\033[94m'
grey = '\033[0m'
endcolor = '\033[0m'
italic = '\x1B[3m'
eitalic = '\x1B[23m'
template = '{0:>7.2%} {3}{2}{4}'
if argv.show_absolute > 0:
template = '{0:>7.2%} {3}{2}{4} ({1})'
- top_n = argv.top_n if argv.top_n > 0 else None
+ top_n = argv.top_n
+
+ if top_n < 0 or top_n > len(counter):
+ top_n = len(counter)
sorted_counter = counter.most_common(top_n)
if argv.alphabetically:
sorted_counter = sorted(sorted_counter)
if argv.reverse:
sorted_counter = reversed(sorted_counter)
for author, contributions in sorted_counter:
relative = float(contributions) / float(sum_lines)
output = template.format(relative, contributions, author, blue,
endcolor, italic, eitalic)
print(output)
n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter))
elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time))
logger.instance.info(n_contributors)
logger.instance.info(elapsed)
| Fix small issue with `--top-n` command switch | ## Code Before:
import logger
import datetime
def out(counter, argv, elapsed_time = None):
sum_lines = sum(counter.values())
blue = '\033[94m'
grey = '\033[0m'
endcolor = '\033[0m'
italic = '\x1B[3m'
eitalic = '\x1B[23m'
template = '{0:>7.2%} {3}{2}{4}'
if argv.show_absolute > 0:
template = '{0:>7.2%} {3}{2}{4} ({1})'
top_n = argv.top_n if argv.top_n > 0 else None
sorted_counter = counter.most_common(top_n)
if argv.alphabetically:
sorted_counter = sorted(sorted_counter)
if argv.reverse:
sorted_counter = reversed(sorted_counter)
for author, contributions in sorted_counter:
relative = float(contributions) / float(sum_lines)
output = template.format(relative, contributions, author, blue,
endcolor, italic, eitalic)
print(output)
n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter))
elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time))
logger.instance.info(n_contributors)
logger.instance.info(elapsed)
## Instruction:
Fix small issue with `--top-n` command switch
## Code After:
import logger
import datetime
def out(counter, argv, elapsed_time = None):
sum_lines = sum(counter.values())
blue = '\033[94m'
grey = '\033[0m'
endcolor = '\033[0m'
italic = '\x1B[3m'
eitalic = '\x1B[23m'
template = '{0:>7.2%} {3}{2}{4}'
if argv.show_absolute > 0:
template = '{0:>7.2%} {3}{2}{4} ({1})'
top_n = argv.top_n
if top_n < 0 or top_n > len(counter):
top_n = len(counter)
sorted_counter = counter.most_common(top_n)
if argv.alphabetically:
sorted_counter = sorted(sorted_counter)
if argv.reverse:
sorted_counter = reversed(sorted_counter)
for author, contributions in sorted_counter:
relative = float(contributions) / float(sum_lines)
output = template.format(relative, contributions, author, blue,
endcolor, italic, eitalic)
print(output)
n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter))
elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time))
logger.instance.info(n_contributors)
logger.instance.info(elapsed)
| import logger
import datetime
def out(counter, argv, elapsed_time = None):
sum_lines = sum(counter.values())
blue = '\033[94m'
grey = '\033[0m'
endcolor = '\033[0m'
italic = '\x1B[3m'
eitalic = '\x1B[23m'
template = '{0:>7.2%} {3}{2}{4}'
if argv.show_absolute > 0:
template = '{0:>7.2%} {3}{2}{4} ({1})'
- top_n = argv.top_n if argv.top_n > 0 else None
+ top_n = argv.top_n
+
+ if top_n < 0 or top_n > len(counter):
+ top_n = len(counter)
sorted_counter = counter.most_common(top_n)
if argv.alphabetically:
sorted_counter = sorted(sorted_counter)
if argv.reverse:
sorted_counter = reversed(sorted_counter)
for author, contributions in sorted_counter:
relative = float(contributions) / float(sum_lines)
output = template.format(relative, contributions, author, blue,
endcolor, italic, eitalic)
print(output)
n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter))
elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time))
logger.instance.info(n_contributors)
logger.instance.info(elapsed) |
a67e45347f0119c4e1a3fb55b401a9acce939c7a | script/lib/util.py | script/lib/util.py |
import sys
def get_output_dir(target_arch, component):
# Build in "out_component" for component build.
output_dir = 'out'
if component == 'shared_library':
output_dir += '_component'
# Build in "out_32" for 32bit target.
if target_arch == 'ia32':
output_dir += '_32'
return output_dir
def get_configuration(target_arch):
config = 'Release'
if target_arch == 'x64' and sys.platform in ['win32', 'cygwin']:
config += '_x64'
return config
|
import sys
def get_output_dir(target_arch, component):
# Build in "out_component" for component build.
output_dir = 'out'
if component == 'shared_library':
output_dir += '_component'
# Build in "out_32" for 32bit target.
if target_arch == 'ia32':
output_dir += '_32'
elif target_arch == 'arm':
output_dir += '_arm'
return output_dir
def get_configuration(target_arch):
config = 'Release'
if target_arch == 'x64' and sys.platform in ['win32', 'cygwin']:
config += '_x64'
return config
| Fix output dir for arm target | Fix output dir for arm target
| Python | mit | atom/libchromiumcontent,eric-seekas/libchromiumcontent,paulcbetts/libchromiumcontent,adamjgray/libchromiumcontent,synaptek/libchromiumcontent,atom/libchromiumcontent,electron/libchromiumcontent,bbondy/libchromiumcontent,hokein/libchromiumcontent,adamjgray/libchromiumcontent,synaptek/libchromiumcontent,hokein/libchromiumcontent,zhanggyb/libchromiumcontent,electron/libchromiumcontent,brave/libchromiumcontent,bbondy/libchromiumcontent,zhanggyb/libchromiumcontent,paulcbetts/libchromiumcontent,eric-seekas/libchromiumcontent,brave/libchromiumcontent |
import sys
def get_output_dir(target_arch, component):
# Build in "out_component" for component build.
output_dir = 'out'
if component == 'shared_library':
output_dir += '_component'
# Build in "out_32" for 32bit target.
if target_arch == 'ia32':
output_dir += '_32'
+ elif target_arch == 'arm':
+ output_dir += '_arm'
return output_dir
def get_configuration(target_arch):
config = 'Release'
if target_arch == 'x64' and sys.platform in ['win32', 'cygwin']:
config += '_x64'
return config
| Fix output dir for arm target | ## Code Before:
import sys
def get_output_dir(target_arch, component):
# Build in "out_component" for component build.
output_dir = 'out'
if component == 'shared_library':
output_dir += '_component'
# Build in "out_32" for 32bit target.
if target_arch == 'ia32':
output_dir += '_32'
return output_dir
def get_configuration(target_arch):
config = 'Release'
if target_arch == 'x64' and sys.platform in ['win32', 'cygwin']:
config += '_x64'
return config
## Instruction:
Fix output dir for arm target
## Code After:
import sys
def get_output_dir(target_arch, component):
# Build in "out_component" for component build.
output_dir = 'out'
if component == 'shared_library':
output_dir += '_component'
# Build in "out_32" for 32bit target.
if target_arch == 'ia32':
output_dir += '_32'
elif target_arch == 'arm':
output_dir += '_arm'
return output_dir
def get_configuration(target_arch):
config = 'Release'
if target_arch == 'x64' and sys.platform in ['win32', 'cygwin']:
config += '_x64'
return config
|
import sys
def get_output_dir(target_arch, component):
# Build in "out_component" for component build.
output_dir = 'out'
if component == 'shared_library':
output_dir += '_component'
# Build in "out_32" for 32bit target.
if target_arch == 'ia32':
output_dir += '_32'
+ elif target_arch == 'arm':
+ output_dir += '_arm'
return output_dir
def get_configuration(target_arch):
config = 'Release'
if target_arch == 'x64' and sys.platform in ['win32', 'cygwin']:
config += '_x64'
return config |
8d831e4834b61c04b3f5f2d8a812095eea8c022f | personDb.py | personDb.py | import pickle
class PersonDb(object):
def __init__(self, dbName, autoload = True):
self.dbName = dbName
self.db = None
if autoload:
self.setup()
def setup(self):
self.db = PersonDb.load(self.dbName)
self.getGroups()
def getGroups(self):
tmp = set()
for person in self.db:
for group in person.group:
tmp.append(person)
self.groups = tmp
def save(data, fileName = 'database'):
filen = PersonDb.fileExtension(fileName)
with open(filen,"wb") as pickleOut:
pickle.dump(data, pickleOut)
def load(fileName = 'database'):
filen = PersonDb.fileExtension(fileName)
with open(filen, "rb") as pickleIn:
data = pickle.load(pickleIn)
return data
def fileExtension(fileName):
result = fileName.strip()
if '.json' not in result:
result += '.json'
return result
| import pickle
import os
class PersonDb(object):
def __init__(self, dbName, autoload = True):
self.dbName = dbName
self.db = None
if autoload:
self.setup()
def setup(self):
self.db = PersonDb.load(self.dbName)
self.getGroups()
def getGroups(self):
tmp = set()
for person in self.db:
for group in person.group:
tmp.append(person)
self.groups = tmp
def save(data, fileName = 'database'):
filen = PersonDb.fileExtension(fileName)
with open(filen,"wb") as pickleOut:
pickle.dump(data, pickleOut)
def load(fileName = 'database'):
filen = PersonDb.fileExtension(fileName)
if os.path.exists(filen):
with open(filen, "rb") as pickleIn:
data = pickle.load(pickleIn)
return data
else:
return []
def fileExtension(fileName):
result = fileName.strip()
if '.json' not in result:
result += '.json'
return result
| Add handling of not present file. | Add handling of not present file.
Signed-off-by: Matej Dujava <03ce64f61b3ea1fda633fb2a103b989e3272d16b@gmail.com>
| Python | mit | matejd11/birthdayNotify | import pickle
+ import os
class PersonDb(object):
def __init__(self, dbName, autoload = True):
self.dbName = dbName
self.db = None
if autoload:
self.setup()
def setup(self):
self.db = PersonDb.load(self.dbName)
self.getGroups()
def getGroups(self):
tmp = set()
for person in self.db:
for group in person.group:
tmp.append(person)
self.groups = tmp
def save(data, fileName = 'database'):
filen = PersonDb.fileExtension(fileName)
with open(filen,"wb") as pickleOut:
pickle.dump(data, pickleOut)
def load(fileName = 'database'):
filen = PersonDb.fileExtension(fileName)
+ if os.path.exists(filen):
- with open(filen, "rb") as pickleIn:
+ with open(filen, "rb") as pickleIn:
- data = pickle.load(pickleIn)
+ data = pickle.load(pickleIn)
- return data
+ return data
+ else:
+ return []
def fileExtension(fileName):
result = fileName.strip()
if '.json' not in result:
result += '.json'
return result
| Add handling of not present file. | ## Code Before:
import pickle
class PersonDb(object):
def __init__(self, dbName, autoload = True):
self.dbName = dbName
self.db = None
if autoload:
self.setup()
def setup(self):
self.db = PersonDb.load(self.dbName)
self.getGroups()
def getGroups(self):
tmp = set()
for person in self.db:
for group in person.group:
tmp.append(person)
self.groups = tmp
def save(data, fileName = 'database'):
filen = PersonDb.fileExtension(fileName)
with open(filen,"wb") as pickleOut:
pickle.dump(data, pickleOut)
def load(fileName = 'database'):
filen = PersonDb.fileExtension(fileName)
with open(filen, "rb") as pickleIn:
data = pickle.load(pickleIn)
return data
def fileExtension(fileName):
result = fileName.strip()
if '.json' not in result:
result += '.json'
return result
## Instruction:
Add handling of not present file.
## Code After:
import pickle
import os
class PersonDb(object):
def __init__(self, dbName, autoload = True):
self.dbName = dbName
self.db = None
if autoload:
self.setup()
def setup(self):
self.db = PersonDb.load(self.dbName)
self.getGroups()
def getGroups(self):
tmp = set()
for person in self.db:
for group in person.group:
tmp.append(person)
self.groups = tmp
def save(data, fileName = 'database'):
filen = PersonDb.fileExtension(fileName)
with open(filen,"wb") as pickleOut:
pickle.dump(data, pickleOut)
def load(fileName = 'database'):
filen = PersonDb.fileExtension(fileName)
if os.path.exists(filen):
with open(filen, "rb") as pickleIn:
data = pickle.load(pickleIn)
return data
else:
return []
def fileExtension(fileName):
result = fileName.strip()
if '.json' not in result:
result += '.json'
return result
| import pickle
+ import os
class PersonDb(object):
def __init__(self, dbName, autoload = True):
self.dbName = dbName
self.db = None
if autoload:
self.setup()
def setup(self):
self.db = PersonDb.load(self.dbName)
self.getGroups()
def getGroups(self):
tmp = set()
for person in self.db:
for group in person.group:
tmp.append(person)
self.groups = tmp
def save(data, fileName = 'database'):
filen = PersonDb.fileExtension(fileName)
with open(filen,"wb") as pickleOut:
pickle.dump(data, pickleOut)
def load(fileName = 'database'):
filen = PersonDb.fileExtension(fileName)
+ if os.path.exists(filen):
- with open(filen, "rb") as pickleIn:
+ with open(filen, "rb") as pickleIn:
? ++++
- data = pickle.load(pickleIn)
+ data = pickle.load(pickleIn)
? ++++
- return data
+ return data
? ++++
+ else:
+ return []
def fileExtension(fileName):
result = fileName.strip()
if '.json' not in result:
result += '.json'
return result |
939c5fd069fafbe353fc9a209d2bd376e8d9bbd6 | gridded/gridded.py | gridded/gridded.py | class Gridded:
_grid_obj_classes = []
_grids_loaded = False
@classmethod
def _load_grid_objs(cls):
from pkg_resources import working_set
for ep in working_set.iter_entry_points('gridded.grid_objects'):
cls._grid_obj_classes.append(ep.load())
@classmethod
def load(cls, nc, *args, **kwargs):
for go in self._grid_obj_classes:
if hasattr(go, 'is_mine') and go.is_mine(nc):
return go(nc, *args, **kwargs)
| class Gridded:
_grid_obj_classes = []
_grids_loaded = False
@classmethod
def _load_grid_objs(cls):
from pkg_resources import working_set
for ep in working_set.iter_entry_points('gridded.grid_objects'):
cls._grid_obj_classes.append(ep.load())
@classmethod
def load(cls, *args, **kwargs):
for go in cls._grid_obj_classes:
if hasattr(go, 'is_mine') and go.is_mine(*args, **kwargs):
return go(*args, **kwargs)
| Fix self- > cls, make super generic (no `nc`) | Fix self- > cls, make super generic (no `nc`)
| Python | mit | pyoceans/gridded | class Gridded:
_grid_obj_classes = []
_grids_loaded = False
@classmethod
def _load_grid_objs(cls):
from pkg_resources import working_set
for ep in working_set.iter_entry_points('gridded.grid_objects'):
cls._grid_obj_classes.append(ep.load())
@classmethod
- def load(cls, nc, *args, **kwargs):
+ def load(cls, *args, **kwargs):
- for go in self._grid_obj_classes:
+ for go in cls._grid_obj_classes:
- if hasattr(go, 'is_mine') and go.is_mine(nc):
+ if hasattr(go, 'is_mine') and go.is_mine(*args, **kwargs):
- return go(nc, *args, **kwargs)
+ return go(*args, **kwargs)
- | Fix self- > cls, make super generic (no `nc`) | ## Code Before:
class Gridded:
_grid_obj_classes = []
_grids_loaded = False
@classmethod
def _load_grid_objs(cls):
from pkg_resources import working_set
for ep in working_set.iter_entry_points('gridded.grid_objects'):
cls._grid_obj_classes.append(ep.load())
@classmethod
def load(cls, nc, *args, **kwargs):
for go in self._grid_obj_classes:
if hasattr(go, 'is_mine') and go.is_mine(nc):
return go(nc, *args, **kwargs)
## Instruction:
Fix self- > cls, make super generic (no `nc`)
## Code After:
class Gridded:
_grid_obj_classes = []
_grids_loaded = False
@classmethod
def _load_grid_objs(cls):
from pkg_resources import working_set
for ep in working_set.iter_entry_points('gridded.grid_objects'):
cls._grid_obj_classes.append(ep.load())
@classmethod
def load(cls, *args, **kwargs):
for go in cls._grid_obj_classes:
if hasattr(go, 'is_mine') and go.is_mine(*args, **kwargs):
return go(*args, **kwargs)
| class Gridded:
_grid_obj_classes = []
_grids_loaded = False
@classmethod
def _load_grid_objs(cls):
from pkg_resources import working_set
for ep in working_set.iter_entry_points('gridded.grid_objects'):
cls._grid_obj_classes.append(ep.load())
@classmethod
- def load(cls, nc, *args, **kwargs):
? ----
+ def load(cls, *args, **kwargs):
- for go in self._grid_obj_classes:
? ---
+ for go in cls._grid_obj_classes:
? ++
- if hasattr(go, 'is_mine') and go.is_mine(nc):
? ^^
+ if hasattr(go, 'is_mine') and go.is_mine(*args, **kwargs):
? ^^^^^^^^^^^^^^^
- return go(nc, *args, **kwargs)
? ----
+ return go(*args, **kwargs)
- |
6cd7e79fc32ebf75776ab0bcf367854d76dd5e03 | src/redditsubscraper/items.py | src/redditsubscraper/items.py |
import scrapy
class Post(scrapy.Item):
"""
A model representing a single Reddit post.
"""
id = scrapy.Field()
class Comment(scrapy.Item):
"""
A model representing a single Reddit comment
"""
id = scrapy.Field()
parent_id = scrapy.Field()
class RedditItemPipeline(object):
pass
|
import scrapy
class Post(scrapy.Item):
"""
A model representing a single Reddit post.
"""
"""An id encoded in base-36 without any prefixes."""
id = scrapy.Field()
class Comment(scrapy.Item):
"""
A model representing a single Reddit comment
"""
"""An id encoded in base-36 without any prefixes."""
id = scrapy.Field()
parent_id = scrapy.Field()
class RedditItemPipeline(object):
pass
| Add comments to item fields. | Add comments to item fields.
| Python | mit | rfkrocktk/subreddit-scraper |
import scrapy
class Post(scrapy.Item):
"""
A model representing a single Reddit post.
"""
+
+ """An id encoded in base-36 without any prefixes."""
id = scrapy.Field()
class Comment(scrapy.Item):
"""
A model representing a single Reddit comment
"""
+
+ """An id encoded in base-36 without any prefixes."""
id = scrapy.Field()
+
parent_id = scrapy.Field()
class RedditItemPipeline(object):
pass
| Add comments to item fields. | ## Code Before:
import scrapy
class Post(scrapy.Item):
"""
A model representing a single Reddit post.
"""
id = scrapy.Field()
class Comment(scrapy.Item):
"""
A model representing a single Reddit comment
"""
id = scrapy.Field()
parent_id = scrapy.Field()
class RedditItemPipeline(object):
pass
## Instruction:
Add comments to item fields.
## Code After:
import scrapy
class Post(scrapy.Item):
"""
A model representing a single Reddit post.
"""
"""An id encoded in base-36 without any prefixes."""
id = scrapy.Field()
class Comment(scrapy.Item):
"""
A model representing a single Reddit comment
"""
"""An id encoded in base-36 without any prefixes."""
id = scrapy.Field()
parent_id = scrapy.Field()
class RedditItemPipeline(object):
pass
|
import scrapy
class Post(scrapy.Item):
"""
A model representing a single Reddit post.
"""
+
+ """An id encoded in base-36 without any prefixes."""
id = scrapy.Field()
class Comment(scrapy.Item):
"""
A model representing a single Reddit comment
"""
+
+ """An id encoded in base-36 without any prefixes."""
id = scrapy.Field()
+
parent_id = scrapy.Field()
class RedditItemPipeline(object):
pass |
ce2e5b0dc3ddafe931a902cb7aa24c3adbc246b7 | fireplace/cards/wog/neutral_legendary.py | fireplace/cards/wog/neutral_legendary.py | from ..utils import *
##
# Minions
| from ..utils import *
##
# Minions
class OG_122:
"Mukla, Tyrant of the Vale"
play = Give(CONTROLLER, "EX1_014t") * 2
class OG_318:
"Hogger, Doom of Elwynn"
events = SELF_DAMAGE.on(Summon(CONTROLLER, "OG_318t"))
class OG_338:
"Nat, the Darkfisher"
events = BeginTurn(OPPONENT).on(COINFLIP & Draw(OPPONENT))
| Implement corrupted Mukla, Hogger and Nat | Implement corrupted Mukla, Hogger and Nat
| Python | agpl-3.0 | beheh/fireplace,NightKev/fireplace,jleclanche/fireplace | from ..utils import *
##
# Minions
+ class OG_122:
+ "Mukla, Tyrant of the Vale"
+ play = Give(CONTROLLER, "EX1_014t") * 2
+
+
+ class OG_318:
+ "Hogger, Doom of Elwynn"
+ events = SELF_DAMAGE.on(Summon(CONTROLLER, "OG_318t"))
+
+
+ class OG_338:
+ "Nat, the Darkfisher"
+ events = BeginTurn(OPPONENT).on(COINFLIP & Draw(OPPONENT))
+ | Implement corrupted Mukla, Hogger and Nat | ## Code Before:
from ..utils import *
##
# Minions
## Instruction:
Implement corrupted Mukla, Hogger and Nat
## Code After:
from ..utils import *
##
# Minions
class OG_122:
"Mukla, Tyrant of the Vale"
play = Give(CONTROLLER, "EX1_014t") * 2
class OG_318:
"Hogger, Doom of Elwynn"
events = SELF_DAMAGE.on(Summon(CONTROLLER, "OG_318t"))
class OG_338:
"Nat, the Darkfisher"
events = BeginTurn(OPPONENT).on(COINFLIP & Draw(OPPONENT))
| from ..utils import *
##
# Minions
+
+ class OG_122:
+ "Mukla, Tyrant of the Vale"
+ play = Give(CONTROLLER, "EX1_014t") * 2
+
+
+ class OG_318:
+ "Hogger, Doom of Elwynn"
+ events = SELF_DAMAGE.on(Summon(CONTROLLER, "OG_318t"))
+
+
+ class OG_338:
+ "Nat, the Darkfisher"
+ events = BeginTurn(OPPONENT).on(COINFLIP & Draw(OPPONENT)) |
91c6c00a16252b2a43a1017ee17b7f6f0302e4be | controlbeast/__init__.py | controlbeast/__init__.py |
VERSION = (0, 1, 0, 'alpha', 0)
COPYRIGHT = ('2013', 'the ControlBeast team')
def get_version(*args, **kwargs):
"""
Returns PEP 386 compliant version number for the Pytain package
"""
from controlbeast.utils.version import get_version
return get_version(*args, **kwargs) |
VERSION = (0, 1, 0, 'alpha', 0)
COPYRIGHT = ('2013', 'the ControlBeast team')
DEFAULTS = {
'scm': 'Git'
}
def get_conf(key):
"""
Get a global configuration value by its key
:param key: string identifying the requested configuration value
:returns the requested configuration value or None
"""
if key in DEFAULTS:
return DEFAULTS[key]
else:
return None
def get_version(*args, **kwargs):
"""
Returns PEP 386 compliant version number for the Pytain package
"""
from controlbeast.utils.version import get_version
return get_version(*args, **kwargs) | Implement simple mechanism for configuration handling | Implement simple mechanism for configuration handling
| Python | isc | daemotron/controlbeast,daemotron/controlbeast |
VERSION = (0, 1, 0, 'alpha', 0)
COPYRIGHT = ('2013', 'the ControlBeast team')
+
+ DEFAULTS = {
+ 'scm': 'Git'
+ }
+
+
+ def get_conf(key):
+ """
+ Get a global configuration value by its key
+
+ :param key: string identifying the requested configuration value
+ :returns the requested configuration value or None
+ """
+ if key in DEFAULTS:
+ return DEFAULTS[key]
+ else:
+ return None
+
def get_version(*args, **kwargs):
"""
Returns PEP 386 compliant version number for the Pytain package
"""
from controlbeast.utils.version import get_version
return get_version(*args, **kwargs) | Implement simple mechanism for configuration handling | ## Code Before:
VERSION = (0, 1, 0, 'alpha', 0)
COPYRIGHT = ('2013', 'the ControlBeast team')
def get_version(*args, **kwargs):
"""
Returns PEP 386 compliant version number for the Pytain package
"""
from controlbeast.utils.version import get_version
return get_version(*args, **kwargs)
## Instruction:
Implement simple mechanism for configuration handling
## Code After:
VERSION = (0, 1, 0, 'alpha', 0)
COPYRIGHT = ('2013', 'the ControlBeast team')
DEFAULTS = {
'scm': 'Git'
}
def get_conf(key):
"""
Get a global configuration value by its key
:param key: string identifying the requested configuration value
:returns the requested configuration value or None
"""
if key in DEFAULTS:
return DEFAULTS[key]
else:
return None
def get_version(*args, **kwargs):
"""
Returns PEP 386 compliant version number for the Pytain package
"""
from controlbeast.utils.version import get_version
return get_version(*args, **kwargs) |
VERSION = (0, 1, 0, 'alpha', 0)
COPYRIGHT = ('2013', 'the ControlBeast team')
+
+ DEFAULTS = {
+ 'scm': 'Git'
+ }
+
+
+ def get_conf(key):
+ """
+ Get a global configuration value by its key
+
+ :param key: string identifying the requested configuration value
+ :returns the requested configuration value or None
+ """
+ if key in DEFAULTS:
+ return DEFAULTS[key]
+ else:
+ return None
+
def get_version(*args, **kwargs):
"""
Returns PEP 386 compliant version number for the Pytain package
"""
from controlbeast.utils.version import get_version
return get_version(*args, **kwargs) |
921df8b8309b40e7a69c2fa0434a51c1cce82c28 | examples/rpc_pipeline.py | examples/rpc_pipeline.py | import asyncio
import aiozmq.rpc
class Handler(aiozmq.rpc.AttrHandler):
@aiozmq.rpc.method
def handle_some_event(self, a: int, b: int):
pass
@asyncio.coroutine
def go():
listener = yield from aiozmq.rpc.serve_pipeline(
Handler(), bind='tcp://*:*')
listener_addr = next(iter(listener.transport.bindings()))
notifier = yield from aiozmq.rpc.connect_pipeline(
connect=listener_addr)
yield from notifier.notify.handle_some_event(1, 2)
listener.close()
notifier.close()
def main():
asyncio.get_event_loop().run_until_complete(go())
print("DONE")
if __name__ == '__main__':
main()
| import asyncio
import aiozmq.rpc
from itertools import count
class Handler(aiozmq.rpc.AttrHandler):
def __init__(self):
self.connected = False
@aiozmq.rpc.method
def remote_func(self, step, a: int, b: int):
self.connected = True
print("HANDLER", step, a, b)
@asyncio.coroutine
def go():
handler = Handler()
listener = yield from aiozmq.rpc.serve_pipeline(
handler, bind='tcp://*:*')
listener_addr = next(iter(listener.transport.bindings()))
notifier = yield from aiozmq.rpc.connect_pipeline(
connect=listener_addr)
for step in count(0):
yield from notifier.notify.remote_func(step, 1, 2)
if handler.connected:
break
else:
yield from asyncio.sleep(0.01)
listener.close()
yield from listener.wait_closed()
notifier.close()
yield from notifier.wait_closed()
def main():
asyncio.get_event_loop().run_until_complete(go())
print("DONE")
if __name__ == '__main__':
main()
| Make rpc pipeine example stable | Make rpc pipeine example stable
| Python | bsd-2-clause | claws/aiozmq,MetaMemoryT/aiozmq,asteven/aiozmq,aio-libs/aiozmq | import asyncio
import aiozmq.rpc
+ from itertools import count
class Handler(aiozmq.rpc.AttrHandler):
+ def __init__(self):
+ self.connected = False
+
@aiozmq.rpc.method
- def handle_some_event(self, a: int, b: int):
- pass
+ def remote_func(self, step, a: int, b: int):
+ self.connected = True
+ print("HANDLER", step, a, b)
@asyncio.coroutine
def go():
+ handler = Handler()
listener = yield from aiozmq.rpc.serve_pipeline(
- Handler(), bind='tcp://*:*')
+ handler, bind='tcp://*:*')
listener_addr = next(iter(listener.transport.bindings()))
notifier = yield from aiozmq.rpc.connect_pipeline(
connect=listener_addr)
- yield from notifier.notify.handle_some_event(1, 2)
+ for step in count(0):
+ yield from notifier.notify.remote_func(step, 1, 2)
+ if handler.connected:
+ break
+ else:
+ yield from asyncio.sleep(0.01)
listener.close()
+ yield from listener.wait_closed()
notifier.close()
+ yield from notifier.wait_closed()
def main():
asyncio.get_event_loop().run_until_complete(go())
print("DONE")
if __name__ == '__main__':
main()
| Make rpc pipeine example stable | ## Code Before:
import asyncio
import aiozmq.rpc
class Handler(aiozmq.rpc.AttrHandler):
@aiozmq.rpc.method
def handle_some_event(self, a: int, b: int):
pass
@asyncio.coroutine
def go():
listener = yield from aiozmq.rpc.serve_pipeline(
Handler(), bind='tcp://*:*')
listener_addr = next(iter(listener.transport.bindings()))
notifier = yield from aiozmq.rpc.connect_pipeline(
connect=listener_addr)
yield from notifier.notify.handle_some_event(1, 2)
listener.close()
notifier.close()
def main():
asyncio.get_event_loop().run_until_complete(go())
print("DONE")
if __name__ == '__main__':
main()
## Instruction:
Make rpc pipeine example stable
## Code After:
import asyncio
import aiozmq.rpc
from itertools import count
class Handler(aiozmq.rpc.AttrHandler):
def __init__(self):
self.connected = False
@aiozmq.rpc.method
def remote_func(self, step, a: int, b: int):
self.connected = True
print("HANDLER", step, a, b)
@asyncio.coroutine
def go():
handler = Handler()
listener = yield from aiozmq.rpc.serve_pipeline(
handler, bind='tcp://*:*')
listener_addr = next(iter(listener.transport.bindings()))
notifier = yield from aiozmq.rpc.connect_pipeline(
connect=listener_addr)
for step in count(0):
yield from notifier.notify.remote_func(step, 1, 2)
if handler.connected:
break
else:
yield from asyncio.sleep(0.01)
listener.close()
yield from listener.wait_closed()
notifier.close()
yield from notifier.wait_closed()
def main():
asyncio.get_event_loop().run_until_complete(go())
print("DONE")
if __name__ == '__main__':
main()
| import asyncio
import aiozmq.rpc
+ from itertools import count
class Handler(aiozmq.rpc.AttrHandler):
+ def __init__(self):
+ self.connected = False
+
@aiozmq.rpc.method
- def handle_some_event(self, a: int, b: int):
- pass
+ def remote_func(self, step, a: int, b: int):
+ self.connected = True
+ print("HANDLER", step, a, b)
@asyncio.coroutine
def go():
+ handler = Handler()
listener = yield from aiozmq.rpc.serve_pipeline(
- Handler(), bind='tcp://*:*')
? ^ --
+ handler, bind='tcp://*:*')
? ^
listener_addr = next(iter(listener.transport.bindings()))
notifier = yield from aiozmq.rpc.connect_pipeline(
connect=listener_addr)
- yield from notifier.notify.handle_some_event(1, 2)
+ for step in count(0):
+ yield from notifier.notify.remote_func(step, 1, 2)
+ if handler.connected:
+ break
+ else:
+ yield from asyncio.sleep(0.01)
listener.close()
+ yield from listener.wait_closed()
notifier.close()
+ yield from notifier.wait_closed()
def main():
asyncio.get_event_loop().run_until_complete(go())
print("DONE")
if __name__ == '__main__':
main() |
8297ca0006362d6a99fef6d8ad94c9fc094cc3ee | oscar/templatetags/form_tags.py | oscar/templatetags/form_tags.py | from django import template
register = template.Library()
@register.tag
def annotate_form_field(parser, token):
"""
Set an attribute on a form field with the widget type
This means templates can use the widget type to render things differently
if they want to. Django doesn't make this available by default.
"""
args = token.split_contents()
if len(args) < 2:
raise template.TemplateSyntaxError(
"annotate_form_field tag requires a form field to be passed")
return FormFieldNode(args[1])
class FormFieldNode(template.Node):
def __init__(self, field_str):
self.field = template.Variable(field_str)
def render(self, context):
field = self.field.resolve(context)
field.widget_type = field.field.widget.__class__.__name__
return ''
| from django import template
register = template.Library()
@register.tag
def annotate_form_field(parser, token):
"""
Set an attribute on a form field with the widget type
This means templates can use the widget type to render things differently
if they want to. Django doesn't make this available by default.
"""
args = token.split_contents()
if len(args) < 2:
raise template.TemplateSyntaxError(
"annotate_form_field tag requires a form field to be passed")
return FormFieldNode(args[1])
class FormFieldNode(template.Node):
def __init__(self, field_str):
self.field = template.Variable(field_str)
def render(self, context):
field = self.field.resolve(context)
if hasattr(field, 'field'):
field.widget_type = field.field.widget.__class__.__name__
return ''
| Adjust form templatetag to handle missing field var | Adjust form templatetag to handle missing field var
When a non-existant field gets passed, the templatetag was raising an
unseemly AttributeError. This change checks to see if the passed var is
actually a form field to avoid said error.
| Python | bsd-3-clause | WillisXChen/django-oscar,spartonia/django-oscar,solarissmoke/django-oscar,ka7eh/django-oscar,manevant/django-oscar,ademuk/django-oscar,dongguangming/django-oscar,thechampanurag/django-oscar,elliotthill/django-oscar,vovanbo/django-oscar,jlmadurga/django-oscar,lijoantony/django-oscar,spartonia/django-oscar,WadeYuChen/django-oscar,michaelkuty/django-oscar,bnprk/django-oscar,makielab/django-oscar,mexeniz/django-oscar,machtfit/django-oscar,amirrpp/django-oscar,solarissmoke/django-oscar,adamend/django-oscar,taedori81/django-oscar,faratro/django-oscar,adamend/django-oscar,john-parton/django-oscar,WillisXChen/django-oscar,QLGu/django-oscar,taedori81/django-oscar,jinnykoo/wuyisj,lijoantony/django-oscar,eddiep1101/django-oscar,marcoantoniooliveira/labweb,DrOctogon/unwash_ecom,anentropic/django-oscar,Bogh/django-oscar,Jannes123/django-oscar,josesanch/django-oscar,okfish/django-oscar,makielab/django-oscar,bschuon/django-oscar,ahmetdaglarbas/e-commerce,binarydud/django-oscar,jinnykoo/wuyisj.com,WillisXChen/django-oscar,saadatqadri/django-oscar,adamend/django-oscar,QLGu/django-oscar,jmt4/django-oscar,rocopartners/django-oscar,itbabu/django-oscar,ahmetdaglarbas/e-commerce,kapt/django-oscar,jinnykoo/wuyisj,amirrpp/django-oscar,Jannes123/django-oscar,WadeYuChen/django-oscar,binarydud/django-oscar,WillisXChen/django-oscar,saadatqadri/django-oscar,nfletton/django-oscar,jinnykoo/wuyisj,manevant/django-oscar,anentropic/django-oscar,jlmadurga/django-oscar,bnprk/django-oscar,mexeniz/django-oscar,binarydud/django-oscar,django-oscar/django-oscar,michaelkuty/django-oscar,itbabu/django-oscar,spartonia/django-oscar,sasha0/django-oscar,rocopartners/django-oscar,bnprk/django-oscar,dongguangming/django-oscar,ka7eh/django-oscar,Idematica/django-oscar,faratro/django-oscar,amirrpp/django-oscar,lijoantony/django-oscar,ka7eh/django-oscar,Bogh/django-oscar,thechampanurag/django-oscar,Bogh/django-oscar,pasqualguerrero/django-oscar,ademuk/django-oscar,jinnykoo/wuyisj.com,manevant/django-oscar,saadatqadri/django-oscar,Jannes123/django-oscar,okfish/django-oscar,QLGu/django-oscar,django-oscar/django-oscar,elliotthill/django-oscar,nfletton/django-oscar,marcoantoniooliveira/labweb,sasha0/django-oscar,dongguangming/django-oscar,Jannes123/django-oscar,bschuon/django-oscar,monikasulik/django-oscar,nickpack/django-oscar,monikasulik/django-oscar,eddiep1101/django-oscar,rocopartners/django-oscar,ka7eh/django-oscar,WillisXChen/django-oscar,taedori81/django-oscar,marcoantoniooliveira/labweb,binarydud/django-oscar,jinnykoo/christmas,anentropic/django-oscar,sasha0/django-oscar,ahmetdaglarbas/e-commerce,MatthewWilkes/django-oscar,nfletton/django-oscar,MatthewWilkes/django-oscar,WillisXChen/django-oscar,bschuon/django-oscar,john-parton/django-oscar,kapari/django-oscar,ademuk/django-oscar,jlmadurga/django-oscar,nickpack/django-oscar,faratro/django-oscar,mexeniz/django-oscar,taedori81/django-oscar,jinnykoo/christmas,makielab/django-oscar,makielab/django-oscar,amirrpp/django-oscar,mexeniz/django-oscar,pdonadeo/django-oscar,pasqualguerrero/django-oscar,lijoantony/django-oscar,kapt/django-oscar,nickpack/django-oscar,vovanbo/django-oscar,sonofatailor/django-oscar,django-oscar/django-oscar,anentropic/django-oscar,Idematica/django-oscar,machtfit/django-oscar,pdonadeo/django-oscar,michaelkuty/django-oscar,MatthewWilkes/django-oscar,pdonadeo/django-oscar,Bogh/django-oscar,QLGu/django-oscar,DrOctogon/unwash_ecom,pasqualguerrero/django-oscar,marcoantoniooliveira/labweb,solarissmoke/django-oscar,kapt/django-oscar,Idematica/django-oscar,monikasulik/django-oscar,DrOctogon/unwash_ecom,jmt4/django-oscar,faratro/django-oscar,kapari/django-oscar,adamend/django-oscar,machtfit/django-oscar,eddiep1101/django-oscar,michaelkuty/django-oscar,sonofatailor/django-oscar,jlmadurga/django-oscar,elliotthill/django-oscar,ademuk/django-oscar,jmt4/django-oscar,bschuon/django-oscar,sonofatailor/django-oscar,itbabu/django-oscar,manevant/django-oscar,solarissmoke/django-oscar,okfish/django-oscar,sonofatailor/django-oscar,dongguangming/django-oscar,jinnykoo/christmas,john-parton/django-oscar,jinnykoo/wuyisj.com,jmt4/django-oscar,WadeYuChen/django-oscar,thechampanurag/django-oscar,pasqualguerrero/django-oscar,vovanbo/django-oscar,saadatqadri/django-oscar,josesanch/django-oscar,eddiep1101/django-oscar,django-oscar/django-oscar,jinnykoo/wuyisj.com,sasha0/django-oscar,nickpack/django-oscar,kapari/django-oscar,thechampanurag/django-oscar,nfletton/django-oscar,bnprk/django-oscar,ahmetdaglarbas/e-commerce,vovanbo/django-oscar,pdonadeo/django-oscar,john-parton/django-oscar,okfish/django-oscar,MatthewWilkes/django-oscar,WadeYuChen/django-oscar,itbabu/django-oscar,josesanch/django-oscar,jinnykoo/wuyisj,monikasulik/django-oscar,spartonia/django-oscar,rocopartners/django-oscar,kapari/django-oscar | from django import template
register = template.Library()
@register.tag
def annotate_form_field(parser, token):
"""
Set an attribute on a form field with the widget type
This means templates can use the widget type to render things differently
if they want to. Django doesn't make this available by default.
"""
args = token.split_contents()
if len(args) < 2:
raise template.TemplateSyntaxError(
"annotate_form_field tag requires a form field to be passed")
return FormFieldNode(args[1])
class FormFieldNode(template.Node):
def __init__(self, field_str):
self.field = template.Variable(field_str)
def render(self, context):
field = self.field.resolve(context)
+ if hasattr(field, 'field'):
- field.widget_type = field.field.widget.__class__.__name__
+ field.widget_type = field.field.widget.__class__.__name__
return ''
| Adjust form templatetag to handle missing field var | ## Code Before:
from django import template
register = template.Library()
@register.tag
def annotate_form_field(parser, token):
"""
Set an attribute on a form field with the widget type
This means templates can use the widget type to render things differently
if they want to. Django doesn't make this available by default.
"""
args = token.split_contents()
if len(args) < 2:
raise template.TemplateSyntaxError(
"annotate_form_field tag requires a form field to be passed")
return FormFieldNode(args[1])
class FormFieldNode(template.Node):
def __init__(self, field_str):
self.field = template.Variable(field_str)
def render(self, context):
field = self.field.resolve(context)
field.widget_type = field.field.widget.__class__.__name__
return ''
## Instruction:
Adjust form templatetag to handle missing field var
## Code After:
from django import template
register = template.Library()
@register.tag
def annotate_form_field(parser, token):
"""
Set an attribute on a form field with the widget type
This means templates can use the widget type to render things differently
if they want to. Django doesn't make this available by default.
"""
args = token.split_contents()
if len(args) < 2:
raise template.TemplateSyntaxError(
"annotate_form_field tag requires a form field to be passed")
return FormFieldNode(args[1])
class FormFieldNode(template.Node):
def __init__(self, field_str):
self.field = template.Variable(field_str)
def render(self, context):
field = self.field.resolve(context)
if hasattr(field, 'field'):
field.widget_type = field.field.widget.__class__.__name__
return ''
| from django import template
register = template.Library()
@register.tag
def annotate_form_field(parser, token):
"""
Set an attribute on a form field with the widget type
This means templates can use the widget type to render things differently
if they want to. Django doesn't make this available by default.
"""
args = token.split_contents()
if len(args) < 2:
raise template.TemplateSyntaxError(
"annotate_form_field tag requires a form field to be passed")
return FormFieldNode(args[1])
class FormFieldNode(template.Node):
def __init__(self, field_str):
self.field = template.Variable(field_str)
def render(self, context):
field = self.field.resolve(context)
+ if hasattr(field, 'field'):
- field.widget_type = field.field.widget.__class__.__name__
+ field.widget_type = field.field.widget.__class__.__name__
? ++++
return '' |
dd9f5980ded9b10210ea524169ef769a6eff3993 | utils/paginate.py | utils/paginate.py | import discord
import asyncio
from typing import List, Tuple
from discord.ext.commands import Context
EMOJI_MAP = {"back": "⬅️", "forward": "➡️"}
async def paginate(ctx: Context, embeds: List[discord.Embed], timeout=30.0) -> None:
msg = ctx.message
emojis = EMOJI_MAP.values()
for reaction in emojis:
await msg.add_react(reaction)
current_index = 0
while True:
try:
reaction, _ = await ctx.bot.wait_for(
"reaction_add",
timeout=timeout,
check=lambda reaction, user: (
user == ctx.author and reaction.emoji in emojis and reaction.message.id == msg.id
),
)
except asyncio.TimeoutError:
return await msg.clear_reactions()
if (reaction.emoji == EMOJI_MAP["back"]):
current_index -= 1
if (reaction.emoji == EMOJI_MAP["forward"]):
current_index += 1
await msg.edit(embed=embeds[current_index])
await msg.remove_reaction(reaction.emoji, ctx.author)
| import discord
import asyncio
from typing import List
from discord.ext.commands import Context
EMOJI_MAP = {"back": "⬅️", "forward": "➡️"}
async def paginate(ctx: Context, embeds: List[discord.Embed], timeout=30.0) -> None:
msg = ctx.message
emojis = EMOJI_MAP.values()
for emoji in emojis:
await msg.add_reaction(emoji)
current_index = 0
while True:
try:
reaction, _ = await ctx.bot.wait_for(
"reaction_add",
timeout=timeout,
check=lambda reaction, user: (
user == ctx.author and reaction.emoji in emojis and reaction.message.id == msg.id
),
)
except asyncio.TimeoutError:
return await msg.clear_reactions()
if reaction.emoji == EMOJI_MAP["back"]:
current_index = current_index - 1 if current_index > 0 else 0
if reaction.emoji == EMOJI_MAP["forward"]:
current_index = current_index + 1 if current_index < len(embeds) - 1 else len(embeds) - 1
await msg.edit(embed=embeds[current_index])
await msg.remove_reaction(reaction.emoji, ctx.author)
| Fix pagination logic & typo | Fix pagination logic & typo
| Python | mit | Naught0/qtbot | import discord
import asyncio
- from typing import List, Tuple
+ from typing import List
from discord.ext.commands import Context
EMOJI_MAP = {"back": "⬅️", "forward": "➡️"}
+
+
async def paginate(ctx: Context, embeds: List[discord.Embed], timeout=30.0) -> None:
msg = ctx.message
emojis = EMOJI_MAP.values()
- for reaction in emojis:
+ for emoji in emojis:
- await msg.add_react(reaction)
+ await msg.add_reaction(emoji)
current_index = 0
while True:
try:
reaction, _ = await ctx.bot.wait_for(
"reaction_add",
timeout=timeout,
check=lambda reaction, user: (
user == ctx.author and reaction.emoji in emojis and reaction.message.id == msg.id
),
)
except asyncio.TimeoutError:
return await msg.clear_reactions()
- if (reaction.emoji == EMOJI_MAP["back"]):
+ if reaction.emoji == EMOJI_MAP["back"]:
- current_index -= 1
+ current_index = current_index - 1 if current_index > 0 else 0
- if (reaction.emoji == EMOJI_MAP["forward"]):
+ if reaction.emoji == EMOJI_MAP["forward"]:
- current_index += 1
+ current_index = current_index + 1 if current_index < len(embeds) - 1 else len(embeds) - 1
await msg.edit(embed=embeds[current_index])
await msg.remove_reaction(reaction.emoji, ctx.author)
| Fix pagination logic & typo | ## Code Before:
import discord
import asyncio
from typing import List, Tuple
from discord.ext.commands import Context
EMOJI_MAP = {"back": "⬅️", "forward": "➡️"}
async def paginate(ctx: Context, embeds: List[discord.Embed], timeout=30.0) -> None:
msg = ctx.message
emojis = EMOJI_MAP.values()
for reaction in emojis:
await msg.add_react(reaction)
current_index = 0
while True:
try:
reaction, _ = await ctx.bot.wait_for(
"reaction_add",
timeout=timeout,
check=lambda reaction, user: (
user == ctx.author and reaction.emoji in emojis and reaction.message.id == msg.id
),
)
except asyncio.TimeoutError:
return await msg.clear_reactions()
if (reaction.emoji == EMOJI_MAP["back"]):
current_index -= 1
if (reaction.emoji == EMOJI_MAP["forward"]):
current_index += 1
await msg.edit(embed=embeds[current_index])
await msg.remove_reaction(reaction.emoji, ctx.author)
## Instruction:
Fix pagination logic & typo
## Code After:
import discord
import asyncio
from typing import List
from discord.ext.commands import Context
EMOJI_MAP = {"back": "⬅️", "forward": "➡️"}
async def paginate(ctx: Context, embeds: List[discord.Embed], timeout=30.0) -> None:
msg = ctx.message
emojis = EMOJI_MAP.values()
for emoji in emojis:
await msg.add_reaction(emoji)
current_index = 0
while True:
try:
reaction, _ = await ctx.bot.wait_for(
"reaction_add",
timeout=timeout,
check=lambda reaction, user: (
user == ctx.author and reaction.emoji in emojis and reaction.message.id == msg.id
),
)
except asyncio.TimeoutError:
return await msg.clear_reactions()
if reaction.emoji == EMOJI_MAP["back"]:
current_index = current_index - 1 if current_index > 0 else 0
if reaction.emoji == EMOJI_MAP["forward"]:
current_index = current_index + 1 if current_index < len(embeds) - 1 else len(embeds) - 1
await msg.edit(embed=embeds[current_index])
await msg.remove_reaction(reaction.emoji, ctx.author)
| import discord
import asyncio
- from typing import List, Tuple
? -------
+ from typing import List
from discord.ext.commands import Context
EMOJI_MAP = {"back": "⬅️", "forward": "➡️"}
+
+
async def paginate(ctx: Context, embeds: List[discord.Embed], timeout=30.0) -> None:
msg = ctx.message
emojis = EMOJI_MAP.values()
- for reaction in emojis:
? - ^^^ --
+ for emoji in emojis:
? ^^^
- await msg.add_react(reaction)
? ------
+ await msg.add_reaction(emoji)
? ++++++
current_index = 0
while True:
try:
reaction, _ = await ctx.bot.wait_for(
"reaction_add",
timeout=timeout,
check=lambda reaction, user: (
user == ctx.author and reaction.emoji in emojis and reaction.message.id == msg.id
),
)
except asyncio.TimeoutError:
return await msg.clear_reactions()
- if (reaction.emoji == EMOJI_MAP["back"]):
? - -
+ if reaction.emoji == EMOJI_MAP["back"]:
- current_index -= 1
+ current_index = current_index - 1 if current_index > 0 else 0
- if (reaction.emoji == EMOJI_MAP["forward"]):
? - -
+ if reaction.emoji == EMOJI_MAP["forward"]:
- current_index += 1
+ current_index = current_index + 1 if current_index < len(embeds) - 1 else len(embeds) - 1
await msg.edit(embed=embeds[current_index])
await msg.remove_reaction(reaction.emoji, ctx.author) |
b771fd2a463266e1c80b1b4cccfe78d822c391a2 | byceps/blueprints/admin/shop/order/forms.py | byceps/blueprints/admin/shop/order/forms.py |
from flask_babel import lazy_gettext
from wtforms import BooleanField, RadioField, StringField, TextAreaField
from wtforms.validators import InputRequired, Length
from .....services.shop.order import service as order_service
from .....services.shop.order.transfer.order import PAYMENT_METHODS
from .....util.l10n import LocalizedForm
class AddNoteForm(LocalizedForm):
text = TextAreaField(lazy_gettext('Text'), validators=[InputRequired()])
class CancelForm(LocalizedForm):
reason = TextAreaField(
lazy_gettext('Reason'),
validators=[InputRequired(), Length(max=1000)],
)
send_email = BooleanField(
lazy_gettext('Inform orderer via email of cancelation.')
)
def _get_payment_method_choices():
return [
(pm, order_service.find_payment_method_label(pm) or pm)
for pm in PAYMENT_METHODS
]
class MarkAsPaidForm(LocalizedForm):
payment_method = RadioField(
lazy_gettext('Payment type'),
choices=_get_payment_method_choices(),
default='bank_transfer',
validators=[InputRequired()],
)
class OrderNumberSequenceCreateForm(LocalizedForm):
prefix = StringField(
lazy_gettext('Static prefix'), validators=[InputRequired()]
)
|
from flask_babel import lazy_gettext
from wtforms import BooleanField, RadioField, StringField, TextAreaField
from wtforms.validators import InputRequired, Length
from .....services.shop.order import service as order_service
from .....services.shop.order.transfer.order import PAYMENT_METHODS
from .....util.l10n import LocalizedForm
class AddNoteForm(LocalizedForm):
text = TextAreaField(lazy_gettext('Text'), validators=[InputRequired()])
class CancelForm(LocalizedForm):
reason = TextAreaField(
lazy_gettext('Reason'),
validators=[InputRequired(), Length(max=1000)],
)
send_email = BooleanField(
lazy_gettext('Inform orderer via email of cancelation.')
)
def _get_payment_method_choices():
choices = [
(pm, order_service.find_payment_method_label(pm) or pm)
for pm in PAYMENT_METHODS
]
choices.sort()
return choices
class MarkAsPaidForm(LocalizedForm):
payment_method = RadioField(
lazy_gettext('Payment type'),
choices=_get_payment_method_choices(),
default='bank_transfer',
validators=[InputRequired()],
)
class OrderNumberSequenceCreateForm(LocalizedForm):
prefix = StringField(
lazy_gettext('Static prefix'), validators=[InputRequired()]
)
| Stabilize order of payment methods in mark-as-paid form | Stabilize order of payment methods in mark-as-paid form
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps |
from flask_babel import lazy_gettext
from wtforms import BooleanField, RadioField, StringField, TextAreaField
from wtforms.validators import InputRequired, Length
from .....services.shop.order import service as order_service
from .....services.shop.order.transfer.order import PAYMENT_METHODS
from .....util.l10n import LocalizedForm
class AddNoteForm(LocalizedForm):
text = TextAreaField(lazy_gettext('Text'), validators=[InputRequired()])
class CancelForm(LocalizedForm):
reason = TextAreaField(
lazy_gettext('Reason'),
validators=[InputRequired(), Length(max=1000)],
)
send_email = BooleanField(
lazy_gettext('Inform orderer via email of cancelation.')
)
def _get_payment_method_choices():
- return [
+ choices = [
(pm, order_service.find_payment_method_label(pm) or pm)
for pm in PAYMENT_METHODS
]
+ choices.sort()
+ return choices
class MarkAsPaidForm(LocalizedForm):
payment_method = RadioField(
lazy_gettext('Payment type'),
choices=_get_payment_method_choices(),
default='bank_transfer',
validators=[InputRequired()],
)
class OrderNumberSequenceCreateForm(LocalizedForm):
prefix = StringField(
lazy_gettext('Static prefix'), validators=[InputRequired()]
)
| Stabilize order of payment methods in mark-as-paid form | ## Code Before:
from flask_babel import lazy_gettext
from wtforms import BooleanField, RadioField, StringField, TextAreaField
from wtforms.validators import InputRequired, Length
from .....services.shop.order import service as order_service
from .....services.shop.order.transfer.order import PAYMENT_METHODS
from .....util.l10n import LocalizedForm
class AddNoteForm(LocalizedForm):
text = TextAreaField(lazy_gettext('Text'), validators=[InputRequired()])
class CancelForm(LocalizedForm):
reason = TextAreaField(
lazy_gettext('Reason'),
validators=[InputRequired(), Length(max=1000)],
)
send_email = BooleanField(
lazy_gettext('Inform orderer via email of cancelation.')
)
def _get_payment_method_choices():
return [
(pm, order_service.find_payment_method_label(pm) or pm)
for pm in PAYMENT_METHODS
]
class MarkAsPaidForm(LocalizedForm):
payment_method = RadioField(
lazy_gettext('Payment type'),
choices=_get_payment_method_choices(),
default='bank_transfer',
validators=[InputRequired()],
)
class OrderNumberSequenceCreateForm(LocalizedForm):
prefix = StringField(
lazy_gettext('Static prefix'), validators=[InputRequired()]
)
## Instruction:
Stabilize order of payment methods in mark-as-paid form
## Code After:
from flask_babel import lazy_gettext
from wtforms import BooleanField, RadioField, StringField, TextAreaField
from wtforms.validators import InputRequired, Length
from .....services.shop.order import service as order_service
from .....services.shop.order.transfer.order import PAYMENT_METHODS
from .....util.l10n import LocalizedForm
class AddNoteForm(LocalizedForm):
text = TextAreaField(lazy_gettext('Text'), validators=[InputRequired()])
class CancelForm(LocalizedForm):
reason = TextAreaField(
lazy_gettext('Reason'),
validators=[InputRequired(), Length(max=1000)],
)
send_email = BooleanField(
lazy_gettext('Inform orderer via email of cancelation.')
)
def _get_payment_method_choices():
choices = [
(pm, order_service.find_payment_method_label(pm) or pm)
for pm in PAYMENT_METHODS
]
choices.sort()
return choices
class MarkAsPaidForm(LocalizedForm):
payment_method = RadioField(
lazy_gettext('Payment type'),
choices=_get_payment_method_choices(),
default='bank_transfer',
validators=[InputRequired()],
)
class OrderNumberSequenceCreateForm(LocalizedForm):
prefix = StringField(
lazy_gettext('Static prefix'), validators=[InputRequired()]
)
|
from flask_babel import lazy_gettext
from wtforms import BooleanField, RadioField, StringField, TextAreaField
from wtforms.validators import InputRequired, Length
from .....services.shop.order import service as order_service
from .....services.shop.order.transfer.order import PAYMENT_METHODS
from .....util.l10n import LocalizedForm
class AddNoteForm(LocalizedForm):
text = TextAreaField(lazy_gettext('Text'), validators=[InputRequired()])
class CancelForm(LocalizedForm):
reason = TextAreaField(
lazy_gettext('Reason'),
validators=[InputRequired(), Length(max=1000)],
)
send_email = BooleanField(
lazy_gettext('Inform orderer via email of cancelation.')
)
def _get_payment_method_choices():
- return [
+ choices = [
(pm, order_service.find_payment_method_label(pm) or pm)
for pm in PAYMENT_METHODS
]
+ choices.sort()
+ return choices
class MarkAsPaidForm(LocalizedForm):
payment_method = RadioField(
lazy_gettext('Payment type'),
choices=_get_payment_method_choices(),
default='bank_transfer',
validators=[InputRequired()],
)
class OrderNumberSequenceCreateForm(LocalizedForm):
prefix = StringField(
lazy_gettext('Static prefix'), validators=[InputRequired()]
) |
5bbdfb6d38878e2e1688fe37415662ec0dc176ee | sphinxcontrib/openstreetmap.py | sphinxcontrib/openstreetmap.py | from docutils import nodes
from docutils.parsers.rst import directives
from sphinx.util.compat import Directive
class openstreetmap(nodes.General, nodes.Element):
pass
class OpenStreetMapDirective(Directive):
"""Directive for embedding OpenStreetMap"""
has_content = False
option_spec = {
'id': directives.unchanged,
'label': directives.unchanged,
'marker': directives.unchanged,
}
def run(self):
node = openstreetmap()
return [node]
def visit_openstreetmap_node(self, node):
self.body.append("<div id='openstreetmap' style='color:red'>OpenStreetMap directive</div>")
def depart_openstreetmap_node(self, node):
pass
def setup(app):
app.add_node(openstreetmap,
html=(visit_openstreetmap_node, depart_openstreetmap_node))
app.add_directive('openstreetmap', OpenStreetMapDirective)
| from docutils import nodes
from docutils.parsers.rst import directives
from sphinx.util.compat import Directive
class openstreetmap(nodes.General, nodes.Element):
pass
class OpenStreetMapDirective(Directive):
"""Directive for embedding OpenStreetMap"""
has_content = False
option_spec = {
'id': directives.unchanged,
'label': directives.unchanged,
'marker': directives.unchanged,
}
def run(self):
node = openstreetmap()
if 'id' in self.options:
node['id'] = self.options['id']
else:
msg = ('openstreetmap directive needs uniqueue id for map data')
return [document.reporter.warning(msg, line=self.lineno)]
return [node]
def visit_openstreetmap_node(self, node):
self.body.append("<div id='openstreetmap' style='color:red'>OpenStreetMap directive</div>")
def depart_openstreetmap_node(self, node):
pass
def setup(app):
app.add_node(openstreetmap,
html=(visit_openstreetmap_node, depart_openstreetmap_node))
app.add_directive('openstreetmap', OpenStreetMapDirective)
| Check whether required id parameter is specified | Check whether required id parameter is specified
| Python | bsd-2-clause | kenhys/sphinxcontrib-openstreetmap,kenhys/sphinxcontrib-openstreetmap | from docutils import nodes
from docutils.parsers.rst import directives
from sphinx.util.compat import Directive
class openstreetmap(nodes.General, nodes.Element):
pass
class OpenStreetMapDirective(Directive):
"""Directive for embedding OpenStreetMap"""
has_content = False
option_spec = {
'id': directives.unchanged,
'label': directives.unchanged,
'marker': directives.unchanged,
}
def run(self):
node = openstreetmap()
+ if 'id' in self.options:
+ node['id'] = self.options['id']
+ else:
+ msg = ('openstreetmap directive needs uniqueue id for map data')
+ return [document.reporter.warning(msg, line=self.lineno)]
return [node]
def visit_openstreetmap_node(self, node):
self.body.append("<div id='openstreetmap' style='color:red'>OpenStreetMap directive</div>")
def depart_openstreetmap_node(self, node):
pass
def setup(app):
app.add_node(openstreetmap,
html=(visit_openstreetmap_node, depart_openstreetmap_node))
app.add_directive('openstreetmap', OpenStreetMapDirective)
| Check whether required id parameter is specified | ## Code Before:
from docutils import nodes
from docutils.parsers.rst import directives
from sphinx.util.compat import Directive
class openstreetmap(nodes.General, nodes.Element):
pass
class OpenStreetMapDirective(Directive):
"""Directive for embedding OpenStreetMap"""
has_content = False
option_spec = {
'id': directives.unchanged,
'label': directives.unchanged,
'marker': directives.unchanged,
}
def run(self):
node = openstreetmap()
return [node]
def visit_openstreetmap_node(self, node):
self.body.append("<div id='openstreetmap' style='color:red'>OpenStreetMap directive</div>")
def depart_openstreetmap_node(self, node):
pass
def setup(app):
app.add_node(openstreetmap,
html=(visit_openstreetmap_node, depart_openstreetmap_node))
app.add_directive('openstreetmap', OpenStreetMapDirective)
## Instruction:
Check whether required id parameter is specified
## Code After:
from docutils import nodes
from docutils.parsers.rst import directives
from sphinx.util.compat import Directive
class openstreetmap(nodes.General, nodes.Element):
pass
class OpenStreetMapDirective(Directive):
"""Directive for embedding OpenStreetMap"""
has_content = False
option_spec = {
'id': directives.unchanged,
'label': directives.unchanged,
'marker': directives.unchanged,
}
def run(self):
node = openstreetmap()
if 'id' in self.options:
node['id'] = self.options['id']
else:
msg = ('openstreetmap directive needs uniqueue id for map data')
return [document.reporter.warning(msg, line=self.lineno)]
return [node]
def visit_openstreetmap_node(self, node):
self.body.append("<div id='openstreetmap' style='color:red'>OpenStreetMap directive</div>")
def depart_openstreetmap_node(self, node):
pass
def setup(app):
app.add_node(openstreetmap,
html=(visit_openstreetmap_node, depart_openstreetmap_node))
app.add_directive('openstreetmap', OpenStreetMapDirective)
| from docutils import nodes
from docutils.parsers.rst import directives
from sphinx.util.compat import Directive
class openstreetmap(nodes.General, nodes.Element):
pass
class OpenStreetMapDirective(Directive):
"""Directive for embedding OpenStreetMap"""
has_content = False
option_spec = {
'id': directives.unchanged,
'label': directives.unchanged,
'marker': directives.unchanged,
}
def run(self):
node = openstreetmap()
+ if 'id' in self.options:
+ node['id'] = self.options['id']
+ else:
+ msg = ('openstreetmap directive needs uniqueue id for map data')
+ return [document.reporter.warning(msg, line=self.lineno)]
return [node]
def visit_openstreetmap_node(self, node):
self.body.append("<div id='openstreetmap' style='color:red'>OpenStreetMap directive</div>")
def depart_openstreetmap_node(self, node):
pass
def setup(app):
app.add_node(openstreetmap,
html=(visit_openstreetmap_node, depart_openstreetmap_node))
app.add_directive('openstreetmap', OpenStreetMapDirective)
|
6557cbe8bee7ded848ba7c3928e2b4f82aedeea8 | linked-list/remove-k-from-list.py | linked-list/remove-k-from-list.py |
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
def remove_k_from_list(l, k):
fake_head = Node(None)
fake_head.next = l
current_node = fake_head
while current_node:
while current_node.next and current_node.next.value == k:
current_node.next = current_node.next.next
current_node = current_node.next
return fake_head.next
|
class Node(object): # define constructor
def __init__(self, value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self, head=None):
self.head = head
def add(self, new_node):
current_node = self.head
if self.head:
while current_node.next:
current_node = current_node.next
current_node.next = new_node # add to end of linked list
else:
self.head = new_node
def remove_k_from_list(l, k):
fake_head = Node(None)
fake_head.next = l
current_node = fake_head
while current_node:
while current_node.next and current_node.next.value == k:
current_node.next = current_node.next.next
current_node = current_node.next
return fake_head.next
| Add linked list class and add method | Add linked list class and add method
| Python | mit | derekmpham/interview-prep,derekmpham/interview-prep |
- class Node(object):
+ class Node(object): # define constructor
def __init__(self, value):
self.value = value
self.next = None
+
+ class LinkedList(object):
+ def __init__(self, head=None):
+ self.head = head
+
+ def add(self, new_node):
+ current_node = self.head
+ if self.head:
+ while current_node.next:
+ current_node = current_node.next
+ current_node.next = new_node # add to end of linked list
+ else:
+ self.head = new_node
def remove_k_from_list(l, k):
fake_head = Node(None)
fake_head.next = l
current_node = fake_head
while current_node:
while current_node.next and current_node.next.value == k:
current_node.next = current_node.next.next
current_node = current_node.next
return fake_head.next
| Add linked list class and add method | ## Code Before:
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
def remove_k_from_list(l, k):
fake_head = Node(None)
fake_head.next = l
current_node = fake_head
while current_node:
while current_node.next and current_node.next.value == k:
current_node.next = current_node.next.next
current_node = current_node.next
return fake_head.next
## Instruction:
Add linked list class and add method
## Code After:
class Node(object): # define constructor
def __init__(self, value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self, head=None):
self.head = head
def add(self, new_node):
current_node = self.head
if self.head:
while current_node.next:
current_node = current_node.next
current_node.next = new_node # add to end of linked list
else:
self.head = new_node
def remove_k_from_list(l, k):
fake_head = Node(None)
fake_head.next = l
current_node = fake_head
while current_node:
while current_node.next and current_node.next.value == k:
current_node.next = current_node.next.next
current_node = current_node.next
return fake_head.next
|
- class Node(object):
+ class Node(object): # define constructor
def __init__(self, value):
self.value = value
self.next = None
+
+ class LinkedList(object):
+ def __init__(self, head=None):
+ self.head = head
+
+ def add(self, new_node):
+ current_node = self.head
+ if self.head:
+ while current_node.next:
+ current_node = current_node.next
+ current_node.next = new_node # add to end of linked list
+ else:
+ self.head = new_node
def remove_k_from_list(l, k):
fake_head = Node(None)
fake_head.next = l
current_node = fake_head
while current_node:
while current_node.next and current_node.next.value == k:
current_node.next = current_node.next.next
current_node = current_node.next
return fake_head.next |
f0b188f398d82b000fdaa40e0aa776520a962a65 | integration_tests/testpyagglom.py | integration_tests/testpyagglom.py | import sys
import platform
import h5py
import numpy
segh5 = sys.argv[1]
predh5 = sys.argv[2]
classifier = sys.argv[3]
threshold = float(sys.argv[4])
from neuroproof import Agglomeration
# open as uint32 and float respectively
seg = numpy.array(h5py.File(segh5)['stack'], numpy.uint32)
pred = numpy.array(h5py.File(predh5)['volume/predictions'], numpy.float32)
pred = pred.transpose((2,1,0,3))
pred = pred.copy()
res = Agglomeration.agglomerate(seg, pred, classifier, threshold)
# The 'golden' results depend on std::unordered, and therefore
# the expected answer is different on Mac and Linux.
if platform.system() == "Darwin":
expected_unique = 239
else:
expected_unique = 233
result_unique = len(numpy.unique(res))
assert result_unique == expected_unique, \
"Expected {} unique labels (including 0) in the resulting segmentation, but got {}"\
.format(expected_unique, len(numpy.unique(res)))
print("SUCCESS")
| import sys
import platform
import h5py
import numpy
segh5 = sys.argv[1]
predh5 = sys.argv[2]
classifier = sys.argv[3]
threshold = float(sys.argv[4])
from neuroproof import Agglomeration
# open as uint32 and float respectively
seg = numpy.array(h5py.File(segh5)['stack'], numpy.uint32)
pred = numpy.array(h5py.File(predh5)['volume/predictions'], numpy.float32)
pred = pred.transpose((2,1,0,3))
pred = pred.copy()
res = Agglomeration.agglomerate(seg, pred, classifier, threshold)
# The 'golden' results depend on std::unordered, and therefore
# the expected answer is different on Mac and Linux.
if platform.system() == "Darwin":
expected_unique = [239]
else:
# Depending on which linux stdlib we use, we might get different results
expected_unique = [232, 233]
result_unique = len(numpy.unique(res))
assert result_unique in expected_unique, \
"Wrong number of unique labels in the segmentation. Expected one of {}, but got {}"\
.format(expected_unique, len(numpy.unique(res)))
print("SUCCESS")
| Allow multiple 'golden' results for agglomeration test on Linux | tests: Allow multiple 'golden' results for agglomeration test on Linux
| Python | bsd-3-clause | janelia-flyem/NeuroProof,janelia-flyem/NeuroProof,janelia-flyem/NeuroProof,janelia-flyem/NeuroProof | import sys
import platform
import h5py
import numpy
segh5 = sys.argv[1]
predh5 = sys.argv[2]
classifier = sys.argv[3]
threshold = float(sys.argv[4])
from neuroproof import Agglomeration
# open as uint32 and float respectively
seg = numpy.array(h5py.File(segh5)['stack'], numpy.uint32)
pred = numpy.array(h5py.File(predh5)['volume/predictions'], numpy.float32)
pred = pred.transpose((2,1,0,3))
pred = pred.copy()
res = Agglomeration.agglomerate(seg, pred, classifier, threshold)
# The 'golden' results depend on std::unordered, and therefore
# the expected answer is different on Mac and Linux.
if platform.system() == "Darwin":
- expected_unique = 239
+ expected_unique = [239]
else:
+ # Depending on which linux stdlib we use, we might get different results
- expected_unique = 233
+ expected_unique = [232, 233]
result_unique = len(numpy.unique(res))
- assert result_unique == expected_unique, \
+ assert result_unique in expected_unique, \
- "Expected {} unique labels (including 0) in the resulting segmentation, but got {}"\
+ "Wrong number of unique labels in the segmentation. Expected one of {}, but got {}"\
.format(expected_unique, len(numpy.unique(res)))
print("SUCCESS")
| Allow multiple 'golden' results for agglomeration test on Linux | ## Code Before:
import sys
import platform
import h5py
import numpy
segh5 = sys.argv[1]
predh5 = sys.argv[2]
classifier = sys.argv[3]
threshold = float(sys.argv[4])
from neuroproof import Agglomeration
# open as uint32 and float respectively
seg = numpy.array(h5py.File(segh5)['stack'], numpy.uint32)
pred = numpy.array(h5py.File(predh5)['volume/predictions'], numpy.float32)
pred = pred.transpose((2,1,0,3))
pred = pred.copy()
res = Agglomeration.agglomerate(seg, pred, classifier, threshold)
# The 'golden' results depend on std::unordered, and therefore
# the expected answer is different on Mac and Linux.
if platform.system() == "Darwin":
expected_unique = 239
else:
expected_unique = 233
result_unique = len(numpy.unique(res))
assert result_unique == expected_unique, \
"Expected {} unique labels (including 0) in the resulting segmentation, but got {}"\
.format(expected_unique, len(numpy.unique(res)))
print("SUCCESS")
## Instruction:
Allow multiple 'golden' results for agglomeration test on Linux
## Code After:
import sys
import platform
import h5py
import numpy
segh5 = sys.argv[1]
predh5 = sys.argv[2]
classifier = sys.argv[3]
threshold = float(sys.argv[4])
from neuroproof import Agglomeration
# open as uint32 and float respectively
seg = numpy.array(h5py.File(segh5)['stack'], numpy.uint32)
pred = numpy.array(h5py.File(predh5)['volume/predictions'], numpy.float32)
pred = pred.transpose((2,1,0,3))
pred = pred.copy()
res = Agglomeration.agglomerate(seg, pred, classifier, threshold)
# The 'golden' results depend on std::unordered, and therefore
# the expected answer is different on Mac and Linux.
if platform.system() == "Darwin":
expected_unique = [239]
else:
# Depending on which linux stdlib we use, we might get different results
expected_unique = [232, 233]
result_unique = len(numpy.unique(res))
assert result_unique in expected_unique, \
"Wrong number of unique labels in the segmentation. Expected one of {}, but got {}"\
.format(expected_unique, len(numpy.unique(res)))
print("SUCCESS")
| import sys
import platform
import h5py
import numpy
segh5 = sys.argv[1]
predh5 = sys.argv[2]
classifier = sys.argv[3]
threshold = float(sys.argv[4])
from neuroproof import Agglomeration
# open as uint32 and float respectively
seg = numpy.array(h5py.File(segh5)['stack'], numpy.uint32)
pred = numpy.array(h5py.File(predh5)['volume/predictions'], numpy.float32)
pred = pred.transpose((2,1,0,3))
pred = pred.copy()
res = Agglomeration.agglomerate(seg, pred, classifier, threshold)
# The 'golden' results depend on std::unordered, and therefore
# the expected answer is different on Mac and Linux.
if platform.system() == "Darwin":
- expected_unique = 239
+ expected_unique = [239]
? + +
else:
+ # Depending on which linux stdlib we use, we might get different results
- expected_unique = 233
+ expected_unique = [232, 233]
? ++++++ +
result_unique = len(numpy.unique(res))
- assert result_unique == expected_unique, \
? ^^
+ assert result_unique in expected_unique, \
? ^^
- "Expected {} unique labels (including 0) in the resulting segmentation, but got {}"\
+ "Wrong number of unique labels in the segmentation. Expected one of {}, but got {}"\
.format(expected_unique, len(numpy.unique(res)))
print("SUCCESS") |
4f3cfe6e990c932d7f86dbd0cf8ae762407278b0 | nucleus/base/urls.py | nucleus/base/urls.py | from django.conf.urls import url
from nucleus.base import views
urlpatterns = (
url(r'^/?$', views.home, name='base.home'),
)
| from django.conf.urls import url
from django.views.generic import RedirectView
urlpatterns = (
url(r'^/?$', RedirectView.as_view(url='/rna/', permanent=True), name='base.home'),
)
| Change root URL to redirect to /rna/ | Change root URL to redirect to /rna/
| Python | mpl-2.0 | mozilla/nucleus,mozilla/nucleus,mozilla/nucleus,mozilla/nucleus | from django.conf.urls import url
+ from django.views.generic import RedirectView
-
- from nucleus.base import views
urlpatterns = (
- url(r'^/?$', views.home, name='base.home'),
+ url(r'^/?$', RedirectView.as_view(url='/rna/', permanent=True), name='base.home'),
)
| Change root URL to redirect to /rna/ | ## Code Before:
from django.conf.urls import url
from nucleus.base import views
urlpatterns = (
url(r'^/?$', views.home, name='base.home'),
)
## Instruction:
Change root URL to redirect to /rna/
## Code After:
from django.conf.urls import url
from django.views.generic import RedirectView
urlpatterns = (
url(r'^/?$', RedirectView.as_view(url='/rna/', permanent=True), name='base.home'),
)
| from django.conf.urls import url
+ from django.views.generic import RedirectView
-
- from nucleus.base import views
urlpatterns = (
- url(r'^/?$', views.home, name='base.home'),
+ url(r'^/?$', RedirectView.as_view(url='/rna/', permanent=True), name='base.home'),
) |
5c12b0c04b25e414b1bd04250cde0c3b1f869104 | hr_emergency_contact/models/hr_employee.py | hr_emergency_contact/models/hr_employee.py |
from openerp import models, fields
class HrEmployee(models.Model):
_name = 'hr.employee'
_inherit = 'hr.employee'
emergency_contact_ids = fields.Many2many(
string='Emergency Contacts',
comodel_name='res.partner',
relation='rel_employee_emergency_contact',
column1='employee_id',
column2='partner_id',
domain=[
('is_company', '=', False),
('parent_id', '=', False),
]
)
|
from openerp import models, fields
class HrEmployee(models.Model):
_inherit = 'hr.employee'
emergency_contact_ids = fields.Many2many(
string='Emergency Contacts',
comodel_name='res.partner',
relation='rel_employee_emergency_contact',
column1='employee_id',
column2='partner_id',
domain=[
('is_company', '=', False),
('parent_id', '=', False),
]
)
| Remove _name attribute on hr.employee | Remove _name attribute on hr.employee
| Python | agpl-3.0 | VitalPet/hr,thinkopensolutions/hr,VitalPet/hr,xpansa/hr,Eficent/hr,Eficent/hr,feketemihai/hr,feketemihai/hr,acsone/hr,open-synergy/hr,open-synergy/hr,xpansa/hr,acsone/hr,thinkopensolutions/hr |
from openerp import models, fields
class HrEmployee(models.Model):
- _name = 'hr.employee'
_inherit = 'hr.employee'
emergency_contact_ids = fields.Many2many(
string='Emergency Contacts',
comodel_name='res.partner',
relation='rel_employee_emergency_contact',
column1='employee_id',
column2='partner_id',
domain=[
('is_company', '=', False),
('parent_id', '=', False),
]
)
| Remove _name attribute on hr.employee | ## Code Before:
from openerp import models, fields
class HrEmployee(models.Model):
_name = 'hr.employee'
_inherit = 'hr.employee'
emergency_contact_ids = fields.Many2many(
string='Emergency Contacts',
comodel_name='res.partner',
relation='rel_employee_emergency_contact',
column1='employee_id',
column2='partner_id',
domain=[
('is_company', '=', False),
('parent_id', '=', False),
]
)
## Instruction:
Remove _name attribute on hr.employee
## Code After:
from openerp import models, fields
class HrEmployee(models.Model):
_inherit = 'hr.employee'
emergency_contact_ids = fields.Many2many(
string='Emergency Contacts',
comodel_name='res.partner',
relation='rel_employee_emergency_contact',
column1='employee_id',
column2='partner_id',
domain=[
('is_company', '=', False),
('parent_id', '=', False),
]
)
|
from openerp import models, fields
class HrEmployee(models.Model):
- _name = 'hr.employee'
_inherit = 'hr.employee'
emergency_contact_ids = fields.Many2many(
string='Emergency Contacts',
comodel_name='res.partner',
relation='rel_employee_emergency_contact',
column1='employee_id',
column2='partner_id',
domain=[
('is_company', '=', False),
('parent_id', '=', False),
]
) |
9fb89c7e76bd3c6db5f7283b91a2852225056b40 | tests/test_analyse.py | tests/test_analyse.py | """Test analysis page."""
def test_analysis(webapp):
"""Test we can analyse a page."""
response = webapp.get('/analyse/646e73747769737465722e7265706f7274')
assert response.status_code == 200
assert 'Use these tools to safely analyse dnstwister.report' in response.body
| """Test analysis page."""
import pytest
import webtest.app
def test_analysis(webapp):
"""Test we can analyse a page."""
response = webapp.get('/analyse/646e73747769737465722e7265706f7274')
assert response.status_code == 200
assert 'Use these tools to safely analyse dnstwister.report' in response.body
def test_bad_domain_fails(webapp):
"""Test the analyse page checks domain validity."""
with pytest.raises(webtest.app.AppError) as err:
webapp.get('/analyse/3234jskdnfsdf7y34')
assert '400 BAD REQUEST' in err.value.message
| Test analyse page checks domain validity | Test analyse page checks domain validity
| Python | unlicense | thisismyrobot/dnstwister,thisismyrobot/dnstwister,thisismyrobot/dnstwister | """Test analysis page."""
+ import pytest
+ import webtest.app
def test_analysis(webapp):
"""Test we can analyse a page."""
response = webapp.get('/analyse/646e73747769737465722e7265706f7274')
assert response.status_code == 200
assert 'Use these tools to safely analyse dnstwister.report' in response.body
+
+ def test_bad_domain_fails(webapp):
+ """Test the analyse page checks domain validity."""
+ with pytest.raises(webtest.app.AppError) as err:
+ webapp.get('/analyse/3234jskdnfsdf7y34')
+ assert '400 BAD REQUEST' in err.value.message
+ | Test analyse page checks domain validity | ## Code Before:
"""Test analysis page."""
def test_analysis(webapp):
"""Test we can analyse a page."""
response = webapp.get('/analyse/646e73747769737465722e7265706f7274')
assert response.status_code == 200
assert 'Use these tools to safely analyse dnstwister.report' in response.body
## Instruction:
Test analyse page checks domain validity
## Code After:
"""Test analysis page."""
import pytest
import webtest.app
def test_analysis(webapp):
"""Test we can analyse a page."""
response = webapp.get('/analyse/646e73747769737465722e7265706f7274')
assert response.status_code == 200
assert 'Use these tools to safely analyse dnstwister.report' in response.body
def test_bad_domain_fails(webapp):
"""Test the analyse page checks domain validity."""
with pytest.raises(webtest.app.AppError) as err:
webapp.get('/analyse/3234jskdnfsdf7y34')
assert '400 BAD REQUEST' in err.value.message
| """Test analysis page."""
+ import pytest
+ import webtest.app
def test_analysis(webapp):
"""Test we can analyse a page."""
response = webapp.get('/analyse/646e73747769737465722e7265706f7274')
assert response.status_code == 200
assert 'Use these tools to safely analyse dnstwister.report' in response.body
+
+
+ def test_bad_domain_fails(webapp):
+ """Test the analyse page checks domain validity."""
+ with pytest.raises(webtest.app.AppError) as err:
+ webapp.get('/analyse/3234jskdnfsdf7y34')
+ assert '400 BAD REQUEST' in err.value.message |
8228a862654dfd0418d1e756042fa8f8746b57b9 | ideascube/conf/kb_usa_wmapache.py | ideascube/conf/kb_usa_wmapache.py | """KoomBook conf"""
from .kb import * # noqa
LANGUAGE_CODE = 'en'
IDEASCUBE_NAME = 'WHITE MOUNTAIN APACHE'
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'blog',
},
{
'id': 'mediacenter',
},
{
'id': 'gutenberg',
},
{
'id': 'wiktionary',
},
{
'id': 'ted',
'sessions': [
('tedbusiness.en', 'Business'),
('teddesign.en', 'Design'),
('tedentertainment.en', 'Entertainment'),
('tedglobalissues.en', 'Global Issues'),
('tedscience.en', 'Science'),
('tedtechnology.en', 'Technology'),
]
},
{
'id': 'khanacademy',
},
]
| """KoomBook conf"""
from .kb import * # noqa
LANGUAGE_CODE = 'en'
IDEASCUBE_NAME = 'WHITE MOUNTAIN APACHE'
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'blog',
},
{
'id': 'mediacenter',
},
{
'id': 'gutenberg',
},
{
'id': 'wikipedia',
},
{
'id': 'wiktionary',
},
{
'id': 'khanacademy',
},
]
| Remove Ted and add Wikiepdia | Remove Ted and add Wikiepdia
| Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube | """KoomBook conf"""
from .kb import * # noqa
LANGUAGE_CODE = 'en'
IDEASCUBE_NAME = 'WHITE MOUNTAIN APACHE'
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'blog',
},
{
'id': 'mediacenter',
},
{
'id': 'gutenberg',
},
{
- 'id': 'wiktionary',
+ 'id': 'wikipedia',
},
{
- 'id': 'ted',
+ 'id': 'wiktionary',
- 'sessions': [
- ('tedbusiness.en', 'Business'),
- ('teddesign.en', 'Design'),
- ('tedentertainment.en', 'Entertainment'),
- ('tedglobalissues.en', 'Global Issues'),
- ('tedscience.en', 'Science'),
- ('tedtechnology.en', 'Technology'),
- ]
},
{
'id': 'khanacademy',
},
]
| Remove Ted and add Wikiepdia | ## Code Before:
"""KoomBook conf"""
from .kb import * # noqa
LANGUAGE_CODE = 'en'
IDEASCUBE_NAME = 'WHITE MOUNTAIN APACHE'
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'blog',
},
{
'id': 'mediacenter',
},
{
'id': 'gutenberg',
},
{
'id': 'wiktionary',
},
{
'id': 'ted',
'sessions': [
('tedbusiness.en', 'Business'),
('teddesign.en', 'Design'),
('tedentertainment.en', 'Entertainment'),
('tedglobalissues.en', 'Global Issues'),
('tedscience.en', 'Science'),
('tedtechnology.en', 'Technology'),
]
},
{
'id': 'khanacademy',
},
]
## Instruction:
Remove Ted and add Wikiepdia
## Code After:
"""KoomBook conf"""
from .kb import * # noqa
LANGUAGE_CODE = 'en'
IDEASCUBE_NAME = 'WHITE MOUNTAIN APACHE'
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'blog',
},
{
'id': 'mediacenter',
},
{
'id': 'gutenberg',
},
{
'id': 'wikipedia',
},
{
'id': 'wiktionary',
},
{
'id': 'khanacademy',
},
]
| """KoomBook conf"""
from .kb import * # noqa
LANGUAGE_CODE = 'en'
IDEASCUBE_NAME = 'WHITE MOUNTAIN APACHE'
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'blog',
},
{
'id': 'mediacenter',
},
{
'id': 'gutenberg',
},
{
- 'id': 'wiktionary',
? - ^^ --
+ 'id': 'wikipedia',
? ^^^^
},
{
- 'id': 'ted',
? ^^
+ 'id': 'wiktionary',
? +++ ^^^^^^
- 'sessions': [
- ('tedbusiness.en', 'Business'),
- ('teddesign.en', 'Design'),
- ('tedentertainment.en', 'Entertainment'),
- ('tedglobalissues.en', 'Global Issues'),
- ('tedscience.en', 'Science'),
- ('tedtechnology.en', 'Technology'),
- ]
},
{
'id': 'khanacademy',
},
] |
36f4144a01ed56baea9036e4e09a5d90b1c13372 | crits/core/management/commands/mapreduces.py | crits/core/management/commands/mapreduces.py | from django.core.management.base import BaseCommand
import crits.stats.handlers as stats
class Command(BaseCommand):
"""
Script Class.
"""
help = "Runs mapreduces for CRITs."
def handle(self, *args, **options):
"""
Script Execution.
"""
stats.generate_yara_hits()
stats.generate_sources()
stats.generate_filetypes()
stats.generate_filetypes()
stats.generate_campaign_stats()
stats.generate_counts()
stats.target_user_stats()
stats.campaign_date_stats()
| from django.core.management.base import BaseCommand
import crits.stats.handlers as stats
class Command(BaseCommand):
"""
Script Class.
"""
help = "Runs mapreduces for CRITs."
def handle(self, *args, **options):
"""
Script Execution.
"""
stats.generate_yara_hits()
stats.generate_sources()
stats.generate_filetypes()
stats.generate_campaign_stats()
stats.generate_counts()
stats.target_user_stats()
stats.campaign_date_stats()
| Remove duplicate call to generate_filetypes() | Remove duplicate call to generate_filetypes() | Python | mit | Magicked/crits,lakiw/cripts,Magicked/crits,lakiw/cripts,lakiw/cripts,Magicked/crits,Magicked/crits,lakiw/cripts | from django.core.management.base import BaseCommand
import crits.stats.handlers as stats
class Command(BaseCommand):
"""
Script Class.
"""
help = "Runs mapreduces for CRITs."
def handle(self, *args, **options):
"""
Script Execution.
"""
stats.generate_yara_hits()
stats.generate_sources()
stats.generate_filetypes()
- stats.generate_filetypes()
stats.generate_campaign_stats()
stats.generate_counts()
stats.target_user_stats()
stats.campaign_date_stats()
| Remove duplicate call to generate_filetypes() | ## Code Before:
from django.core.management.base import BaseCommand
import crits.stats.handlers as stats
class Command(BaseCommand):
"""
Script Class.
"""
help = "Runs mapreduces for CRITs."
def handle(self, *args, **options):
"""
Script Execution.
"""
stats.generate_yara_hits()
stats.generate_sources()
stats.generate_filetypes()
stats.generate_filetypes()
stats.generate_campaign_stats()
stats.generate_counts()
stats.target_user_stats()
stats.campaign_date_stats()
## Instruction:
Remove duplicate call to generate_filetypes()
## Code After:
from django.core.management.base import BaseCommand
import crits.stats.handlers as stats
class Command(BaseCommand):
"""
Script Class.
"""
help = "Runs mapreduces for CRITs."
def handle(self, *args, **options):
"""
Script Execution.
"""
stats.generate_yara_hits()
stats.generate_sources()
stats.generate_filetypes()
stats.generate_campaign_stats()
stats.generate_counts()
stats.target_user_stats()
stats.campaign_date_stats()
| from django.core.management.base import BaseCommand
import crits.stats.handlers as stats
class Command(BaseCommand):
"""
Script Class.
"""
help = "Runs mapreduces for CRITs."
def handle(self, *args, **options):
"""
Script Execution.
"""
stats.generate_yara_hits()
stats.generate_sources()
stats.generate_filetypes()
- stats.generate_filetypes()
stats.generate_campaign_stats()
stats.generate_counts()
stats.target_user_stats()
stats.campaign_date_stats() |
77d72fe0502c64294dbacdbf8defbb44ee21c088 | schools/admin.py | schools/admin.py | from django.contrib import admin
from .models import *
class SchoolBuildingPhotoInline(admin.TabularInline):
model = SchoolBuildingPhoto
@admin.register(SchoolBuilding)
class SchoolBuildingAdmin(admin.ModelAdmin):
fields = ('school', 'building', 'begin_year', 'end_year')
readonly_fields = fields
list_display = ('__str__', 'has_photo')
list_filter = ('photos',)
inlines = [SchoolBuildingPhotoInline]
| from django.contrib import admin
from .models import *
class SchoolBuildingPhotoInline(admin.TabularInline):
model = SchoolBuildingPhoto
@admin.register(SchoolBuilding)
class SchoolBuildingAdmin(admin.ModelAdmin):
fields = ('school', 'building', 'begin_year', 'end_year')
readonly_fields = fields
search_fields = ['school__names__types__value']
list_display = ('__str__', 'has_photo')
list_filter = ('photos',)
inlines = [SchoolBuildingPhotoInline]
| Add search based on school name | Add search based on school name
| Python | agpl-3.0 | City-of-Helsinki/kore,City-of-Helsinki/kore,Rikuoja/kore,Rikuoja/kore | from django.contrib import admin
from .models import *
class SchoolBuildingPhotoInline(admin.TabularInline):
model = SchoolBuildingPhoto
@admin.register(SchoolBuilding)
class SchoolBuildingAdmin(admin.ModelAdmin):
fields = ('school', 'building', 'begin_year', 'end_year')
readonly_fields = fields
+ search_fields = ['school__names__types__value']
list_display = ('__str__', 'has_photo')
list_filter = ('photos',)
inlines = [SchoolBuildingPhotoInline]
| Add search based on school name | ## Code Before:
from django.contrib import admin
from .models import *
class SchoolBuildingPhotoInline(admin.TabularInline):
model = SchoolBuildingPhoto
@admin.register(SchoolBuilding)
class SchoolBuildingAdmin(admin.ModelAdmin):
fields = ('school', 'building', 'begin_year', 'end_year')
readonly_fields = fields
list_display = ('__str__', 'has_photo')
list_filter = ('photos',)
inlines = [SchoolBuildingPhotoInline]
## Instruction:
Add search based on school name
## Code After:
from django.contrib import admin
from .models import *
class SchoolBuildingPhotoInline(admin.TabularInline):
model = SchoolBuildingPhoto
@admin.register(SchoolBuilding)
class SchoolBuildingAdmin(admin.ModelAdmin):
fields = ('school', 'building', 'begin_year', 'end_year')
readonly_fields = fields
search_fields = ['school__names__types__value']
list_display = ('__str__', 'has_photo')
list_filter = ('photos',)
inlines = [SchoolBuildingPhotoInline]
| from django.contrib import admin
from .models import *
class SchoolBuildingPhotoInline(admin.TabularInline):
model = SchoolBuildingPhoto
@admin.register(SchoolBuilding)
class SchoolBuildingAdmin(admin.ModelAdmin):
fields = ('school', 'building', 'begin_year', 'end_year')
readonly_fields = fields
+ search_fields = ['school__names__types__value']
list_display = ('__str__', 'has_photo')
list_filter = ('photos',)
inlines = [SchoolBuildingPhotoInline] |
171974ab9c069abe14c25ef220f683d4905d1454 | socorro/external/rabbitmq/rmq_new_crash_source.py | socorro/external/rabbitmq/rmq_new_crash_source.py |
from configman import Namespace, RequiredConfig
from configman.converters import class_converter
from functools import partial
#==============================================================================
class RMQNewCrashSource(RequiredConfig):
"""this class is a refactoring of the iteratior portion of the legacy
Socorro processor. It isolates just the part of fetching the ooids of
jobs to be processed"""
required_config = Namespace()
required_config.source.add_option(
'crashstorage_class',
doc='the source storage class',
default='socorro.external.rabbitmq.crashstorage.RabbitMQCrashStorage',
from_string_converter=class_converter
)
#--------------------------------------------------------------------------
def __init__(self, config, processor_name, quit_check_callback=None):
self.config = config
self.crash_store = config.crashstorage_class(config)
#--------------------------------------------------------------------------
def close(self):
pass
#--------------------------------------------------------------------------
def __iter__(self):
"""an adapter that allows this class can serve as an iterator in a
fetch_transform_save app"""
for a_crash_id in self.crash_store.new_crashes():
yield (
(a_crash_id,),
{'finished_func': partial(
self.crash_store.ack_crash,
a_crash_id
)}
)
#--------------------------------------------------------------------------
def __call__(self):
return self.__iter__()
|
from configman import Namespace, RequiredConfig
from configman.converters import class_converter
from functools import partial
#==============================================================================
class RMQNewCrashSource(RequiredConfig):
"""An iterable of crashes from RabbitMQ"""
required_config = Namespace()
required_config.source.add_option(
'crashstorage_class',
doc='the source storage class',
default='socorro.external.rabbitmq.crashstorage.RabbitMQCrashStorage',
from_string_converter=class_converter
)
#--------------------------------------------------------------------------
def __init__(self, config, processor_name, quit_check_callback=None):
self.config = config
self.crash_store = config.crashstorage_class(config)
#--------------------------------------------------------------------------
def close(self):
pass
#--------------------------------------------------------------------------
def __iter__(self):
"""Return an iterator over crashes from RabbitMQ.
Each crash is a tuple of the ``(args, kwargs)`` variety. The lone arg
is a crash ID, and the kwargs contain only a callback function which
the FTS app will call to send an ack to Rabbit after processing is
complete.
"""
for a_crash_id in self.crash_store.new_crashes():
yield (
(a_crash_id,),
{'finished_func': partial(
self.crash_store.ack_crash,
a_crash_id
)}
)
#--------------------------------------------------------------------------
def __call__(self):
return self.__iter__()
| Correct docs on RabbitMQ crash source. | Correct docs on RabbitMQ crash source.
| Python | mpl-2.0 | linearregression/socorro,linearregression/socorro,Serg09/socorro,Serg09/socorro,linearregression/socorro,m8ttyB/socorro,Serg09/socorro,luser/socorro,twobraids/socorro,lonnen/socorro,bsmedberg/socorro,AdrianGaudebert/socorro,cliqz/socorro,yglazko/socorro,pcabido/socorro,lonnen/socorro,twobraids/socorro,bsmedberg/socorro,adngdb/socorro,bsmedberg/socorro,AdrianGaudebert/socorro,Tayamarn/socorro,cliqz/socorro,Tchanders/socorro,twobraids/socorro,Serg09/socorro,pcabido/socorro,m8ttyB/socorro,linearregression/socorro,KaiRo-at/socorro,spthaolt/socorro,Tayamarn/socorro,luser/socorro,Tchanders/socorro,spthaolt/socorro,KaiRo-at/socorro,KaiRo-at/socorro,mozilla/socorro,mozilla/socorro,Tayamarn/socorro,Tayamarn/socorro,Serg09/socorro,cliqz/socorro,adngdb/socorro,spthaolt/socorro,mozilla/socorro,yglazko/socorro,luser/socorro,Serg09/socorro,yglazko/socorro,AdrianGaudebert/socorro,cliqz/socorro,pcabido/socorro,rhelmer/socorro,Tchanders/socorro,Tayamarn/socorro,AdrianGaudebert/socorro,yglazko/socorro,m8ttyB/socorro,bsmedberg/socorro,lonnen/socorro,adngdb/socorro,m8ttyB/socorro,rhelmer/socorro,Tchanders/socorro,mozilla/socorro,luser/socorro,twobraids/socorro,adngdb/socorro,mozilla/socorro,m8ttyB/socorro,Tchanders/socorro,luser/socorro,AdrianGaudebert/socorro,bsmedberg/socorro,twobraids/socorro,spthaolt/socorro,Tayamarn/socorro,mozilla/socorro,twobraids/socorro,KaiRo-at/socorro,pcabido/socorro,linearregression/socorro,Tchanders/socorro,KaiRo-at/socorro,cliqz/socorro,lonnen/socorro,pcabido/socorro,yglazko/socorro,adngdb/socorro,rhelmer/socorro,pcabido/socorro,linearregression/socorro,AdrianGaudebert/socorro,luser/socorro,spthaolt/socorro,rhelmer/socorro,KaiRo-at/socorro,cliqz/socorro,m8ttyB/socorro,rhelmer/socorro,adngdb/socorro,spthaolt/socorro,rhelmer/socorro,yglazko/socorro |
from configman import Namespace, RequiredConfig
from configman.converters import class_converter
from functools import partial
+
#==============================================================================
class RMQNewCrashSource(RequiredConfig):
+ """An iterable of crashes from RabbitMQ"""
+
- """this class is a refactoring of the iteratior portion of the legacy
- Socorro processor. It isolates just the part of fetching the ooids of
- jobs to be processed"""
required_config = Namespace()
required_config.source.add_option(
'crashstorage_class',
doc='the source storage class',
default='socorro.external.rabbitmq.crashstorage.RabbitMQCrashStorage',
from_string_converter=class_converter
)
#--------------------------------------------------------------------------
def __init__(self, config, processor_name, quit_check_callback=None):
self.config = config
self.crash_store = config.crashstorage_class(config)
#--------------------------------------------------------------------------
def close(self):
pass
#--------------------------------------------------------------------------
def __iter__(self):
- """an adapter that allows this class can serve as an iterator in a
- fetch_transform_save app"""
+ """Return an iterator over crashes from RabbitMQ.
+
+ Each crash is a tuple of the ``(args, kwargs)`` variety. The lone arg
+ is a crash ID, and the kwargs contain only a callback function which
+ the FTS app will call to send an ack to Rabbit after processing is
+ complete.
+
+ """
for a_crash_id in self.crash_store.new_crashes():
yield (
- (a_crash_id,),
+ (a_crash_id,),
{'finished_func': partial(
self.crash_store.ack_crash,
a_crash_id
)}
)
#--------------------------------------------------------------------------
def __call__(self):
return self.__iter__()
| Correct docs on RabbitMQ crash source. | ## Code Before:
from configman import Namespace, RequiredConfig
from configman.converters import class_converter
from functools import partial
#==============================================================================
class RMQNewCrashSource(RequiredConfig):
"""this class is a refactoring of the iteratior portion of the legacy
Socorro processor. It isolates just the part of fetching the ooids of
jobs to be processed"""
required_config = Namespace()
required_config.source.add_option(
'crashstorage_class',
doc='the source storage class',
default='socorro.external.rabbitmq.crashstorage.RabbitMQCrashStorage',
from_string_converter=class_converter
)
#--------------------------------------------------------------------------
def __init__(self, config, processor_name, quit_check_callback=None):
self.config = config
self.crash_store = config.crashstorage_class(config)
#--------------------------------------------------------------------------
def close(self):
pass
#--------------------------------------------------------------------------
def __iter__(self):
"""an adapter that allows this class can serve as an iterator in a
fetch_transform_save app"""
for a_crash_id in self.crash_store.new_crashes():
yield (
(a_crash_id,),
{'finished_func': partial(
self.crash_store.ack_crash,
a_crash_id
)}
)
#--------------------------------------------------------------------------
def __call__(self):
return self.__iter__()
## Instruction:
Correct docs on RabbitMQ crash source.
## Code After:
from configman import Namespace, RequiredConfig
from configman.converters import class_converter
from functools import partial
#==============================================================================
class RMQNewCrashSource(RequiredConfig):
"""An iterable of crashes from RabbitMQ"""
required_config = Namespace()
required_config.source.add_option(
'crashstorage_class',
doc='the source storage class',
default='socorro.external.rabbitmq.crashstorage.RabbitMQCrashStorage',
from_string_converter=class_converter
)
#--------------------------------------------------------------------------
def __init__(self, config, processor_name, quit_check_callback=None):
self.config = config
self.crash_store = config.crashstorage_class(config)
#--------------------------------------------------------------------------
def close(self):
pass
#--------------------------------------------------------------------------
def __iter__(self):
"""Return an iterator over crashes from RabbitMQ.
Each crash is a tuple of the ``(args, kwargs)`` variety. The lone arg
is a crash ID, and the kwargs contain only a callback function which
the FTS app will call to send an ack to Rabbit after processing is
complete.
"""
for a_crash_id in self.crash_store.new_crashes():
yield (
(a_crash_id,),
{'finished_func': partial(
self.crash_store.ack_crash,
a_crash_id
)}
)
#--------------------------------------------------------------------------
def __call__(self):
return self.__iter__()
|
from configman import Namespace, RequiredConfig
from configman.converters import class_converter
from functools import partial
+
#==============================================================================
class RMQNewCrashSource(RequiredConfig):
+ """An iterable of crashes from RabbitMQ"""
+
- """this class is a refactoring of the iteratior portion of the legacy
- Socorro processor. It isolates just the part of fetching the ooids of
- jobs to be processed"""
required_config = Namespace()
required_config.source.add_option(
'crashstorage_class',
doc='the source storage class',
default='socorro.external.rabbitmq.crashstorage.RabbitMQCrashStorage',
from_string_converter=class_converter
)
#--------------------------------------------------------------------------
def __init__(self, config, processor_name, quit_check_callback=None):
self.config = config
self.crash_store = config.crashstorage_class(config)
#--------------------------------------------------------------------------
def close(self):
pass
#--------------------------------------------------------------------------
def __iter__(self):
- """an adapter that allows this class can serve as an iterator in a
- fetch_transform_save app"""
+ """Return an iterator over crashes from RabbitMQ.
+
+ Each crash is a tuple of the ``(args, kwargs)`` variety. The lone arg
+ is a crash ID, and the kwargs contain only a callback function which
+ the FTS app will call to send an ack to Rabbit after processing is
+ complete.
+
+ """
for a_crash_id in self.crash_store.new_crashes():
yield (
- (a_crash_id,),
? -
+ (a_crash_id,),
{'finished_func': partial(
self.crash_store.ack_crash,
a_crash_id
)}
)
#--------------------------------------------------------------------------
def __call__(self):
return self.__iter__() |
6db2bb9b1634a7b37790207e5b8d420de643a9cb | turbasen/__init__.py | turbasen/__init__.py | VERSION = '1.0.0'
def configure(**settings):
from .settings import Settings
for key, value in settings.items():
Settings.setattr(key, value)
| VERSION = '1.0.0'
from .models import \
Omrade, \
Sted
def configure(**settings):
from .settings import Settings
for key, value in settings.items():
Settings.setattr(key, value)
| Add relevant models to turbasen module | Add relevant models to turbasen module
| Python | mit | Turbasen/turbasen.py | VERSION = '1.0.0'
+
+ from .models import \
+ Omrade, \
+ Sted
def configure(**settings):
from .settings import Settings
for key, value in settings.items():
Settings.setattr(key, value)
| Add relevant models to turbasen module | ## Code Before:
VERSION = '1.0.0'
def configure(**settings):
from .settings import Settings
for key, value in settings.items():
Settings.setattr(key, value)
## Instruction:
Add relevant models to turbasen module
## Code After:
VERSION = '1.0.0'
from .models import \
Omrade, \
Sted
def configure(**settings):
from .settings import Settings
for key, value in settings.items():
Settings.setattr(key, value)
| VERSION = '1.0.0'
+
+ from .models import \
+ Omrade, \
+ Sted
def configure(**settings):
from .settings import Settings
for key, value in settings.items():
Settings.setattr(key, value) |
aaaaa995a77110b779d9613d95800af609324edc | falcom/tree/test/test_tree.py | falcom/tree/test/test_tree.py | from hamcrest import *
import unittest
from ..read_only_tree import Tree
from ..mutable_tree import MutableTree
class GivenNothing (unittest.TestCase):
def test_cannot_init_tree_with_value (self):
assert_that(calling(Tree).with_args(value="hi"),
raises(TypeError))
def test_can_init_from_mutable_tree (self):
mtree = MutableTree(value=1)
mtree.append_value(2)
mtree.append_value(3)
mtree[0].append_value(4)
mtree[0].append_value(5)
mtree[0][0].append_value(6)
t = Tree(mtree)
class GivenEmptyTree (unittest.TestCase):
def test_empty_tree_has_null_value (self):
t = Tree()
assert_that(t.value, is_(none()))
def test_cannot_modify_value_for_empty_tree (self):
t = Tree()
assert_that(calling(setattr).with_args(t, "value", "hi"),
raises(AttributeError))
| from hamcrest import *
import unittest
from ..read_only_tree import Tree
from ..mutable_tree import MutableTree
class GivenNothing (unittest.TestCase):
def test_cannot_init_tree_with_value (self):
assert_that(calling(Tree).with_args(value="hi"),
raises(TypeError))
def test_can_init_from_mutable_tree (self):
mtree = MutableTree(value=1)
mtree.append_value(2)
mtree.append_value(3)
mtree[0].append_value(4)
mtree[0].append_value(5)
mtree[0][0].append_value(6)
t = Tree(mtree)
class GivenEmptyTree (unittest.TestCase):
def setUp (self):
self.tree = Tree()
def test_empty_tree_has_null_value (self):
assert_that(self.tree.value, is_(none()))
def test_cannot_modify_value_for_empty_tree (self):
assert_that(calling(setattr).with_args(self.tree,
"value",
"hi"),
raises(AttributeError))
| Replace duplicate code with setUp method | Replace duplicate code with setUp method
| Python | bsd-3-clause | mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation | from hamcrest import *
import unittest
from ..read_only_tree import Tree
from ..mutable_tree import MutableTree
class GivenNothing (unittest.TestCase):
def test_cannot_init_tree_with_value (self):
assert_that(calling(Tree).with_args(value="hi"),
raises(TypeError))
def test_can_init_from_mutable_tree (self):
mtree = MutableTree(value=1)
mtree.append_value(2)
mtree.append_value(3)
mtree[0].append_value(4)
mtree[0].append_value(5)
mtree[0][0].append_value(6)
t = Tree(mtree)
class GivenEmptyTree (unittest.TestCase):
+ def setUp (self):
+ self.tree = Tree()
+
def test_empty_tree_has_null_value (self):
- t = Tree()
- assert_that(t.value, is_(none()))
+ assert_that(self.tree.value, is_(none()))
def test_cannot_modify_value_for_empty_tree (self):
- t = Tree()
- assert_that(calling(setattr).with_args(t, "value", "hi"),
+ assert_that(calling(setattr).with_args(self.tree,
+ "value",
+ "hi"),
raises(AttributeError))
| Replace duplicate code with setUp method | ## Code Before:
from hamcrest import *
import unittest
from ..read_only_tree import Tree
from ..mutable_tree import MutableTree
class GivenNothing (unittest.TestCase):
def test_cannot_init_tree_with_value (self):
assert_that(calling(Tree).with_args(value="hi"),
raises(TypeError))
def test_can_init_from_mutable_tree (self):
mtree = MutableTree(value=1)
mtree.append_value(2)
mtree.append_value(3)
mtree[0].append_value(4)
mtree[0].append_value(5)
mtree[0][0].append_value(6)
t = Tree(mtree)
class GivenEmptyTree (unittest.TestCase):
def test_empty_tree_has_null_value (self):
t = Tree()
assert_that(t.value, is_(none()))
def test_cannot_modify_value_for_empty_tree (self):
t = Tree()
assert_that(calling(setattr).with_args(t, "value", "hi"),
raises(AttributeError))
## Instruction:
Replace duplicate code with setUp method
## Code After:
from hamcrest import *
import unittest
from ..read_only_tree import Tree
from ..mutable_tree import MutableTree
class GivenNothing (unittest.TestCase):
def test_cannot_init_tree_with_value (self):
assert_that(calling(Tree).with_args(value="hi"),
raises(TypeError))
def test_can_init_from_mutable_tree (self):
mtree = MutableTree(value=1)
mtree.append_value(2)
mtree.append_value(3)
mtree[0].append_value(4)
mtree[0].append_value(5)
mtree[0][0].append_value(6)
t = Tree(mtree)
class GivenEmptyTree (unittest.TestCase):
def setUp (self):
self.tree = Tree()
def test_empty_tree_has_null_value (self):
assert_that(self.tree.value, is_(none()))
def test_cannot_modify_value_for_empty_tree (self):
assert_that(calling(setattr).with_args(self.tree,
"value",
"hi"),
raises(AttributeError))
| from hamcrest import *
import unittest
from ..read_only_tree import Tree
from ..mutable_tree import MutableTree
class GivenNothing (unittest.TestCase):
def test_cannot_init_tree_with_value (self):
assert_that(calling(Tree).with_args(value="hi"),
raises(TypeError))
def test_can_init_from_mutable_tree (self):
mtree = MutableTree(value=1)
mtree.append_value(2)
mtree.append_value(3)
mtree[0].append_value(4)
mtree[0].append_value(5)
mtree[0][0].append_value(6)
t = Tree(mtree)
class GivenEmptyTree (unittest.TestCase):
+ def setUp (self):
+ self.tree = Tree()
+
def test_empty_tree_has_null_value (self):
- t = Tree()
- assert_that(t.value, is_(none()))
+ assert_that(self.tree.value, is_(none()))
? +++++ +++
def test_cannot_modify_value_for_empty_tree (self):
- t = Tree()
- assert_that(calling(setattr).with_args(t, "value", "hi"),
? ----------------
+ assert_that(calling(setattr).with_args(self.tree,
? +++++ +++
+ "value",
+ "hi"),
raises(AttributeError)) |
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)
| 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) |
a5baa5f333625244c1e0935745dadedb7df444c3 | setup.py | setup.py |
import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='whack',
version='0.3.0',
description='Utility for installing binaries from source with a single command',
long_description=read("README"),
author='Michael Williamson',
url='http://github.com/mwilliamson/whack',
scripts=["scripts/whack"],
packages=['whack'],
install_requires=['blah>=0.1.10,<0.2', 'requests', "catchy==0.1.0"],
)
|
import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='whack',
version='0.3.0',
description='Utility for installing binaries from source with a single command',
long_description=read("README"),
author='Michael Williamson',
url='http://github.com/mwilliamson/whack',
scripts=["scripts/whack"],
packages=['whack'],
install_requires=['blah>=0.1.10,<0.2', 'requests>=1,<2', "catchy>=0.1.0,<0.2"],
)
| Update install_requires to be more accurate | Update install_requires to be more accurate
| Python | bsd-2-clause | mwilliamson/whack |
import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='whack',
version='0.3.0',
description='Utility for installing binaries from source with a single command',
long_description=read("README"),
author='Michael Williamson',
url='http://github.com/mwilliamson/whack',
scripts=["scripts/whack"],
packages=['whack'],
- install_requires=['blah>=0.1.10,<0.2', 'requests', "catchy==0.1.0"],
+ install_requires=['blah>=0.1.10,<0.2', 'requests>=1,<2', "catchy>=0.1.0,<0.2"],
)
| Update install_requires to be more accurate | ## Code Before:
import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='whack',
version='0.3.0',
description='Utility for installing binaries from source with a single command',
long_description=read("README"),
author='Michael Williamson',
url='http://github.com/mwilliamson/whack',
scripts=["scripts/whack"],
packages=['whack'],
install_requires=['blah>=0.1.10,<0.2', 'requests', "catchy==0.1.0"],
)
## Instruction:
Update install_requires to be more accurate
## Code After:
import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='whack',
version='0.3.0',
description='Utility for installing binaries from source with a single command',
long_description=read("README"),
author='Michael Williamson',
url='http://github.com/mwilliamson/whack',
scripts=["scripts/whack"],
packages=['whack'],
install_requires=['blah>=0.1.10,<0.2', 'requests>=1,<2', "catchy>=0.1.0,<0.2"],
)
|
import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='whack',
version='0.3.0',
description='Utility for installing binaries from source with a single command',
long_description=read("README"),
author='Michael Williamson',
url='http://github.com/mwilliamson/whack',
scripts=["scripts/whack"],
packages=['whack'],
- install_requires=['blah>=0.1.10,<0.2', 'requests', "catchy==0.1.0"],
? ^
+ install_requires=['blah>=0.1.10,<0.2', 'requests>=1,<2', "catchy>=0.1.0,<0.2"],
? ++++++ ^ +++++
) |
0336651c6538d756eb40babe086975a0f7fcabd6 | qual/tests/test_historical_calendar.py | qual/tests/test_historical_calendar.py | from test_calendar import CalendarTest
from qual.calendars import EnglishHistoricalCalendar
class TestHistoricalCalendar(object):
def setUp(self):
self.calendar = self.calendar_type()
def test_before_switch(self):
for triplet in self.julian_triplets:
self.check_valid_date(*triplet)
def test_after_switch(self):
for triplet in self.gregorian_triplets:
self.check_valid_date(*triplet)
def test_during_switch(self):
for triplet in self.transition_triplets:
self.check_invalid_date(*triplet)
class TestEnglishHistoricalCalendar(TestHistoricalCalendar, CalendarTest):
calendar_type = EnglishHistoricalCalendar
gregorian_triplets = [(1752, 9, 13)]
julian_triplets = [(1752, 9, 1)]
transition_triplets = [(1752, 9, 6)]
| from test_calendar import CalendarTest
from qual.calendars import EnglishHistoricalCalendar
class TestHistoricalCalendar(object):
def setUp(self):
self.calendar = self.calendar_type()
def test_before_switch(self):
for triplet in self.julian_triplets:
self.check_valid_date(*triplet)
def test_after_switch(self):
for triplet in self.gregorian_triplets:
self.check_valid_date(*triplet)
def test_during_switch(self):
for triplet in self.transition_triplets:
self.check_invalid_date(*triplet)
class TestEnglishHistoricalCalendar(TestHistoricalCalendar, CalendarTest):
calendar_type = EnglishHistoricalCalendar
gregorian_triplets = [(1752, 9, 14)]
julian_triplets = [(1752, 9, 1), (1752, 9, 2)]
transition_triplets = [(1752, 9, 3), (1752, 9, 6), (1752, 9, 13)]
| Correct test for the right missing days and present days. | Correct test for the right missing days and present days.
1st and 2nd of September 1752 happened, so did 14th. 3rd to 13th did not.
| Python | apache-2.0 | jwg4/qual,jwg4/calexicon | from test_calendar import CalendarTest
from qual.calendars import EnglishHistoricalCalendar
class TestHistoricalCalendar(object):
def setUp(self):
self.calendar = self.calendar_type()
def test_before_switch(self):
for triplet in self.julian_triplets:
self.check_valid_date(*triplet)
def test_after_switch(self):
for triplet in self.gregorian_triplets:
self.check_valid_date(*triplet)
def test_during_switch(self):
for triplet in self.transition_triplets:
self.check_invalid_date(*triplet)
class TestEnglishHistoricalCalendar(TestHistoricalCalendar, CalendarTest):
calendar_type = EnglishHistoricalCalendar
- gregorian_triplets = [(1752, 9, 13)]
+ gregorian_triplets = [(1752, 9, 14)]
- julian_triplets = [(1752, 9, 1)]
+ julian_triplets = [(1752, 9, 1), (1752, 9, 2)]
- transition_triplets = [(1752, 9, 6)]
+ transition_triplets = [(1752, 9, 3), (1752, 9, 6), (1752, 9, 13)]
| Correct test for the right missing days and present days. | ## Code Before:
from test_calendar import CalendarTest
from qual.calendars import EnglishHistoricalCalendar
class TestHistoricalCalendar(object):
def setUp(self):
self.calendar = self.calendar_type()
def test_before_switch(self):
for triplet in self.julian_triplets:
self.check_valid_date(*triplet)
def test_after_switch(self):
for triplet in self.gregorian_triplets:
self.check_valid_date(*triplet)
def test_during_switch(self):
for triplet in self.transition_triplets:
self.check_invalid_date(*triplet)
class TestEnglishHistoricalCalendar(TestHistoricalCalendar, CalendarTest):
calendar_type = EnglishHistoricalCalendar
gregorian_triplets = [(1752, 9, 13)]
julian_triplets = [(1752, 9, 1)]
transition_triplets = [(1752, 9, 6)]
## Instruction:
Correct test for the right missing days and present days.
## Code After:
from test_calendar import CalendarTest
from qual.calendars import EnglishHistoricalCalendar
class TestHistoricalCalendar(object):
def setUp(self):
self.calendar = self.calendar_type()
def test_before_switch(self):
for triplet in self.julian_triplets:
self.check_valid_date(*triplet)
def test_after_switch(self):
for triplet in self.gregorian_triplets:
self.check_valid_date(*triplet)
def test_during_switch(self):
for triplet in self.transition_triplets:
self.check_invalid_date(*triplet)
class TestEnglishHistoricalCalendar(TestHistoricalCalendar, CalendarTest):
calendar_type = EnglishHistoricalCalendar
gregorian_triplets = [(1752, 9, 14)]
julian_triplets = [(1752, 9, 1), (1752, 9, 2)]
transition_triplets = [(1752, 9, 3), (1752, 9, 6), (1752, 9, 13)]
| from test_calendar import CalendarTest
from qual.calendars import EnglishHistoricalCalendar
class TestHistoricalCalendar(object):
def setUp(self):
self.calendar = self.calendar_type()
def test_before_switch(self):
for triplet in self.julian_triplets:
self.check_valid_date(*triplet)
def test_after_switch(self):
for triplet in self.gregorian_triplets:
self.check_valid_date(*triplet)
def test_during_switch(self):
for triplet in self.transition_triplets:
self.check_invalid_date(*triplet)
class TestEnglishHistoricalCalendar(TestHistoricalCalendar, CalendarTest):
calendar_type = EnglishHistoricalCalendar
- gregorian_triplets = [(1752, 9, 13)]
? ^
+ gregorian_triplets = [(1752, 9, 14)]
? ^
- julian_triplets = [(1752, 9, 1)]
+ julian_triplets = [(1752, 9, 1), (1752, 9, 2)]
? ++++++++++++++
- transition_triplets = [(1752, 9, 6)]
+ transition_triplets = [(1752, 9, 3), (1752, 9, 6), (1752, 9, 13)] |
db02cadeb115bf3f7a8dd9be40d8a62d75d3559f | corehq/apps/hqwebapp/middleware.py | corehq/apps/hqwebapp/middleware.py | from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN
from corehq.util.soft_assert import soft_assert
from django.conf import settings
class HQCsrfViewMiddleWare(CsrfViewMiddleware):
def _reject(self, request, reason):
if settings.CSRF_ALWAYS_OFF and reason in [REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN]:
warning = "Request at {url} doesn't contain a csrf token. Letting the request pass through for now. "\
"Check if we are sending csrf_token in the corresponding POST form, if not fix it. "\
"Read more here https://github.com/dimagi/commcare-hq/pull/9227".format(
url=request.path
)
_assert = soft_assert(notify_admins=True, exponential_backoff=True)
_assert(False, warning)
return self._accept(request)
else:
return super(HQCsrfViewMiddleWare, self)._reject(request, reason)
| import logging
from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN
from django.conf import settings
logger = logging.getLogger('')
class HQCsrfViewMiddleWare(CsrfViewMiddleware):
def _reject(self, request, reason):
if settings.CSRF_ALWAYS_OFF and reason in [REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN]:
warning = "Request at {url} doesn't contain a csrf token. Letting the request pass through for now. "\
"Check if we are sending csrf_token in the corresponding POST form, if not fix it. "\
"Read more here https://github.com/dimagi/commcare-hq/pull/9227".format(
url=request.path
)
logger.error(warning)
return self._accept(request)
else:
return super(HQCsrfViewMiddleWare, self)._reject(request, reason)
| Revert "Revert "log to file, don't email"" | Revert "Revert "log to file, don't email""
This reverts commit 95245bb7fab6efe5a72cb8abbf4380a26b72a720.
| Python | bsd-3-clause | qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq | + import logging
+
from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN
+ from django.conf import settings
- from corehq.util.soft_assert import soft_assert
- from django.conf import settings
+
+ logger = logging.getLogger('')
class HQCsrfViewMiddleWare(CsrfViewMiddleware):
def _reject(self, request, reason):
if settings.CSRF_ALWAYS_OFF and reason in [REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN]:
warning = "Request at {url} doesn't contain a csrf token. Letting the request pass through for now. "\
"Check if we are sending csrf_token in the corresponding POST form, if not fix it. "\
"Read more here https://github.com/dimagi/commcare-hq/pull/9227".format(
url=request.path
)
+ logger.error(warning)
- _assert = soft_assert(notify_admins=True, exponential_backoff=True)
- _assert(False, warning)
-
return self._accept(request)
else:
return super(HQCsrfViewMiddleWare, self)._reject(request, reason)
| Revert "Revert "log to file, don't email"" | ## Code Before:
from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN
from corehq.util.soft_assert import soft_assert
from django.conf import settings
class HQCsrfViewMiddleWare(CsrfViewMiddleware):
def _reject(self, request, reason):
if settings.CSRF_ALWAYS_OFF and reason in [REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN]:
warning = "Request at {url} doesn't contain a csrf token. Letting the request pass through for now. "\
"Check if we are sending csrf_token in the corresponding POST form, if not fix it. "\
"Read more here https://github.com/dimagi/commcare-hq/pull/9227".format(
url=request.path
)
_assert = soft_assert(notify_admins=True, exponential_backoff=True)
_assert(False, warning)
return self._accept(request)
else:
return super(HQCsrfViewMiddleWare, self)._reject(request, reason)
## Instruction:
Revert "Revert "log to file, don't email""
## Code After:
import logging
from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN
from django.conf import settings
logger = logging.getLogger('')
class HQCsrfViewMiddleWare(CsrfViewMiddleware):
def _reject(self, request, reason):
if settings.CSRF_ALWAYS_OFF and reason in [REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN]:
warning = "Request at {url} doesn't contain a csrf token. Letting the request pass through for now. "\
"Check if we are sending csrf_token in the corresponding POST form, if not fix it. "\
"Read more here https://github.com/dimagi/commcare-hq/pull/9227".format(
url=request.path
)
logger.error(warning)
return self._accept(request)
else:
return super(HQCsrfViewMiddleWare, self)._reject(request, reason)
| + import logging
+
from django.middleware.csrf import CsrfViewMiddleware, REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN
+ from django.conf import settings
- from corehq.util.soft_assert import soft_assert
- from django.conf import settings
+
+ logger = logging.getLogger('')
class HQCsrfViewMiddleWare(CsrfViewMiddleware):
def _reject(self, request, reason):
if settings.CSRF_ALWAYS_OFF and reason in [REASON_NO_CSRF_COOKIE, REASON_BAD_TOKEN]:
warning = "Request at {url} doesn't contain a csrf token. Letting the request pass through for now. "\
"Check if we are sending csrf_token in the corresponding POST form, if not fix it. "\
"Read more here https://github.com/dimagi/commcare-hq/pull/9227".format(
url=request.path
)
+ logger.error(warning)
- _assert = soft_assert(notify_admins=True, exponential_backoff=True)
- _assert(False, warning)
-
return self._accept(request)
else:
return super(HQCsrfViewMiddleWare, self)._reject(request, reason) |
c96e82caaa3fd560263c54db71772b44e9cd78d7 | examples/upgrade_local_charm_k8s.py | examples/upgrade_local_charm_k8s.py | from juju import jasyncio
from juju.model import Model
async def main():
model = Model()
print('Connecting to model')
# Connect to current model with current user, per Juju CLI
await model.connect()
try:
print('Deploying bundle')
applications = await model.deploy(
'./examples/k8s-local-bundle/bundle.yaml',
)
print('Waiting for active')
await model.wait_for_idle(status='active')
print("Successfully deployed!")
await applications[0].upgrade_charm(path='./examples/charms/onos.charm')
await model.wait_for_idle(status='active')
print('Removing bundle')
for application in applications:
await application.remove()
finally:
print('Disconnecting from model')
await model.disconnect()
print("Success")
if __name__ == '__main__':
jasyncio.run(main())
| from juju import jasyncio
from juju.model import Model
async def main():
model = Model()
print('Connecting to model')
# Connect to current model with current user, per Juju CLI
await model.connect()
try:
print('Deploying bundle')
applications = await model.deploy(
'./examples/k8s-local-bundle/bundle.yaml',
)
print('Waiting for active')
await model.wait_for_idle(status='active')
print("Successfully deployed!")
local_path = './examples/charms/onos.charm'
print('Upgrading charm with %s' % local_path)
await applications[0].upgrade_charm(path=local_path)
await model.wait_for_idle(status='active')
print('Removing bundle')
for application in applications:
await application.remove()
finally:
print('Disconnecting from model')
await model.disconnect()
print("Success")
if __name__ == '__main__':
jasyncio.run(main())
| Make the example more informative | Make the example more informative
| Python | apache-2.0 | juju/python-libjuju,juju/python-libjuju | from juju import jasyncio
from juju.model import Model
async def main():
model = Model()
print('Connecting to model')
# Connect to current model with current user, per Juju CLI
await model.connect()
try:
print('Deploying bundle')
applications = await model.deploy(
'./examples/k8s-local-bundle/bundle.yaml',
)
print('Waiting for active')
await model.wait_for_idle(status='active')
print("Successfully deployed!")
+ local_path = './examples/charms/onos.charm'
+ print('Upgrading charm with %s' % local_path)
- await applications[0].upgrade_charm(path='./examples/charms/onos.charm')
+ await applications[0].upgrade_charm(path=local_path)
await model.wait_for_idle(status='active')
print('Removing bundle')
for application in applications:
await application.remove()
finally:
print('Disconnecting from model')
await model.disconnect()
print("Success")
if __name__ == '__main__':
jasyncio.run(main())
| Make the example more informative | ## Code Before:
from juju import jasyncio
from juju.model import Model
async def main():
model = Model()
print('Connecting to model')
# Connect to current model with current user, per Juju CLI
await model.connect()
try:
print('Deploying bundle')
applications = await model.deploy(
'./examples/k8s-local-bundle/bundle.yaml',
)
print('Waiting for active')
await model.wait_for_idle(status='active')
print("Successfully deployed!")
await applications[0].upgrade_charm(path='./examples/charms/onos.charm')
await model.wait_for_idle(status='active')
print('Removing bundle')
for application in applications:
await application.remove()
finally:
print('Disconnecting from model')
await model.disconnect()
print("Success")
if __name__ == '__main__':
jasyncio.run(main())
## Instruction:
Make the example more informative
## Code After:
from juju import jasyncio
from juju.model import Model
async def main():
model = Model()
print('Connecting to model')
# Connect to current model with current user, per Juju CLI
await model.connect()
try:
print('Deploying bundle')
applications = await model.deploy(
'./examples/k8s-local-bundle/bundle.yaml',
)
print('Waiting for active')
await model.wait_for_idle(status='active')
print("Successfully deployed!")
local_path = './examples/charms/onos.charm'
print('Upgrading charm with %s' % local_path)
await applications[0].upgrade_charm(path=local_path)
await model.wait_for_idle(status='active')
print('Removing bundle')
for application in applications:
await application.remove()
finally:
print('Disconnecting from model')
await model.disconnect()
print("Success")
if __name__ == '__main__':
jasyncio.run(main())
| from juju import jasyncio
from juju.model import Model
async def main():
model = Model()
print('Connecting to model')
# Connect to current model with current user, per Juju CLI
await model.connect()
try:
print('Deploying bundle')
applications = await model.deploy(
'./examples/k8s-local-bundle/bundle.yaml',
)
print('Waiting for active')
await model.wait_for_idle(status='active')
print("Successfully deployed!")
+ local_path = './examples/charms/onos.charm'
+ print('Upgrading charm with %s' % local_path)
- await applications[0].upgrade_charm(path='./examples/charms/onos.charm')
? ^^^^^ ^ ^^^^^ ----------------
+ await applications[0].upgrade_charm(path=local_path)
? ^^^ ^^ ^^
await model.wait_for_idle(status='active')
print('Removing bundle')
for application in applications:
await application.remove()
finally:
print('Disconnecting from model')
await model.disconnect()
print("Success")
if __name__ == '__main__':
jasyncio.run(main()) |
ad346d73a27c021de131ec871dc19da2e17854ee | armstrong/dev/virtualdjango/base.py | armstrong/dev/virtualdjango/base.py | import os, sys
DEFAULT_SETTINGS = {
'DATABASE_ENGINE': 'sqlite3',
'DATABASES': {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase'
}
},
}
class VirtualDjango(object):
def __init__(self,
caller=sys.modules['__main__'],
default_settings=DEFAULT_SETTINGS):
self.caller = caller
self.default_settings = default_settings
def configure_settings(self, customizations, reset=True):
# Django expects a `DATABASE_ENGINE` value
custom_settings = self.default_settings
custom_settings.update(customizations)
settings = self.settings
if reset:
settings._wrapped = None
settings.configure(**custom_settings)
@property
def settings(self):
from django.conf import settings
return settings
@property
def call_command(self):
from django.core.management import call_command
return call_command
def run(self, my_settings):
if hasattr(self.caller, 'setUp'):
self.caller.setUp()
self.configure_settings(my_settings)
return self.call_command
| import django
import os, sys
DEFAULT_SETTINGS = {
'DATABASE_ENGINE': 'sqlite3',
'DATABASES': {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase'
}
},
}
class VirtualDjango(object):
def __init__(self,
caller=sys.modules['__main__'],
default_settings=DEFAULT_SETTINGS):
self.caller = caller
self.default_settings = default_settings
def configure_settings(self, customizations, reset=True):
# Django expects a `DATABASE_ENGINE` value
custom_settings = self.default_settings
custom_settings.update(customizations)
settings = self.settings
if reset:
self.reset_settings(settings)
settings.configure(**custom_settings)
def reset_settings(self, settings):
if django.VERSION[:2] == (1, 3):
settings._wrapped = None
return
# This is the way to reset settings going forward
from django.utils.functional import empty
settings._wrapped = empty
@property
def settings(self):
from django.conf import settings
return settings
@property
def call_command(self):
from django.core.management import call_command
return call_command
def run(self, my_settings):
if hasattr(self.caller, 'setUp'):
self.caller.setUp()
self.configure_settings(my_settings)
return self.call_command
| Adjust the settings reset to work with Django 1.4 | Adjust the settings reset to work with Django 1.4
Django changed the `settings._wrapped` value from `None` to the special
`empty` object. This change maintains backwards compatibility for
1.3.X, while using the new method for all other versions of Django.
| Python | apache-2.0 | armstrong/armstrong.dev | + import django
import os, sys
DEFAULT_SETTINGS = {
'DATABASE_ENGINE': 'sqlite3',
'DATABASES': {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase'
}
},
}
class VirtualDjango(object):
def __init__(self,
caller=sys.modules['__main__'],
default_settings=DEFAULT_SETTINGS):
self.caller = caller
self.default_settings = default_settings
def configure_settings(self, customizations, reset=True):
# Django expects a `DATABASE_ENGINE` value
custom_settings = self.default_settings
custom_settings.update(customizations)
settings = self.settings
if reset:
+ self.reset_settings(settings)
+ settings.configure(**custom_settings)
+
+ def reset_settings(self, settings):
+ if django.VERSION[:2] == (1, 3):
settings._wrapped = None
- settings.configure(**custom_settings)
+ return
+
+ # This is the way to reset settings going forward
+ from django.utils.functional import empty
+ settings._wrapped = empty
@property
def settings(self):
from django.conf import settings
return settings
@property
def call_command(self):
from django.core.management import call_command
return call_command
def run(self, my_settings):
if hasattr(self.caller, 'setUp'):
self.caller.setUp()
self.configure_settings(my_settings)
return self.call_command
| Adjust the settings reset to work with Django 1.4 | ## Code Before:
import os, sys
DEFAULT_SETTINGS = {
'DATABASE_ENGINE': 'sqlite3',
'DATABASES': {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase'
}
},
}
class VirtualDjango(object):
def __init__(self,
caller=sys.modules['__main__'],
default_settings=DEFAULT_SETTINGS):
self.caller = caller
self.default_settings = default_settings
def configure_settings(self, customizations, reset=True):
# Django expects a `DATABASE_ENGINE` value
custom_settings = self.default_settings
custom_settings.update(customizations)
settings = self.settings
if reset:
settings._wrapped = None
settings.configure(**custom_settings)
@property
def settings(self):
from django.conf import settings
return settings
@property
def call_command(self):
from django.core.management import call_command
return call_command
def run(self, my_settings):
if hasattr(self.caller, 'setUp'):
self.caller.setUp()
self.configure_settings(my_settings)
return self.call_command
## Instruction:
Adjust the settings reset to work with Django 1.4
## Code After:
import django
import os, sys
DEFAULT_SETTINGS = {
'DATABASE_ENGINE': 'sqlite3',
'DATABASES': {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase'
}
},
}
class VirtualDjango(object):
def __init__(self,
caller=sys.modules['__main__'],
default_settings=DEFAULT_SETTINGS):
self.caller = caller
self.default_settings = default_settings
def configure_settings(self, customizations, reset=True):
# Django expects a `DATABASE_ENGINE` value
custom_settings = self.default_settings
custom_settings.update(customizations)
settings = self.settings
if reset:
self.reset_settings(settings)
settings.configure(**custom_settings)
def reset_settings(self, settings):
if django.VERSION[:2] == (1, 3):
settings._wrapped = None
return
# This is the way to reset settings going forward
from django.utils.functional import empty
settings._wrapped = empty
@property
def settings(self):
from django.conf import settings
return settings
@property
def call_command(self):
from django.core.management import call_command
return call_command
def run(self, my_settings):
if hasattr(self.caller, 'setUp'):
self.caller.setUp()
self.configure_settings(my_settings)
return self.call_command
| + import django
import os, sys
DEFAULT_SETTINGS = {
'DATABASE_ENGINE': 'sqlite3',
'DATABASES': {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase'
}
},
}
class VirtualDjango(object):
def __init__(self,
caller=sys.modules['__main__'],
default_settings=DEFAULT_SETTINGS):
self.caller = caller
self.default_settings = default_settings
def configure_settings(self, customizations, reset=True):
# Django expects a `DATABASE_ENGINE` value
custom_settings = self.default_settings
custom_settings.update(customizations)
settings = self.settings
if reset:
+ self.reset_settings(settings)
+ settings.configure(**custom_settings)
+
+ def reset_settings(self, settings):
+ if django.VERSION[:2] == (1, 3):
settings._wrapped = None
- settings.configure(**custom_settings)
+ return
+
+ # This is the way to reset settings going forward
+ from django.utils.functional import empty
+ settings._wrapped = empty
@property
def settings(self):
from django.conf import settings
return settings
@property
def call_command(self):
from django.core.management import call_command
return call_command
def run(self, my_settings):
if hasattr(self.caller, 'setUp'):
self.caller.setUp()
self.configure_settings(my_settings)
return self.call_command
|
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
| 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 |
0cb3aa5947b5c5da802c05ae16bc138441c2c921 | accounts/views.py | accounts/views.py | from django.shortcuts import render
def index(request):
if not request.user.is_authenticated():
return render(request, 'account/index.html')
else:
return render(request, 'account/user_home.html')
| from django.core.urlresolvers import reverse
from django.shortcuts import redirect, render
def index(request):
if not request.user.is_authenticated():
return render(request, 'account/index.html')
else:
return redirect(reverse('quizzes:index'))
| Use quiz index as user home temporarily | Use quiz index as user home temporarily
| Python | mit | lockhawksp/beethoven,lockhawksp/beethoven | + from django.core.urlresolvers import reverse
- from django.shortcuts import render
+ from django.shortcuts import redirect, render
def index(request):
if not request.user.is_authenticated():
return render(request, 'account/index.html')
else:
- return render(request, 'account/user_home.html')
+ return redirect(reverse('quizzes:index'))
| Use quiz index as user home temporarily | ## Code Before:
from django.shortcuts import render
def index(request):
if not request.user.is_authenticated():
return render(request, 'account/index.html')
else:
return render(request, 'account/user_home.html')
## Instruction:
Use quiz index as user home temporarily
## Code After:
from django.core.urlresolvers import reverse
from django.shortcuts import redirect, render
def index(request):
if not request.user.is_authenticated():
return render(request, 'account/index.html')
else:
return redirect(reverse('quizzes:index'))
| + from django.core.urlresolvers import reverse
- from django.shortcuts import render
+ from django.shortcuts import redirect, render
? ++++++++++
def index(request):
if not request.user.is_authenticated():
return render(request, 'account/index.html')
else:
- return render(request, 'account/user_home.html')
+ return redirect(reverse('quizzes:index')) |
2fba1c04c8083211df8664d87080480a1f63ed2a | csunplugged/utils/group_lessons_by_age.py | csunplugged/utils/group_lessons_by_age.py | """Return ordered groups of lessons."""
from collections import OrderedDict
from topics.models import (
AgeGroup,
LessonNumber,
)
def group_lessons_by_age(lessons):
"""Return ordered groups of lessons.
Lessons are grouped by the lesson minimum age and maximum ages,
and then order by number.
Args:
lessons: QuerySet of Lesson objects (QuerySet).
Returns:
A ordered dictionary of grouped lessons.
The key is a tuple of the minimum age and maximum ages for
the lessons.
The value for a key is a sorted list of lessons (ordered by number).
"""
grouped_lessons = OrderedDict()
for age_group in AgeGroup.objects.distinct():
for lesson in age_group.lessons.filter(id__in=lessons).order_by("lessonnumber"):
lesson.number = LessonNumber.objects.get(lesson=lesson, age_group=age_group).number
if age_group in grouped_lessons.keys():
grouped_lessons[age_group].append(lesson)
else:
grouped_lessons[age_group] = [lesson]
return grouped_lessons
| """Return ordered groups of lessons."""
from collections import OrderedDict
from topics.models import (
AgeGroup,
LessonNumber,
)
def group_lessons_by_age(lessons):
"""Return ordered groups of lessons.
Lessons are grouped by the lesson minimum age and maximum ages,
and then order by number.
Args:
lessons: QuerySet of Lesson objects (QuerySet).
Returns:
A ordered dictionary of grouped lessons.
The key is a tuple of the minimum age and maximum ages for
the lessons.
The value for a key is a sorted list of lessons (ordered by number).
"""
grouped_lessons = OrderedDict()
for age_group in AgeGroup.objects.distinct():
for lesson in age_group.lessons.filter(id__in=lessons).order_by("lessonnumber"):
lesson.number = LessonNumber.objects.get(lesson=lesson, age_group=age_group).number
if age_group in grouped_lessons.keys():
grouped_lessons[ages].add(lesson)
else:
grouped_lessons[ages] = set([lesson])
return grouped_lessons
| Fix bug where lessons are duplicated across age groups. | Fix bug where lessons are duplicated across age groups.
| Python | mit | uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged | """Return ordered groups of lessons."""
from collections import OrderedDict
from topics.models import (
AgeGroup,
LessonNumber,
)
def group_lessons_by_age(lessons):
"""Return ordered groups of lessons.
Lessons are grouped by the lesson minimum age and maximum ages,
and then order by number.
Args:
lessons: QuerySet of Lesson objects (QuerySet).
Returns:
A ordered dictionary of grouped lessons.
The key is a tuple of the minimum age and maximum ages for
the lessons.
The value for a key is a sorted list of lessons (ordered by number).
"""
grouped_lessons = OrderedDict()
for age_group in AgeGroup.objects.distinct():
for lesson in age_group.lessons.filter(id__in=lessons).order_by("lessonnumber"):
lesson.number = LessonNumber.objects.get(lesson=lesson, age_group=age_group).number
if age_group in grouped_lessons.keys():
- grouped_lessons[age_group].append(lesson)
+ grouped_lessons[ages].add(lesson)
else:
- grouped_lessons[age_group] = [lesson]
+ grouped_lessons[ages] = set([lesson])
return grouped_lessons
| Fix bug where lessons are duplicated across age groups. | ## Code Before:
"""Return ordered groups of lessons."""
from collections import OrderedDict
from topics.models import (
AgeGroup,
LessonNumber,
)
def group_lessons_by_age(lessons):
"""Return ordered groups of lessons.
Lessons are grouped by the lesson minimum age and maximum ages,
and then order by number.
Args:
lessons: QuerySet of Lesson objects (QuerySet).
Returns:
A ordered dictionary of grouped lessons.
The key is a tuple of the minimum age and maximum ages for
the lessons.
The value for a key is a sorted list of lessons (ordered by number).
"""
grouped_lessons = OrderedDict()
for age_group in AgeGroup.objects.distinct():
for lesson in age_group.lessons.filter(id__in=lessons).order_by("lessonnumber"):
lesson.number = LessonNumber.objects.get(lesson=lesson, age_group=age_group).number
if age_group in grouped_lessons.keys():
grouped_lessons[age_group].append(lesson)
else:
grouped_lessons[age_group] = [lesson]
return grouped_lessons
## Instruction:
Fix bug where lessons are duplicated across age groups.
## Code After:
"""Return ordered groups of lessons."""
from collections import OrderedDict
from topics.models import (
AgeGroup,
LessonNumber,
)
def group_lessons_by_age(lessons):
"""Return ordered groups of lessons.
Lessons are grouped by the lesson minimum age and maximum ages,
and then order by number.
Args:
lessons: QuerySet of Lesson objects (QuerySet).
Returns:
A ordered dictionary of grouped lessons.
The key is a tuple of the minimum age and maximum ages for
the lessons.
The value for a key is a sorted list of lessons (ordered by number).
"""
grouped_lessons = OrderedDict()
for age_group in AgeGroup.objects.distinct():
for lesson in age_group.lessons.filter(id__in=lessons).order_by("lessonnumber"):
lesson.number = LessonNumber.objects.get(lesson=lesson, age_group=age_group).number
if age_group in grouped_lessons.keys():
grouped_lessons[ages].add(lesson)
else:
grouped_lessons[ages] = set([lesson])
return grouped_lessons
| """Return ordered groups of lessons."""
from collections import OrderedDict
from topics.models import (
AgeGroup,
LessonNumber,
)
def group_lessons_by_age(lessons):
"""Return ordered groups of lessons.
Lessons are grouped by the lesson minimum age and maximum ages,
and then order by number.
Args:
lessons: QuerySet of Lesson objects (QuerySet).
Returns:
A ordered dictionary of grouped lessons.
The key is a tuple of the minimum age and maximum ages for
the lessons.
The value for a key is a sorted list of lessons (ordered by number).
"""
grouped_lessons = OrderedDict()
for age_group in AgeGroup.objects.distinct():
for lesson in age_group.lessons.filter(id__in=lessons).order_by("lessonnumber"):
lesson.number = LessonNumber.objects.get(lesson=lesson, age_group=age_group).number
if age_group in grouped_lessons.keys():
- grouped_lessons[age_group].append(lesson)
? ^^^^^^ ^^^^
+ grouped_lessons[ages].add(lesson)
? ^ ^
else:
- grouped_lessons[age_group] = [lesson]
? ^^^^^^
+ grouped_lessons[ages] = set([lesson])
? ^ ++++ +
return grouped_lessons |
63a32acb6e2f9aadec015361f04283999f75be79 | examples/app/localmodule.py | examples/app/localmodule.py | def install_module(app):
"""Installs this localmodule."""
install_module
| class IndexResource(object):
def on_get(self, req, res):
res.body = 'Hello. This is app.'
def install_module(app):
"""Installs this localmodule."""
app.api.add_route('/', IndexResource())
| Add IndexResource to example module. | Add IndexResource to example module.
| Python | apache-2.0 | slinghq/sling | + class IndexResource(object):
+
+ def on_get(self, req, res):
+ res.body = 'Hello. This is app.'
+
+
def install_module(app):
"""Installs this localmodule."""
- install_module
+ app.api.add_route('/', IndexResource())
| Add IndexResource to example module. | ## Code Before:
def install_module(app):
"""Installs this localmodule."""
install_module
## Instruction:
Add IndexResource to example module.
## Code After:
class IndexResource(object):
def on_get(self, req, res):
res.body = 'Hello. This is app.'
def install_module(app):
"""Installs this localmodule."""
app.api.add_route('/', IndexResource())
| + class IndexResource(object):
+
+ def on_get(self, req, res):
+ res.body = 'Hello. This is app.'
+
+
def install_module(app):
"""Installs this localmodule."""
- install_module
+ app.api.add_route('/', IndexResource()) |
c00a55b8337dbc354921c195dfa4becc7ee1346a | ipython/profile_default/startup/00-imports.py | ipython/profile_default/startup/00-imports.py | """Imports for IPython"""
# pylint: disable=W0611
# import this
import os
import re
import sys
import inspect
pyprint = print
mores = []
try:
from rich.console import Console
console = Console(color_system="standard")
print = console.print
mores += ["rich"]
except ImportError:
pass
try:
from importlib import reload
except ImportError:
def reload(x):
raise NotImplementedError("importlib.reload is not available")
try:
import requests
mores += ["requests"]
except ModuleNotFoundError:
pass
try:
import pysyte
from pysyte.types import paths
from pysyte.types.paths import path
from pysyte import cli
except ImportError as e:
print(e)
sys.stderr.write("pip install pysyte # please")
try:
from pathlib import Path
mores += ["Path"]
except ImportError:
pass
more = ", ".join([" "] + mores) if mores else ""
executable = sys.executable.replace(os.environ['HOME'], '~')
version = sys.version.split()[0]
stdout = lambda x: sys.stdout.write(f"{x}\n")
stdout(f"import os, re, sys, inspect, pysyte, paths, path, cli{more}")
stdout("")
stdout(f"{executable} {version}")
| """Imports for IPython"""
# pylint: disable=W0611
# import this
import os
import re
import sys
import inspect
pyprint = print
mores = []
try:
from rich.console import Console
console = Console(color_system="standard")
print = console.print
mores += ["rich"]
from rich import pretty
pretty.install()
except ImportError:
pass
try:
from importlib import reload
except ImportError:
def reload(x):
raise NotImplementedError("importlib.reload is not available")
try:
import requests
mores += ["requests"]
except ModuleNotFoundError:
pass
try:
import pysyte
from pysyte.types import paths
from pysyte.types.paths import path
from pysyte import cli
except ImportError as e:
print(e)
sys.stderr.write("pip install pysyte # please")
try:
from pathlib import Path
mores += ["Path"]
except ImportError:
pass
more = ", ".join([" "] + mores) if mores else ""
executable = sys.executable.replace(os.environ['HOME'], '~')
version = sys.version.split()[0]
stdout = lambda x: sys.stdout.write(f"{x}\n")
stdout(f"import os, re, sys, inspect, pysyte, paths, path, cli{more}")
stdout("")
stdout(f"{executable} {version}")
| Use rich for printing in ipython | Use rich for printing in ipython
| Python | mit | jalanb/jab,jalanb/dotjab,jalanb/dotjab,jalanb/jab | """Imports for IPython"""
# pylint: disable=W0611
# import this
import os
import re
import sys
import inspect
pyprint = print
mores = []
try:
from rich.console import Console
console = Console(color_system="standard")
print = console.print
mores += ["rich"]
+ from rich import pretty
+ pretty.install()
except ImportError:
pass
try:
from importlib import reload
except ImportError:
def reload(x):
raise NotImplementedError("importlib.reload is not available")
try:
import requests
mores += ["requests"]
except ModuleNotFoundError:
pass
try:
import pysyte
from pysyte.types import paths
from pysyte.types.paths import path
from pysyte import cli
except ImportError as e:
print(e)
sys.stderr.write("pip install pysyte # please")
try:
from pathlib import Path
mores += ["Path"]
except ImportError:
pass
more = ", ".join([" "] + mores) if mores else ""
executable = sys.executable.replace(os.environ['HOME'], '~')
version = sys.version.split()[0]
stdout = lambda x: sys.stdout.write(f"{x}\n")
stdout(f"import os, re, sys, inspect, pysyte, paths, path, cli{more}")
stdout("")
stdout(f"{executable} {version}")
| Use rich for printing in ipython | ## Code Before:
"""Imports for IPython"""
# pylint: disable=W0611
# import this
import os
import re
import sys
import inspect
pyprint = print
mores = []
try:
from rich.console import Console
console = Console(color_system="standard")
print = console.print
mores += ["rich"]
except ImportError:
pass
try:
from importlib import reload
except ImportError:
def reload(x):
raise NotImplementedError("importlib.reload is not available")
try:
import requests
mores += ["requests"]
except ModuleNotFoundError:
pass
try:
import pysyte
from pysyte.types import paths
from pysyte.types.paths import path
from pysyte import cli
except ImportError as e:
print(e)
sys.stderr.write("pip install pysyte # please")
try:
from pathlib import Path
mores += ["Path"]
except ImportError:
pass
more = ", ".join([" "] + mores) if mores else ""
executable = sys.executable.replace(os.environ['HOME'], '~')
version = sys.version.split()[0]
stdout = lambda x: sys.stdout.write(f"{x}\n")
stdout(f"import os, re, sys, inspect, pysyte, paths, path, cli{more}")
stdout("")
stdout(f"{executable} {version}")
## Instruction:
Use rich for printing in ipython
## Code After:
"""Imports for IPython"""
# pylint: disable=W0611
# import this
import os
import re
import sys
import inspect
pyprint = print
mores = []
try:
from rich.console import Console
console = Console(color_system="standard")
print = console.print
mores += ["rich"]
from rich import pretty
pretty.install()
except ImportError:
pass
try:
from importlib import reload
except ImportError:
def reload(x):
raise NotImplementedError("importlib.reload is not available")
try:
import requests
mores += ["requests"]
except ModuleNotFoundError:
pass
try:
import pysyte
from pysyte.types import paths
from pysyte.types.paths import path
from pysyte import cli
except ImportError as e:
print(e)
sys.stderr.write("pip install pysyte # please")
try:
from pathlib import Path
mores += ["Path"]
except ImportError:
pass
more = ", ".join([" "] + mores) if mores else ""
executable = sys.executable.replace(os.environ['HOME'], '~')
version = sys.version.split()[0]
stdout = lambda x: sys.stdout.write(f"{x}\n")
stdout(f"import os, re, sys, inspect, pysyte, paths, path, cli{more}")
stdout("")
stdout(f"{executable} {version}")
| """Imports for IPython"""
# pylint: disable=W0611
# import this
import os
import re
import sys
import inspect
pyprint = print
mores = []
try:
from rich.console import Console
console = Console(color_system="standard")
print = console.print
mores += ["rich"]
+ from rich import pretty
+ pretty.install()
except ImportError:
pass
try:
from importlib import reload
except ImportError:
def reload(x):
raise NotImplementedError("importlib.reload is not available")
try:
import requests
mores += ["requests"]
except ModuleNotFoundError:
pass
try:
import pysyte
from pysyte.types import paths
from pysyte.types.paths import path
from pysyte import cli
except ImportError as e:
print(e)
sys.stderr.write("pip install pysyte # please")
try:
from pathlib import Path
mores += ["Path"]
except ImportError:
pass
more = ", ".join([" "] + mores) if mores else ""
executable = sys.executable.replace(os.environ['HOME'], '~')
version = sys.version.split()[0]
stdout = lambda x: sys.stdout.write(f"{x}\n")
stdout(f"import os, re, sys, inspect, pysyte, paths, path, cli{more}")
stdout("")
stdout(f"{executable} {version}")
|
9cb2bf5d1432bf45666f939356bfe7057d8e5960 | server/mod_auth/auth.py | server/mod_auth/auth.py | from flask import Response
from flask_login import login_user
from server.models import User
from server.login_manager import login_manager
@login_manager.user_loader
def load_user(user_id):
"""Returns a user from the database based on their id"""
return User.query.filter_by(id=user_id).first()
def handle_basic_auth(request):
auth = request.authorization
if not auth:
return None
return User.query.filter_by(
username=auth.username,
password=auth.password
).first()
def login(request):
"""Handle a login request from a user."""
user = handle_basic_auth(request)
if user:
login_user(user, remember=True)
return 'OK'
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
| import flask
from flask_login import login_user
from server.models import User
from server.login_manager import login_manager
@login_manager.user_loader
def load_user(user_id: int) -> User:
"""Returns a user from the database based on their id
:param user_id: a users unique id
:return: User object with corresponding id, or none if user does not exist
"""
return User.query.filter_by(id=user_id).first()
def handle_basic_auth(request: flask.Request) -> User:
"""Verifies a request using BASIC auth
:param request: flask request object
:return: User object corresponding to login information, or none if user does not exist
"""
auth = request.authorization
if not auth:
return None
return User.query.filter_by(
username=auth.username,
password=auth.password
).first()
def login(request: flask.Request) -> flask.Response:
"""Handle a login request from a user
:param request: incoming request object
:return: flask response object
"""
user = handle_basic_auth(request)
if user:
login_user(user, remember=True)
return 'OK'
return flask.Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
| Add type declartions and docstrings | Add type declartions and docstrings
| Python | mit | ganemone/ontheside,ganemone/ontheside,ganemone/ontheside | + import flask
- from flask import Response
-
from flask_login import login_user
from server.models import User
from server.login_manager import login_manager
@login_manager.user_loader
- def load_user(user_id):
+ def load_user(user_id: int) -> User:
- """Returns a user from the database based on their id"""
+ """Returns a user from the database based on their id
+
+ :param user_id: a users unique id
+ :return: User object with corresponding id, or none if user does not exist
+ """
return User.query.filter_by(id=user_id).first()
- def handle_basic_auth(request):
+ def handle_basic_auth(request: flask.Request) -> User:
+ """Verifies a request using BASIC auth
+
+ :param request: flask request object
+ :return: User object corresponding to login information, or none if user does not exist
+ """
auth = request.authorization
if not auth:
return None
return User.query.filter_by(
username=auth.username,
password=auth.password
).first()
- def login(request):
+ def login(request: flask.Request) -> flask.Response:
- """Handle a login request from a user."""
+ """Handle a login request from a user
+
+ :param request: incoming request object
+ :return: flask response object
+ """
user = handle_basic_auth(request)
if user:
login_user(user, remember=True)
return 'OK'
- return Response(
+ return flask.Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
| Add type declartions and docstrings | ## Code Before:
from flask import Response
from flask_login import login_user
from server.models import User
from server.login_manager import login_manager
@login_manager.user_loader
def load_user(user_id):
"""Returns a user from the database based on their id"""
return User.query.filter_by(id=user_id).first()
def handle_basic_auth(request):
auth = request.authorization
if not auth:
return None
return User.query.filter_by(
username=auth.username,
password=auth.password
).first()
def login(request):
"""Handle a login request from a user."""
user = handle_basic_auth(request)
if user:
login_user(user, remember=True)
return 'OK'
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
## Instruction:
Add type declartions and docstrings
## Code After:
import flask
from flask_login import login_user
from server.models import User
from server.login_manager import login_manager
@login_manager.user_loader
def load_user(user_id: int) -> User:
"""Returns a user from the database based on their id
:param user_id: a users unique id
:return: User object with corresponding id, or none if user does not exist
"""
return User.query.filter_by(id=user_id).first()
def handle_basic_auth(request: flask.Request) -> User:
"""Verifies a request using BASIC auth
:param request: flask request object
:return: User object corresponding to login information, or none if user does not exist
"""
auth = request.authorization
if not auth:
return None
return User.query.filter_by(
username=auth.username,
password=auth.password
).first()
def login(request: flask.Request) -> flask.Response:
"""Handle a login request from a user
:param request: incoming request object
:return: flask response object
"""
user = handle_basic_auth(request)
if user:
login_user(user, remember=True)
return 'OK'
return flask.Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
| + import flask
- from flask import Response
-
from flask_login import login_user
from server.models import User
from server.login_manager import login_manager
@login_manager.user_loader
- def load_user(user_id):
+ def load_user(user_id: int) -> User:
? +++++ ++++++++
- """Returns a user from the database based on their id"""
? ---
+ """Returns a user from the database based on their id
+
+ :param user_id: a users unique id
+ :return: User object with corresponding id, or none if user does not exist
+ """
return User.query.filter_by(id=user_id).first()
- def handle_basic_auth(request):
+ def handle_basic_auth(request: flask.Request) -> User:
+ """Verifies a request using BASIC auth
+
+ :param request: flask request object
+ :return: User object corresponding to login information, or none if user does not exist
+ """
auth = request.authorization
if not auth:
return None
return User.query.filter_by(
username=auth.username,
password=auth.password
).first()
- def login(request):
+ def login(request: flask.Request) -> flask.Response:
- """Handle a login request from a user."""
? ----
+ """Handle a login request from a user
+
+ :param request: incoming request object
+ :return: flask response object
+ """
user = handle_basic_auth(request)
if user:
login_user(user, remember=True)
return 'OK'
- return Response(
+ return flask.Response(
? ++++++
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'}) |
e066eae6bb0f9d555a53f9ee2901c77ffebd3647 | tracer/cachemanager/cachemanager.py | tracer/cachemanager/cachemanager.py | import pickle
import claripy
import logging
from ..simprocedures import receive
l = logging.getLogger("tracer.cachemanager.CacheManager")
class CacheManager(object):
def __init__(self):
self.tracer = None
def set_tracer(self, tracer):
self.tracer = tracer
def cacher(self, simstate):
raise NotImplementedError("subclasses must implement this method")
def cache_lookup(self):
raise NotImplementedError("subclasses must implement this method")
def _prepare_cache_data(self, simstate):
state = self.tracer.previous.state
ds = None
try:
ds = pickle.dumps((self.tracer.bb_cnt - 1, self.tracer.cgc_flag_bytes, state, claripy.ast.base.var_counter), pickle.HIGHEST_PROTOCOL)
except RuntimeError as e: # maximum recursion depth can be reached here
l.error("unable to cache state, '%s' during pickling", e.message)
# unhook receive
receive.cache_hook = None
# add preconstraints to tracer
self.tracer._preconstrain_state(simstate)
return ds
| import pickle
import claripy
import logging
from ..simprocedures import receive
l = logging.getLogger("tracer.cachemanager.CacheManager")
class CacheManager(object):
def __init__(self):
self.tracer = None
def set_tracer(self, tracer):
self.tracer = tracer
def cacher(self, simstate):
raise NotImplementedError("subclasses must implement this method")
def cache_lookup(self):
raise NotImplementedError("subclasses must implement this method")
def _prepare_cache_data(self, simstate):
if self.tracer.previous != None:
state = self.tracer.previous.state
else:
state = None
ds = None
try:
ds = pickle.dumps((self.tracer.bb_cnt - 1, self.tracer.cgc_flag_bytes, state, claripy.ast.base.var_counter), pickle.HIGHEST_PROTOCOL)
except RuntimeError as e: # maximum recursion depth can be reached here
l.error("unable to cache state, '%s' during pickling", e.message)
# unhook receive
receive.cache_hook = None
# add preconstraints to tracer
self.tracer._preconstrain_state(simstate)
return ds
| Fix a bug in the cache manager | Fix a bug in the cache manager
It is possible that the previous state is None
| Python | bsd-2-clause | schieb/angr,schieb/angr,angr/angr,angr/angr,tyb0807/angr,iamahuman/angr,f-prettyland/angr,tyb0807/angr,iamahuman/angr,iamahuman/angr,tyb0807/angr,angr/angr,schieb/angr,angr/tracer,f-prettyland/angr,f-prettyland/angr | import pickle
import claripy
import logging
from ..simprocedures import receive
l = logging.getLogger("tracer.cachemanager.CacheManager")
class CacheManager(object):
def __init__(self):
self.tracer = None
def set_tracer(self, tracer):
self.tracer = tracer
def cacher(self, simstate):
raise NotImplementedError("subclasses must implement this method")
def cache_lookup(self):
raise NotImplementedError("subclasses must implement this method")
def _prepare_cache_data(self, simstate):
+ if self.tracer.previous != None:
- state = self.tracer.previous.state
+ state = self.tracer.previous.state
+ else:
+ state = None
ds = None
try:
ds = pickle.dumps((self.tracer.bb_cnt - 1, self.tracer.cgc_flag_bytes, state, claripy.ast.base.var_counter), pickle.HIGHEST_PROTOCOL)
except RuntimeError as e: # maximum recursion depth can be reached here
l.error("unable to cache state, '%s' during pickling", e.message)
# unhook receive
receive.cache_hook = None
# add preconstraints to tracer
self.tracer._preconstrain_state(simstate)
return ds
| Fix a bug in the cache manager | ## Code Before:
import pickle
import claripy
import logging
from ..simprocedures import receive
l = logging.getLogger("tracer.cachemanager.CacheManager")
class CacheManager(object):
def __init__(self):
self.tracer = None
def set_tracer(self, tracer):
self.tracer = tracer
def cacher(self, simstate):
raise NotImplementedError("subclasses must implement this method")
def cache_lookup(self):
raise NotImplementedError("subclasses must implement this method")
def _prepare_cache_data(self, simstate):
state = self.tracer.previous.state
ds = None
try:
ds = pickle.dumps((self.tracer.bb_cnt - 1, self.tracer.cgc_flag_bytes, state, claripy.ast.base.var_counter), pickle.HIGHEST_PROTOCOL)
except RuntimeError as e: # maximum recursion depth can be reached here
l.error("unable to cache state, '%s' during pickling", e.message)
# unhook receive
receive.cache_hook = None
# add preconstraints to tracer
self.tracer._preconstrain_state(simstate)
return ds
## Instruction:
Fix a bug in the cache manager
## Code After:
import pickle
import claripy
import logging
from ..simprocedures import receive
l = logging.getLogger("tracer.cachemanager.CacheManager")
class CacheManager(object):
def __init__(self):
self.tracer = None
def set_tracer(self, tracer):
self.tracer = tracer
def cacher(self, simstate):
raise NotImplementedError("subclasses must implement this method")
def cache_lookup(self):
raise NotImplementedError("subclasses must implement this method")
def _prepare_cache_data(self, simstate):
if self.tracer.previous != None:
state = self.tracer.previous.state
else:
state = None
ds = None
try:
ds = pickle.dumps((self.tracer.bb_cnt - 1, self.tracer.cgc_flag_bytes, state, claripy.ast.base.var_counter), pickle.HIGHEST_PROTOCOL)
except RuntimeError as e: # maximum recursion depth can be reached here
l.error("unable to cache state, '%s' during pickling", e.message)
# unhook receive
receive.cache_hook = None
# add preconstraints to tracer
self.tracer._preconstrain_state(simstate)
return ds
| import pickle
import claripy
import logging
from ..simprocedures import receive
l = logging.getLogger("tracer.cachemanager.CacheManager")
class CacheManager(object):
def __init__(self):
self.tracer = None
def set_tracer(self, tracer):
self.tracer = tracer
def cacher(self, simstate):
raise NotImplementedError("subclasses must implement this method")
def cache_lookup(self):
raise NotImplementedError("subclasses must implement this method")
def _prepare_cache_data(self, simstate):
+ if self.tracer.previous != None:
- state = self.tracer.previous.state
+ state = self.tracer.previous.state
? ++++
+ else:
+ state = None
ds = None
try:
ds = pickle.dumps((self.tracer.bb_cnt - 1, self.tracer.cgc_flag_bytes, state, claripy.ast.base.var_counter), pickle.HIGHEST_PROTOCOL)
except RuntimeError as e: # maximum recursion depth can be reached here
l.error("unable to cache state, '%s' during pickling", e.message)
# unhook receive
receive.cache_hook = None
# add preconstraints to tracer
self.tracer._preconstrain_state(simstate)
return ds |
9334d20adb15f3a6be393c57c797311e31fcd8fc | ConectorDriverComando.py | ConectorDriverComando.py | from serial import SerialException
import importlib
import threading
import logging
class ConectorError(Exception):
pass
class ConectorDriverComando:
driver = None
def __init__(self, comando, driver, *args, **kwargs):
logging.getLogger().info("inicializando ConectorDriverComando driver de %s" % driver)
self._comando = comando
self.driver_name = driver
# instanciar el driver dinamicamente segun el driver pasado como parametro
libraryName = "Drivers." + driver + "Driver"
driverModule = importlib.import_module(libraryName)
driverClass = getattr(driverModule, driver + "Driver")
self.driver = driverClass(**kwargs)
def sendCommand(self, *args):
logging.getLogger().info("Enviando comando %s" % args)
return self.driver.sendCommand(*args)
def close(self):
# Si el driver es Receipt, se cierra desde la misma clase del driver, sino, tira error de Bad File Descriptor por querer cerrarlo dos veces.
if self.driver_name == "ReceiptDirectJet":
if self.driver.connected is False:
return None
self.driver.close()
self.driver = None | from serial import SerialException
import importlib
import threading
import logging
class ConectorError(Exception):
pass
class ConectorDriverComando:
driver = None
def __init__(self, comando, driver, *args, **kwargs):
# logging.getLogger().info("inicializando ConectorDriverComando driver de %s" % driver)
logging.getLogger().info("inicializando ConectorDriverComando driver de '${0}'".format(driver))
self._comando = comando
self.driver_name = driver
# instanciar el driver dinamicamente segun el driver pasado como parametro
libraryName = "Drivers." + driver + "Driver"
driverModule = importlib.import_module(libraryName)
driverClass = getattr(driverModule, driver + "Driver")
self.driver = driverClass(**kwargs)
def sendCommand(self, *args):
# logging.getLogger().info("Enviando comando %s" % args)
logging.getLogger().info("Enviando comando '${0}'".format(args))
return self.driver.sendCommand(*args)
def close(self):
# Si el driver es Receipt, se cierra desde la misma clase del driver, sino, tira error de Bad File Descriptor por querer cerrarlo dos veces.
if self.driver_name == "ReceiptDirectJet":
if self.driver.connected is False:
return None
self.driver.close()
self.driver = None | FIX Format String Error in Conector Driver Comando | FIX Format String Error in Conector Driver Comando
| Python | mit | ristorantino/fiscalberry,ristorantino/fiscalberry,ristorantino/fiscalberry,ristorantino/fiscalberry | from serial import SerialException
import importlib
import threading
import logging
class ConectorError(Exception):
pass
class ConectorDriverComando:
driver = None
def __init__(self, comando, driver, *args, **kwargs):
- logging.getLogger().info("inicializando ConectorDriverComando driver de %s" % driver)
+ # logging.getLogger().info("inicializando ConectorDriverComando driver de %s" % driver)
+ logging.getLogger().info("inicializando ConectorDriverComando driver de '${0}'".format(driver))
self._comando = comando
self.driver_name = driver
# instanciar el driver dinamicamente segun el driver pasado como parametro
libraryName = "Drivers." + driver + "Driver"
driverModule = importlib.import_module(libraryName)
driverClass = getattr(driverModule, driver + "Driver")
self.driver = driverClass(**kwargs)
def sendCommand(self, *args):
- logging.getLogger().info("Enviando comando %s" % args)
+ # logging.getLogger().info("Enviando comando %s" % args)
+ logging.getLogger().info("Enviando comando '${0}'".format(args))
return self.driver.sendCommand(*args)
def close(self):
# Si el driver es Receipt, se cierra desde la misma clase del driver, sino, tira error de Bad File Descriptor por querer cerrarlo dos veces.
if self.driver_name == "ReceiptDirectJet":
if self.driver.connected is False:
return None
self.driver.close()
self.driver = None | FIX Format String Error in Conector Driver Comando | ## Code Before:
from serial import SerialException
import importlib
import threading
import logging
class ConectorError(Exception):
pass
class ConectorDriverComando:
driver = None
def __init__(self, comando, driver, *args, **kwargs):
logging.getLogger().info("inicializando ConectorDriverComando driver de %s" % driver)
self._comando = comando
self.driver_name = driver
# instanciar el driver dinamicamente segun el driver pasado como parametro
libraryName = "Drivers." + driver + "Driver"
driverModule = importlib.import_module(libraryName)
driverClass = getattr(driverModule, driver + "Driver")
self.driver = driverClass(**kwargs)
def sendCommand(self, *args):
logging.getLogger().info("Enviando comando %s" % args)
return self.driver.sendCommand(*args)
def close(self):
# Si el driver es Receipt, se cierra desde la misma clase del driver, sino, tira error de Bad File Descriptor por querer cerrarlo dos veces.
if self.driver_name == "ReceiptDirectJet":
if self.driver.connected is False:
return None
self.driver.close()
self.driver = None
## Instruction:
FIX Format String Error in Conector Driver Comando
## Code After:
from serial import SerialException
import importlib
import threading
import logging
class ConectorError(Exception):
pass
class ConectorDriverComando:
driver = None
def __init__(self, comando, driver, *args, **kwargs):
# logging.getLogger().info("inicializando ConectorDriverComando driver de %s" % driver)
logging.getLogger().info("inicializando ConectorDriverComando driver de '${0}'".format(driver))
self._comando = comando
self.driver_name = driver
# instanciar el driver dinamicamente segun el driver pasado como parametro
libraryName = "Drivers." + driver + "Driver"
driverModule = importlib.import_module(libraryName)
driverClass = getattr(driverModule, driver + "Driver")
self.driver = driverClass(**kwargs)
def sendCommand(self, *args):
# logging.getLogger().info("Enviando comando %s" % args)
logging.getLogger().info("Enviando comando '${0}'".format(args))
return self.driver.sendCommand(*args)
def close(self):
# Si el driver es Receipt, se cierra desde la misma clase del driver, sino, tira error de Bad File Descriptor por querer cerrarlo dos veces.
if self.driver_name == "ReceiptDirectJet":
if self.driver.connected is False:
return None
self.driver.close()
self.driver = None | from serial import SerialException
import importlib
import threading
import logging
class ConectorError(Exception):
pass
class ConectorDriverComando:
driver = None
def __init__(self, comando, driver, *args, **kwargs):
- logging.getLogger().info("inicializando ConectorDriverComando driver de %s" % driver)
+ # logging.getLogger().info("inicializando ConectorDriverComando driver de %s" % driver)
? ++
+ logging.getLogger().info("inicializando ConectorDriverComando driver de '${0}'".format(driver))
self._comando = comando
self.driver_name = driver
# instanciar el driver dinamicamente segun el driver pasado como parametro
libraryName = "Drivers." + driver + "Driver"
driverModule = importlib.import_module(libraryName)
driverClass = getattr(driverModule, driver + "Driver")
self.driver = driverClass(**kwargs)
def sendCommand(self, *args):
- logging.getLogger().info("Enviando comando %s" % args)
+ # logging.getLogger().info("Enviando comando %s" % args)
? ++
+ logging.getLogger().info("Enviando comando '${0}'".format(args))
return self.driver.sendCommand(*args)
def close(self):
# Si el driver es Receipt, se cierra desde la misma clase del driver, sino, tira error de Bad File Descriptor por querer cerrarlo dos veces.
if self.driver_name == "ReceiptDirectJet":
if self.driver.connected is False:
return None
self.driver.close()
self.driver = None |
09ae901f6def59a2d44aa994cb545afb559f9eb1 | dodo_commands/system_commands/activate.py | dodo_commands/system_commands/activate.py | from dodo_commands.system_commands import DodoCommand
from dodo_commands.dodo_activate import Activator
class Command(DodoCommand): # noqa
help = ""
decorators = []
def add_arguments_imp(self, parser): # noqa
parser.add_argument('project', nargs='?')
group = parser.add_mutually_exclusive_group()
group.add_argument('--latest', action="store_true")
group.add_argument('--create', action="store_true")
def handle_imp(self, project, latest, create, **kwargs): # noqa
Activator().run(project, latest, create)
| from dodo_commands.system_commands import DodoCommand, CommandError
from dodo_commands.dodo_activate import Activator
class Command(DodoCommand): # noqa
help = ""
decorators = []
def add_arguments_imp(self, parser): # noqa
parser.add_argument('project', nargs='?')
group = parser.add_mutually_exclusive_group()
group.add_argument('--latest', action="store_true")
group.add_argument('--create', action="store_true")
def handle_imp(self, project, latest, create, **kwargs): # noqa
if not project and not latest:
raise CommandError("No project was specified")
Activator().run(project, latest, create)
| Fix crash when no project is specified | Fix crash when no project is specified
| Python | mit | mnieber/dodo_commands | - from dodo_commands.system_commands import DodoCommand
+ from dodo_commands.system_commands import DodoCommand, CommandError
from dodo_commands.dodo_activate import Activator
class Command(DodoCommand): # noqa
help = ""
decorators = []
def add_arguments_imp(self, parser): # noqa
parser.add_argument('project', nargs='?')
group = parser.add_mutually_exclusive_group()
group.add_argument('--latest', action="store_true")
group.add_argument('--create', action="store_true")
def handle_imp(self, project, latest, create, **kwargs): # noqa
+ if not project and not latest:
+ raise CommandError("No project was specified")
Activator().run(project, latest, create)
| Fix crash when no project is specified | ## Code Before:
from dodo_commands.system_commands import DodoCommand
from dodo_commands.dodo_activate import Activator
class Command(DodoCommand): # noqa
help = ""
decorators = []
def add_arguments_imp(self, parser): # noqa
parser.add_argument('project', nargs='?')
group = parser.add_mutually_exclusive_group()
group.add_argument('--latest', action="store_true")
group.add_argument('--create', action="store_true")
def handle_imp(self, project, latest, create, **kwargs): # noqa
Activator().run(project, latest, create)
## Instruction:
Fix crash when no project is specified
## Code After:
from dodo_commands.system_commands import DodoCommand, CommandError
from dodo_commands.dodo_activate import Activator
class Command(DodoCommand): # noqa
help = ""
decorators = []
def add_arguments_imp(self, parser): # noqa
parser.add_argument('project', nargs='?')
group = parser.add_mutually_exclusive_group()
group.add_argument('--latest', action="store_true")
group.add_argument('--create', action="store_true")
def handle_imp(self, project, latest, create, **kwargs): # noqa
if not project and not latest:
raise CommandError("No project was specified")
Activator().run(project, latest, create)
| - from dodo_commands.system_commands import DodoCommand
+ from dodo_commands.system_commands import DodoCommand, CommandError
? ++++++++++++++
from dodo_commands.dodo_activate import Activator
class Command(DodoCommand): # noqa
help = ""
decorators = []
def add_arguments_imp(self, parser): # noqa
parser.add_argument('project', nargs='?')
group = parser.add_mutually_exclusive_group()
group.add_argument('--latest', action="store_true")
group.add_argument('--create', action="store_true")
def handle_imp(self, project, latest, create, **kwargs): # noqa
+ if not project and not latest:
+ raise CommandError("No project was specified")
Activator().run(project, latest, create) |
b42dddaa45a8915a653f4b145f2a58eb6996f28a | home/openbox/lib/helpers.py | home/openbox/lib/helpers.py | import os.path, os
def run_as_browser(fn):
def wrapped(*args, **kwargs):
rv = fn(*args, **kwargs)
return 'sudo -Hiu browser %s' % rv
return wrapped
class Helpers:
@property
@run_as_browser
def default_firefox_bin(self):
candidates = [
'/usr/local/lib/firefox/firefox-bin',
'/usr/local/lib/firefox3/firefox-bin',
'/usr/bin/iceweasel',
]
return self._pick(candidates, os.path.exists)
@property
@run_as_browser
def default_firefox_wrapper(self):
candidates = [
'firefox', 'firefox3'
]
return self._pick(candidates, self._wrapper_tester)
default_firefox = default_firefox_wrapper
@property
def as_browser(self):
return 'sudo -Hiu browser'
@property
def opera(self):
return 'sudo -Hiu browser opera'
@property
def chrome(self):
return 'sudo -Hiu browser chrome'
def have_bin(self, basename):
return self._wrapper_tester(basename)
def _wrapper_tester(self, candidate):
dirs = os.environ['PATH'].split(':')
for dir in dirs:
path = os.path.join(dir, candidate)
if os.path.exists(path):
return True
return False
def _pick(self, candidates, tester):
for candidate in candidates:
if tester(candidate):
return candidate
# consider raising here
return None
| import os.path, os
def run_as_browser(fn):
def wrapped(*args, **kwargs):
rv = fn(*args, **kwargs)
return 'sudo -Hiu browser env XAUTHORITY=/home/browser/.Xauthority %s' % rv
return wrapped
class Helpers:
@property
@run_as_browser
def default_firefox_bin(self):
candidates = [
'/usr/local/lib/firefox/firefox-bin',
'/usr/local/lib/firefox3/firefox-bin',
'/usr/bin/iceweasel',
]
return self._pick(candidates, os.path.exists)
@property
@run_as_browser
def default_firefox_wrapper(self):
candidates = [
'firefox', 'firefox3'
]
return self._pick(candidates, self._wrapper_tester)
default_firefox = default_firefox_wrapper
@property
def as_browser(self):
return 'sudo -Hiu browser'
@property
def opera(self):
return 'sudo -Hiu browser opera'
@property
def chrome(self):
return 'sudo -Hiu browser chrome'
def have_bin(self, basename):
return self._wrapper_tester(basename)
def _wrapper_tester(self, candidate):
dirs = os.environ['PATH'].split(':')
for dir in dirs:
path = os.path.join(dir, candidate)
if os.path.exists(path):
return True
return False
def _pick(self, candidates, tester):
for candidate in candidates:
if tester(candidate):
return candidate
# consider raising here
return None
| Fix firefox invocation as browser | Fix firefox invocation as browser
| Python | bsd-2-clause | p/pubfiles,p/pubfiles,p/pubfiles,p/pubfiles,p/pubfiles | import os.path, os
def run_as_browser(fn):
def wrapped(*args, **kwargs):
rv = fn(*args, **kwargs)
- return 'sudo -Hiu browser %s' % rv
+ return 'sudo -Hiu browser env XAUTHORITY=/home/browser/.Xauthority %s' % rv
return wrapped
class Helpers:
@property
@run_as_browser
def default_firefox_bin(self):
candidates = [
'/usr/local/lib/firefox/firefox-bin',
'/usr/local/lib/firefox3/firefox-bin',
'/usr/bin/iceweasel',
]
return self._pick(candidates, os.path.exists)
@property
@run_as_browser
def default_firefox_wrapper(self):
candidates = [
'firefox', 'firefox3'
]
return self._pick(candidates, self._wrapper_tester)
default_firefox = default_firefox_wrapper
@property
def as_browser(self):
return 'sudo -Hiu browser'
@property
def opera(self):
return 'sudo -Hiu browser opera'
@property
def chrome(self):
return 'sudo -Hiu browser chrome'
def have_bin(self, basename):
return self._wrapper_tester(basename)
def _wrapper_tester(self, candidate):
dirs = os.environ['PATH'].split(':')
for dir in dirs:
path = os.path.join(dir, candidate)
if os.path.exists(path):
return True
return False
def _pick(self, candidates, tester):
for candidate in candidates:
if tester(candidate):
return candidate
# consider raising here
return None
| Fix firefox invocation as browser | ## Code Before:
import os.path, os
def run_as_browser(fn):
def wrapped(*args, **kwargs):
rv = fn(*args, **kwargs)
return 'sudo -Hiu browser %s' % rv
return wrapped
class Helpers:
@property
@run_as_browser
def default_firefox_bin(self):
candidates = [
'/usr/local/lib/firefox/firefox-bin',
'/usr/local/lib/firefox3/firefox-bin',
'/usr/bin/iceweasel',
]
return self._pick(candidates, os.path.exists)
@property
@run_as_browser
def default_firefox_wrapper(self):
candidates = [
'firefox', 'firefox3'
]
return self._pick(candidates, self._wrapper_tester)
default_firefox = default_firefox_wrapper
@property
def as_browser(self):
return 'sudo -Hiu browser'
@property
def opera(self):
return 'sudo -Hiu browser opera'
@property
def chrome(self):
return 'sudo -Hiu browser chrome'
def have_bin(self, basename):
return self._wrapper_tester(basename)
def _wrapper_tester(self, candidate):
dirs = os.environ['PATH'].split(':')
for dir in dirs:
path = os.path.join(dir, candidate)
if os.path.exists(path):
return True
return False
def _pick(self, candidates, tester):
for candidate in candidates:
if tester(candidate):
return candidate
# consider raising here
return None
## Instruction:
Fix firefox invocation as browser
## Code After:
import os.path, os
def run_as_browser(fn):
def wrapped(*args, **kwargs):
rv = fn(*args, **kwargs)
return 'sudo -Hiu browser env XAUTHORITY=/home/browser/.Xauthority %s' % rv
return wrapped
class Helpers:
@property
@run_as_browser
def default_firefox_bin(self):
candidates = [
'/usr/local/lib/firefox/firefox-bin',
'/usr/local/lib/firefox3/firefox-bin',
'/usr/bin/iceweasel',
]
return self._pick(candidates, os.path.exists)
@property
@run_as_browser
def default_firefox_wrapper(self):
candidates = [
'firefox', 'firefox3'
]
return self._pick(candidates, self._wrapper_tester)
default_firefox = default_firefox_wrapper
@property
def as_browser(self):
return 'sudo -Hiu browser'
@property
def opera(self):
return 'sudo -Hiu browser opera'
@property
def chrome(self):
return 'sudo -Hiu browser chrome'
def have_bin(self, basename):
return self._wrapper_tester(basename)
def _wrapper_tester(self, candidate):
dirs = os.environ['PATH'].split(':')
for dir in dirs:
path = os.path.join(dir, candidate)
if os.path.exists(path):
return True
return False
def _pick(self, candidates, tester):
for candidate in candidates:
if tester(candidate):
return candidate
# consider raising here
return None
| import os.path, os
def run_as_browser(fn):
def wrapped(*args, **kwargs):
rv = fn(*args, **kwargs)
- return 'sudo -Hiu browser %s' % rv
+ return 'sudo -Hiu browser env XAUTHORITY=/home/browser/.Xauthority %s' % rv
return wrapped
class Helpers:
@property
@run_as_browser
def default_firefox_bin(self):
candidates = [
'/usr/local/lib/firefox/firefox-bin',
'/usr/local/lib/firefox3/firefox-bin',
'/usr/bin/iceweasel',
]
return self._pick(candidates, os.path.exists)
@property
@run_as_browser
def default_firefox_wrapper(self):
candidates = [
'firefox', 'firefox3'
]
return self._pick(candidates, self._wrapper_tester)
default_firefox = default_firefox_wrapper
@property
def as_browser(self):
return 'sudo -Hiu browser'
@property
def opera(self):
return 'sudo -Hiu browser opera'
@property
def chrome(self):
return 'sudo -Hiu browser chrome'
def have_bin(self, basename):
return self._wrapper_tester(basename)
def _wrapper_tester(self, candidate):
dirs = os.environ['PATH'].split(':')
for dir in dirs:
path = os.path.join(dir, candidate)
if os.path.exists(path):
return True
return False
def _pick(self, candidates, tester):
for candidate in candidates:
if tester(candidate):
return candidate
# consider raising here
return None |
853108e1c5cd9fca27d0f1dc8324b4b2a4d4b871 | pyqode/python/plugins/pyqode_python_plugin.py | pyqode/python/plugins/pyqode_python_plugin.py | # This only works with PyQt, PySide does not support the QtDesigner module
import os
if not 'QT_API' in os.environ:
os.environ.setdefault("QT_API", "PyQt")
import pcef.python
PLUGINS_TYPES = {'QPythonCodeEdit': pcef.python.QPythonCodeEdit}
try:
from pyqode.core.plugins.pcef_core_plugin import QCodeEditPlugin
class QPythonCodeEditPlugin(QCodeEditPlugin):
_module = 'pcef.python' # path to the widget's module
_class = 'QPythonCodeEdit' # name of the widget class
_name = "QPythonCodeEdit"
_icon = None
_type = pcef.python.QPythonCodeEdit
def createWidget(self, parent):
return pcef.python.QPythonCodeEdit(parent)
except ImportError:
print("Cannot use pcef plugins without PyQt4")
| # This only works with PyQt, PySide does not support the QtDesigner module
import os
if not 'QT_API' in os.environ:
os.environ.setdefault("QT_API", "PyQt")
import pyqode.python
PLUGINS_TYPES = {'QPythonCodeEdit': pyqode.python.QPythonCodeEdit}
try:
from pyqode.core.plugins.pcef_core_plugin import QCodeEditPlugin
class QPythonCodeEditPlugin(QCodeEditPlugin):
_module = 'pcef.python' # path to the widget's module
_class = 'QPythonCodeEdit' # name of the widget class
_name = "QPythonCodeEdit"
_icon = None
_type = pyqode.python.QPythonCodeEdit
def createWidget(self, parent):
return pyqode.python.QPythonCodeEdit(parent)
except ImportError:
print("Cannot use pcef plugins without PyQt4")
| Fix bug with python plugin and pyside | Fix bug with python plugin and pyside
| Python | mit | pyQode/pyqode.python,mmolero/pyqode.python,pyQode/pyqode.python,zwadar/pyqode.python | # This only works with PyQt, PySide does not support the QtDesigner module
import os
if not 'QT_API' in os.environ:
os.environ.setdefault("QT_API", "PyQt")
- import pcef.python
+ import pyqode.python
- PLUGINS_TYPES = {'QPythonCodeEdit': pcef.python.QPythonCodeEdit}
+ PLUGINS_TYPES = {'QPythonCodeEdit': pyqode.python.QPythonCodeEdit}
try:
from pyqode.core.plugins.pcef_core_plugin import QCodeEditPlugin
class QPythonCodeEditPlugin(QCodeEditPlugin):
_module = 'pcef.python' # path to the widget's module
_class = 'QPythonCodeEdit' # name of the widget class
_name = "QPythonCodeEdit"
_icon = None
- _type = pcef.python.QPythonCodeEdit
+ _type = pyqode.python.QPythonCodeEdit
def createWidget(self, parent):
- return pcef.python.QPythonCodeEdit(parent)
+ return pyqode.python.QPythonCodeEdit(parent)
except ImportError:
print("Cannot use pcef plugins without PyQt4")
| Fix bug with python plugin and pyside | ## Code Before:
# This only works with PyQt, PySide does not support the QtDesigner module
import os
if not 'QT_API' in os.environ:
os.environ.setdefault("QT_API", "PyQt")
import pcef.python
PLUGINS_TYPES = {'QPythonCodeEdit': pcef.python.QPythonCodeEdit}
try:
from pyqode.core.plugins.pcef_core_plugin import QCodeEditPlugin
class QPythonCodeEditPlugin(QCodeEditPlugin):
_module = 'pcef.python' # path to the widget's module
_class = 'QPythonCodeEdit' # name of the widget class
_name = "QPythonCodeEdit"
_icon = None
_type = pcef.python.QPythonCodeEdit
def createWidget(self, parent):
return pcef.python.QPythonCodeEdit(parent)
except ImportError:
print("Cannot use pcef plugins without PyQt4")
## Instruction:
Fix bug with python plugin and pyside
## Code After:
# This only works with PyQt, PySide does not support the QtDesigner module
import os
if not 'QT_API' in os.environ:
os.environ.setdefault("QT_API", "PyQt")
import pyqode.python
PLUGINS_TYPES = {'QPythonCodeEdit': pyqode.python.QPythonCodeEdit}
try:
from pyqode.core.plugins.pcef_core_plugin import QCodeEditPlugin
class QPythonCodeEditPlugin(QCodeEditPlugin):
_module = 'pcef.python' # path to the widget's module
_class = 'QPythonCodeEdit' # name of the widget class
_name = "QPythonCodeEdit"
_icon = None
_type = pyqode.python.QPythonCodeEdit
def createWidget(self, parent):
return pyqode.python.QPythonCodeEdit(parent)
except ImportError:
print("Cannot use pcef plugins without PyQt4")
| # This only works with PyQt, PySide does not support the QtDesigner module
import os
if not 'QT_API' in os.environ:
os.environ.setdefault("QT_API", "PyQt")
- import pcef.python
? ^ -
+ import pyqode.python
? ^^^^
- PLUGINS_TYPES = {'QPythonCodeEdit': pcef.python.QPythonCodeEdit}
? ^ -
+ PLUGINS_TYPES = {'QPythonCodeEdit': pyqode.python.QPythonCodeEdit}
? ^^^^
try:
from pyqode.core.plugins.pcef_core_plugin import QCodeEditPlugin
class QPythonCodeEditPlugin(QCodeEditPlugin):
_module = 'pcef.python' # path to the widget's module
_class = 'QPythonCodeEdit' # name of the widget class
_name = "QPythonCodeEdit"
_icon = None
- _type = pcef.python.QPythonCodeEdit
? ^ -
+ _type = pyqode.python.QPythonCodeEdit
? ^^^^
def createWidget(self, parent):
- return pcef.python.QPythonCodeEdit(parent)
? ^ -
+ return pyqode.python.QPythonCodeEdit(parent)
? ^^^^
except ImportError:
print("Cannot use pcef plugins without PyQt4") |
7842919b2af368c640363b4e4e05144049b111ba | ovp_core/emails.py | ovp_core/emails.py | from django.core.mail import EmailMultiAlternatives
from django.template import Context, Template
from django.template.loader import get_template
from django.conf import settings
import threading
class EmailThread(threading.Thread):
def __init__(self, msg):
self.msg = msg
threading.Thread.__init__(self)
def run (self):
return self.msg.send() > 0
class BaseMail:
"""
This class is responsible for firing emails
"""
from_email = ''
def __init__(self, user, async_mail=None):
self.user = user
self.async_mail = async_mail
def sendEmail(self, template_name, subject, context):
ctx = Context(context)
text_content = get_template('email/{}.txt'.format(template_name)).render(ctx)
html_content = get_template('email/{}.html'.format(template_name)).render(ctx)
msg = EmailMultiAlternatives(subject, text_content, self.from_email, [self.user.email])
msg.attach_alternative(text_content, "text/plain")
msg.attach_alternative(html_content, "text/html")
if self.async_mail:
async_flag="async"
else:
async_flag=getattr(settings, "DEFAULT_SEND_EMAIL", "async")
if async_flag == "async":
t = EmailThread(msg)
t.start()
return t
else:
return msg.send() > 0
| from django.core.mail import EmailMultiAlternatives
from django.template import Context, Template
from django.template.loader import get_template
from django.conf import settings
import threading
class EmailThread(threading.Thread):
def __init__(self, msg):
self.msg = msg
threading.Thread.__init__(self)
def run (self):
return self.msg.send() > 0
class BaseMail:
"""
This class is responsible for firing emails
"""
from_email = ''
def __init__(self, email_address, async_mail=None):
self.email_address = email_address
self.async_mail = async_mail
def sendEmail(self, template_name, subject, context):
ctx = Context(context)
text_content = get_template('email/{}.txt'.format(template_name)).render(ctx)
html_content = get_template('email/{}.html'.format(template_name)).render(ctx)
msg = EmailMultiAlternatives(subject, text_content, self.from_email, [self.email_address])
msg.attach_alternative(text_content, "text/plain")
msg.attach_alternative(html_content, "text/html")
if self.async_mail:
async_flag="async"
else:
async_flag=getattr(settings, "DEFAULT_SEND_EMAIL", "async")
if async_flag == "async":
t = EmailThread(msg)
t.start()
return t
else:
return msg.send() > 0
| Remove BaseMail dependency on User object | Remove BaseMail dependency on User object
| Python | agpl-3.0 | OpenVolunteeringPlatform/django-ovp-core,OpenVolunteeringPlatform/django-ovp-core | from django.core.mail import EmailMultiAlternatives
from django.template import Context, Template
from django.template.loader import get_template
from django.conf import settings
import threading
class EmailThread(threading.Thread):
def __init__(self, msg):
self.msg = msg
threading.Thread.__init__(self)
def run (self):
return self.msg.send() > 0
class BaseMail:
"""
This class is responsible for firing emails
"""
from_email = ''
- def __init__(self, user, async_mail=None):
+ def __init__(self, email_address, async_mail=None):
- self.user = user
+ self.email_address = email_address
self.async_mail = async_mail
def sendEmail(self, template_name, subject, context):
ctx = Context(context)
text_content = get_template('email/{}.txt'.format(template_name)).render(ctx)
html_content = get_template('email/{}.html'.format(template_name)).render(ctx)
- msg = EmailMultiAlternatives(subject, text_content, self.from_email, [self.user.email])
+ msg = EmailMultiAlternatives(subject, text_content, self.from_email, [self.email_address])
msg.attach_alternative(text_content, "text/plain")
msg.attach_alternative(html_content, "text/html")
if self.async_mail:
async_flag="async"
else:
async_flag=getattr(settings, "DEFAULT_SEND_EMAIL", "async")
if async_flag == "async":
t = EmailThread(msg)
t.start()
return t
else:
return msg.send() > 0
| Remove BaseMail dependency on User object | ## Code Before:
from django.core.mail import EmailMultiAlternatives
from django.template import Context, Template
from django.template.loader import get_template
from django.conf import settings
import threading
class EmailThread(threading.Thread):
def __init__(self, msg):
self.msg = msg
threading.Thread.__init__(self)
def run (self):
return self.msg.send() > 0
class BaseMail:
"""
This class is responsible for firing emails
"""
from_email = ''
def __init__(self, user, async_mail=None):
self.user = user
self.async_mail = async_mail
def sendEmail(self, template_name, subject, context):
ctx = Context(context)
text_content = get_template('email/{}.txt'.format(template_name)).render(ctx)
html_content = get_template('email/{}.html'.format(template_name)).render(ctx)
msg = EmailMultiAlternatives(subject, text_content, self.from_email, [self.user.email])
msg.attach_alternative(text_content, "text/plain")
msg.attach_alternative(html_content, "text/html")
if self.async_mail:
async_flag="async"
else:
async_flag=getattr(settings, "DEFAULT_SEND_EMAIL", "async")
if async_flag == "async":
t = EmailThread(msg)
t.start()
return t
else:
return msg.send() > 0
## Instruction:
Remove BaseMail dependency on User object
## Code After:
from django.core.mail import EmailMultiAlternatives
from django.template import Context, Template
from django.template.loader import get_template
from django.conf import settings
import threading
class EmailThread(threading.Thread):
def __init__(self, msg):
self.msg = msg
threading.Thread.__init__(self)
def run (self):
return self.msg.send() > 0
class BaseMail:
"""
This class is responsible for firing emails
"""
from_email = ''
def __init__(self, email_address, async_mail=None):
self.email_address = email_address
self.async_mail = async_mail
def sendEmail(self, template_name, subject, context):
ctx = Context(context)
text_content = get_template('email/{}.txt'.format(template_name)).render(ctx)
html_content = get_template('email/{}.html'.format(template_name)).render(ctx)
msg = EmailMultiAlternatives(subject, text_content, self.from_email, [self.email_address])
msg.attach_alternative(text_content, "text/plain")
msg.attach_alternative(html_content, "text/html")
if self.async_mail:
async_flag="async"
else:
async_flag=getattr(settings, "DEFAULT_SEND_EMAIL", "async")
if async_flag == "async":
t = EmailThread(msg)
t.start()
return t
else:
return msg.send() > 0
| from django.core.mail import EmailMultiAlternatives
from django.template import Context, Template
from django.template.loader import get_template
from django.conf import settings
import threading
class EmailThread(threading.Thread):
def __init__(self, msg):
self.msg = msg
threading.Thread.__init__(self)
def run (self):
return self.msg.send() > 0
class BaseMail:
"""
This class is responsible for firing emails
"""
from_email = ''
- def __init__(self, user, async_mail=None):
? ^ ^^
+ def __init__(self, email_address, async_mail=None):
? ^^^^^^^^^^^ ^
- self.user = user
+ self.email_address = email_address
self.async_mail = async_mail
def sendEmail(self, template_name, subject, context):
ctx = Context(context)
text_content = get_template('email/{}.txt'.format(template_name)).render(ctx)
html_content = get_template('email/{}.html'.format(template_name)).render(ctx)
- msg = EmailMultiAlternatives(subject, text_content, self.from_email, [self.user.email])
? -----
+ msg = EmailMultiAlternatives(subject, text_content, self.from_email, [self.email_address])
? ++++++++
msg.attach_alternative(text_content, "text/plain")
msg.attach_alternative(html_content, "text/html")
if self.async_mail:
async_flag="async"
else:
async_flag=getattr(settings, "DEFAULT_SEND_EMAIL", "async")
if async_flag == "async":
t = EmailThread(msg)
t.start()
return t
else:
return msg.send() > 0 |
b1ae1c97095b69da3fb6a7f394ffc484dd6b4780 | main.py | main.py | import document
import time
evalstr = '''
var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText);
'''
b = document.createElement('button')
b.innerHTML = 'Run'
b.setAttribute('id', 'runinjector')
b.setAttribute('onclick', evalstr)
pre = document.getElementById('edoutput')
pre.appendChild(b)
bridge = None
while True:
time.sleep(1)
bridge = document.getElementById('injectedcanvas')
if bridge != None:
break
bridge.innerHTML = 'ready'
# Put Python<->JS class here.
class Canvas:
def fillRect(self, x, y, width, height):
cmd = document.createElement('span');
cmd.innerHTML = "{0} {1} {2} {3}".format(x, y, width, height)
bridge.appendChild(cmd)
# Your code here
| import document
import time
evalstr = '''
var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText);
'''
pre = document.getElementById('edoutput')
b = document.getElementById('runinjector')
if b == None:
b = document.createElement('button')
pre.appendChild(b)
b.innerHTML = 'Run'
b.setAttribute('id', 'runinjector')
b.setAttribute('onclick', evalstr)
canvas = document.getElementById('injectedcanvas')
if canvas != None:
div = document.getElementsByClassName('main')[0]
div.removeChild(canvas)
bridge = None
while True:
time.sleep(1)
bridge = document.getElementById('injectedcanvas')
if bridge != None:
break
bridge.innerHTML = 'ready'
# Put Python<->JS class here.
class Canvas:
def fillRect(self, x, y, width, height):
cmd = document.createElement('span');
cmd.innerHTML = "fillrect {0} {1} {2} {3}".format(x, y, width, height)
bridge.appendChild(cmd)
# Your code here
| Fix funny things when rerunning code | Fix funny things when rerunning code
Prevent multiple "Run" buttons from appearing.
Remove the canvas after pressing the Skulpt "Run" button.
| Python | mit | Zirientis/skulpt-canvas,Zirientis/skulpt-canvas | import document
import time
evalstr = '''
var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText);
'''
+ pre = document.getElementById('edoutput')
+
+ b = document.getElementById('runinjector')
+ if b == None:
- b = document.createElement('button')
+ b = document.createElement('button')
+ pre.appendChild(b)
b.innerHTML = 'Run'
b.setAttribute('id', 'runinjector')
b.setAttribute('onclick', evalstr)
- pre = document.getElementById('edoutput')
- pre.appendChild(b)
+
+ canvas = document.getElementById('injectedcanvas')
+ if canvas != None:
+ div = document.getElementsByClassName('main')[0]
+ div.removeChild(canvas)
bridge = None
while True:
time.sleep(1)
bridge = document.getElementById('injectedcanvas')
if bridge != None:
break
bridge.innerHTML = 'ready'
# Put Python<->JS class here.
class Canvas:
def fillRect(self, x, y, width, height):
cmd = document.createElement('span');
- cmd.innerHTML = "{0} {1} {2} {3}".format(x, y, width, height)
+ cmd.innerHTML = "fillrect {0} {1} {2} {3}".format(x, y, width, height)
bridge.appendChild(cmd)
# Your code here
| Fix funny things when rerunning code | ## Code Before:
import document
import time
evalstr = '''
var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText);
'''
b = document.createElement('button')
b.innerHTML = 'Run'
b.setAttribute('id', 'runinjector')
b.setAttribute('onclick', evalstr)
pre = document.getElementById('edoutput')
pre.appendChild(b)
bridge = None
while True:
time.sleep(1)
bridge = document.getElementById('injectedcanvas')
if bridge != None:
break
bridge.innerHTML = 'ready'
# Put Python<->JS class here.
class Canvas:
def fillRect(self, x, y, width, height):
cmd = document.createElement('span');
cmd.innerHTML = "{0} {1} {2} {3}".format(x, y, width, height)
bridge.appendChild(cmd)
# Your code here
## Instruction:
Fix funny things when rerunning code
## Code After:
import document
import time
evalstr = '''
var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText);
'''
pre = document.getElementById('edoutput')
b = document.getElementById('runinjector')
if b == None:
b = document.createElement('button')
pre.appendChild(b)
b.innerHTML = 'Run'
b.setAttribute('id', 'runinjector')
b.setAttribute('onclick', evalstr)
canvas = document.getElementById('injectedcanvas')
if canvas != None:
div = document.getElementsByClassName('main')[0]
div.removeChild(canvas)
bridge = None
while True:
time.sleep(1)
bridge = document.getElementById('injectedcanvas')
if bridge != None:
break
bridge.innerHTML = 'ready'
# Put Python<->JS class here.
class Canvas:
def fillRect(self, x, y, width, height):
cmd = document.createElement('span');
cmd.innerHTML = "fillrect {0} {1} {2} {3}".format(x, y, width, height)
bridge.appendChild(cmd)
# Your code here
| import document
import time
evalstr = '''
var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText);
'''
+ pre = document.getElementById('edoutput')
+
+ b = document.getElementById('runinjector')
+ if b == None:
- b = document.createElement('button')
+ b = document.createElement('button')
? +
+ pre.appendChild(b)
b.innerHTML = 'Run'
b.setAttribute('id', 'runinjector')
b.setAttribute('onclick', evalstr)
- pre = document.getElementById('edoutput')
- pre.appendChild(b)
+
+ canvas = document.getElementById('injectedcanvas')
+ if canvas != None:
+ div = document.getElementsByClassName('main')[0]
+ div.removeChild(canvas)
bridge = None
while True:
time.sleep(1)
bridge = document.getElementById('injectedcanvas')
if bridge != None:
break
bridge.innerHTML = 'ready'
# Put Python<->JS class here.
class Canvas:
def fillRect(self, x, y, width, height):
cmd = document.createElement('span');
- cmd.innerHTML = "{0} {1} {2} {3}".format(x, y, width, height)
+ cmd.innerHTML = "fillrect {0} {1} {2} {3}".format(x, y, width, height)
? +++++++++
bridge.appendChild(cmd)
# Your code here |
d96b6fa97272057f0fb67f2440f1b5b642b92bbe | src/python/tensorflow_cloud/core/tests/examples/multi_file_example/scale_model.py | src/python/tensorflow_cloud/core/tests/examples/multi_file_example/scale_model.py |
import tensorflow_cloud as tfc
tfc.run(
entry_point="train_model.py", requirements_txt="requirements.txt", stream_logs=True
)
|
import tensorflow_cloud as tfc
gcp_bucket = "your-gcp-bucket"
tfc.run(
entry_point="train_model.py",
requirements_txt="requirements.txt",
docker_image_bucket_name=gcp_bucket,
stream_logs=True,
)
| Add storage bucket to run() call | Add storage bucket to run() call | Python | apache-2.0 | tensorflow/cloud,tensorflow/cloud |
import tensorflow_cloud as tfc
+ gcp_bucket = "your-gcp-bucket"
+
tfc.run(
- entry_point="train_model.py", requirements_txt="requirements.txt", stream_logs=True
+ entry_point="train_model.py",
+ requirements_txt="requirements.txt",
+ docker_image_bucket_name=gcp_bucket,
+ stream_logs=True,
)
| Add storage bucket to run() call | ## Code Before:
import tensorflow_cloud as tfc
tfc.run(
entry_point="train_model.py", requirements_txt="requirements.txt", stream_logs=True
)
## Instruction:
Add storage bucket to run() call
## Code After:
import tensorflow_cloud as tfc
gcp_bucket = "your-gcp-bucket"
tfc.run(
entry_point="train_model.py",
requirements_txt="requirements.txt",
docker_image_bucket_name=gcp_bucket,
stream_logs=True,
)
|
import tensorflow_cloud as tfc
+ gcp_bucket = "your-gcp-bucket"
+
tfc.run(
- entry_point="train_model.py", requirements_txt="requirements.txt", stream_logs=True
+ entry_point="train_model.py",
+ requirements_txt="requirements.txt",
+ docker_image_bucket_name=gcp_bucket,
+ stream_logs=True,
) |
6df1e7a7f0987efc8e34c521e8c4de9a75f9dfde | troposphere/auth.py | troposphere/auth.py | import logging
from troposphere.query import only_current_tokens
logger = logging.getLogger(__name__)
def has_valid_token(user):
"""
Returns boolean indicating if there are non-expired authentication
tokens associated with the user.
"""
logger.info(hasattr(user, "auth_tokens"))
non_expired_tokens = user.auth_tokens.filter(only_current_tokens())
return len(non_expired_tokens) > 0
def get_current_tokens(user):
"""
Returns the non-expired authentication tokens.
"""
logger.info(hasattr(user, "auth_tokens"))
return user.auth_tokens.filter(only_current_tokens())
| import logging
from troposphere.query import only_current_tokens
logger = logging.getLogger(__name__)
def has_valid_token(user):
"""
Returns boolean indicating if there are non-expired authentication
tokens associated with the user.
"""
logger.info("user has auth_tokens attributes? %s" %
(hasattr(user, "auth_tokens")))
return user.auth_tokens.filter(only_current_tokens()).exists()
def get_current_tokens(user):
"""
Returns the non-expired authentication tokens.
"""
logger.info("user has auth_tokens attributes? %s" %
(hasattr(user, "auth_tokens")))
return user.auth_tokens.filter(only_current_tokens())
| Use exists() check from QuerySet; give logger-info context | Use exists() check from QuerySet; give logger-info context
| Python | apache-2.0 | CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend | import logging
from troposphere.query import only_current_tokens
logger = logging.getLogger(__name__)
def has_valid_token(user):
"""
Returns boolean indicating if there are non-expired authentication
tokens associated with the user.
"""
+ logger.info("user has auth_tokens attributes? %s" %
- logger.info(hasattr(user, "auth_tokens"))
+ (hasattr(user, "auth_tokens")))
+
- non_expired_tokens = user.auth_tokens.filter(only_current_tokens())
+ return user.auth_tokens.filter(only_current_tokens()).exists()
- return len(non_expired_tokens) > 0
def get_current_tokens(user):
"""
Returns the non-expired authentication tokens.
"""
+ logger.info("user has auth_tokens attributes? %s" %
- logger.info(hasattr(user, "auth_tokens"))
+ (hasattr(user, "auth_tokens")))
+
return user.auth_tokens.filter(only_current_tokens())
| Use exists() check from QuerySet; give logger-info context | ## Code Before:
import logging
from troposphere.query import only_current_tokens
logger = logging.getLogger(__name__)
def has_valid_token(user):
"""
Returns boolean indicating if there are non-expired authentication
tokens associated with the user.
"""
logger.info(hasattr(user, "auth_tokens"))
non_expired_tokens = user.auth_tokens.filter(only_current_tokens())
return len(non_expired_tokens) > 0
def get_current_tokens(user):
"""
Returns the non-expired authentication tokens.
"""
logger.info(hasattr(user, "auth_tokens"))
return user.auth_tokens.filter(only_current_tokens())
## Instruction:
Use exists() check from QuerySet; give logger-info context
## Code After:
import logging
from troposphere.query import only_current_tokens
logger = logging.getLogger(__name__)
def has_valid_token(user):
"""
Returns boolean indicating if there are non-expired authentication
tokens associated with the user.
"""
logger.info("user has auth_tokens attributes? %s" %
(hasattr(user, "auth_tokens")))
return user.auth_tokens.filter(only_current_tokens()).exists()
def get_current_tokens(user):
"""
Returns the non-expired authentication tokens.
"""
logger.info("user has auth_tokens attributes? %s" %
(hasattr(user, "auth_tokens")))
return user.auth_tokens.filter(only_current_tokens())
| import logging
from troposphere.query import only_current_tokens
logger = logging.getLogger(__name__)
def has_valid_token(user):
"""
Returns boolean indicating if there are non-expired authentication
tokens associated with the user.
"""
+ logger.info("user has auth_tokens attributes? %s" %
- logger.info(hasattr(user, "auth_tokens"))
? ^^^^^^^^^^^
+ (hasattr(user, "auth_tokens")))
? ^^^^ +
+
- non_expired_tokens = user.auth_tokens.filter(only_current_tokens())
? -------- -- ^^^ ---
+ return user.auth_tokens.filter(only_current_tokens()).exists()
? ^^ +++++++++
- return len(non_expired_tokens) > 0
def get_current_tokens(user):
"""
Returns the non-expired authentication tokens.
"""
+ logger.info("user has auth_tokens attributes? %s" %
- logger.info(hasattr(user, "auth_tokens"))
? ^^^^^^^^^^^
+ (hasattr(user, "auth_tokens")))
? ^^^^ +
+
return user.auth_tokens.filter(only_current_tokens()) |
2621e71926942113e8c9c85fe48d7448a790f916 | bluebottle/bb_organizations/serializers.py | bluebottle/bb_organizations/serializers.py | from rest_framework import serializers
from bluebottle.utils.model_dispatcher import get_organization_model, get_organizationmember_model
ORGANIZATION_MODEL = get_organization_model()
MEMBER_MODEL = get_organizationmember_model()
ORGANIZATION_FIELDS = ( 'id', 'name', 'slug', 'address_line1', 'address_line2',
'city', 'state', 'country', 'postal_code', 'phone_number',
'email', 'person')
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
model = ORGANIZATION_MODEL
fields = ORGANIZATION_FIELDS
class ManageOrganizationSerializer(OrganizationSerializer):
slug = serializers.SlugField(required=False)
name = serializers.CharField(required=True)
email = serializers.EmailField(required=False)
class Meta:
model = ORGANIZATION_MODEL
fields = ORGANIZATION_FIELDS + ('partner_organizations',
'created', 'updated')
| from rest_framework import serializers
from bluebottle.utils.model_dispatcher import get_organization_model, get_organizationmember_model
ORGANIZATION_MODEL = get_organization_model()
MEMBER_MODEL = get_organizationmember_model()
ORGANIZATION_FIELDS = ( 'id', 'name', 'slug', 'address_line1', 'address_line2',
'city', 'state', 'country', 'postal_code', 'phone_number',
'email')
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
model = ORGANIZATION_MODEL
fields = ORGANIZATION_FIELDS
class ManageOrganizationSerializer(OrganizationSerializer):
slug = serializers.SlugField(required=False)
name = serializers.CharField(required=True)
email = serializers.EmailField(required=False)
class Meta:
model = ORGANIZATION_MODEL
fields = ORGANIZATION_FIELDS + ('partner_organizations',
'created', 'updated')
| Remove person from organization serializer | Remove person from organization serializer
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle | from rest_framework import serializers
from bluebottle.utils.model_dispatcher import get_organization_model, get_organizationmember_model
ORGANIZATION_MODEL = get_organization_model()
MEMBER_MODEL = get_organizationmember_model()
ORGANIZATION_FIELDS = ( 'id', 'name', 'slug', 'address_line1', 'address_line2',
'city', 'state', 'country', 'postal_code', 'phone_number',
- 'email', 'person')
+ 'email')
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
model = ORGANIZATION_MODEL
fields = ORGANIZATION_FIELDS
class ManageOrganizationSerializer(OrganizationSerializer):
slug = serializers.SlugField(required=False)
name = serializers.CharField(required=True)
email = serializers.EmailField(required=False)
class Meta:
model = ORGANIZATION_MODEL
fields = ORGANIZATION_FIELDS + ('partner_organizations',
'created', 'updated')
| Remove person from organization serializer | ## Code Before:
from rest_framework import serializers
from bluebottle.utils.model_dispatcher import get_organization_model, get_organizationmember_model
ORGANIZATION_MODEL = get_organization_model()
MEMBER_MODEL = get_organizationmember_model()
ORGANIZATION_FIELDS = ( 'id', 'name', 'slug', 'address_line1', 'address_line2',
'city', 'state', 'country', 'postal_code', 'phone_number',
'email', 'person')
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
model = ORGANIZATION_MODEL
fields = ORGANIZATION_FIELDS
class ManageOrganizationSerializer(OrganizationSerializer):
slug = serializers.SlugField(required=False)
name = serializers.CharField(required=True)
email = serializers.EmailField(required=False)
class Meta:
model = ORGANIZATION_MODEL
fields = ORGANIZATION_FIELDS + ('partner_organizations',
'created', 'updated')
## Instruction:
Remove person from organization serializer
## Code After:
from rest_framework import serializers
from bluebottle.utils.model_dispatcher import get_organization_model, get_organizationmember_model
ORGANIZATION_MODEL = get_organization_model()
MEMBER_MODEL = get_organizationmember_model()
ORGANIZATION_FIELDS = ( 'id', 'name', 'slug', 'address_line1', 'address_line2',
'city', 'state', 'country', 'postal_code', 'phone_number',
'email')
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
model = ORGANIZATION_MODEL
fields = ORGANIZATION_FIELDS
class ManageOrganizationSerializer(OrganizationSerializer):
slug = serializers.SlugField(required=False)
name = serializers.CharField(required=True)
email = serializers.EmailField(required=False)
class Meta:
model = ORGANIZATION_MODEL
fields = ORGANIZATION_FIELDS + ('partner_organizations',
'created', 'updated')
| from rest_framework import serializers
from bluebottle.utils.model_dispatcher import get_organization_model, get_organizationmember_model
ORGANIZATION_MODEL = get_organization_model()
MEMBER_MODEL = get_organizationmember_model()
ORGANIZATION_FIELDS = ( 'id', 'name', 'slug', 'address_line1', 'address_line2',
'city', 'state', 'country', 'postal_code', 'phone_number',
- 'email', 'person')
? ----------
+ 'email')
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
model = ORGANIZATION_MODEL
fields = ORGANIZATION_FIELDS
class ManageOrganizationSerializer(OrganizationSerializer):
slug = serializers.SlugField(required=False)
name = serializers.CharField(required=True)
email = serializers.EmailField(required=False)
class Meta:
model = ORGANIZATION_MODEL
fields = ORGANIZATION_FIELDS + ('partner_organizations',
'created', 'updated') |
758a8bff354d1e1542b5c4614276bdfa229f3dbc | extended_choices/__init__.py | extended_choices/__init__.py | """Little helper application to improve django choices (for fields)"""
from __future__ import unicode_literals
from .choices import Choices, OrderedChoices
__author__ = 'Stephane "Twidi" Ange;'
__contact__ = "s.angel@twidi.com"
__homepage__ = "https://pypi.python.org/pypi/django-extended-choices"
__version__ = "1.1.1"
| """Little helper application to improve django choices (for fields)"""
from __future__ import unicode_literals
from .choices import Choices, OrderedChoices
__all__ = ['Choices', 'OrderedChoices']
__author__ = 'Stephane "Twidi" Ange;'
__contact__ = "s.angel@twidi.com"
__homepage__ = "https://pypi.python.org/pypi/django-extended-choices"
__version__ = "1.1.1"
| Add `__all__` at package root level | Add `__all__` at package root level
| Python | bsd-3-clause | twidi/django-extended-choices | """Little helper application to improve django choices (for fields)"""
from __future__ import unicode_literals
from .choices import Choices, OrderedChoices
+ __all__ = ['Choices', 'OrderedChoices']
__author__ = 'Stephane "Twidi" Ange;'
__contact__ = "s.angel@twidi.com"
__homepage__ = "https://pypi.python.org/pypi/django-extended-choices"
__version__ = "1.1.1"
| Add `__all__` at package root level | ## Code Before:
"""Little helper application to improve django choices (for fields)"""
from __future__ import unicode_literals
from .choices import Choices, OrderedChoices
__author__ = 'Stephane "Twidi" Ange;'
__contact__ = "s.angel@twidi.com"
__homepage__ = "https://pypi.python.org/pypi/django-extended-choices"
__version__ = "1.1.1"
## Instruction:
Add `__all__` at package root level
## Code After:
"""Little helper application to improve django choices (for fields)"""
from __future__ import unicode_literals
from .choices import Choices, OrderedChoices
__all__ = ['Choices', 'OrderedChoices']
__author__ = 'Stephane "Twidi" Ange;'
__contact__ = "s.angel@twidi.com"
__homepage__ = "https://pypi.python.org/pypi/django-extended-choices"
__version__ = "1.1.1"
| """Little helper application to improve django choices (for fields)"""
from __future__ import unicode_literals
from .choices import Choices, OrderedChoices
+ __all__ = ['Choices', 'OrderedChoices']
__author__ = 'Stephane "Twidi" Ange;'
__contact__ = "s.angel@twidi.com"
__homepage__ = "https://pypi.python.org/pypi/django-extended-choices"
__version__ = "1.1.1" |
1179163881fe1dedab81a02a940c711479a334ab | Instanssi/admin_auth/forms.py | Instanssi/admin_auth/forms.py |
from django import forms
from uni_form.helper import FormHelper
from uni_form.layout import Submit, Layout, Fieldset, ButtonHolder
class LoginForm(forms.Form):
username = forms.CharField(label=u"Käyttäjätunnus", help_text=u"Admin-paneelin käyttäjätunnuksesi. Huom! OpenID-tunnukset eivät kelpaa!")
password = forms.CharField(label=u"Salasana")
def __init__(self, *args, **kwargs):
super(LoginForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
u'',
'username',
'password',
ButtonHolder (
Submit('submit', 'Kirjaudu sisään')
)
)
)
|
from django import forms
from uni_form.helper import FormHelper
from uni_form.layout import Submit, Layout, Fieldset, ButtonHolder
class LoginForm(forms.Form):
username = forms.CharField(label=u"Käyttäjätunnus", help_text=u"Admin-paneelin käyttäjätunnuksesi. Huom! OpenID-tunnukset eivät kelpaa!")
password = forms.CharField(label=u"Salasana", widget=forms.PasswordInput)
def __init__(self, *args, **kwargs):
super(LoginForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
u'',
'username',
'password',
ButtonHolder (
Submit('submit', 'Kirjaudu sisään')
)
)
)
| Use passwordinput in password field. | admin_auth: Use passwordinput in password field.
| Python | mit | Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org |
from django import forms
from uni_form.helper import FormHelper
from uni_form.layout import Submit, Layout, Fieldset, ButtonHolder
class LoginForm(forms.Form):
username = forms.CharField(label=u"Käyttäjätunnus", help_text=u"Admin-paneelin käyttäjätunnuksesi. Huom! OpenID-tunnukset eivät kelpaa!")
- password = forms.CharField(label=u"Salasana")
+ password = forms.CharField(label=u"Salasana", widget=forms.PasswordInput)
def __init__(self, *args, **kwargs):
super(LoginForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
u'',
'username',
'password',
ButtonHolder (
Submit('submit', 'Kirjaudu sisään')
)
)
)
| Use passwordinput in password field. | ## Code Before:
from django import forms
from uni_form.helper import FormHelper
from uni_form.layout import Submit, Layout, Fieldset, ButtonHolder
class LoginForm(forms.Form):
username = forms.CharField(label=u"Käyttäjätunnus", help_text=u"Admin-paneelin käyttäjätunnuksesi. Huom! OpenID-tunnukset eivät kelpaa!")
password = forms.CharField(label=u"Salasana")
def __init__(self, *args, **kwargs):
super(LoginForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
u'',
'username',
'password',
ButtonHolder (
Submit('submit', 'Kirjaudu sisään')
)
)
)
## Instruction:
Use passwordinput in password field.
## Code After:
from django import forms
from uni_form.helper import FormHelper
from uni_form.layout import Submit, Layout, Fieldset, ButtonHolder
class LoginForm(forms.Form):
username = forms.CharField(label=u"Käyttäjätunnus", help_text=u"Admin-paneelin käyttäjätunnuksesi. Huom! OpenID-tunnukset eivät kelpaa!")
password = forms.CharField(label=u"Salasana", widget=forms.PasswordInput)
def __init__(self, *args, **kwargs):
super(LoginForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
u'',
'username',
'password',
ButtonHolder (
Submit('submit', 'Kirjaudu sisään')
)
)
)
|
from django import forms
from uni_form.helper import FormHelper
from uni_form.layout import Submit, Layout, Fieldset, ButtonHolder
class LoginForm(forms.Form):
username = forms.CharField(label=u"Käyttäjätunnus", help_text=u"Admin-paneelin käyttäjätunnuksesi. Huom! OpenID-tunnukset eivät kelpaa!")
- password = forms.CharField(label=u"Salasana")
+ password = forms.CharField(label=u"Salasana", widget=forms.PasswordInput)
? ++++++++++++++++++++++++++++
def __init__(self, *args, **kwargs):
super(LoginForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
u'',
'username',
'password',
ButtonHolder (
Submit('submit', 'Kirjaudu sisään')
)
)
) |
39d370f314431e44e7eb978865be4f7696625eec | scraper/models.py | scraper/models.py | from django.db import models
class Author(models.Model):
name = models.TextField()
def __str__(self):
return self.name
class Paper(models.Model):
url = models.TextField()
title = models.TextField()
citations = models.IntegerField()
abstract = models.TextField()
journal = models.TextField()
volume = models.IntegerField(null=True)
issue = models.IntegerField(null=True)
year = models.IntegerField()
authors = models.ManyToManyField(Author)
class Project(models.Model):
researcher = models.ForeignKey(Author)
title = models.TextField()
url = models.TextField()
funding_amount = models.IntegerField()
year = models.IntegerField()
| from django.db import models
class Author(models.Model):
name = models.TextField()
def __str__(self):
return self.name
class Paper(models.Model):
url = models.TextField()
title = models.TextField()
citations = models.IntegerField()
abstract = models.TextField()
journal = models.TextField()
volume = models.IntegerField(null=True)
issue = models.IntegerField(null=True)
year = models.IntegerField()
authors = models.ManyToManyField(Author)
class Meta:
ordering = ['year', 'title']
class Project(models.Model):
researcher = models.ForeignKey(Author)
title = models.TextField()
url = models.TextField()
funding_amount = models.IntegerField()
year = models.IntegerField()
class Meta:
ordering = ['year', 'title']
| Order entries in table by year, then title | Order entries in table by year, then title
| Python | mit | Spferical/cure-alzheimers-fund-tracker,Spferical/cure-alzheimers-fund-tracker,Spferical/cure-alzheimers-fund-tracker | from django.db import models
class Author(models.Model):
name = models.TextField()
def __str__(self):
return self.name
class Paper(models.Model):
url = models.TextField()
title = models.TextField()
citations = models.IntegerField()
abstract = models.TextField()
journal = models.TextField()
volume = models.IntegerField(null=True)
issue = models.IntegerField(null=True)
year = models.IntegerField()
authors = models.ManyToManyField(Author)
+ class Meta:
+ ordering = ['year', 'title']
class Project(models.Model):
researcher = models.ForeignKey(Author)
title = models.TextField()
url = models.TextField()
funding_amount = models.IntegerField()
year = models.IntegerField()
+ class Meta:
+ ordering = ['year', 'title']
| Order entries in table by year, then title | ## Code Before:
from django.db import models
class Author(models.Model):
name = models.TextField()
def __str__(self):
return self.name
class Paper(models.Model):
url = models.TextField()
title = models.TextField()
citations = models.IntegerField()
abstract = models.TextField()
journal = models.TextField()
volume = models.IntegerField(null=True)
issue = models.IntegerField(null=True)
year = models.IntegerField()
authors = models.ManyToManyField(Author)
class Project(models.Model):
researcher = models.ForeignKey(Author)
title = models.TextField()
url = models.TextField()
funding_amount = models.IntegerField()
year = models.IntegerField()
## Instruction:
Order entries in table by year, then title
## Code After:
from django.db import models
class Author(models.Model):
name = models.TextField()
def __str__(self):
return self.name
class Paper(models.Model):
url = models.TextField()
title = models.TextField()
citations = models.IntegerField()
abstract = models.TextField()
journal = models.TextField()
volume = models.IntegerField(null=True)
issue = models.IntegerField(null=True)
year = models.IntegerField()
authors = models.ManyToManyField(Author)
class Meta:
ordering = ['year', 'title']
class Project(models.Model):
researcher = models.ForeignKey(Author)
title = models.TextField()
url = models.TextField()
funding_amount = models.IntegerField()
year = models.IntegerField()
class Meta:
ordering = ['year', 'title']
| from django.db import models
class Author(models.Model):
name = models.TextField()
def __str__(self):
return self.name
class Paper(models.Model):
url = models.TextField()
title = models.TextField()
citations = models.IntegerField()
abstract = models.TextField()
journal = models.TextField()
volume = models.IntegerField(null=True)
issue = models.IntegerField(null=True)
year = models.IntegerField()
authors = models.ManyToManyField(Author)
+ class Meta:
+ ordering = ['year', 'title']
class Project(models.Model):
researcher = models.ForeignKey(Author)
title = models.TextField()
url = models.TextField()
funding_amount = models.IntegerField()
year = models.IntegerField()
+ class Meta:
+ ordering = ['year', 'title'] |
60a10e8fbfd40197db8226f0791c7064c80fe370 | run.py | run.py | import os
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--run', action="store_true")
parser.add_argument('--deploy', action="store_true")
args = parser.parse_args()
if not any(vars(args).values()):
parser.print_help()
elif args.run:
os.system("ENVIRONMENT=development python server.py")
elif args.deploy:
os.system("git push heroku master")
| import sys
import os
import argparse
import shutil
from efselab import build
parser = argparse.ArgumentParser()
parser.add_argument('--run', action="store_true")
parser.add_argument('--deploy', action="store_true")
parser.add_argument('--update', action="store_true")
args = parser.parse_args()
if not any(vars(args).values()):
parser.print_help()
elif args.run:
os.system("ENVIRONMENT=development python server.py")
elif args.deploy:
os.system("git push heroku master")
elif args.update:
if not os.path.exists("../efselab/"):
sys.exit("Couldn't find a local efselab checkout...")
shutil.copy("../efselab/fasthash.c", "./efselab")
shutil.copy("../efselab/lemmatize.c", "./efselab")
shutil.copy("../efselab/pysuc.c", "./efselab/suc.c")
if not os.path.exists("../efselab/swe-pipeline"):
sys.exit("Couldn't find a local swe-pipeline directory for models...")
shutil.copy("../efselab/swe-pipeline/suc.bin", "./efselab")
shutil.copy("../efselab/swe-pipeline/suc-saldo.lemmas", "./efselab")
print("Building new files...")
os.chdir("efselab")
build.main()
| Add new update command that updates efselab dependencies. | Add new update command that updates efselab dependencies.
Former-commit-id: 6cfed1b9af9c0bbf34b7e58e3aa8ac3bada85aa7 | Python | mit | EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger | + import sys
import os
import argparse
+ import shutil
+
+ from efselab import build
+
parser = argparse.ArgumentParser()
parser.add_argument('--run', action="store_true")
parser.add_argument('--deploy', action="store_true")
+ parser.add_argument('--update', action="store_true")
args = parser.parse_args()
if not any(vars(args).values()):
parser.print_help()
elif args.run:
os.system("ENVIRONMENT=development python server.py")
elif args.deploy:
os.system("git push heroku master")
+ elif args.update:
+ if not os.path.exists("../efselab/"):
+ sys.exit("Couldn't find a local efselab checkout...")
+ shutil.copy("../efselab/fasthash.c", "./efselab")
+ shutil.copy("../efselab/lemmatize.c", "./efselab")
+ shutil.copy("../efselab/pysuc.c", "./efselab/suc.c")
+
+ if not os.path.exists("../efselab/swe-pipeline"):
+ sys.exit("Couldn't find a local swe-pipeline directory for models...")
+
+ shutil.copy("../efselab/swe-pipeline/suc.bin", "./efselab")
+ shutil.copy("../efselab/swe-pipeline/suc-saldo.lemmas", "./efselab")
+
+ print("Building new files...")
+ os.chdir("efselab")
+ build.main()
+ | Add new update command that updates efselab dependencies. | ## Code Before:
import os
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--run', action="store_true")
parser.add_argument('--deploy', action="store_true")
args = parser.parse_args()
if not any(vars(args).values()):
parser.print_help()
elif args.run:
os.system("ENVIRONMENT=development python server.py")
elif args.deploy:
os.system("git push heroku master")
## Instruction:
Add new update command that updates efselab dependencies.
## Code After:
import sys
import os
import argparse
import shutil
from efselab import build
parser = argparse.ArgumentParser()
parser.add_argument('--run', action="store_true")
parser.add_argument('--deploy', action="store_true")
parser.add_argument('--update', action="store_true")
args = parser.parse_args()
if not any(vars(args).values()):
parser.print_help()
elif args.run:
os.system("ENVIRONMENT=development python server.py")
elif args.deploy:
os.system("git push heroku master")
elif args.update:
if not os.path.exists("../efselab/"):
sys.exit("Couldn't find a local efselab checkout...")
shutil.copy("../efselab/fasthash.c", "./efselab")
shutil.copy("../efselab/lemmatize.c", "./efselab")
shutil.copy("../efselab/pysuc.c", "./efselab/suc.c")
if not os.path.exists("../efselab/swe-pipeline"):
sys.exit("Couldn't find a local swe-pipeline directory for models...")
shutil.copy("../efselab/swe-pipeline/suc.bin", "./efselab")
shutil.copy("../efselab/swe-pipeline/suc-saldo.lemmas", "./efselab")
print("Building new files...")
os.chdir("efselab")
build.main()
| + import sys
import os
import argparse
+ import shutil
+
+ from efselab import build
+
parser = argparse.ArgumentParser()
parser.add_argument('--run', action="store_true")
parser.add_argument('--deploy', action="store_true")
+ parser.add_argument('--update', action="store_true")
args = parser.parse_args()
if not any(vars(args).values()):
parser.print_help()
elif args.run:
os.system("ENVIRONMENT=development python server.py")
elif args.deploy:
os.system("git push heroku master")
+ elif args.update:
+ if not os.path.exists("../efselab/"):
+ sys.exit("Couldn't find a local efselab checkout...")
+
+ shutil.copy("../efselab/fasthash.c", "./efselab")
+ shutil.copy("../efselab/lemmatize.c", "./efselab")
+ shutil.copy("../efselab/pysuc.c", "./efselab/suc.c")
+
+ if not os.path.exists("../efselab/swe-pipeline"):
+ sys.exit("Couldn't find a local swe-pipeline directory for models...")
+
+ shutil.copy("../efselab/swe-pipeline/suc.bin", "./efselab")
+ shutil.copy("../efselab/swe-pipeline/suc-saldo.lemmas", "./efselab")
+
+ print("Building new files...")
+ os.chdir("efselab")
+ build.main() |
2114527f8de7b7e5175b43c54b4b84db2f169a01 | djangocms_forms/migrations/0004_redirect_delay.py | djangocms_forms/migrations/0004_redirect_delay.py | from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('djangocms_forms', '0003_add_referrer_field'),
]
operations = [
migrations.AddField(
model_name='formdefinition',
name='redirect_delay',
field=models.PositiveIntegerField(verbose_name='Redirect Delay', blank=True, null=True, help_text="Wait this number of milliseconds before redirecting."),
),
]
| from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('djangocms_forms', '0003_add_referrer_field'),
]
operations = [
migrations.AddField(
model_name='formdefinition',
name='redirect_delay',
field=models.PositiveIntegerField(verbose_name='Redirect Delay', blank=True, null=True, help_text="Wait this number of milliseconds before redirecting. 1000 milliseconds = 1 second."),
),
]
| Update migrations — `verbose_name` for `redirect_delay` fields | Update migrations — `verbose_name` for `redirect_delay` fields
| Python | bsd-3-clause | mishbahr/djangocms-forms,mishbahr/djangocms-forms,mishbahr/djangocms-forms | from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('djangocms_forms', '0003_add_referrer_field'),
]
operations = [
migrations.AddField(
model_name='formdefinition',
name='redirect_delay',
- field=models.PositiveIntegerField(verbose_name='Redirect Delay', blank=True, null=True, help_text="Wait this number of milliseconds before redirecting."),
+ field=models.PositiveIntegerField(verbose_name='Redirect Delay', blank=True, null=True, help_text="Wait this number of milliseconds before redirecting. 1000 milliseconds = 1 second."),
),
]
| Update migrations — `verbose_name` for `redirect_delay` fields | ## Code Before:
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('djangocms_forms', '0003_add_referrer_field'),
]
operations = [
migrations.AddField(
model_name='formdefinition',
name='redirect_delay',
field=models.PositiveIntegerField(verbose_name='Redirect Delay', blank=True, null=True, help_text="Wait this number of milliseconds before redirecting."),
),
]
## Instruction:
Update migrations — `verbose_name` for `redirect_delay` fields
## Code After:
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('djangocms_forms', '0003_add_referrer_field'),
]
operations = [
migrations.AddField(
model_name='formdefinition',
name='redirect_delay',
field=models.PositiveIntegerField(verbose_name='Redirect Delay', blank=True, null=True, help_text="Wait this number of milliseconds before redirecting. 1000 milliseconds = 1 second."),
),
]
| from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('djangocms_forms', '0003_add_referrer_field'),
]
operations = [
migrations.AddField(
model_name='formdefinition',
name='redirect_delay',
- field=models.PositiveIntegerField(verbose_name='Redirect Delay', blank=True, null=True, help_text="Wait this number of milliseconds before redirecting."),
+ field=models.PositiveIntegerField(verbose_name='Redirect Delay', blank=True, null=True, help_text="Wait this number of milliseconds before redirecting. 1000 milliseconds = 1 second."),
? ++++++++++++++++++++++++++++++
),
] |
14d170eece4e8bb105f5316fb0c6e672a3253b08 | py3flowtools/flowtools_wrapper.py | py3flowtools/flowtools_wrapper.py |
from __future__ import division, print_function, unicode_literals
import io
import os
import sys
from .flow_line import FlowLine
if sys.version_info.major < 3:
import subprocess32 as subprocess
else:
import subprocess
FLOW_EXPORT_ARGS = [
'flow-export',
'-f', '2',
]
def FlowToolsLog(file_path):
with io.open(file_path, mode='rb') as flow_fd, \
io.open(os.devnull, mode='wb') as DEVNULL:
with subprocess.Popen(
FLOW_EXPORT_ARGS,
stdin=flow_fd,
stdout=subprocess.PIPE,
stderr=DEVNULL
) as proc:
iterator = iter(proc.stdout.readline, b'')
try:
next(iterator)
except StopIteration:
msg = 'Could not extract data from {}'.format(file_path)
raise IOError(msg)
for line in iterator:
parsed_line = FlowLine(line)
yield parsed_line
|
from __future__ import division, print_function, unicode_literals
import io
import os
import sys
from .flow_line import FlowLine
if sys.version_info.major < 3:
import subprocess32 as subprocess
else:
import subprocess
FLOW_EXPORT_ARGS = [
'flow-export',
'-f', '2',
]
class FlowToolsLog(object):
def __init__(self, file_path):
self._file_path = file_path
def __iter__(self):
self._parser = self._reader()
return self
def __next__(self):
return next(self._parser)
def next(self):
"""
next method included for compatibility with Python 2
"""
return self.__next__()
def _reader(self):
with io.open(self._file_path, mode='rb') as flow_fd, \
io.open(os.devnull, mode='wb') as DEVNULL:
with subprocess.Popen(
FLOW_EXPORT_ARGS,
stdin=flow_fd,
stdout=subprocess.PIPE,
stderr=DEVNULL
) as proc:
iterator = iter(proc.stdout.readline, b'')
try:
next(iterator)
except StopIteration:
msg = 'Could not extract data from {}'.format(
self._file_path
)
raise IOError(msg)
for line in iterator:
parsed_line = FlowLine(line)
yield parsed_line
| Convert FlowToolsLog to a class | Convert FlowToolsLog to a class
| Python | mit | bbayles/py3flowtools |
from __future__ import division, print_function, unicode_literals
import io
import os
import sys
from .flow_line import FlowLine
if sys.version_info.major < 3:
import subprocess32 as subprocess
else:
import subprocess
FLOW_EXPORT_ARGS = [
'flow-export',
'-f', '2',
]
+ class FlowToolsLog(object):
+ def __init__(self, file_path):
+ self._file_path = file_path
- def FlowToolsLog(file_path):
- with io.open(file_path, mode='rb') as flow_fd, \
- io.open(os.devnull, mode='wb') as DEVNULL:
- with subprocess.Popen(
- FLOW_EXPORT_ARGS,
- stdin=flow_fd,
- stdout=subprocess.PIPE,
- stderr=DEVNULL
- ) as proc:
- iterator = iter(proc.stdout.readline, b'')
- try:
- next(iterator)
- except StopIteration:
- msg = 'Could not extract data from {}'.format(file_path)
- raise IOError(msg)
- for line in iterator:
- parsed_line = FlowLine(line)
- yield parsed_line
+ def __iter__(self):
+ self._parser = self._reader()
+ return self
+
+ def __next__(self):
+ return next(self._parser)
+
+ def next(self):
+ """
+ next method included for compatibility with Python 2
+ """
+ return self.__next__()
+
+ def _reader(self):
+ with io.open(self._file_path, mode='rb') as flow_fd, \
+ io.open(os.devnull, mode='wb') as DEVNULL:
+ with subprocess.Popen(
+ FLOW_EXPORT_ARGS,
+ stdin=flow_fd,
+ stdout=subprocess.PIPE,
+ stderr=DEVNULL
+ ) as proc:
+ iterator = iter(proc.stdout.readline, b'')
+ try:
+ next(iterator)
+ except StopIteration:
+ msg = 'Could not extract data from {}'.format(
+ self._file_path
+ )
+ raise IOError(msg)
+ for line in iterator:
+ parsed_line = FlowLine(line)
+ yield parsed_line
+ | Convert FlowToolsLog to a class | ## Code Before:
from __future__ import division, print_function, unicode_literals
import io
import os
import sys
from .flow_line import FlowLine
if sys.version_info.major < 3:
import subprocess32 as subprocess
else:
import subprocess
FLOW_EXPORT_ARGS = [
'flow-export',
'-f', '2',
]
def FlowToolsLog(file_path):
with io.open(file_path, mode='rb') as flow_fd, \
io.open(os.devnull, mode='wb') as DEVNULL:
with subprocess.Popen(
FLOW_EXPORT_ARGS,
stdin=flow_fd,
stdout=subprocess.PIPE,
stderr=DEVNULL
) as proc:
iterator = iter(proc.stdout.readline, b'')
try:
next(iterator)
except StopIteration:
msg = 'Could not extract data from {}'.format(file_path)
raise IOError(msg)
for line in iterator:
parsed_line = FlowLine(line)
yield parsed_line
## Instruction:
Convert FlowToolsLog to a class
## Code After:
from __future__ import division, print_function, unicode_literals
import io
import os
import sys
from .flow_line import FlowLine
if sys.version_info.major < 3:
import subprocess32 as subprocess
else:
import subprocess
FLOW_EXPORT_ARGS = [
'flow-export',
'-f', '2',
]
class FlowToolsLog(object):
def __init__(self, file_path):
self._file_path = file_path
def __iter__(self):
self._parser = self._reader()
return self
def __next__(self):
return next(self._parser)
def next(self):
"""
next method included for compatibility with Python 2
"""
return self.__next__()
def _reader(self):
with io.open(self._file_path, mode='rb') as flow_fd, \
io.open(os.devnull, mode='wb') as DEVNULL:
with subprocess.Popen(
FLOW_EXPORT_ARGS,
stdin=flow_fd,
stdout=subprocess.PIPE,
stderr=DEVNULL
) as proc:
iterator = iter(proc.stdout.readline, b'')
try:
next(iterator)
except StopIteration:
msg = 'Could not extract data from {}'.format(
self._file_path
)
raise IOError(msg)
for line in iterator:
parsed_line = FlowLine(line)
yield parsed_line
|
from __future__ import division, print_function, unicode_literals
import io
import os
import sys
from .flow_line import FlowLine
if sys.version_info.major < 3:
import subprocess32 as subprocess
else:
import subprocess
FLOW_EXPORT_ARGS = [
'flow-export',
'-f', '2',
]
- def FlowToolsLog(file_path):
+ class FlowToolsLog(object):
+ def __init__(self, file_path):
+ self._file_path = file_path
+
+ def __iter__(self):
+ self._parser = self._reader()
+ return self
+
+ def __next__(self):
+ return next(self._parser)
+
+ def next(self):
+ """
+ next method included for compatibility with Python 2
+ """
+ return self.__next__()
+
+ def _reader(self):
- with io.open(file_path, mode='rb') as flow_fd, \
+ with io.open(self._file_path, mode='rb') as flow_fd, \
? ++++ ++++++
- io.open(os.devnull, mode='wb') as DEVNULL:
+ io.open(os.devnull, mode='wb') as DEVNULL:
? ++++
- with subprocess.Popen(
+ with subprocess.Popen(
? ++++
- FLOW_EXPORT_ARGS,
+ FLOW_EXPORT_ARGS,
? ++++
- stdin=flow_fd,
+ stdin=flow_fd,
? ++++
- stdout=subprocess.PIPE,
+ stdout=subprocess.PIPE,
? ++++
- stderr=DEVNULL
+ stderr=DEVNULL
? ++++
- ) as proc:
+ ) as proc:
? ++++
- iterator = iter(proc.stdout.readline, b'')
+ iterator = iter(proc.stdout.readline, b'')
? ++++
- try:
+ try:
? ++++
- next(iterator)
+ next(iterator)
? ++++
- except StopIteration:
+ except StopIteration:
? ++++
- msg = 'Could not extract data from {}'.format(file_path)
? ----------
+ msg = 'Could not extract data from {}'.format(
? ++++
+ self._file_path
+ )
- raise IOError(msg)
+ raise IOError(msg)
? ++++
- for line in iterator:
+ for line in iterator:
? ++++
- parsed_line = FlowLine(line)
+ parsed_line = FlowLine(line)
? ++++
- yield parsed_line
+ yield parsed_line
? ++++
|
81ca235178a742e0041f2483d1f80d367d77264d | markov.py | markov.py | import random
class Markov:
def __init__(self, source, k=5):
self.source = source
self.k = k
self._init_source()
def _init_source(self):
self.seeds = {}
for i in range(len(self.source) - self.k - 1):
seed = tuple(self.source[i:i+self.k])
if seed not in self.seeds:
self.seeds[seed] = []
self.seeds[seed].append(self.source[i+self.k])
print('Markov dict initialized with {} keys'.format(len(self.seeds.keys())))
def chain(self, length=50, seed=None):
if not seed or seed not in self.seeds:
seed = random.choice(list(self.seeds.keys()))
output = []
while len(output) < length:
if seed not in self.seeds:
seed = random.choice(list(self.seeds.keys()))
next = random.choice(self.seeds[seed])
output.append(next)
seed = tuple(list(seed[1:]) + [next])
return ' '.join(output)
def find_seed(self, start_word):
seeds = list(self.seeds.keys())
seeds = list(filter(lambda s: start_word in s, seeds))
return random.choice(seeds)
| import random
class Markov:
def __init__(self, source, k=5):
self.source = source
self.k = k
self._init_source()
def _init_source(self):
self.seeds = {}
for i in range(len(self.source) - self.k - 1):
seed = tuple(self.source[i:i+self.k])
if seed not in self.seeds:
self.seeds[seed] = []
self.seeds[seed].append(self.source[i+self.k])
print('Markov dict initialized with {} keys'.format(len(self.seeds.keys())))
def chain(self, length=50, seed=None):
if not seed or seed not in self.seeds:
seed = random.choice(list(self.seeds.keys()))
output = []
while len(output) < length:
if seed not in self.seeds:
seed = random.choice(list(self.seeds.keys()))
next = random.choice(self.seeds[seed])
output.append(next)
seed = tuple(list(seed[1:]) + [next])
return ' '.join(output)
def find_seed(self, start_word):
seeds = list(self.seeds.keys())
seeds = list(filter(lambda s: start_word in s, seeds))
if len(seeds) == 0:
return None
return random.choice(seeds)
| Fix find_seed behavior when the word is not present | Fix find_seed behavior when the word is not present
| Python | mit | calzoneman/MarkovBot,calzoneman/MarkovBot | import random
class Markov:
def __init__(self, source, k=5):
self.source = source
self.k = k
self._init_source()
def _init_source(self):
self.seeds = {}
for i in range(len(self.source) - self.k - 1):
seed = tuple(self.source[i:i+self.k])
if seed not in self.seeds:
self.seeds[seed] = []
self.seeds[seed].append(self.source[i+self.k])
print('Markov dict initialized with {} keys'.format(len(self.seeds.keys())))
def chain(self, length=50, seed=None):
if not seed or seed not in self.seeds:
seed = random.choice(list(self.seeds.keys()))
output = []
while len(output) < length:
if seed not in self.seeds:
seed = random.choice(list(self.seeds.keys()))
next = random.choice(self.seeds[seed])
output.append(next)
seed = tuple(list(seed[1:]) + [next])
return ' '.join(output)
def find_seed(self, start_word):
seeds = list(self.seeds.keys())
seeds = list(filter(lambda s: start_word in s, seeds))
+ if len(seeds) == 0:
+ return None
return random.choice(seeds)
| Fix find_seed behavior when the word is not present | ## Code Before:
import random
class Markov:
def __init__(self, source, k=5):
self.source = source
self.k = k
self._init_source()
def _init_source(self):
self.seeds = {}
for i in range(len(self.source) - self.k - 1):
seed = tuple(self.source[i:i+self.k])
if seed not in self.seeds:
self.seeds[seed] = []
self.seeds[seed].append(self.source[i+self.k])
print('Markov dict initialized with {} keys'.format(len(self.seeds.keys())))
def chain(self, length=50, seed=None):
if not seed or seed not in self.seeds:
seed = random.choice(list(self.seeds.keys()))
output = []
while len(output) < length:
if seed not in self.seeds:
seed = random.choice(list(self.seeds.keys()))
next = random.choice(self.seeds[seed])
output.append(next)
seed = tuple(list(seed[1:]) + [next])
return ' '.join(output)
def find_seed(self, start_word):
seeds = list(self.seeds.keys())
seeds = list(filter(lambda s: start_word in s, seeds))
return random.choice(seeds)
## Instruction:
Fix find_seed behavior when the word is not present
## Code After:
import random
class Markov:
def __init__(self, source, k=5):
self.source = source
self.k = k
self._init_source()
def _init_source(self):
self.seeds = {}
for i in range(len(self.source) - self.k - 1):
seed = tuple(self.source[i:i+self.k])
if seed not in self.seeds:
self.seeds[seed] = []
self.seeds[seed].append(self.source[i+self.k])
print('Markov dict initialized with {} keys'.format(len(self.seeds.keys())))
def chain(self, length=50, seed=None):
if not seed or seed not in self.seeds:
seed = random.choice(list(self.seeds.keys()))
output = []
while len(output) < length:
if seed not in self.seeds:
seed = random.choice(list(self.seeds.keys()))
next = random.choice(self.seeds[seed])
output.append(next)
seed = tuple(list(seed[1:]) + [next])
return ' '.join(output)
def find_seed(self, start_word):
seeds = list(self.seeds.keys())
seeds = list(filter(lambda s: start_word in s, seeds))
if len(seeds) == 0:
return None
return random.choice(seeds)
| import random
class Markov:
def __init__(self, source, k=5):
self.source = source
self.k = k
self._init_source()
def _init_source(self):
self.seeds = {}
for i in range(len(self.source) - self.k - 1):
seed = tuple(self.source[i:i+self.k])
if seed not in self.seeds:
self.seeds[seed] = []
self.seeds[seed].append(self.source[i+self.k])
print('Markov dict initialized with {} keys'.format(len(self.seeds.keys())))
def chain(self, length=50, seed=None):
if not seed or seed not in self.seeds:
seed = random.choice(list(self.seeds.keys()))
output = []
while len(output) < length:
if seed not in self.seeds:
seed = random.choice(list(self.seeds.keys()))
next = random.choice(self.seeds[seed])
output.append(next)
seed = tuple(list(seed[1:]) + [next])
return ' '.join(output)
def find_seed(self, start_word):
seeds = list(self.seeds.keys())
seeds = list(filter(lambda s: start_word in s, seeds))
+ if len(seeds) == 0:
+ return None
return random.choice(seeds) |
5448e38d14589b7558513f51d0abf541790be817 | i3pystatus/core/command.py | i3pystatus/core/command.py | import subprocess
def run_through_shell(command, enable_shell=False):
"""
Retrieves output of command
Returns tuple success (boolean)/ stdout(string) / stderr (string)
Don't use this function with programs that outputs lots of data since the output is saved
in one variable
"""
returncode = None
try:
proc = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=enable_shell)
out, stderr = proc.communicate()
out = out.decode("UTF-8")
stderr = stderr.decode("UTF-8")
returncode = proc.returncode
except OSError as e:
out = e.strerror
stderr = e.strerror
except subprocess.CalledProcessError as e:
out = e.output
return returncode, out, stderr
| from collections import namedtuple
import subprocess
CommandResult = namedtuple("Result", ['rc', 'out', 'err'])
def run_through_shell(command, enable_shell=False):
"""
Retrieves output of command
Returns tuple success (boolean)/ stdout(string) / stderr (string)
Don't use this function with programs that outputs lots of data since the output is saved
in one variable
"""
returncode = None
stderr = None
try:
proc = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=enable_shell)
out, stderr = proc.communicate()
out = out.decode("UTF-8")
stderr = stderr.decode("UTF-8")
returncode = proc.returncode
except OSError as e:
out = e.strerror
stderr = e.strerror
except subprocess.CalledProcessError as e:
out = e.output
return CommandResult(returncode, out, stderr)
| Use named tuple for return value | Use named tuple for return value
| Python | mit | m45t3r/i3pystatus,teto/i3pystatus,yang-ling/i3pystatus,opatut/i3pystatus,m45t3r/i3pystatus,juliushaertl/i3pystatus,Elder-of-Ozone/i3pystatus,MaicoTimmerman/i3pystatus,paulollivier/i3pystatus,onkelpit/i3pystatus,richese/i3pystatus,asmikhailov/i3pystatus,enkore/i3pystatus,juliushaertl/i3pystatus,eBrnd/i3pystatus,claria/i3pystatus,plumps/i3pystatus,eBrnd/i3pystatus,ismaelpuerto/i3pystatus,opatut/i3pystatus,richese/i3pystatus,drwahl/i3pystatus,Elder-of-Ozone/i3pystatus,ncoop/i3pystatus,fmarchenko/i3pystatus,paulollivier/i3pystatus,ismaelpuerto/i3pystatus,plumps/i3pystatus,schroeji/i3pystatus,yang-ling/i3pystatus,teto/i3pystatus,Arvedui/i3pystatus,ncoop/i3pystatus,drwahl/i3pystatus,schroeji/i3pystatus,onkelpit/i3pystatus,claria/i3pystatus,MaicoTimmerman/i3pystatus,asmikhailov/i3pystatus,facetoe/i3pystatus,enkore/i3pystatus,fmarchenko/i3pystatus,Arvedui/i3pystatus,facetoe/i3pystatus | + from collections import namedtuple
import subprocess
+
+ CommandResult = namedtuple("Result", ['rc', 'out', 'err'])
def run_through_shell(command, enable_shell=False):
"""
Retrieves output of command
Returns tuple success (boolean)/ stdout(string) / stderr (string)
Don't use this function with programs that outputs lots of data since the output is saved
in one variable
"""
+
returncode = None
+ stderr = None
try:
proc = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=enable_shell)
-
out, stderr = proc.communicate()
out = out.decode("UTF-8")
stderr = stderr.decode("UTF-8")
returncode = proc.returncode
except OSError as e:
out = e.strerror
stderr = e.strerror
except subprocess.CalledProcessError as e:
out = e.output
- return returncode, out, stderr
+ return CommandResult(returncode, out, stderr)
| Use named tuple for return value | ## Code Before:
import subprocess
def run_through_shell(command, enable_shell=False):
"""
Retrieves output of command
Returns tuple success (boolean)/ stdout(string) / stderr (string)
Don't use this function with programs that outputs lots of data since the output is saved
in one variable
"""
returncode = None
try:
proc = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=enable_shell)
out, stderr = proc.communicate()
out = out.decode("UTF-8")
stderr = stderr.decode("UTF-8")
returncode = proc.returncode
except OSError as e:
out = e.strerror
stderr = e.strerror
except subprocess.CalledProcessError as e:
out = e.output
return returncode, out, stderr
## Instruction:
Use named tuple for return value
## Code After:
from collections import namedtuple
import subprocess
CommandResult = namedtuple("Result", ['rc', 'out', 'err'])
def run_through_shell(command, enable_shell=False):
"""
Retrieves output of command
Returns tuple success (boolean)/ stdout(string) / stderr (string)
Don't use this function with programs that outputs lots of data since the output is saved
in one variable
"""
returncode = None
stderr = None
try:
proc = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=enable_shell)
out, stderr = proc.communicate()
out = out.decode("UTF-8")
stderr = stderr.decode("UTF-8")
returncode = proc.returncode
except OSError as e:
out = e.strerror
stderr = e.strerror
except subprocess.CalledProcessError as e:
out = e.output
return CommandResult(returncode, out, stderr)
| + from collections import namedtuple
import subprocess
+
+ CommandResult = namedtuple("Result", ['rc', 'out', 'err'])
def run_through_shell(command, enable_shell=False):
"""
Retrieves output of command
Returns tuple success (boolean)/ stdout(string) / stderr (string)
Don't use this function with programs that outputs lots of data since the output is saved
in one variable
"""
+
returncode = None
+ stderr = None
try:
proc = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=enable_shell)
-
out, stderr = proc.communicate()
out = out.decode("UTF-8")
stderr = stderr.decode("UTF-8")
returncode = proc.returncode
except OSError as e:
out = e.strerror
stderr = e.strerror
except subprocess.CalledProcessError as e:
out = e.output
- return returncode, out, stderr
+ return CommandResult(returncode, out, stderr)
? ++++++++++++++ +
|
96bf0e8dbf30650ba91e70a766071c6e348da6f3 | reactive/nodemanager.py | reactive/nodemanager.py | from charms.reactive import when, when_not, set_state, remove_state
from charms.hadoop import get_hadoop_base
from jujubigdata.handlers import YARN
from jujubigdata import utils
@when('resourcemanager.ready')
@when_not('nodemanager.started')
def start_nodemanager(resourcemanager):
hadoop = get_hadoop_base()
yarn = YARN(hadoop)
yarn.configure_nodemanager(
resourcemanager.resourcemanagers()[0], resourcemanager.port(),
resourcemanager.hs_http(), resourcemanager.hs_ipc())
utils.install_ssh_key('yarn', resourcemanager.ssh_key())
utils.update_kv_hosts(resourcemanager.hosts_map())
utils.manage_etc_hosts()
yarn.start_nodemanager()
hadoop.open_ports('nodemanager')
set_state('nodemanager.started')
@when('nodemanager.started')
@when_not('resourcemanager.ready')
def stop_nodemanager():
hadoop = get_hadoop_base()
yarn = YARN(hadoop)
yarn.stop_nodemanager()
hadoop.close_ports('nodemanager')
remove_state('nodemanager.started')
| from charms.reactive import when, when_not, set_state, remove_state
from charms.layer.hadoop_base import get_hadoop_base
from jujubigdata.handlers import YARN
from jujubigdata import utils
@when('resourcemanager.ready')
@when_not('nodemanager.started')
def start_nodemanager(resourcemanager):
hadoop = get_hadoop_base()
yarn = YARN(hadoop)
yarn.configure_nodemanager(
resourcemanager.resourcemanagers()[0], resourcemanager.port(),
resourcemanager.hs_http(), resourcemanager.hs_ipc())
utils.install_ssh_key('yarn', resourcemanager.ssh_key())
utils.update_kv_hosts(resourcemanager.hosts_map())
utils.manage_etc_hosts()
yarn.start_nodemanager()
hadoop.open_ports('nodemanager')
set_state('nodemanager.started')
@when('nodemanager.started')
@when_not('resourcemanager.ready')
def stop_nodemanager():
hadoop = get_hadoop_base()
yarn = YARN(hadoop)
yarn.stop_nodemanager()
hadoop.close_ports('nodemanager')
remove_state('nodemanager.started')
| Update charms.hadoop reference to follow convention | Update charms.hadoop reference to follow convention
| Python | apache-2.0 | juju-solutions/layer-apache-hadoop-nodemanager | from charms.reactive import when, when_not, set_state, remove_state
- from charms.hadoop import get_hadoop_base
+ from charms.layer.hadoop_base import get_hadoop_base
from jujubigdata.handlers import YARN
from jujubigdata import utils
@when('resourcemanager.ready')
@when_not('nodemanager.started')
def start_nodemanager(resourcemanager):
hadoop = get_hadoop_base()
yarn = YARN(hadoop)
yarn.configure_nodemanager(
resourcemanager.resourcemanagers()[0], resourcemanager.port(),
resourcemanager.hs_http(), resourcemanager.hs_ipc())
utils.install_ssh_key('yarn', resourcemanager.ssh_key())
utils.update_kv_hosts(resourcemanager.hosts_map())
utils.manage_etc_hosts()
yarn.start_nodemanager()
hadoop.open_ports('nodemanager')
set_state('nodemanager.started')
@when('nodemanager.started')
@when_not('resourcemanager.ready')
def stop_nodemanager():
hadoop = get_hadoop_base()
yarn = YARN(hadoop)
yarn.stop_nodemanager()
hadoop.close_ports('nodemanager')
remove_state('nodemanager.started')
| Update charms.hadoop reference to follow convention | ## Code Before:
from charms.reactive import when, when_not, set_state, remove_state
from charms.hadoop import get_hadoop_base
from jujubigdata.handlers import YARN
from jujubigdata import utils
@when('resourcemanager.ready')
@when_not('nodemanager.started')
def start_nodemanager(resourcemanager):
hadoop = get_hadoop_base()
yarn = YARN(hadoop)
yarn.configure_nodemanager(
resourcemanager.resourcemanagers()[0], resourcemanager.port(),
resourcemanager.hs_http(), resourcemanager.hs_ipc())
utils.install_ssh_key('yarn', resourcemanager.ssh_key())
utils.update_kv_hosts(resourcemanager.hosts_map())
utils.manage_etc_hosts()
yarn.start_nodemanager()
hadoop.open_ports('nodemanager')
set_state('nodemanager.started')
@when('nodemanager.started')
@when_not('resourcemanager.ready')
def stop_nodemanager():
hadoop = get_hadoop_base()
yarn = YARN(hadoop)
yarn.stop_nodemanager()
hadoop.close_ports('nodemanager')
remove_state('nodemanager.started')
## Instruction:
Update charms.hadoop reference to follow convention
## Code After:
from charms.reactive import when, when_not, set_state, remove_state
from charms.layer.hadoop_base import get_hadoop_base
from jujubigdata.handlers import YARN
from jujubigdata import utils
@when('resourcemanager.ready')
@when_not('nodemanager.started')
def start_nodemanager(resourcemanager):
hadoop = get_hadoop_base()
yarn = YARN(hadoop)
yarn.configure_nodemanager(
resourcemanager.resourcemanagers()[0], resourcemanager.port(),
resourcemanager.hs_http(), resourcemanager.hs_ipc())
utils.install_ssh_key('yarn', resourcemanager.ssh_key())
utils.update_kv_hosts(resourcemanager.hosts_map())
utils.manage_etc_hosts()
yarn.start_nodemanager()
hadoop.open_ports('nodemanager')
set_state('nodemanager.started')
@when('nodemanager.started')
@when_not('resourcemanager.ready')
def stop_nodemanager():
hadoop = get_hadoop_base()
yarn = YARN(hadoop)
yarn.stop_nodemanager()
hadoop.close_ports('nodemanager')
remove_state('nodemanager.started')
| from charms.reactive import when, when_not, set_state, remove_state
- from charms.hadoop import get_hadoop_base
+ from charms.layer.hadoop_base import get_hadoop_base
? ++++++ +++++
from jujubigdata.handlers import YARN
from jujubigdata import utils
@when('resourcemanager.ready')
@when_not('nodemanager.started')
def start_nodemanager(resourcemanager):
hadoop = get_hadoop_base()
yarn = YARN(hadoop)
yarn.configure_nodemanager(
resourcemanager.resourcemanagers()[0], resourcemanager.port(),
resourcemanager.hs_http(), resourcemanager.hs_ipc())
utils.install_ssh_key('yarn', resourcemanager.ssh_key())
utils.update_kv_hosts(resourcemanager.hosts_map())
utils.manage_etc_hosts()
yarn.start_nodemanager()
hadoop.open_ports('nodemanager')
set_state('nodemanager.started')
@when('nodemanager.started')
@when_not('resourcemanager.ready')
def stop_nodemanager():
hadoop = get_hadoop_base()
yarn = YARN(hadoop)
yarn.stop_nodemanager()
hadoop.close_ports('nodemanager')
remove_state('nodemanager.started') |
23d5d0e0e77dc0b0816df51a8a1e42bc4069112b | rst2pdf/style2yaml.py | rst2pdf/style2yaml.py |
import argparse
import json
import yaml
from rst2pdf.dumpstyle import fixstyle
from rst2pdf.rson import loads as rloads
def main():
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
'paths',
metavar='PATH',
nargs='+',
help='An RSON-formatted file to convert.',
)
args = parser.parse_args()
for path in args.paths:
# read rson from a file
with open(path, 'rb') as fh:
style_data = fixstyle(rloads(fh.read()))
# output the style as json, then parse that
json_style = json.dumps(style_data)
reparsed_style = json.loads(json_style)
yaml_style = yaml.dump(reparsed_style, default_flow_style=None)
print(yaml_style)
if __name__ == '__main__':
main()
|
import argparse
import json
import os
import yaml
from rst2pdf.dumpstyle import fixstyle
from rst2pdf.rson import loads as rloads
def main():
# set up the command, optional --save parameter, and a list of paths
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
'--save',
action='store_true',
help='Save .yaml version of the file (rather than output to stdout)',
)
parser.add_argument(
'paths',
metavar='PATH',
nargs='+',
help='An RSON-formatted file to convert.',
)
args = parser.parse_args()
# loop over the files
for path in args.paths:
# read rson from a file
with open(path, 'rb') as fh:
style_data = fixstyle(rloads(fh.read()))
# output the style as json (already supported), then parse that
json_style = json.dumps(style_data)
reparsed_style = json.loads(json_style)
yaml_style = yaml.dump(reparsed_style, default_flow_style=None)
# output the yaml or save to a file
if args.save:
new_path = '.'.join((os.path.splitext(path)[0], 'yaml'))
if os.path.exists(new_path):
print("File " + new_path + " exists, cannot overwrite")
else:
print("Creating file " + new_path)
with open(new_path, 'w') as file:
file.write(yaml_style)
else:
print(yaml_style)
if __name__ == '__main__':
main()
| Add save functionality to the conversion script | Add save functionality to the conversion script
| Python | mit | rst2pdf/rst2pdf,rst2pdf/rst2pdf |
import argparse
import json
+ import os
import yaml
from rst2pdf.dumpstyle import fixstyle
from rst2pdf.rson import loads as rloads
def main():
+ # set up the command, optional --save parameter, and a list of paths
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
+ )
+ parser.add_argument(
+ '--save',
+ action='store_true',
+ help='Save .yaml version of the file (rather than output to stdout)',
)
parser.add_argument(
'paths',
metavar='PATH',
nargs='+',
help='An RSON-formatted file to convert.',
)
args = parser.parse_args()
+
+ # loop over the files
for path in args.paths:
# read rson from a file
with open(path, 'rb') as fh:
style_data = fixstyle(rloads(fh.read()))
- # output the style as json, then parse that
+ # output the style as json (already supported), then parse that
json_style = json.dumps(style_data)
reparsed_style = json.loads(json_style)
yaml_style = yaml.dump(reparsed_style, default_flow_style=None)
+
+ # output the yaml or save to a file
+ if args.save:
+ new_path = '.'.join((os.path.splitext(path)[0], 'yaml'))
+
+ if os.path.exists(new_path):
+ print("File " + new_path + " exists, cannot overwrite")
+ else:
+ print("Creating file " + new_path)
+ with open(new_path, 'w') as file:
+ file.write(yaml_style)
+ else:
- print(yaml_style)
+ print(yaml_style)
if __name__ == '__main__':
main()
| Add save functionality to the conversion script | ## Code Before:
import argparse
import json
import yaml
from rst2pdf.dumpstyle import fixstyle
from rst2pdf.rson import loads as rloads
def main():
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
'paths',
metavar='PATH',
nargs='+',
help='An RSON-formatted file to convert.',
)
args = parser.parse_args()
for path in args.paths:
# read rson from a file
with open(path, 'rb') as fh:
style_data = fixstyle(rloads(fh.read()))
# output the style as json, then parse that
json_style = json.dumps(style_data)
reparsed_style = json.loads(json_style)
yaml_style = yaml.dump(reparsed_style, default_flow_style=None)
print(yaml_style)
if __name__ == '__main__':
main()
## Instruction:
Add save functionality to the conversion script
## Code After:
import argparse
import json
import os
import yaml
from rst2pdf.dumpstyle import fixstyle
from rst2pdf.rson import loads as rloads
def main():
# set up the command, optional --save parameter, and a list of paths
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
'--save',
action='store_true',
help='Save .yaml version of the file (rather than output to stdout)',
)
parser.add_argument(
'paths',
metavar='PATH',
nargs='+',
help='An RSON-formatted file to convert.',
)
args = parser.parse_args()
# loop over the files
for path in args.paths:
# read rson from a file
with open(path, 'rb') as fh:
style_data = fixstyle(rloads(fh.read()))
# output the style as json (already supported), then parse that
json_style = json.dumps(style_data)
reparsed_style = json.loads(json_style)
yaml_style = yaml.dump(reparsed_style, default_flow_style=None)
# output the yaml or save to a file
if args.save:
new_path = '.'.join((os.path.splitext(path)[0], 'yaml'))
if os.path.exists(new_path):
print("File " + new_path + " exists, cannot overwrite")
else:
print("Creating file " + new_path)
with open(new_path, 'w') as file:
file.write(yaml_style)
else:
print(yaml_style)
if __name__ == '__main__':
main()
|
import argparse
import json
+ import os
import yaml
from rst2pdf.dumpstyle import fixstyle
from rst2pdf.rson import loads as rloads
def main():
+ # set up the command, optional --save parameter, and a list of paths
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
+ )
+ parser.add_argument(
+ '--save',
+ action='store_true',
+ help='Save .yaml version of the file (rather than output to stdout)',
)
parser.add_argument(
'paths',
metavar='PATH',
nargs='+',
help='An RSON-formatted file to convert.',
)
args = parser.parse_args()
+
+ # loop over the files
for path in args.paths:
# read rson from a file
with open(path, 'rb') as fh:
style_data = fixstyle(rloads(fh.read()))
- # output the style as json, then parse that
+ # output the style as json (already supported), then parse that
? ++++++++++++++++++++
json_style = json.dumps(style_data)
reparsed_style = json.loads(json_style)
yaml_style = yaml.dump(reparsed_style, default_flow_style=None)
+
+ # output the yaml or save to a file
+ if args.save:
+ new_path = '.'.join((os.path.splitext(path)[0], 'yaml'))
+
+ if os.path.exists(new_path):
+ print("File " + new_path + " exists, cannot overwrite")
+ else:
+ print("Creating file " + new_path)
+ with open(new_path, 'w') as file:
+ file.write(yaml_style)
+ else:
- print(yaml_style)
+ print(yaml_style)
? ++++
if __name__ == '__main__':
main() |
c1acb68ef54309584816fbf5c93e38266accb2f0 | nova/db/sqlalchemy/session.py | nova/db/sqlalchemy/session.py |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from nova import flags
FLAGS = flags.FLAGS
_ENGINE = None
_MAKER = None
def get_session(autocommit=True, expire_on_commit=False):
"""Helper method to grab session"""
global _ENGINE
global _MAKER
if not _MAKER:
if not _ENGINE:
_ENGINE = create_engine(FLAGS.sql_connection, echo=False)
_MAKER = (sessionmaker(bind=_ENGINE,
autocommit=autocommit,
expire_on_commit=expire_on_commit))
session = _MAKER()
return session
|
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from nova import flags
FLAGS = flags.FLAGS
_ENGINE = None
_MAKER = None
def get_session(autocommit=True, expire_on_commit=False):
"""Helper method to grab session"""
global _ENGINE
global _MAKER
if not _MAKER:
if not _ENGINE:
_ENGINE = create_engine(FLAGS.sql_connection, pool_recycle=3600, echo=False)
_MAKER = (sessionmaker(bind=_ENGINE,
autocommit=autocommit,
expire_on_commit=expire_on_commit))
session = _MAKER()
return session
| Add the pool_recycle setting to enable connection pooling features for the sql engine. The setting is hard-coded to 3600 seconds (one hour) per the recommendation provided on sqlalchemy's site | Add the pool_recycle setting to enable connection pooling features for the sql engine. The setting is hard-coded to 3600 seconds (one hour) per the recommendation provided on sqlalchemy's site | Python | apache-2.0 | qwefi/nova,tanglei528/nova,houshengbo/nova_vmware_compute_driver,SUSE-Cloud/nova,gooddata/openstack-nova,gspilio/nova,TwinkleChawla/nova,felixma/nova,viggates/nova,TieWei/nova,varunarya10/nova_test_latest,Yusuke1987/openstack_template,eonpatapon/nova,ruslanloman/nova,petrutlucian94/nova_dev,fajoy/nova,gooddata/openstack-nova,yrobla/nova,petrutlucian94/nova_dev,rahulunair/nova,devoid/nova,joker946/nova,paulmathews/nova,belmiromoreira/nova,termie/nova-migration-demo,watonyweng/nova,psiwczak/openstack,Stavitsky/nova,maheshp/novatest,termie/pupa,klmitch/nova,LoHChina/nova,termie/nova-migration-demo,yrobla/nova,aristanetworks/arista-ovs-nova,jianghuaw/nova,projectcalico/calico-nova,Yuriy-Leonov/nova,blueboxgroup/nova,Metaswitch/calico-nova,leilihh/nova,affo/nova,KarimAllah/nova,eharney/nova,shahar-stratoscale/nova,superstack/nova,berrange/nova,NoBodyCam/TftpPxeBootBareMetal,CEG-FYP-OpenStack/scheduler,sacharya/nova,MountainWei/nova,cloudbase/nova,rahulunair/nova,tealover/nova,zzicewind/nova,OpenAcademy-OpenStack/nova-scheduler,jianghuaw/nova,eneabio/nova,shootstar/novatest,alaski/nova,mikalstill/nova,termie/pupa,rajalokan/nova,projectcalico/calico-nova,sridevikoushik31/nova,Triv90/Nova,CloudServer/nova,ntt-sic/nova,hanlind/nova,zhimin711/nova,houshengbo/nova_vmware_compute_driver,watonyweng/nova,dstroppa/openstack-smartos-nova-grizzly,scripnichenko/nova,Francis-Liu/animated-broccoli,CEG-FYP-OpenStack/scheduler,akash1808/nova,bigswitch/nova,fnordahl/nova,sridevikoushik31/nova,josephsuh/extra-specs,virtualopensystems/nova,shahar-stratoscale/nova,kimjaejoong/nova,redhat-openstack/nova,berrange/nova,gooddata/openstack-nova,sridevikoushik31/nova,zzicewind/nova,eonpatapon/nova,Brocade-OpenSource/OpenStack-DNRM-Nova,petrutlucian94/nova,KarimAllah/nova,angdraug/nova,JioCloud/nova_test_latest,tangfeixiong/nova,gspilio/nova,maoy/zknova,bclau/nova,josephsuh/extra-specs,imsplitbit/nova,mahak/nova,sileht/deb-openstack-nova,devendermishrajio/nova,cloudbau/nova,Yusuke1987/openstack_template,vladikr/nova_drafts,Juniper/nova,ruslanloman/nova,rrader/nova-docker-plugin,double12gzh/nova,varunarya10/nova_test_latest,usc-isi/nova,mmnelemane/nova,LoHChina/nova,SUSE-Cloud/nova,zhimin711/nova,vmturbo/nova,termie/pupa,cloudbase/nova,alaski/nova,CiscoSystems/nova,MountainWei/nova,JianyuWang/nova,dstroppa/openstack-smartos-nova-grizzly,phenoxim/nova,DirectXMan12/nova-hacking,Stavitsky/nova,rajalokan/nova,yosshy/nova,vmturbo/nova,Triv90/Nova,plumgrid/plumgrid-nova,TwinkleChawla/nova,thomasem/nova,salv-orlando/MyRepo,fnordahl/nova,yatinkumbhare/openstack-nova,eneabio/nova,maoy/zknova,cloudbase/nova,dawnpower/nova,jeffrey4l/nova,mahak/nova,rahulunair/nova,apporc/nova,tanglei528/nova,tudorvio/nova,JioCloud/nova,orbitfp7/nova,termie/nova-migration-demo,barnsnake351/nova,NewpTone/stacklab-nova,mikalstill/nova,noironetworks/nova,usc-isi/nova,badock/nova,NoBodyCam/TftpPxeBootBareMetal,Juniper/nova,cloudbau/nova,tianweizhang/nova,redhat-openstack/nova,rickerc/nova_audit,mgagne/nova,eharney/nova,petrutlucian94/nova,aristanetworks/arista-ovs-nova,usc-isi/extra-specs,citrix-openstack-build/nova,houshengbo/nova_vmware_compute_driver,josephsuh/extra-specs,vmturbo/nova,JioCloud/nova,zaina/nova,leilihh/nova,luogangyi/bcec-nova,vmturbo/nova,rajalokan/nova,openstack/nova,dstroppa/openstack-smartos-nova-grizzly,cloudbase/nova-virtualbox,rickerc/nova_audit,BeyondTheClouds/nova,Juniper/nova,jianghuaw/nova,nikesh-mahalka/nova,sileht/deb-openstack-nova,alvarolopez/nova,savi-dev/nova,ewindisch/nova,felixma/nova,akash1808/nova,badock/nova,bgxavier/nova,adelina-t/nova,fajoy/nova,tianweizhang/nova,gooddata/openstack-nova,spring-week-topos/nova-week,paulmathews/nova,tealover/nova,KarimAllah/nova,sileht/deb-openstack-nova,plumgrid/plumgrid-nova,Yuriy-Leonov/nova,CiscoSystems/nova,silenceli/nova,sebrandon1/nova,isyippee/nova,belmiromoreira/nova,barnsnake351/nova,anotherjesse/nova,apporc/nova,anotherjesse/nova,jeffrey4l/nova,j-carpentier/nova,saleemjaveds/https-github.com-openstack-nova,saleemjaveds/https-github.com-openstack-nova,dawnpower/nova,Juniper/nova,bgxavier/nova,openstack/nova,alexandrucoman/vbox-nova-driver,silenceli/nova,ted-gould/nova,mahak/nova,edulramirez/nova,blueboxgroup/nova,orbitfp7/nova,joker946/nova,kimjaejoong/nova,NewpTone/stacklab-nova,scripnichenko/nova,akash1808/nova_test_latest,NeCTAR-RC/nova,viggates/nova,anotherjesse/nova,paulmathews/nova,luogangyi/bcec-nova,virtualopensystems/nova,ted-gould/nova,bclau/nova,fajoy/nova,JianyuWang/nova,shootstar/novatest,BeyondTheClouds/nova,iuliat/nova,mmnelemane/nova,superstack/nova,vladikr/nova_drafts,BeyondTheClouds/nova,Tehsmash/nova,NeCTAR-RC/nova,angdraug/nova,shail2810/nova,dims/nova,yrobla/nova,gspilio/nova,zaina/nova,sacharya/nova,takeshineshiro/nova,phenoxim/nova,NoBodyCam/TftpPxeBootBareMetal,devoid/nova,hanlind/nova,eneabio/nova,usc-isi/nova,CCI-MOC/nova,ntt-sic/nova,russellb/nova,superstack/nova,sebrandon1/nova,Metaswitch/calico-nova,whitepages/nova,cernops/nova,sebrandon1/nova,openstack/nova,klmitch/nova,leilihh/novaha,russellb/nova,savi-dev/nova,tudorvio/nova,CCI-MOC/nova,maelnor/nova,TieWei/nova,hanlind/nova,DirectXMan12/nova-hacking,sridevikoushik31/openstack,dims/nova,iuliat/nova,devendermishrajio/nova,mandeepdhami/nova,noironetworks/nova,devendermishrajio/nova_test_latest,maelnor/nova,sridevikoushik31/nova,DirectXMan12/nova-hacking,Francis-Liu/animated-broccoli,leilihh/novaha,JioCloud/nova_test_latest,salv-orlando/MyRepo,citrix-openstack-build/nova,jianghuaw/nova,usc-isi/extra-specs,tangfeixiong/nova,klmitch/nova,rrader/nova-docker-plugin,maoy/zknova,OpenAcademy-OpenStack/nova-scheduler,cernops/nova,NewpTone/stacklab-nova,whitepages/nova,imsplitbit/nova,akash1808/nova_test_latest,aristanetworks/arista-ovs-nova,CloudServer/nova,raildo/nova,devendermishrajio/nova_test_latest,cyx1231st/nova,psiwczak/openstack,eayunstack/nova,klmitch/nova,adelina-t/nova,mikalstill/nova,double12gzh/nova,russellb/nova,maheshp/novatest,thomasem/nova,rajalokan/nova,nikesh-mahalka/nova,Tehsmash/nova,shail2810/nova,Brocade-OpenSource/OpenStack-DNRM-Nova,bigswitch/nova,salv-orlando/MyRepo,j-carpentier/nova,cyx1231st/nova,isyippee/nova,edulramirez/nova,maheshp/novatest,psiwczak/openstack,mandeepdhami/nova,savi-dev/nova,usc-isi/extra-specs,alexandrucoman/vbox-nova-driver,raildo/nova,yatinkumbhare/openstack-nova,qwefi/nova,mgagne/nova,yosshy/nova,Triv90/Nova,cloudbase/nova-virtualbox,spring-week-topos/nova-week,takeshineshiro/nova,ewindisch/nova,eayunstack/nova,alvarolopez/nova,sridevikoushik31/openstack,affo/nova,cernops/nova,sridevikoushik31/openstack |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from nova import flags
FLAGS = flags.FLAGS
_ENGINE = None
_MAKER = None
def get_session(autocommit=True, expire_on_commit=False):
"""Helper method to grab session"""
global _ENGINE
global _MAKER
if not _MAKER:
if not _ENGINE:
- _ENGINE = create_engine(FLAGS.sql_connection, echo=False)
+ _ENGINE = create_engine(FLAGS.sql_connection, pool_recycle=3600, echo=False)
_MAKER = (sessionmaker(bind=_ENGINE,
autocommit=autocommit,
expire_on_commit=expire_on_commit))
session = _MAKER()
return session
| Add the pool_recycle setting to enable connection pooling features for the sql engine. The setting is hard-coded to 3600 seconds (one hour) per the recommendation provided on sqlalchemy's site | ## Code Before:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from nova import flags
FLAGS = flags.FLAGS
_ENGINE = None
_MAKER = None
def get_session(autocommit=True, expire_on_commit=False):
"""Helper method to grab session"""
global _ENGINE
global _MAKER
if not _MAKER:
if not _ENGINE:
_ENGINE = create_engine(FLAGS.sql_connection, echo=False)
_MAKER = (sessionmaker(bind=_ENGINE,
autocommit=autocommit,
expire_on_commit=expire_on_commit))
session = _MAKER()
return session
## Instruction:
Add the pool_recycle setting to enable connection pooling features for the sql engine. The setting is hard-coded to 3600 seconds (one hour) per the recommendation provided on sqlalchemy's site
## Code After:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from nova import flags
FLAGS = flags.FLAGS
_ENGINE = None
_MAKER = None
def get_session(autocommit=True, expire_on_commit=False):
"""Helper method to grab session"""
global _ENGINE
global _MAKER
if not _MAKER:
if not _ENGINE:
_ENGINE = create_engine(FLAGS.sql_connection, pool_recycle=3600, echo=False)
_MAKER = (sessionmaker(bind=_ENGINE,
autocommit=autocommit,
expire_on_commit=expire_on_commit))
session = _MAKER()
return session
|
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from nova import flags
FLAGS = flags.FLAGS
_ENGINE = None
_MAKER = None
def get_session(autocommit=True, expire_on_commit=False):
"""Helper method to grab session"""
global _ENGINE
global _MAKER
if not _MAKER:
if not _ENGINE:
- _ENGINE = create_engine(FLAGS.sql_connection, echo=False)
+ _ENGINE = create_engine(FLAGS.sql_connection, pool_recycle=3600, echo=False)
? +++++++++++++++++++
_MAKER = (sessionmaker(bind=_ENGINE,
autocommit=autocommit,
expire_on_commit=expire_on_commit))
session = _MAKER()
return session |
2edd0ee699cfc0ef66d27ccb87ddefad26aa1a77 | Challenges/chall_31.py | Challenges/chall_31.py |
'''
Uses Anaconda environment with Pillow for image processing
- Python 3.7, numpy, and Pillow (PIL)
- Run `source activate imgPIL`, `python chall_31.py`
'''
from PIL import Image
def main():
'''
Hint: where am I? Picture of rock near a beach
short break, this ***REALLY*** has nothing to do with Python
Login required: island: country
Next page:
UFO's ?
That was too easy. You are still on 31...
Window element with iterations attribute of 128
'''
left = 0.34
top = 0.57
width = 0.036
height = 0.027
max_iter = 128
with Image.open('./mandelbrot_chall_31/mandelbrot.gif') as mandelbrot:
pass
return 0
if __name__ == '__main__':
main()
|
'''
Uses Anaconda environment with Pillow for image processing
- Python 3.7, numpy, and Pillow (PIL)
- Run `source activate imgPIL`, `python chall_31.py`
'''
from PIL import Image
def main():
'''
Hint: where am I? Picture of rock near a beach
short break, this ***REALLY*** has nothing to do with Python
Login required: island: country -> search for Grandpa rock
Next page:
UFO's ?
That was too easy. You are still on 31...
Window element with iterations attribute of 128
'''
left = 0.34
top = 0.57
w_step = 0.036 # x-axis = reals
h_step = 0.027 # y-axis = imaginaries
max_iter = 128
with Image.open('./mandelbrot_chall_31/mandelbrot.gif') as mandelbrot:
w, h = mandelbrot.size
print('W: {}, H: {}'.format(w, h))
# f_c(z) = z^2 + c for f_c(0), f_c(f_c(0)), etc.
for n_iter in range(max_iter):
pass
return 0
if __name__ == '__main__':
main()
| Add info for mandelbrot set | Add info for mandelbrot set
| Python | mit | HKuz/PythonChallenge |
'''
Uses Anaconda environment with Pillow for image processing
- Python 3.7, numpy, and Pillow (PIL)
- Run `source activate imgPIL`, `python chall_31.py`
'''
from PIL import Image
def main():
'''
Hint: where am I? Picture of rock near a beach
short break, this ***REALLY*** has nothing to do with Python
- Login required: island: country
+ Login required: island: country -> search for Grandpa rock
Next page:
UFO's ?
That was too easy. You are still on 31...
Window element with iterations attribute of 128
'''
left = 0.34
top = 0.57
- width = 0.036
- height = 0.027
+ w_step = 0.036 # x-axis = reals
+ h_step = 0.027 # y-axis = imaginaries
max_iter = 128
with Image.open('./mandelbrot_chall_31/mandelbrot.gif') as mandelbrot:
+ w, h = mandelbrot.size
+ print('W: {}, H: {}'.format(w, h))
+
+ # f_c(z) = z^2 + c for f_c(0), f_c(f_c(0)), etc.
+ for n_iter in range(max_iter):
- pass
+ pass
+
return 0
if __name__ == '__main__':
main()
| Add info for mandelbrot set | ## Code Before:
'''
Uses Anaconda environment with Pillow for image processing
- Python 3.7, numpy, and Pillow (PIL)
- Run `source activate imgPIL`, `python chall_31.py`
'''
from PIL import Image
def main():
'''
Hint: where am I? Picture of rock near a beach
short break, this ***REALLY*** has nothing to do with Python
Login required: island: country
Next page:
UFO's ?
That was too easy. You are still on 31...
Window element with iterations attribute of 128
'''
left = 0.34
top = 0.57
width = 0.036
height = 0.027
max_iter = 128
with Image.open('./mandelbrot_chall_31/mandelbrot.gif') as mandelbrot:
pass
return 0
if __name__ == '__main__':
main()
## Instruction:
Add info for mandelbrot set
## Code After:
'''
Uses Anaconda environment with Pillow for image processing
- Python 3.7, numpy, and Pillow (PIL)
- Run `source activate imgPIL`, `python chall_31.py`
'''
from PIL import Image
def main():
'''
Hint: where am I? Picture of rock near a beach
short break, this ***REALLY*** has nothing to do with Python
Login required: island: country -> search for Grandpa rock
Next page:
UFO's ?
That was too easy. You are still on 31...
Window element with iterations attribute of 128
'''
left = 0.34
top = 0.57
w_step = 0.036 # x-axis = reals
h_step = 0.027 # y-axis = imaginaries
max_iter = 128
with Image.open('./mandelbrot_chall_31/mandelbrot.gif') as mandelbrot:
w, h = mandelbrot.size
print('W: {}, H: {}'.format(w, h))
# f_c(z) = z^2 + c for f_c(0), f_c(f_c(0)), etc.
for n_iter in range(max_iter):
pass
return 0
if __name__ == '__main__':
main()
|
'''
Uses Anaconda environment with Pillow for image processing
- Python 3.7, numpy, and Pillow (PIL)
- Run `source activate imgPIL`, `python chall_31.py`
'''
from PIL import Image
def main():
'''
Hint: where am I? Picture of rock near a beach
short break, this ***REALLY*** has nothing to do with Python
- Login required: island: country
+ Login required: island: country -> search for Grandpa rock
Next page:
UFO's ?
That was too easy. You are still on 31...
Window element with iterations attribute of 128
'''
left = 0.34
top = 0.57
- width = 0.036
- height = 0.027
+ w_step = 0.036 # x-axis = reals
+ h_step = 0.027 # y-axis = imaginaries
max_iter = 128
with Image.open('./mandelbrot_chall_31/mandelbrot.gif') as mandelbrot:
+ w, h = mandelbrot.size
+ print('W: {}, H: {}'.format(w, h))
+
+ # f_c(z) = z^2 + c for f_c(0), f_c(f_c(0)), etc.
+ for n_iter in range(max_iter):
- pass
+ pass
? ++++
+
return 0
if __name__ == '__main__':
main() |
07bf035221667bdd80ed8570079163d1162d0dd2 | cartoframes/__init__.py | cartoframes/__init__.py | from ._version import __version__
from .core.cartodataframe import CartoDataFrame
from .core.logger import set_log_level
from .io.carto import read_carto, to_carto, has_table, delete_table, describe_table, \
update_table, copy_table, create_table_from_query
__all__ = [
'__version__',
'CartoDataFrame',
'read_carto',
'to_carto',
'has_table',
'delete_table',
'describe_table',
'update_table',
'copy_table',
'create_table_from_query',
'set_log_level'
]
| from ._version import __version__
from .utils.utils import check_package
from .core.cartodataframe import CartoDataFrame
from .core.logger import set_log_level
from .io.carto import read_carto, to_carto, has_table, delete_table, describe_table, \
update_table, copy_table, create_table_from_query
# Check installed packages versions
check_package('carto', '>=1.8.2')
check_package('pandas', '>=0.23.0')
check_package('geopandas', '>=0.6.0')
__all__ = [
'__version__',
'CartoDataFrame',
'read_carto',
'to_carto',
'has_table',
'delete_table',
'describe_table',
'update_table',
'copy_table',
'create_table_from_query',
'set_log_level'
]
| Check critical dependencies versions on runtime | Check critical dependencies versions on runtime
| Python | bsd-3-clause | CartoDB/cartoframes,CartoDB/cartoframes | from ._version import __version__
+ from .utils.utils import check_package
from .core.cartodataframe import CartoDataFrame
from .core.logger import set_log_level
from .io.carto import read_carto, to_carto, has_table, delete_table, describe_table, \
update_table, copy_table, create_table_from_query
+
+
+ # Check installed packages versions
+ check_package('carto', '>=1.8.2')
+ check_package('pandas', '>=0.23.0')
+ check_package('geopandas', '>=0.6.0')
__all__ = [
'__version__',
'CartoDataFrame',
'read_carto',
'to_carto',
'has_table',
'delete_table',
'describe_table',
'update_table',
'copy_table',
'create_table_from_query',
'set_log_level'
]
| Check critical dependencies versions on runtime | ## Code Before:
from ._version import __version__
from .core.cartodataframe import CartoDataFrame
from .core.logger import set_log_level
from .io.carto import read_carto, to_carto, has_table, delete_table, describe_table, \
update_table, copy_table, create_table_from_query
__all__ = [
'__version__',
'CartoDataFrame',
'read_carto',
'to_carto',
'has_table',
'delete_table',
'describe_table',
'update_table',
'copy_table',
'create_table_from_query',
'set_log_level'
]
## Instruction:
Check critical dependencies versions on runtime
## Code After:
from ._version import __version__
from .utils.utils import check_package
from .core.cartodataframe import CartoDataFrame
from .core.logger import set_log_level
from .io.carto import read_carto, to_carto, has_table, delete_table, describe_table, \
update_table, copy_table, create_table_from_query
# Check installed packages versions
check_package('carto', '>=1.8.2')
check_package('pandas', '>=0.23.0')
check_package('geopandas', '>=0.6.0')
__all__ = [
'__version__',
'CartoDataFrame',
'read_carto',
'to_carto',
'has_table',
'delete_table',
'describe_table',
'update_table',
'copy_table',
'create_table_from_query',
'set_log_level'
]
| from ._version import __version__
+ from .utils.utils import check_package
from .core.cartodataframe import CartoDataFrame
from .core.logger import set_log_level
from .io.carto import read_carto, to_carto, has_table, delete_table, describe_table, \
update_table, copy_table, create_table_from_query
+
+
+ # Check installed packages versions
+ check_package('carto', '>=1.8.2')
+ check_package('pandas', '>=0.23.0')
+ check_package('geopandas', '>=0.6.0')
__all__ = [
'__version__',
'CartoDataFrame',
'read_carto',
'to_carto',
'has_table',
'delete_table',
'describe_table',
'update_table',
'copy_table',
'create_table_from_query',
'set_log_level'
] |
c6427c035b9d1d38618ebfed33f729e3d10f270d | config.py | config.py | from katagawa.kg import Katagawa
from schema.config import Guild
class Config:
def __init__(self, bot):
dsn = f'postgresql://beattie:passwd@localhost/config'
self.db = Katagawa(dsn)
self.bot = bot
self.bot.loop.create_task(self.db.connect())
def __del__(self):
self.bot.loop.create_task(self.db.close())
async def get(self, key):
async with self.db.get_session() as s:
query = s.select(Guild).where(Guild.id == key)
guild = await query.first()
return {k.name: v for k, v in guild.to_dict().items()}
async def set(self, gid, **kwargs):
async with self.db.get_session() as s:
s.merge(Guild(id=gid, **kwargs))
async def add(self, gid, **kwargs):
async with self.db.get_session() as s:
s.add(Guild(id=gid, **kwargs))
async def remove(self, gid):
async with self.db.get_session() as s:
await s.execute(f'delete from guild where id = {gid}')
| from katagawa.kg import Katagawa
from schema.config import Guild
class Config:
def __init__(self, bot):
dsn = f'postgresql://beattie:passwd@localhost/config'
self.db = Katagawa(dsn)
self.bot = bot
self.bot.loop.create_task(self.db.connect())
def __del__(self):
self.bot.loop.create_task(self.db.close())
async def get(self, key):
async with self.db.get_session() as s:
query = s.select(Guild).where(Guild.id == key)
guild = await query.first()
return {k.name: v for k, v in guild.to_dict().items()}
async def set(self, gid, **kwargs):
async with self.db.get_session() as s:
guild = await s.select(Guild).where(Guild.id == gid).first()
for key, value in kwargs.items():
setattr(guild, key, value)
s.merge(guild)
async def add(self, gid, **kwargs):
async with self.db.get_session() as s:
s.add(Guild(id=gid, **kwargs))
async def remove(self, gid):
async with self.db.get_session() as s:
await s.execute(f'delete from guild where id = {gid}')
| Change set to merge correctly | Change set to merge correctly
| Python | mit | BeatButton/beattie,BeatButton/beattie-bot | from katagawa.kg import Katagawa
from schema.config import Guild
class Config:
def __init__(self, bot):
dsn = f'postgresql://beattie:passwd@localhost/config'
self.db = Katagawa(dsn)
self.bot = bot
self.bot.loop.create_task(self.db.connect())
def __del__(self):
self.bot.loop.create_task(self.db.close())
async def get(self, key):
async with self.db.get_session() as s:
query = s.select(Guild).where(Guild.id == key)
guild = await query.first()
return {k.name: v for k, v in guild.to_dict().items()}
async def set(self, gid, **kwargs):
async with self.db.get_session() as s:
- s.merge(Guild(id=gid, **kwargs))
+ guild = await s.select(Guild).where(Guild.id == gid).first()
+ for key, value in kwargs.items():
+ setattr(guild, key, value)
+ s.merge(guild)
async def add(self, gid, **kwargs):
async with self.db.get_session() as s:
s.add(Guild(id=gid, **kwargs))
async def remove(self, gid):
async with self.db.get_session() as s:
await s.execute(f'delete from guild where id = {gid}')
| Change set to merge correctly | ## Code Before:
from katagawa.kg import Katagawa
from schema.config import Guild
class Config:
def __init__(self, bot):
dsn = f'postgresql://beattie:passwd@localhost/config'
self.db = Katagawa(dsn)
self.bot = bot
self.bot.loop.create_task(self.db.connect())
def __del__(self):
self.bot.loop.create_task(self.db.close())
async def get(self, key):
async with self.db.get_session() as s:
query = s.select(Guild).where(Guild.id == key)
guild = await query.first()
return {k.name: v for k, v in guild.to_dict().items()}
async def set(self, gid, **kwargs):
async with self.db.get_session() as s:
s.merge(Guild(id=gid, **kwargs))
async def add(self, gid, **kwargs):
async with self.db.get_session() as s:
s.add(Guild(id=gid, **kwargs))
async def remove(self, gid):
async with self.db.get_session() as s:
await s.execute(f'delete from guild where id = {gid}')
## Instruction:
Change set to merge correctly
## Code After:
from katagawa.kg import Katagawa
from schema.config import Guild
class Config:
def __init__(self, bot):
dsn = f'postgresql://beattie:passwd@localhost/config'
self.db = Katagawa(dsn)
self.bot = bot
self.bot.loop.create_task(self.db.connect())
def __del__(self):
self.bot.loop.create_task(self.db.close())
async def get(self, key):
async with self.db.get_session() as s:
query = s.select(Guild).where(Guild.id == key)
guild = await query.first()
return {k.name: v for k, v in guild.to_dict().items()}
async def set(self, gid, **kwargs):
async with self.db.get_session() as s:
guild = await s.select(Guild).where(Guild.id == gid).first()
for key, value in kwargs.items():
setattr(guild, key, value)
s.merge(guild)
async def add(self, gid, **kwargs):
async with self.db.get_session() as s:
s.add(Guild(id=gid, **kwargs))
async def remove(self, gid):
async with self.db.get_session() as s:
await s.execute(f'delete from guild where id = {gid}')
| from katagawa.kg import Katagawa
from schema.config import Guild
class Config:
def __init__(self, bot):
dsn = f'postgresql://beattie:passwd@localhost/config'
self.db = Katagawa(dsn)
self.bot = bot
self.bot.loop.create_task(self.db.connect())
def __del__(self):
self.bot.loop.create_task(self.db.close())
async def get(self, key):
async with self.db.get_session() as s:
query = s.select(Guild).where(Guild.id == key)
guild = await query.first()
return {k.name: v for k, v in guild.to_dict().items()}
async def set(self, gid, **kwargs):
async with self.db.get_session() as s:
- s.merge(Guild(id=gid, **kwargs))
+ guild = await s.select(Guild).where(Guild.id == gid).first()
+ for key, value in kwargs.items():
+ setattr(guild, key, value)
+ s.merge(guild)
async def add(self, gid, **kwargs):
async with self.db.get_session() as s:
s.add(Guild(id=gid, **kwargs))
async def remove(self, gid):
async with self.db.get_session() as s:
await s.execute(f'delete from guild where id = {gid}') |
e28541c00be7f02b3ca6de25e4f95ce4dd099524 | nodeconductor/iaas/perms.py | nodeconductor/iaas/perms.py | from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic, StaffPermissionLogic
from nodeconductor.structure.models import ProjectRole
PERMISSION_LOGICS = (
('iaas.Instance', FilteredCollaboratorsPermissionLogic(
collaborators_query='project__roles__permission_group__user',
collaborators_filter={
'project__roles__role_type': ProjectRole.ADMINISTRATOR,
},
any_permission=True,
)),
('iaas.Template', StaffPermissionLogic(any_permission=True)),
('iaas.TemplateMapping', StaffPermissionLogic(any_permission=True)),
('iaas.Image', StaffPermissionLogic(any_permission=True)),
('iaas.TemplateLicense', StaffPermissionLogic(any_permission=True)),
)
| from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic, StaffPermissionLogic
from nodeconductor.structure.models import ProjectRole
PERMISSION_LOGICS = (
('iaas.Instance', FilteredCollaboratorsPermissionLogic(
collaborators_query='project__roles__permission_group__user',
collaborators_filter={
'project__roles__role_type': ProjectRole.ADMINISTRATOR,
},
any_permission=True,
)),
('iaas.Template', StaffPermissionLogic(any_permission=True)),
('iaas.TemplateMapping', StaffPermissionLogic(any_permission=True)),
('iaas.Image', StaffPermissionLogic(any_permission=True)),
('iaas.TemplateLicense', StaffPermissionLogic(any_permission=True)),
('iaas.InstanceSlaHistory', StaffPermissionLogic(any_permission=True)),
)
| Allow InstanceSlaHistory to be managed by staff | Allow InstanceSlaHistory to be managed by staff
| Python | mit | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor | from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic, StaffPermissionLogic
from nodeconductor.structure.models import ProjectRole
PERMISSION_LOGICS = (
('iaas.Instance', FilteredCollaboratorsPermissionLogic(
collaborators_query='project__roles__permission_group__user',
collaborators_filter={
'project__roles__role_type': ProjectRole.ADMINISTRATOR,
},
any_permission=True,
)),
('iaas.Template', StaffPermissionLogic(any_permission=True)),
('iaas.TemplateMapping', StaffPermissionLogic(any_permission=True)),
('iaas.Image', StaffPermissionLogic(any_permission=True)),
('iaas.TemplateLicense', StaffPermissionLogic(any_permission=True)),
-
+ ('iaas.InstanceSlaHistory', StaffPermissionLogic(any_permission=True)),
)
| Allow InstanceSlaHistory to be managed by staff | ## Code Before:
from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic, StaffPermissionLogic
from nodeconductor.structure.models import ProjectRole
PERMISSION_LOGICS = (
('iaas.Instance', FilteredCollaboratorsPermissionLogic(
collaborators_query='project__roles__permission_group__user',
collaborators_filter={
'project__roles__role_type': ProjectRole.ADMINISTRATOR,
},
any_permission=True,
)),
('iaas.Template', StaffPermissionLogic(any_permission=True)),
('iaas.TemplateMapping', StaffPermissionLogic(any_permission=True)),
('iaas.Image', StaffPermissionLogic(any_permission=True)),
('iaas.TemplateLicense', StaffPermissionLogic(any_permission=True)),
)
## Instruction:
Allow InstanceSlaHistory to be managed by staff
## Code After:
from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic, StaffPermissionLogic
from nodeconductor.structure.models import ProjectRole
PERMISSION_LOGICS = (
('iaas.Instance', FilteredCollaboratorsPermissionLogic(
collaborators_query='project__roles__permission_group__user',
collaborators_filter={
'project__roles__role_type': ProjectRole.ADMINISTRATOR,
},
any_permission=True,
)),
('iaas.Template', StaffPermissionLogic(any_permission=True)),
('iaas.TemplateMapping', StaffPermissionLogic(any_permission=True)),
('iaas.Image', StaffPermissionLogic(any_permission=True)),
('iaas.TemplateLicense', StaffPermissionLogic(any_permission=True)),
('iaas.InstanceSlaHistory', StaffPermissionLogic(any_permission=True)),
)
| from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic, StaffPermissionLogic
from nodeconductor.structure.models import ProjectRole
PERMISSION_LOGICS = (
('iaas.Instance', FilteredCollaboratorsPermissionLogic(
collaborators_query='project__roles__permission_group__user',
collaborators_filter={
'project__roles__role_type': ProjectRole.ADMINISTRATOR,
},
any_permission=True,
)),
('iaas.Template', StaffPermissionLogic(any_permission=True)),
('iaas.TemplateMapping', StaffPermissionLogic(any_permission=True)),
('iaas.Image', StaffPermissionLogic(any_permission=True)),
('iaas.TemplateLicense', StaffPermissionLogic(any_permission=True)),
-
+ ('iaas.InstanceSlaHistory', StaffPermissionLogic(any_permission=True)),
) |
a55f5c1229e67808560b3b55c65d524a737294fa | experiment/consumers.py | experiment/consumers.py | import datetime
import json
from channels.generic.websocket import JsonWebsocketConsumer
from auth_API.helpers import get_or_create_user_information
from experiment.models import ExperimentAction
class ExperimentConsumer(JsonWebsocketConsumer):
##### WebSocket event handlers
def connect(self):
"""
Called when the websocket is handshaking as part of initial connection.
"""
# Accept the connection
self.accept()
def receive_json(self, content, **kwargs):
"""
Called when we get a text frame. Channels will JSON-decode the payload
for us and pass it as the first argument.
"""
# Get an updated session store
user_info = get_or_create_user_information(self.scope['session'], self.scope['user'], 'EOSS')
if hasattr(user_info, 'experimentcontext'):
experiment_context = user_info.experimentcontext
if content.get('msg_type') == 'add_action':
experiment_stage = experiment_context.experimentstage_set.all().order_by("id")[content['stage']]
ExperimentAction.objects.create(experimentstage=experiment_stage, action=json.dumps(content['action']),
date=datetime.datetime.utcnow())
self.send_json({
'action': content['action'],
'date': datetime.datetime.utcnow().isoformat()
})
elif content.get('msg_type') == 'update_state':
experiment_context.current_state = json.dumps(content['state'])
experiment_context.save()
self.send_json({
"state": content["state"]
})
| import datetime
import json
from channels.generic.websocket import JsonWebsocketConsumer
from auth_API.helpers import get_or_create_user_information
from experiment.models import ExperimentAction
class ExperimentConsumer(JsonWebsocketConsumer):
##### WebSocket event handlers
def connect(self):
"""
Called when the websocket is handshaking as part of initial connection.
"""
# Accept the connection
self.accept()
def receive_json(self, content, **kwargs):
"""
Called when we get a text frame. Channels will JSON-decode the payload
for us and pass it as the first argument.
"""
# Get an updated session store
user_info = get_or_create_user_information(self.scope['session'], self.scope['user'], 'EOSS')
if hasattr(user_info, 'experimentcontext'):
experiment_context = user_info.experimentcontext
if content.get('msg_type') == 'add_action':
experiment_stage = experiment_context.experimentstage_set.all().order_by("id")[content['stage']]
ExperimentAction.objects.create(experimentstage=experiment_stage, action=json.dumps(content['action']),
date=datetime.datetime.utcnow())
self.send_json({
'action': content['action'],
'date': datetime.datetime.utcnow().isoformat()
})
elif content.get('msg_type') == 'update_state':
experiment_context.current_state = json.dumps(content['state'])
experiment_context.save()
self.send_json({
"state": json.loads(experiment_context.current_state)
})
| Send what state is saved | Send what state is saved
| Python | mit | seakers/daphne_brain,seakers/daphne_brain | import datetime
import json
from channels.generic.websocket import JsonWebsocketConsumer
from auth_API.helpers import get_or_create_user_information
from experiment.models import ExperimentAction
class ExperimentConsumer(JsonWebsocketConsumer):
##### WebSocket event handlers
def connect(self):
"""
Called when the websocket is handshaking as part of initial connection.
"""
# Accept the connection
self.accept()
def receive_json(self, content, **kwargs):
"""
Called when we get a text frame. Channels will JSON-decode the payload
for us and pass it as the first argument.
"""
# Get an updated session store
user_info = get_or_create_user_information(self.scope['session'], self.scope['user'], 'EOSS')
if hasattr(user_info, 'experimentcontext'):
experiment_context = user_info.experimentcontext
if content.get('msg_type') == 'add_action':
experiment_stage = experiment_context.experimentstage_set.all().order_by("id")[content['stage']]
ExperimentAction.objects.create(experimentstage=experiment_stage, action=json.dumps(content['action']),
date=datetime.datetime.utcnow())
self.send_json({
'action': content['action'],
'date': datetime.datetime.utcnow().isoformat()
})
elif content.get('msg_type') == 'update_state':
experiment_context.current_state = json.dumps(content['state'])
experiment_context.save()
self.send_json({
- "state": content["state"]
+ "state": json.loads(experiment_context.current_state)
})
| Send what state is saved | ## Code Before:
import datetime
import json
from channels.generic.websocket import JsonWebsocketConsumer
from auth_API.helpers import get_or_create_user_information
from experiment.models import ExperimentAction
class ExperimentConsumer(JsonWebsocketConsumer):
##### WebSocket event handlers
def connect(self):
"""
Called when the websocket is handshaking as part of initial connection.
"""
# Accept the connection
self.accept()
def receive_json(self, content, **kwargs):
"""
Called when we get a text frame. Channels will JSON-decode the payload
for us and pass it as the first argument.
"""
# Get an updated session store
user_info = get_or_create_user_information(self.scope['session'], self.scope['user'], 'EOSS')
if hasattr(user_info, 'experimentcontext'):
experiment_context = user_info.experimentcontext
if content.get('msg_type') == 'add_action':
experiment_stage = experiment_context.experimentstage_set.all().order_by("id")[content['stage']]
ExperimentAction.objects.create(experimentstage=experiment_stage, action=json.dumps(content['action']),
date=datetime.datetime.utcnow())
self.send_json({
'action': content['action'],
'date': datetime.datetime.utcnow().isoformat()
})
elif content.get('msg_type') == 'update_state':
experiment_context.current_state = json.dumps(content['state'])
experiment_context.save()
self.send_json({
"state": content["state"]
})
## Instruction:
Send what state is saved
## Code After:
import datetime
import json
from channels.generic.websocket import JsonWebsocketConsumer
from auth_API.helpers import get_or_create_user_information
from experiment.models import ExperimentAction
class ExperimentConsumer(JsonWebsocketConsumer):
##### WebSocket event handlers
def connect(self):
"""
Called when the websocket is handshaking as part of initial connection.
"""
# Accept the connection
self.accept()
def receive_json(self, content, **kwargs):
"""
Called when we get a text frame. Channels will JSON-decode the payload
for us and pass it as the first argument.
"""
# Get an updated session store
user_info = get_or_create_user_information(self.scope['session'], self.scope['user'], 'EOSS')
if hasattr(user_info, 'experimentcontext'):
experiment_context = user_info.experimentcontext
if content.get('msg_type') == 'add_action':
experiment_stage = experiment_context.experimentstage_set.all().order_by("id")[content['stage']]
ExperimentAction.objects.create(experimentstage=experiment_stage, action=json.dumps(content['action']),
date=datetime.datetime.utcnow())
self.send_json({
'action': content['action'],
'date': datetime.datetime.utcnow().isoformat()
})
elif content.get('msg_type') == 'update_state':
experiment_context.current_state = json.dumps(content['state'])
experiment_context.save()
self.send_json({
"state": json.loads(experiment_context.current_state)
})
| import datetime
import json
from channels.generic.websocket import JsonWebsocketConsumer
from auth_API.helpers import get_or_create_user_information
from experiment.models import ExperimentAction
class ExperimentConsumer(JsonWebsocketConsumer):
##### WebSocket event handlers
def connect(self):
"""
Called when the websocket is handshaking as part of initial connection.
"""
# Accept the connection
self.accept()
def receive_json(self, content, **kwargs):
"""
Called when we get a text frame. Channels will JSON-decode the payload
for us and pass it as the first argument.
"""
# Get an updated session store
user_info = get_or_create_user_information(self.scope['session'], self.scope['user'], 'EOSS')
if hasattr(user_info, 'experimentcontext'):
experiment_context = user_info.experimentcontext
if content.get('msg_type') == 'add_action':
experiment_stage = experiment_context.experimentstage_set.all().order_by("id")[content['stage']]
ExperimentAction.objects.create(experimentstage=experiment_stage, action=json.dumps(content['action']),
date=datetime.datetime.utcnow())
self.send_json({
'action': content['action'],
'date': datetime.datetime.utcnow().isoformat()
})
elif content.get('msg_type') == 'update_state':
experiment_context.current_state = json.dumps(content['state'])
experiment_context.save()
self.send_json({
- "state": content["state"]
+ "state": json.loads(experiment_context.current_state)
}) |
2fa8b2f4a63579633272b1cc8d972baf27c661f2 | pmg/models/__init__.py | pmg/models/__init__.py | from .users import *
from .resources import *
from .emails import *
from .pages import *
from .soundcloud_track import *
| from .users import *
from .resources import *
from .emails import *
from .pages import *
from .soundcloud_track import SoundcloudTrack
| Fix error on admin user_report view | Fix error on admin user_report view
| Python | apache-2.0 | Code4SA/pmg-cms-2,Code4SA/pmg-cms-2,Code4SA/pmg-cms-2 | from .users import *
from .resources import *
from .emails import *
from .pages import *
- from .soundcloud_track import *
+ from .soundcloud_track import SoundcloudTrack
| Fix error on admin user_report view | ## Code Before:
from .users import *
from .resources import *
from .emails import *
from .pages import *
from .soundcloud_track import *
## Instruction:
Fix error on admin user_report view
## Code After:
from .users import *
from .resources import *
from .emails import *
from .pages import *
from .soundcloud_track import SoundcloudTrack
| from .users import *
from .resources import *
from .emails import *
from .pages import *
- from .soundcloud_track import *
? ^
+ from .soundcloud_track import SoundcloudTrack
? ^^^^^^^^^^^^^^^
|
baaa7e4818ac71898ff3b601d006f5e23d444bee | pyes/exceptions.py | pyes/exceptions.py |
__author__ = 'Alberto Paro'
__all__ = ['NoServerAvailable',
"QueryError",
"NotFoundException",
"AlreadyExistsException",
"IndexMissingException",
"SearchPhaseExecutionException",
"InvalidQuery",
"InvalidParameterQuery",
"QueryParameterError",
"ReplicationShardOperationFailedException",
"ClusterBlockException",
"MapperParsingException",
"ElasticSearchException",
]
class NoServerAvailable(Exception):
pass
class InvalidQuery(Exception):
pass
class InvalidParameterQuery(InvalidQuery):
pass
class QueryError(Exception):
pass
class QueryParameterError(Exception):
pass
class ElasticSearchException(Exception):
"""Base class of exceptions raised as a result of parsing an error return
from ElasticSearch.
An exception of this class will be raised if no more specific subclass is
appropriate.
"""
def __init__(self, error, status=None, result=None):
super(ElasticSearchException, self).__init__(error)
self.status = status
self.result = result
class ElasticSearchIllegalArgumentException(ElasticSearchException):
pass
class IndexMissingException(ElasticSearchException):
pass
class NotFoundException(ElasticSearchException):
pass
class AlreadyExistsException(ElasticSearchException):
pass
class SearchPhaseExecutionException(ElasticSearchException):
pass
class ReplicationShardOperationFailedException(ElasticSearchException):
pass
class ClusterBlockException(ElasticSearchException):
pass
class MapperParsingException(ElasticSearchException):
pass
|
__author__ = 'Alberto Paro'
__all__ = ['NoServerAvailable',
"QueryError",
"NotFoundException",
"AlreadyExistsException",
"IndexMissingException",
"SearchPhaseExecutionException",
"InvalidQuery",
"InvalidParameterQuery",
"QueryParameterError",
"ScriptFieldsError",
"ReplicationShardOperationFailedException",
"ClusterBlockException",
"MapperParsingException",
"ElasticSearchException",
]
class NoServerAvailable(Exception):
pass
class InvalidQuery(Exception):
pass
class InvalidParameterQuery(InvalidQuery):
pass
class QueryError(Exception):
pass
class QueryParameterError(Exception):
pass
class ScriptFieldsError(Exception):
pass
class ElasticSearchException(Exception):
"""Base class of exceptions raised as a result of parsing an error return
from ElasticSearch.
An exception of this class will be raised if no more specific subclass is
appropriate.
"""
def __init__(self, error, status=None, result=None):
super(ElasticSearchException, self).__init__(error)
self.status = status
self.result = result
class ElasticSearchIllegalArgumentException(ElasticSearchException):
pass
class IndexMissingException(ElasticSearchException):
pass
class NotFoundException(ElasticSearchException):
pass
class AlreadyExistsException(ElasticSearchException):
pass
class SearchPhaseExecutionException(ElasticSearchException):
pass
class ReplicationShardOperationFailedException(ElasticSearchException):
pass
class ClusterBlockException(ElasticSearchException):
pass
class MapperParsingException(ElasticSearchException):
pass
| Add exception type for script_fields related errors | Add exception type for script_fields related errors | Python | bsd-3-clause | jayzeng/pyes,rookdev/pyes,haiwen/pyes,mavarick/pyes,haiwen/pyes,mouadino/pyes,haiwen/pyes,HackLinux/pyes,Fiedzia/pyes,jayzeng/pyes,mavarick/pyes,aparo/pyes,aparo/pyes,mouadino/pyes,Fiedzia/pyes,mavarick/pyes,HackLinux/pyes,aparo/pyes,rookdev/pyes,Fiedzia/pyes,jayzeng/pyes,HackLinux/pyes |
__author__ = 'Alberto Paro'
__all__ = ['NoServerAvailable',
"QueryError",
"NotFoundException",
"AlreadyExistsException",
"IndexMissingException",
"SearchPhaseExecutionException",
"InvalidQuery",
"InvalidParameterQuery",
"QueryParameterError",
+ "ScriptFieldsError",
"ReplicationShardOperationFailedException",
"ClusterBlockException",
"MapperParsingException",
"ElasticSearchException",
]
class NoServerAvailable(Exception):
pass
class InvalidQuery(Exception):
pass
class InvalidParameterQuery(InvalidQuery):
pass
class QueryError(Exception):
pass
class QueryParameterError(Exception):
pass
+ class ScriptFieldsError(Exception):
+ pass
class ElasticSearchException(Exception):
"""Base class of exceptions raised as a result of parsing an error return
from ElasticSearch.
An exception of this class will be raised if no more specific subclass is
appropriate.
"""
def __init__(self, error, status=None, result=None):
super(ElasticSearchException, self).__init__(error)
self.status = status
self.result = result
class ElasticSearchIllegalArgumentException(ElasticSearchException):
pass
class IndexMissingException(ElasticSearchException):
pass
class NotFoundException(ElasticSearchException):
pass
class AlreadyExistsException(ElasticSearchException):
pass
class SearchPhaseExecutionException(ElasticSearchException):
pass
class ReplicationShardOperationFailedException(ElasticSearchException):
pass
class ClusterBlockException(ElasticSearchException):
pass
class MapperParsingException(ElasticSearchException):
pass
| Add exception type for script_fields related errors | ## Code Before:
__author__ = 'Alberto Paro'
__all__ = ['NoServerAvailable',
"QueryError",
"NotFoundException",
"AlreadyExistsException",
"IndexMissingException",
"SearchPhaseExecutionException",
"InvalidQuery",
"InvalidParameterQuery",
"QueryParameterError",
"ReplicationShardOperationFailedException",
"ClusterBlockException",
"MapperParsingException",
"ElasticSearchException",
]
class NoServerAvailable(Exception):
pass
class InvalidQuery(Exception):
pass
class InvalidParameterQuery(InvalidQuery):
pass
class QueryError(Exception):
pass
class QueryParameterError(Exception):
pass
class ElasticSearchException(Exception):
"""Base class of exceptions raised as a result of parsing an error return
from ElasticSearch.
An exception of this class will be raised if no more specific subclass is
appropriate.
"""
def __init__(self, error, status=None, result=None):
super(ElasticSearchException, self).__init__(error)
self.status = status
self.result = result
class ElasticSearchIllegalArgumentException(ElasticSearchException):
pass
class IndexMissingException(ElasticSearchException):
pass
class NotFoundException(ElasticSearchException):
pass
class AlreadyExistsException(ElasticSearchException):
pass
class SearchPhaseExecutionException(ElasticSearchException):
pass
class ReplicationShardOperationFailedException(ElasticSearchException):
pass
class ClusterBlockException(ElasticSearchException):
pass
class MapperParsingException(ElasticSearchException):
pass
## Instruction:
Add exception type for script_fields related errors
## Code After:
__author__ = 'Alberto Paro'
__all__ = ['NoServerAvailable',
"QueryError",
"NotFoundException",
"AlreadyExistsException",
"IndexMissingException",
"SearchPhaseExecutionException",
"InvalidQuery",
"InvalidParameterQuery",
"QueryParameterError",
"ScriptFieldsError",
"ReplicationShardOperationFailedException",
"ClusterBlockException",
"MapperParsingException",
"ElasticSearchException",
]
class NoServerAvailable(Exception):
pass
class InvalidQuery(Exception):
pass
class InvalidParameterQuery(InvalidQuery):
pass
class QueryError(Exception):
pass
class QueryParameterError(Exception):
pass
class ScriptFieldsError(Exception):
pass
class ElasticSearchException(Exception):
"""Base class of exceptions raised as a result of parsing an error return
from ElasticSearch.
An exception of this class will be raised if no more specific subclass is
appropriate.
"""
def __init__(self, error, status=None, result=None):
super(ElasticSearchException, self).__init__(error)
self.status = status
self.result = result
class ElasticSearchIllegalArgumentException(ElasticSearchException):
pass
class IndexMissingException(ElasticSearchException):
pass
class NotFoundException(ElasticSearchException):
pass
class AlreadyExistsException(ElasticSearchException):
pass
class SearchPhaseExecutionException(ElasticSearchException):
pass
class ReplicationShardOperationFailedException(ElasticSearchException):
pass
class ClusterBlockException(ElasticSearchException):
pass
class MapperParsingException(ElasticSearchException):
pass
|
__author__ = 'Alberto Paro'
__all__ = ['NoServerAvailable',
"QueryError",
"NotFoundException",
"AlreadyExistsException",
"IndexMissingException",
"SearchPhaseExecutionException",
"InvalidQuery",
"InvalidParameterQuery",
"QueryParameterError",
+ "ScriptFieldsError",
"ReplicationShardOperationFailedException",
"ClusterBlockException",
"MapperParsingException",
"ElasticSearchException",
]
class NoServerAvailable(Exception):
pass
class InvalidQuery(Exception):
pass
class InvalidParameterQuery(InvalidQuery):
pass
class QueryError(Exception):
pass
class QueryParameterError(Exception):
pass
+ class ScriptFieldsError(Exception):
+ pass
class ElasticSearchException(Exception):
"""Base class of exceptions raised as a result of parsing an error return
from ElasticSearch.
An exception of this class will be raised if no more specific subclass is
appropriate.
"""
def __init__(self, error, status=None, result=None):
super(ElasticSearchException, self).__init__(error)
self.status = status
self.result = result
class ElasticSearchIllegalArgumentException(ElasticSearchException):
pass
class IndexMissingException(ElasticSearchException):
pass
class NotFoundException(ElasticSearchException):
pass
class AlreadyExistsException(ElasticSearchException):
pass
class SearchPhaseExecutionException(ElasticSearchException):
pass
class ReplicationShardOperationFailedException(ElasticSearchException):
pass
class ClusterBlockException(ElasticSearchException):
pass
class MapperParsingException(ElasticSearchException):
pass |
18808b6594d7e2b1c81a2cf4351708e179fb29bb | tests/test_utils.py | tests/test_utils.py | from __future__ import absolute_import, unicode_literals
from badwolf.utils import sanitize_sensitive_data
def test_sanitize_basic_auth_urls():
text = 'abc http://user:pwd@example.com def'
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not in sanitized
assert 'http://***:***@example.com' in sanitized
text = '''abc
http://user:pwd@example.com
def
'''
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not in sanitized
assert 'http://***:***@example.com' in sanitized
text = '''abc
http://example.com
-e git+https://user:pwd@example.com/
def
'''
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not in sanitized
assert 'http://example.com' in sanitized
assert 'git+https://***:***@example.com' in sanitized
| from __future__ import absolute_import, unicode_literals
from badwolf.utils import sanitize_sensitive_data
def test_sanitize_basic_auth_urls():
text = 'abc http://user:pwd@example.com def'
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not in sanitized
assert 'http://***:***@example.com' in sanitized
text = '''abc
http://user:pwd@example.com
def
'''
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not in sanitized
assert 'http://***:***@example.com' in sanitized
text = '''abc
http://example.com
-e git+https://user:pwd@example.com/
def
'''
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not in sanitized
assert 'http://example.com' in sanitized
assert 'git+https://***:***@example.com' in sanitized
lots_of_urls = ['-e git+https://user:pwd@example.com abcd'] * 1000
lots_of_urls.extend(['abc http://example.com def'] * 1000)
text = '\n'.join(lots_of_urls)
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not in sanitized
assert 'http://example.com' in sanitized
assert 'git+https://***:***@example.com' in sanitized
| Update test case for sanitize_sensitive_data | Update test case for sanitize_sensitive_data
| Python | mit | bosondata/badwolf,bosondata/badwolf,bosondata/badwolf | from __future__ import absolute_import, unicode_literals
from badwolf.utils import sanitize_sensitive_data
def test_sanitize_basic_auth_urls():
text = 'abc http://user:pwd@example.com def'
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not in sanitized
assert 'http://***:***@example.com' in sanitized
text = '''abc
http://user:pwd@example.com
def
'''
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not in sanitized
assert 'http://***:***@example.com' in sanitized
text = '''abc
http://example.com
-e git+https://user:pwd@example.com/
def
'''
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not in sanitized
assert 'http://example.com' in sanitized
assert 'git+https://***:***@example.com' in sanitized
+ lots_of_urls = ['-e git+https://user:pwd@example.com abcd'] * 1000
+ lots_of_urls.extend(['abc http://example.com def'] * 1000)
+ text = '\n'.join(lots_of_urls)
+ sanitized = sanitize_sensitive_data(text)
+ assert 'user' not in sanitized
+ assert 'pwd' not in sanitized
+ assert 'http://example.com' in sanitized
+ assert 'git+https://***:***@example.com' in sanitized
+ | Update test case for sanitize_sensitive_data | ## Code Before:
from __future__ import absolute_import, unicode_literals
from badwolf.utils import sanitize_sensitive_data
def test_sanitize_basic_auth_urls():
text = 'abc http://user:pwd@example.com def'
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not in sanitized
assert 'http://***:***@example.com' in sanitized
text = '''abc
http://user:pwd@example.com
def
'''
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not in sanitized
assert 'http://***:***@example.com' in sanitized
text = '''abc
http://example.com
-e git+https://user:pwd@example.com/
def
'''
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not in sanitized
assert 'http://example.com' in sanitized
assert 'git+https://***:***@example.com' in sanitized
## Instruction:
Update test case for sanitize_sensitive_data
## Code After:
from __future__ import absolute_import, unicode_literals
from badwolf.utils import sanitize_sensitive_data
def test_sanitize_basic_auth_urls():
text = 'abc http://user:pwd@example.com def'
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not in sanitized
assert 'http://***:***@example.com' in sanitized
text = '''abc
http://user:pwd@example.com
def
'''
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not in sanitized
assert 'http://***:***@example.com' in sanitized
text = '''abc
http://example.com
-e git+https://user:pwd@example.com/
def
'''
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not in sanitized
assert 'http://example.com' in sanitized
assert 'git+https://***:***@example.com' in sanitized
lots_of_urls = ['-e git+https://user:pwd@example.com abcd'] * 1000
lots_of_urls.extend(['abc http://example.com def'] * 1000)
text = '\n'.join(lots_of_urls)
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not in sanitized
assert 'http://example.com' in sanitized
assert 'git+https://***:***@example.com' in sanitized
| from __future__ import absolute_import, unicode_literals
from badwolf.utils import sanitize_sensitive_data
def test_sanitize_basic_auth_urls():
text = 'abc http://user:pwd@example.com def'
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not in sanitized
assert 'http://***:***@example.com' in sanitized
text = '''abc
http://user:pwd@example.com
def
'''
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not in sanitized
assert 'http://***:***@example.com' in sanitized
text = '''abc
http://example.com
-e git+https://user:pwd@example.com/
def
'''
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not in sanitized
assert 'http://example.com' in sanitized
assert 'git+https://***:***@example.com' in sanitized
+
+ lots_of_urls = ['-e git+https://user:pwd@example.com abcd'] * 1000
+ lots_of_urls.extend(['abc http://example.com def'] * 1000)
+ text = '\n'.join(lots_of_urls)
+ sanitized = sanitize_sensitive_data(text)
+ assert 'user' not in sanitized
+ assert 'pwd' not in sanitized
+ assert 'http://example.com' in sanitized
+ assert 'git+https://***:***@example.com' in sanitized |
039a19032bebd1e6852990f8aacf05042f000070 | args.py | args.py | import inspect
def argspec_set(func):
if not hasattr(func, 'argspec'):
func.argspec = inspect.getargspec(func)
def argspec_iscompat(func, lenargs):
spec = func.argspec
minargs = len(spec.args) - len(spec.defaults or ())
maxargs = len(spec.args) if spec.varargs is None else None
return lenargs >= minargs and (maxargs is None or lenargs <= maxargs)
class ArgCountError(Exception):
pass
| import inspect
def argspec_set(func):
if not hasattr(func, 'argspec'):
func.argspec = inspect.getargspec(func)
def argspec_iscompat(func, lenargs):
spec = func.argspec
minargs = len(spec.args) - len(spec.defaults or ())
maxargs = len(spec.args) if spec.varargs is None else float("infinity")
return minargs <= lenargs <= maxargs
class ArgCountError(Exception):
pass
| Simplify funcion arg compatibility check | Simplify funcion arg compatibility check
| Python | mit | infogulch/pyspades-events | import inspect
def argspec_set(func):
if not hasattr(func, 'argspec'):
func.argspec = inspect.getargspec(func)
def argspec_iscompat(func, lenargs):
spec = func.argspec
minargs = len(spec.args) - len(spec.defaults or ())
- maxargs = len(spec.args) if spec.varargs is None else None
+ maxargs = len(spec.args) if spec.varargs is None else float("infinity")
- return lenargs >= minargs and (maxargs is None or lenargs <= maxargs)
+ return minargs <= lenargs <= maxargs
class ArgCountError(Exception):
pass
| Simplify funcion arg compatibility check | ## Code Before:
import inspect
def argspec_set(func):
if not hasattr(func, 'argspec'):
func.argspec = inspect.getargspec(func)
def argspec_iscompat(func, lenargs):
spec = func.argspec
minargs = len(spec.args) - len(spec.defaults or ())
maxargs = len(spec.args) if spec.varargs is None else None
return lenargs >= minargs and (maxargs is None or lenargs <= maxargs)
class ArgCountError(Exception):
pass
## Instruction:
Simplify funcion arg compatibility check
## Code After:
import inspect
def argspec_set(func):
if not hasattr(func, 'argspec'):
func.argspec = inspect.getargspec(func)
def argspec_iscompat(func, lenargs):
spec = func.argspec
minargs = len(spec.args) - len(spec.defaults or ())
maxargs = len(spec.args) if spec.varargs is None else float("infinity")
return minargs <= lenargs <= maxargs
class ArgCountError(Exception):
pass
| import inspect
def argspec_set(func):
if not hasattr(func, 'argspec'):
func.argspec = inspect.getargspec(func)
def argspec_iscompat(func, lenargs):
spec = func.argspec
minargs = len(spec.args) - len(spec.defaults or ())
- maxargs = len(spec.args) if spec.varargs is None else None
? ^ ^
+ maxargs = len(spec.args) if spec.varargs is None else float("infinity")
? ^^ +++++ ^^^^^^^^
- return lenargs >= minargs and (maxargs is None or lenargs <= maxargs)
+ return minargs <= lenargs <= maxargs
class ArgCountError(Exception):
pass |
523a25d30241ecdd0abdb7545b1454714b003edc | astrospam/pyastro16.py | astrospam/pyastro16.py |
import numpy as np
def times(a, b):
"""
Multiply a by b.
Parameters
----------
a : `numpy.ndarray`
Array one.
b : `numpy.ndarray`
Array two
Returns
-------
result : `numpy.ndarray`
``a`` multiplied by ``b``
"""
return np.multipy(a, b)
class PyAstro(object):
"""
This is a class docstring, here you must describe the parameters for the
creation of the class, which is normally the signature of the ``__init__``
method.
Parameters
----------
awesomeness_level : `int`
How awesome is pyastro16??!
day : `int`
Day of the conference. Defaults to 1.
Attributes
----------
awesomeness_level: `int`
How awesome is this class attributes?! You can document attributes that
are not properties here.
"""
def __init__(self, awesomeness_level, day=1):
"""
This docstring is not used, because it is for a hidden method.
"""
self.awesomeness_level = awesomeness_level
self._day = day
@property
def day(self):
"""
Day of the conference.
Properties are automatically documented as attributes
"""
return self._day
|
import numpy as np
def times(a, b):
"""
Multiply a by b.
Parameters
----------
a : `numpy.ndarray`
Array one.
b : `numpy.ndarray`
Array two
Returns
-------
result : `numpy.ndarray`
``a`` multiplied by ``b``
"""
return np.multipy(a, b)
class PyAstro(object):
"""
This is a class docstring, here you must describe the parameters for the
creation of the class, which is normally the signature of the ``__init__``
method.
Parameters
----------
awesomeness_level : `int`
How awesome is pyastro16??!
day : `int`
Day of the conference. Defaults to 1.
Attributes
----------
awesomeness_level: `int`
How awesome is this class attributes?! You can document attributes that
are not properties here.
"""
def __init__(self, awesomeness_level, day=1):
"""
This docstring is not used, because it is for a hidden method.
"""
self.awesomeness_level = awesomeness_level
self._day = day
@property
def day(self):
"""
Day of the conference.
Properties are automatically documented as attributes
"""
return self._day
class PyAstro16(PyAstro):
"""
The 2016 edition of the python in astronomy conference.
"""
__doc__ += PyAstro.__doc__
| Add a subclass for the dot graph | Add a subclass for the dot graph
| Python | mit | cdeil/sphinx-tutorial |
import numpy as np
def times(a, b):
"""
Multiply a by b.
Parameters
----------
a : `numpy.ndarray`
Array one.
b : `numpy.ndarray`
Array two
Returns
-------
result : `numpy.ndarray`
``a`` multiplied by ``b``
"""
return np.multipy(a, b)
class PyAstro(object):
"""
This is a class docstring, here you must describe the parameters for the
creation of the class, which is normally the signature of the ``__init__``
method.
Parameters
----------
awesomeness_level : `int`
How awesome is pyastro16??!
day : `int`
Day of the conference. Defaults to 1.
Attributes
----------
awesomeness_level: `int`
How awesome is this class attributes?! You can document attributes that
are not properties here.
"""
def __init__(self, awesomeness_level, day=1):
"""
This docstring is not used, because it is for a hidden method.
"""
self.awesomeness_level = awesomeness_level
self._day = day
@property
def day(self):
"""
Day of the conference.
Properties are automatically documented as attributes
"""
return self._day
+
+ class PyAstro16(PyAstro):
+ """
+ The 2016 edition of the python in astronomy conference.
+
+ """
+ __doc__ += PyAstro.__doc__
+ | Add a subclass for the dot graph | ## Code Before:
import numpy as np
def times(a, b):
"""
Multiply a by b.
Parameters
----------
a : `numpy.ndarray`
Array one.
b : `numpy.ndarray`
Array two
Returns
-------
result : `numpy.ndarray`
``a`` multiplied by ``b``
"""
return np.multipy(a, b)
class PyAstro(object):
"""
This is a class docstring, here you must describe the parameters for the
creation of the class, which is normally the signature of the ``__init__``
method.
Parameters
----------
awesomeness_level : `int`
How awesome is pyastro16??!
day : `int`
Day of the conference. Defaults to 1.
Attributes
----------
awesomeness_level: `int`
How awesome is this class attributes?! You can document attributes that
are not properties here.
"""
def __init__(self, awesomeness_level, day=1):
"""
This docstring is not used, because it is for a hidden method.
"""
self.awesomeness_level = awesomeness_level
self._day = day
@property
def day(self):
"""
Day of the conference.
Properties are automatically documented as attributes
"""
return self._day
## Instruction:
Add a subclass for the dot graph
## Code After:
import numpy as np
def times(a, b):
"""
Multiply a by b.
Parameters
----------
a : `numpy.ndarray`
Array one.
b : `numpy.ndarray`
Array two
Returns
-------
result : `numpy.ndarray`
``a`` multiplied by ``b``
"""
return np.multipy(a, b)
class PyAstro(object):
"""
This is a class docstring, here you must describe the parameters for the
creation of the class, which is normally the signature of the ``__init__``
method.
Parameters
----------
awesomeness_level : `int`
How awesome is pyastro16??!
day : `int`
Day of the conference. Defaults to 1.
Attributes
----------
awesomeness_level: `int`
How awesome is this class attributes?! You can document attributes that
are not properties here.
"""
def __init__(self, awesomeness_level, day=1):
"""
This docstring is not used, because it is for a hidden method.
"""
self.awesomeness_level = awesomeness_level
self._day = day
@property
def day(self):
"""
Day of the conference.
Properties are automatically documented as attributes
"""
return self._day
class PyAstro16(PyAstro):
"""
The 2016 edition of the python in astronomy conference.
"""
__doc__ += PyAstro.__doc__
|
import numpy as np
def times(a, b):
"""
Multiply a by b.
Parameters
----------
a : `numpy.ndarray`
Array one.
b : `numpy.ndarray`
Array two
Returns
-------
result : `numpy.ndarray`
``a`` multiplied by ``b``
"""
return np.multipy(a, b)
class PyAstro(object):
"""
This is a class docstring, here you must describe the parameters for the
creation of the class, which is normally the signature of the ``__init__``
method.
Parameters
----------
awesomeness_level : `int`
How awesome is pyastro16??!
day : `int`
Day of the conference. Defaults to 1.
Attributes
----------
awesomeness_level: `int`
How awesome is this class attributes?! You can document attributes that
are not properties here.
"""
def __init__(self, awesomeness_level, day=1):
"""
This docstring is not used, because it is for a hidden method.
"""
self.awesomeness_level = awesomeness_level
self._day = day
@property
def day(self):
"""
Day of the conference.
Properties are automatically documented as attributes
"""
return self._day
+
+
+ class PyAstro16(PyAstro):
+ """
+ The 2016 edition of the python in astronomy conference.
+
+ """
+ __doc__ += PyAstro.__doc__ |
45fb01574d410c2a764e5b40a5e93a44fa8f6584 | flask_admin/contrib/geoa/form.py | flask_admin/contrib/geoa/form.py | from flask.ext.admin.model.form import converts
from flask.ext.admin.contrib.sqla.form import AdminModelConverter as SQLAAdminConverter
from .fields import GeoJSONField
class AdminModelConverter(SQLAAdminConverter):
@converts('Geometry')
def convert_geom(self, column, field_args, **extra):
field_args['geometry_type'] = column.type.geometry_type
field_args['srid'] = column.type.srid
field_args['session'] = self.session
return GeoJSONField(**field_args)
| from flask.ext.admin.model.form import converts
from flask.ext.admin.contrib.sqla.form import AdminModelConverter as SQLAAdminConverter
from .fields import GeoJSONField
class AdminModelConverter(SQLAAdminConverter):
@converts('Geography', 'Geometry')
def convert_geom(self, column, field_args, **extra):
field_args['geometry_type'] = column.type.geometry_type
field_args['srid'] = column.type.srid
field_args['session'] = self.session
return GeoJSONField(**field_args)
| Add Geography Type to GeoAlchemy Backend | Add Geography Type to GeoAlchemy Backend
The current GeoAlchemy backend only works with geometry columns, and ignores geography columns (which are also supported by geoalchemy). This 1-word fix adds support for geography columns. | Python | bsd-3-clause | litnimax/flask-admin,petrus-jvrensburg/flask-admin,closeio/flask-admin,torotil/flask-admin,jmagnusson/flask-admin,marrybird/flask-admin,dxmo/flask-admin,ondoheer/flask-admin,plaes/flask-admin,LennartP/flask-admin,jamesbeebop/flask-admin,NickWoodhams/flask-admin,closeio/flask-admin,CoolCloud/flask-admin,radioprotector/flask-admin,iurisilvio/flask-admin,chase-seibert/flask-admin,marrybird/flask-admin,betterlife/flask-admin,dxmo/flask-admin,petrus-jvrensburg/flask-admin,wuxiangfeng/flask-admin,likaiguo/flask-admin,mrjoes/flask-admin,AlmogCohen/flask-admin,phantomxc/flask-admin,chase-seibert/flask-admin,chase-seibert/flask-admin,likaiguo/flask-admin,chase-seibert/flask-admin,iurisilvio/flask-admin,CoolCloud/flask-admin,Kha/flask-admin,ibushong/test-repo,Junnplus/flask-admin,quokkaproject/flask-admin,wuxiangfeng/flask-admin,ArtemSerga/flask-admin,quokkaproject/flask-admin,lifei/flask-admin,HermasT/flask-admin,torotil/flask-admin,plaes/flask-admin,AlmogCohen/flask-admin,late-warrior/flask-admin,likaiguo/flask-admin,rochacbruno/flask-admin,janusnic/flask-admin,NickWoodhams/flask-admin,toddetzel/flask-admin,ArtemSerga/flask-admin,likaiguo/flask-admin,ondoheer/flask-admin,mikelambert/flask-admin,ArtemSerga/flask-admin,ibushong/test-repo,mrjoes/flask-admin,Kha/flask-admin,phantomxc/flask-admin,CoolCloud/flask-admin,ondoheer/flask-admin,mikelambert/flask-admin,janusnic/flask-admin,jamesbeebop/flask-admin,radioprotector/flask-admin,betterlife/flask-admin,flask-admin/flask-admin,plaes/flask-admin,jschneier/flask-admin,flabe81/flask-admin,torotil/flask-admin,AlmogCohen/flask-admin,betterlife/flask-admin,betterlife/flask-admin,mikelambert/flask-admin,jmagnusson/flask-admin,jamesbeebop/flask-admin,flabe81/flask-admin,plaes/flask-admin,jamesbeebop/flask-admin,iurisilvio/flask-admin,jschneier/flask-admin,radioprotector/flask-admin,Kha/flask-admin,Kha/flask-admin,quokkaproject/flask-admin,LennartP/flask-admin,phantomxc/flask-admin,HermasT/flask-admin,janusnic/flask-admin,late-warrior/flask-admin,mrjoes/flask-admin,marrybird/flask-admin,closeio/flask-admin,CoolCloud/flask-admin,AlmogCohen/flask-admin,NickWoodhams/flask-admin,iurisilvio/flask-admin,NickWoodhams/flask-admin,ibushong/test-repo,HermasT/flask-admin,litnimax/flask-admin,late-warrior/flask-admin,Junnplus/flask-admin,jmagnusson/flask-admin,HermasT/flask-admin,torotil/flask-admin,jmagnusson/flask-admin,LennartP/flask-admin,radioprotector/flask-admin,toddetzel/flask-admin,jschneier/flask-admin,jschneier/flask-admin,phantomxc/flask-admin,mrjoes/flask-admin,petrus-jvrensburg/flask-admin,ibushong/test-repo,lifei/flask-admin,rochacbruno/flask-admin,LennartP/flask-admin,lifei/flask-admin,flask-admin/flask-admin,ondoheer/flask-admin,flask-admin/flask-admin,flask-admin/flask-admin,dxmo/flask-admin,ArtemSerga/flask-admin,janusnic/flask-admin,Junnplus/flask-admin,litnimax/flask-admin,wuxiangfeng/flask-admin,petrus-jvrensburg/flask-admin,Junnplus/flask-admin,rochacbruno/flask-admin,litnimax/flask-admin,marrybird/flask-admin,mikelambert/flask-admin,flabe81/flask-admin,lifei/flask-admin,quokkaproject/flask-admin,toddetzel/flask-admin,flabe81/flask-admin,rochacbruno/flask-admin,wuxiangfeng/flask-admin,dxmo/flask-admin,closeio/flask-admin,late-warrior/flask-admin,toddetzel/flask-admin | from flask.ext.admin.model.form import converts
from flask.ext.admin.contrib.sqla.form import AdminModelConverter as SQLAAdminConverter
from .fields import GeoJSONField
class AdminModelConverter(SQLAAdminConverter):
- @converts('Geometry')
+ @converts('Geography', 'Geometry')
def convert_geom(self, column, field_args, **extra):
field_args['geometry_type'] = column.type.geometry_type
field_args['srid'] = column.type.srid
field_args['session'] = self.session
return GeoJSONField(**field_args)
| Add Geography Type to GeoAlchemy Backend | ## Code Before:
from flask.ext.admin.model.form import converts
from flask.ext.admin.contrib.sqla.form import AdminModelConverter as SQLAAdminConverter
from .fields import GeoJSONField
class AdminModelConverter(SQLAAdminConverter):
@converts('Geometry')
def convert_geom(self, column, field_args, **extra):
field_args['geometry_type'] = column.type.geometry_type
field_args['srid'] = column.type.srid
field_args['session'] = self.session
return GeoJSONField(**field_args)
## Instruction:
Add Geography Type to GeoAlchemy Backend
## Code After:
from flask.ext.admin.model.form import converts
from flask.ext.admin.contrib.sqla.form import AdminModelConverter as SQLAAdminConverter
from .fields import GeoJSONField
class AdminModelConverter(SQLAAdminConverter):
@converts('Geography', 'Geometry')
def convert_geom(self, column, field_args, **extra):
field_args['geometry_type'] = column.type.geometry_type
field_args['srid'] = column.type.srid
field_args['session'] = self.session
return GeoJSONField(**field_args)
| from flask.ext.admin.model.form import converts
from flask.ext.admin.contrib.sqla.form import AdminModelConverter as SQLAAdminConverter
from .fields import GeoJSONField
class AdminModelConverter(SQLAAdminConverter):
- @converts('Geometry')
+ @converts('Geography', 'Geometry')
? +++++++++++++
def convert_geom(self, column, field_args, **extra):
field_args['geometry_type'] = column.type.geometry_type
field_args['srid'] = column.type.srid
field_args['session'] = self.session
return GeoJSONField(**field_args) |
3a9359660ff4c782e0de16e8115b754a3e17d7e7 | inthe_am/taskmanager/models/usermetadata.py | inthe_am/taskmanager/models/usermetadata.py | from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
class UserMetadata(models.Model):
user = models.ForeignKey(
User, related_name="metadata", unique=True, on_delete=models.CASCADE
)
tos_version = models.IntegerField(default=0)
tos_accepted = models.DateTimeField(default=None, null=True,)
privacy_policy_version = models.IntegerField(default=0)
privacy_policy_accepted = models.DateTimeField(default=None, null=True,)
colorscheme = models.CharField(default="dark-yellow-green.theme", max_length=255,)
@property
def tos_up_to_date(self):
return self.tos_version == settings.TOS_VERSION
@property
def privacy_policy_up_to_date(self):
return self.privacy_policy_version == settings.PRIVACY_POLICY_VERSION
@classmethod
def get_for_user(cls, user):
meta, created = UserMetadata.objects.get_or_create(user=user)
return meta
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
from . import TaskStore
if self.tos_up_to_date and self.privacy_policy_up_to_date:
store = TaskStore.get_for_user(self.user)
store.taskd_account.resume()
def __str__(self):
return self.user.username
class Meta:
app_label = "taskmanager"
| from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
class UserMetadata(models.Model):
user = models.OneToOneField(
User, related_name="metadata", on_delete=models.CASCADE
)
tos_version = models.IntegerField(default=0)
tos_accepted = models.DateTimeField(default=None, null=True,)
privacy_policy_version = models.IntegerField(default=0)
privacy_policy_accepted = models.DateTimeField(default=None, null=True,)
colorscheme = models.CharField(default="dark-yellow-green.theme", max_length=255,)
@property
def tos_up_to_date(self):
return self.tos_version == settings.TOS_VERSION
@property
def privacy_policy_up_to_date(self):
return self.privacy_policy_version == settings.PRIVACY_POLICY_VERSION
@classmethod
def get_for_user(cls, user):
meta, created = UserMetadata.objects.get_or_create(user=user)
return meta
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
from . import TaskStore
if self.tos_up_to_date and self.privacy_policy_up_to_date:
store = TaskStore.get_for_user(self.user)
store.taskd_account.resume()
def __str__(self):
return self.user.username
class Meta:
app_label = "taskmanager"
| Change mapping to avoid warning | Change mapping to avoid warning
| Python | agpl-3.0 | coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am | from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
class UserMetadata(models.Model):
- user = models.ForeignKey(
+ user = models.OneToOneField(
- User, related_name="metadata", unique=True, on_delete=models.CASCADE
+ User, related_name="metadata", on_delete=models.CASCADE
)
tos_version = models.IntegerField(default=0)
tos_accepted = models.DateTimeField(default=None, null=True,)
privacy_policy_version = models.IntegerField(default=0)
privacy_policy_accepted = models.DateTimeField(default=None, null=True,)
colorscheme = models.CharField(default="dark-yellow-green.theme", max_length=255,)
@property
def tos_up_to_date(self):
return self.tos_version == settings.TOS_VERSION
@property
def privacy_policy_up_to_date(self):
return self.privacy_policy_version == settings.PRIVACY_POLICY_VERSION
@classmethod
def get_for_user(cls, user):
meta, created = UserMetadata.objects.get_or_create(user=user)
return meta
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
from . import TaskStore
if self.tos_up_to_date and self.privacy_policy_up_to_date:
store = TaskStore.get_for_user(self.user)
store.taskd_account.resume()
def __str__(self):
return self.user.username
class Meta:
app_label = "taskmanager"
| Change mapping to avoid warning | ## Code Before:
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
class UserMetadata(models.Model):
user = models.ForeignKey(
User, related_name="metadata", unique=True, on_delete=models.CASCADE
)
tos_version = models.IntegerField(default=0)
tos_accepted = models.DateTimeField(default=None, null=True,)
privacy_policy_version = models.IntegerField(default=0)
privacy_policy_accepted = models.DateTimeField(default=None, null=True,)
colorscheme = models.CharField(default="dark-yellow-green.theme", max_length=255,)
@property
def tos_up_to_date(self):
return self.tos_version == settings.TOS_VERSION
@property
def privacy_policy_up_to_date(self):
return self.privacy_policy_version == settings.PRIVACY_POLICY_VERSION
@classmethod
def get_for_user(cls, user):
meta, created = UserMetadata.objects.get_or_create(user=user)
return meta
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
from . import TaskStore
if self.tos_up_to_date and self.privacy_policy_up_to_date:
store = TaskStore.get_for_user(self.user)
store.taskd_account.resume()
def __str__(self):
return self.user.username
class Meta:
app_label = "taskmanager"
## Instruction:
Change mapping to avoid warning
## Code After:
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
class UserMetadata(models.Model):
user = models.OneToOneField(
User, related_name="metadata", on_delete=models.CASCADE
)
tos_version = models.IntegerField(default=0)
tos_accepted = models.DateTimeField(default=None, null=True,)
privacy_policy_version = models.IntegerField(default=0)
privacy_policy_accepted = models.DateTimeField(default=None, null=True,)
colorscheme = models.CharField(default="dark-yellow-green.theme", max_length=255,)
@property
def tos_up_to_date(self):
return self.tos_version == settings.TOS_VERSION
@property
def privacy_policy_up_to_date(self):
return self.privacy_policy_version == settings.PRIVACY_POLICY_VERSION
@classmethod
def get_for_user(cls, user):
meta, created = UserMetadata.objects.get_or_create(user=user)
return meta
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
from . import TaskStore
if self.tos_up_to_date and self.privacy_policy_up_to_date:
store = TaskStore.get_for_user(self.user)
store.taskd_account.resume()
def __str__(self):
return self.user.username
class Meta:
app_label = "taskmanager"
| from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
class UserMetadata(models.Model):
- user = models.ForeignKey(
+ user = models.OneToOneField(
- User, related_name="metadata", unique=True, on_delete=models.CASCADE
? -------------
+ User, related_name="metadata", on_delete=models.CASCADE
)
tos_version = models.IntegerField(default=0)
tos_accepted = models.DateTimeField(default=None, null=True,)
privacy_policy_version = models.IntegerField(default=0)
privacy_policy_accepted = models.DateTimeField(default=None, null=True,)
colorscheme = models.CharField(default="dark-yellow-green.theme", max_length=255,)
@property
def tos_up_to_date(self):
return self.tos_version == settings.TOS_VERSION
@property
def privacy_policy_up_to_date(self):
return self.privacy_policy_version == settings.PRIVACY_POLICY_VERSION
@classmethod
def get_for_user(cls, user):
meta, created = UserMetadata.objects.get_or_create(user=user)
return meta
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
from . import TaskStore
if self.tos_up_to_date and self.privacy_policy_up_to_date:
store = TaskStore.get_for_user(self.user)
store.taskd_account.resume()
def __str__(self):
return self.user.username
class Meta:
app_label = "taskmanager" |
d478c966192241cccf53ac665820fd9a62ebcdeb | huxley/api/permissions.py | huxley/api/permissions.py |
from rest_framework import permissions
class IsSuperuserOrReadOnly(permissions.BasePermission):
'''Allow writes if superuser, read-only otherwise.'''
def has_permission(self, request, view):
return (request.user.is_superuser or
request.method in permissions.SAFE_METHODS)
class IsUserOrSuperuser(permissions.BasePermission):
'''Accept only the users themselves or superusers.'''
def has_object_permission(self, request, view, obj):
return request.user.is_superuser or request.user == obj
class IsAdvisorOrSuperuser(permissions.BasePermission):
'''Accept only the school's advisor or superusers.'''
def has_object_permission(self, request, view, obj):
return request.user.is_superuser or request.user == obj.advisor
class IsPostOrSuperuserOnly(permissions.BasePermission):
'''Accept POST (create) requests, superusers-only otherwise.'''
def has_object_permissions(self, request, view, obj):
return request.method == 'POST' or request.user.is_superuser
|
from rest_framework import permissions
class IsSuperuserOrReadOnly(permissions.BasePermission):
'''Allow writes if superuser, read-only otherwise.'''
def has_permission(self, request, view):
return (request.user.is_superuser or
request.method in permissions.SAFE_METHODS)
class IsUserOrSuperuser(permissions.BasePermission):
'''Accept only the users themselves or superusers.'''
def has_object_permission(self, request, view, obj):
return request.user.is_superuser or request.user == obj
class IsAdvisorOrSuperuser(permissions.BasePermission):
'''Accept only the school's advisor or superusers.'''
def has_object_permission(self, request, view, obj):
return request.user.is_superuser or request.user == obj.advisor
class IsPostOrSuperuserOnly(permissions.BasePermission):
'''Accept POST (create) requests, superusers-only otherwise.'''
def has_permission(self, request, view):
return request.method == 'POST' or request.user.is_superuser
| Make IsPostOrSuperuserOnly a non-object-level permission. | Make IsPostOrSuperuserOnly a non-object-level permission.
| Python | bsd-3-clause | nathanielparke/huxley,bmun/huxley,bmun/huxley,nathanielparke/huxley,bmun/huxley,ctmunwebmaster/huxley,nathanielparke/huxley,ctmunwebmaster/huxley,nathanielparke/huxley,bmun/huxley,ctmunwebmaster/huxley,ctmunwebmaster/huxley |
from rest_framework import permissions
class IsSuperuserOrReadOnly(permissions.BasePermission):
'''Allow writes if superuser, read-only otherwise.'''
def has_permission(self, request, view):
return (request.user.is_superuser or
request.method in permissions.SAFE_METHODS)
class IsUserOrSuperuser(permissions.BasePermission):
'''Accept only the users themselves or superusers.'''
def has_object_permission(self, request, view, obj):
return request.user.is_superuser or request.user == obj
class IsAdvisorOrSuperuser(permissions.BasePermission):
'''Accept only the school's advisor or superusers.'''
def has_object_permission(self, request, view, obj):
return request.user.is_superuser or request.user == obj.advisor
class IsPostOrSuperuserOnly(permissions.BasePermission):
'''Accept POST (create) requests, superusers-only otherwise.'''
- def has_object_permissions(self, request, view, obj):
+ def has_permission(self, request, view):
return request.method == 'POST' or request.user.is_superuser
| Make IsPostOrSuperuserOnly a non-object-level permission. | ## Code Before:
from rest_framework import permissions
class IsSuperuserOrReadOnly(permissions.BasePermission):
'''Allow writes if superuser, read-only otherwise.'''
def has_permission(self, request, view):
return (request.user.is_superuser or
request.method in permissions.SAFE_METHODS)
class IsUserOrSuperuser(permissions.BasePermission):
'''Accept only the users themselves or superusers.'''
def has_object_permission(self, request, view, obj):
return request.user.is_superuser or request.user == obj
class IsAdvisorOrSuperuser(permissions.BasePermission):
'''Accept only the school's advisor or superusers.'''
def has_object_permission(self, request, view, obj):
return request.user.is_superuser or request.user == obj.advisor
class IsPostOrSuperuserOnly(permissions.BasePermission):
'''Accept POST (create) requests, superusers-only otherwise.'''
def has_object_permissions(self, request, view, obj):
return request.method == 'POST' or request.user.is_superuser
## Instruction:
Make IsPostOrSuperuserOnly a non-object-level permission.
## Code After:
from rest_framework import permissions
class IsSuperuserOrReadOnly(permissions.BasePermission):
'''Allow writes if superuser, read-only otherwise.'''
def has_permission(self, request, view):
return (request.user.is_superuser or
request.method in permissions.SAFE_METHODS)
class IsUserOrSuperuser(permissions.BasePermission):
'''Accept only the users themselves or superusers.'''
def has_object_permission(self, request, view, obj):
return request.user.is_superuser or request.user == obj
class IsAdvisorOrSuperuser(permissions.BasePermission):
'''Accept only the school's advisor or superusers.'''
def has_object_permission(self, request, view, obj):
return request.user.is_superuser or request.user == obj.advisor
class IsPostOrSuperuserOnly(permissions.BasePermission):
'''Accept POST (create) requests, superusers-only otherwise.'''
def has_permission(self, request, view):
return request.method == 'POST' or request.user.is_superuser
|
from rest_framework import permissions
class IsSuperuserOrReadOnly(permissions.BasePermission):
'''Allow writes if superuser, read-only otherwise.'''
def has_permission(self, request, view):
return (request.user.is_superuser or
request.method in permissions.SAFE_METHODS)
class IsUserOrSuperuser(permissions.BasePermission):
'''Accept only the users themselves or superusers.'''
def has_object_permission(self, request, view, obj):
return request.user.is_superuser or request.user == obj
class IsAdvisorOrSuperuser(permissions.BasePermission):
'''Accept only the school's advisor or superusers.'''
def has_object_permission(self, request, view, obj):
return request.user.is_superuser or request.user == obj.advisor
class IsPostOrSuperuserOnly(permissions.BasePermission):
'''Accept POST (create) requests, superusers-only otherwise.'''
- def has_object_permissions(self, request, view, obj):
? ------- - -----
+ def has_permission(self, request, view):
return request.method == 'POST' or request.user.is_superuser |
cca106b4cb647e82838deb359cf6f9ef813992a9 | dbaas/integrations/credentials/admin/integration_credential.py | dbaas/integrations/credentials/admin/integration_credential.py | from __future__ import absolute_import, unicode_literals
from django.contrib import admin
class IntegrationCredentialAdmin(admin.ModelAdmin):
search_fields = ("endpoint",)
list_display = ("user","endpoint",)
save_on_top = True | from __future__ import absolute_import, unicode_literals
from django.contrib import admin
class IntegrationCredentialAdmin(admin.ModelAdmin):
search_fields = ("endpoint",)
list_display = ("endpoint","user",)
save_on_top = True | Change field order at integration credential admin index page | Change field order at integration credential admin index page
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | from __future__ import absolute_import, unicode_literals
from django.contrib import admin
class IntegrationCredentialAdmin(admin.ModelAdmin):
search_fields = ("endpoint",)
- list_display = ("user","endpoint",)
+ list_display = ("endpoint","user",)
save_on_top = True | Change field order at integration credential admin index page | ## Code Before:
from __future__ import absolute_import, unicode_literals
from django.contrib import admin
class IntegrationCredentialAdmin(admin.ModelAdmin):
search_fields = ("endpoint",)
list_display = ("user","endpoint",)
save_on_top = True
## Instruction:
Change field order at integration credential admin index page
## Code After:
from __future__ import absolute_import, unicode_literals
from django.contrib import admin
class IntegrationCredentialAdmin(admin.ModelAdmin):
search_fields = ("endpoint",)
list_display = ("endpoint","user",)
save_on_top = True | from __future__ import absolute_import, unicode_literals
from django.contrib import admin
class IntegrationCredentialAdmin(admin.ModelAdmin):
search_fields = ("endpoint",)
- list_display = ("user","endpoint",)
? -------
+ list_display = ("endpoint","user",)
? +++++++
save_on_top = True |
924be2b545a4d00b9eacc5aa1c974e8ebf407c2f | shade/tests/unit/test_shade.py | shade/tests/unit/test_shade.py |
from shade.tests import base
class TestShade(base.TestCase):
def test_something(self):
pass
|
import shade
from shade.tests import base
class TestShade(base.TestCase):
def test_openstack_cloud(self):
self.assertIsInstance(shade.openstack_cloud(), shade.OpenStackCloud)
| Add basic unit test for shade.openstack_cloud | Add basic unit test for shade.openstack_cloud
Just getting basic minimal surface area unit tests to help when making
changes. This exposed some python3 incompatibilities in
os-client-config, which is why the change Depends on
Ia78bd8edd17c7d2360ad958b3de734503d400774.
Change-Id: I9cf5082d01861a0b6b372728a33ce9df9ee8d300
Depends-On: Ia78bd8edd17c7d2360ad958b3de734503d400774
| Python | apache-2.0 | stackforge/python-openstacksdk,openstack-infra/shade,openstack/python-openstacksdk,openstack/python-openstacksdk,openstack-infra/shade,dtroyer/python-openstacksdk,stackforge/python-openstacksdk,dtroyer/python-openstacksdk,jsmartin/shade,jsmartin/shade |
+ import shade
from shade.tests import base
class TestShade(base.TestCase):
- def test_something(self):
- pass
+ def test_openstack_cloud(self):
+ self.assertIsInstance(shade.openstack_cloud(), shade.OpenStackCloud)
| Add basic unit test for shade.openstack_cloud | ## Code Before:
from shade.tests import base
class TestShade(base.TestCase):
def test_something(self):
pass
## Instruction:
Add basic unit test for shade.openstack_cloud
## Code After:
import shade
from shade.tests import base
class TestShade(base.TestCase):
def test_openstack_cloud(self):
self.assertIsInstance(shade.openstack_cloud(), shade.OpenStackCloud)
|
+ import shade
from shade.tests import base
class TestShade(base.TestCase):
- def test_something(self):
- pass
+ def test_openstack_cloud(self):
+ self.assertIsInstance(shade.openstack_cloud(), shade.OpenStackCloud) |
7148264a374301cb6cf9d35f3b17f3a02652600f | manage.py | manage.py | import os
from app import create_app, db
from app.models import User, Role, Permission
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
def make_shell_context():
return dict(app=app, db=db, User=User, Role=Role, Permission=Permission)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@manager.command
def test():
"""Run the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
if __name__ == '__main__':
manager.run()
| import os
from app import create_app, db
from app.models import User, Role, Permission
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
def make_shell_context():
return dict(app=app, db=db, User=User, Role=Role, Permission=Permission)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@manager.command
def seed():
"""Seed the database."""
Role.insert_roles()
@manager.command
def test():
"""Run the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
if __name__ == '__main__':
manager.run()
| Add command to seed database | Add command to seed database
| Python | mit | richgieg/flask-now,richgieg/flask-now | import os
from app import create_app, db
from app.models import User, Role, Permission
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
def make_shell_context():
return dict(app=app, db=db, User=User, Role=Role, Permission=Permission)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@manager.command
+ def seed():
+ """Seed the database."""
+ Role.insert_roles()
+
+
+ @manager.command
def test():
"""Run the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
if __name__ == '__main__':
manager.run()
| Add command to seed database | ## Code Before:
import os
from app import create_app, db
from app.models import User, Role, Permission
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
def make_shell_context():
return dict(app=app, db=db, User=User, Role=Role, Permission=Permission)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@manager.command
def test():
"""Run the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
if __name__ == '__main__':
manager.run()
## Instruction:
Add command to seed database
## Code After:
import os
from app import create_app, db
from app.models import User, Role, Permission
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
def make_shell_context():
return dict(app=app, db=db, User=User, Role=Role, Permission=Permission)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@manager.command
def seed():
"""Seed the database."""
Role.insert_roles()
@manager.command
def test():
"""Run the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
if __name__ == '__main__':
manager.run()
| import os
from app import create_app, db
from app.models import User, Role, Permission
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
def make_shell_context():
return dict(app=app, db=db, User=User, Role=Role, Permission=Permission)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@manager.command
+ def seed():
+ """Seed the database."""
+ Role.insert_roles()
+
+
+ @manager.command
def test():
"""Run the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
if __name__ == '__main__':
manager.run() |
0c84f6dd314ea62019356b09363f98118a4da776 | txircd/factory.py | txircd/factory.py | from twisted.internet.protocol import ClientFactory, Factory
from txircd.server import IRCServer
from txircd.user import IRCUser
from ipaddress import ip_address
import re
ipv4MappedAddr = re.compile("::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})")
def unmapIPv4(ip: str) -> str:
"""
Converts an IPv6-mapped IPv4 address to a bare IPv4 address.
"""
mapped = ipv4MappedAddr.match(ip)
if mapped:
return mapped.group(1)
return ip
class UserFactory(Factory):
protocol = IRCUser
def __init__(self, ircd):
self.ircd = ircd
def buildProtocol(self, addr):
return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host)))
class ServerListenFactory(Factory):
protocol = IRCServer
def __init__(self, ircd):
self.ircd = ircd
def buildProtocol(self, addr):
return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host)), True)
class ServerConnectFactory(ClientFactory):
protocol = IRCServer
def __init__(self, ircd):
self.ircd = ircd
def buildProtocol(self, addr):
return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host)), False) | from twisted.internet.protocol import ClientFactory, Factory
from txircd.server import IRCServer
from txircd.user import IRCUser
from ipaddress import ip_address
from typing import Union
def unmapIPv4(ip: str) -> Union["IPv4Address", "IPv6Address"]:
"""
Converts an IPv6-mapped IPv4 address to a bare IPv4 address.
"""
addr = ip_address(ip)
if addr.ipv4_mapped is None:
return addr
return addr.ipv4_mapped
class UserFactory(Factory):
protocol = IRCUser
def __init__(self, ircd):
self.ircd = ircd
def buildProtocol(self, addr):
return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host)))
class ServerListenFactory(Factory):
protocol = IRCServer
def __init__(self, ircd):
self.ircd = ircd
def buildProtocol(self, addr):
return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host)), True)
class ServerConnectFactory(ClientFactory):
protocol = IRCServer
def __init__(self, ircd):
self.ircd = ircd
def buildProtocol(self, addr):
return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host)), False) | Use built-in IP address functionality to unmap IPv4 addresses | Use built-in IP address functionality to unmap IPv4 addresses
| Python | bsd-3-clause | Heufneutje/txircd | from twisted.internet.protocol import ClientFactory, Factory
from txircd.server import IRCServer
from txircd.user import IRCUser
from ipaddress import ip_address
- import re
+ from typing import Union
+ def unmapIPv4(ip: str) -> Union["IPv4Address", "IPv6Address"]:
- ipv4MappedAddr = re.compile("::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})")
- def unmapIPv4(ip: str) -> str:
"""
Converts an IPv6-mapped IPv4 address to a bare IPv4 address.
"""
- mapped = ipv4MappedAddr.match(ip)
- if mapped:
- return mapped.group(1)
- return ip
+ addr = ip_address(ip)
+ if addr.ipv4_mapped is None:
+ return addr
+ return addr.ipv4_mapped
class UserFactory(Factory):
protocol = IRCUser
def __init__(self, ircd):
self.ircd = ircd
def buildProtocol(self, addr):
return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host)))
class ServerListenFactory(Factory):
protocol = IRCServer
def __init__(self, ircd):
self.ircd = ircd
def buildProtocol(self, addr):
return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host)), True)
class ServerConnectFactory(ClientFactory):
protocol = IRCServer
def __init__(self, ircd):
self.ircd = ircd
def buildProtocol(self, addr):
return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host)), False) | Use built-in IP address functionality to unmap IPv4 addresses | ## Code Before:
from twisted.internet.protocol import ClientFactory, Factory
from txircd.server import IRCServer
from txircd.user import IRCUser
from ipaddress import ip_address
import re
ipv4MappedAddr = re.compile("::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})")
def unmapIPv4(ip: str) -> str:
"""
Converts an IPv6-mapped IPv4 address to a bare IPv4 address.
"""
mapped = ipv4MappedAddr.match(ip)
if mapped:
return mapped.group(1)
return ip
class UserFactory(Factory):
protocol = IRCUser
def __init__(self, ircd):
self.ircd = ircd
def buildProtocol(self, addr):
return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host)))
class ServerListenFactory(Factory):
protocol = IRCServer
def __init__(self, ircd):
self.ircd = ircd
def buildProtocol(self, addr):
return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host)), True)
class ServerConnectFactory(ClientFactory):
protocol = IRCServer
def __init__(self, ircd):
self.ircd = ircd
def buildProtocol(self, addr):
return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host)), False)
## Instruction:
Use built-in IP address functionality to unmap IPv4 addresses
## Code After:
from twisted.internet.protocol import ClientFactory, Factory
from txircd.server import IRCServer
from txircd.user import IRCUser
from ipaddress import ip_address
from typing import Union
def unmapIPv4(ip: str) -> Union["IPv4Address", "IPv6Address"]:
"""
Converts an IPv6-mapped IPv4 address to a bare IPv4 address.
"""
addr = ip_address(ip)
if addr.ipv4_mapped is None:
return addr
return addr.ipv4_mapped
class UserFactory(Factory):
protocol = IRCUser
def __init__(self, ircd):
self.ircd = ircd
def buildProtocol(self, addr):
return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host)))
class ServerListenFactory(Factory):
protocol = IRCServer
def __init__(self, ircd):
self.ircd = ircd
def buildProtocol(self, addr):
return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host)), True)
class ServerConnectFactory(ClientFactory):
protocol = IRCServer
def __init__(self, ircd):
self.ircd = ircd
def buildProtocol(self, addr):
return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host)), False) | from twisted.internet.protocol import ClientFactory, Factory
from txircd.server import IRCServer
from txircd.user import IRCUser
from ipaddress import ip_address
- import re
+ from typing import Union
+ def unmapIPv4(ip: str) -> Union["IPv4Address", "IPv6Address"]:
- ipv4MappedAddr = re.compile("::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})")
- def unmapIPv4(ip: str) -> str:
"""
Converts an IPv6-mapped IPv4 address to a bare IPv4 address.
"""
- mapped = ipv4MappedAddr.match(ip)
- if mapped:
- return mapped.group(1)
- return ip
+ addr = ip_address(ip)
+ if addr.ipv4_mapped is None:
+ return addr
+ return addr.ipv4_mapped
class UserFactory(Factory):
protocol = IRCUser
def __init__(self, ircd):
self.ircd = ircd
def buildProtocol(self, addr):
return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host)))
class ServerListenFactory(Factory):
protocol = IRCServer
def __init__(self, ircd):
self.ircd = ircd
def buildProtocol(self, addr):
return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host)), True)
class ServerConnectFactory(ClientFactory):
protocol = IRCServer
def __init__(self, ircd):
self.ircd = ircd
def buildProtocol(self, addr):
return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host)), False) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.