commit
stringlengths 40
40
| old_file
stringlengths 4
118
| new_file
stringlengths 4
118
| old_contents
stringlengths 10
3.52k
| new_contents
stringlengths 21
3.18k
| subject
stringlengths 16
444
| message
stringlengths 17
2.63k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 7
43k
| ndiff
stringlengths 52
3.32k
| instruction
stringlengths 16
444
| content
stringlengths 133
4.32k
| fuzzy_diff
stringlengths 17
3.24k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
42a4a8b4480bc481e0467ae7ee46c60400d63f77 | theme-installer.py | theme-installer.py | import sys
from inc.functions import *
from PySide.QtGui import QApplication, QPixmap, QSplashScreen
from ui.mainwindow import MainWindow
# The app
if __name__ == '__main__':
# Create app
app = QApplication(sys.argv)
app.setApplicationName('LMMS Theme Installer')
# Show window
window = MainWindow()
window.show()
# Closed connection
app.lastWindowClosed.connect(app.quit)
# Run it
sys.exit(app.exec_()) | import sys
from inc.functions import *
from PySide.QtGui import QApplication, QPixmap, QSplashScreen
from ui.mainwindow import MainWindow
# Create tmp directory if it doesn't exist
if not os.path.exists(os.path.join(os.getcwd(), 'tmp')):
os.mkdir(os.path.join(os.getcwd(), 'tmp'))
# The app
if __name__ == '__main__':
# Create app
app = QApplication(sys.argv)
app.setApplicationName('LMMS Theme Installer')
# Show window
window = MainWindow()
window.show()
# Closed connection
app.lastWindowClosed.connect(app.quit)
# Run it
sys.exit(app.exec_()) | Create tmp directory if it doesn't exist | Create tmp directory if it doesn't exist
| Python | lgpl-2.1 | kmklr72/LMMS-Theme-Installer | import sys
from inc.functions import *
from PySide.QtGui import QApplication, QPixmap, QSplashScreen
from ui.mainwindow import MainWindow
+
+ # Create tmp directory if it doesn't exist
+ if not os.path.exists(os.path.join(os.getcwd(), 'tmp')):
+ os.mkdir(os.path.join(os.getcwd(), 'tmp'))
# The app
if __name__ == '__main__':
# Create app
app = QApplication(sys.argv)
app.setApplicationName('LMMS Theme Installer')
# Show window
window = MainWindow()
window.show()
# Closed connection
app.lastWindowClosed.connect(app.quit)
# Run it
sys.exit(app.exec_()) | Create tmp directory if it doesn't exist | ## Code Before:
import sys
from inc.functions import *
from PySide.QtGui import QApplication, QPixmap, QSplashScreen
from ui.mainwindow import MainWindow
# The app
if __name__ == '__main__':
# Create app
app = QApplication(sys.argv)
app.setApplicationName('LMMS Theme Installer')
# Show window
window = MainWindow()
window.show()
# Closed connection
app.lastWindowClosed.connect(app.quit)
# Run it
sys.exit(app.exec_())
## Instruction:
Create tmp directory if it doesn't exist
## Code After:
import sys
from inc.functions import *
from PySide.QtGui import QApplication, QPixmap, QSplashScreen
from ui.mainwindow import MainWindow
# Create tmp directory if it doesn't exist
if not os.path.exists(os.path.join(os.getcwd(), 'tmp')):
os.mkdir(os.path.join(os.getcwd(), 'tmp'))
# The app
if __name__ == '__main__':
# Create app
app = QApplication(sys.argv)
app.setApplicationName('LMMS Theme Installer')
# Show window
window = MainWindow()
window.show()
# Closed connection
app.lastWindowClosed.connect(app.quit)
# Run it
sys.exit(app.exec_()) | ...
from ui.mainwindow import MainWindow
# Create tmp directory if it doesn't exist
if not os.path.exists(os.path.join(os.getcwd(), 'tmp')):
os.mkdir(os.path.join(os.getcwd(), 'tmp'))
# The app
... |
453497b0755d8bc2d6bd6ccc3830394e50ed9a07 | pywikibot/families/outreach_family.py | pywikibot/families/outreach_family.py |
__version__ = '$Id$'
from pywikibot import family
# Outreach wiki custom family
class Family(family.WikimediaFamily):
def __init__(self):
super(Family, self).__init__()
self.name = u'outreach'
self.langs = {
'outreach': 'outreach.wikimedia.org',
}
self.interwiki_forward = 'wikipedia'
def version(self, code):
return "1.24wmf6"
|
__version__ = '$Id$'
from pywikibot import family
# Outreach wiki custom family
class Family(family.WikimediaFamily):
def __init__(self):
super(Family, self).__init__()
self.name = u'outreach'
self.langs = {
'outreach': 'outreach.wikimedia.org',
}
self.interwiki_forward = 'wikipedia'
| Update mw version 1.24wmf11 derived from super class | Update mw version 1.24wmf11 derived from super class
Change-Id: If142c57a88179f80e2e652e844c7aadbc2468f7c
| Python | mit | trishnaguha/pywikibot-core,Darkdadaah/pywikibot-core,VcamX/pywikibot-core,magul/pywikibot-core,PersianWikipedia/pywikibot-core,magul/pywikibot-core,icyflame/batman,Darkdadaah/pywikibot-core,wikimedia/pywikibot-core,happy5214/pywikibot-core,TridevGuha/pywikibot-core,wikimedia/pywikibot-core,hasteur/g13bot_tools_new,valhallasw/pywikibot-core,jayvdb/pywikibot-core,jayvdb/pywikibot-core,smalyshev/pywikibot-core,npdoty/pywikibot,hasteur/g13bot_tools_new,xZise/pywikibot-core,h4ck3rm1k3/pywikibot-core,darthbhyrava/pywikibot-local,h4ck3rm1k3/pywikibot-core,hasteur/g13bot_tools_new,happy5214/pywikibot-core,npdoty/pywikibot,emijrp/pywikibot-core |
__version__ = '$Id$'
from pywikibot import family
# Outreach wiki custom family
class Family(family.WikimediaFamily):
def __init__(self):
super(Family, self).__init__()
self.name = u'outreach'
self.langs = {
'outreach': 'outreach.wikimedia.org',
}
self.interwiki_forward = 'wikipedia'
- def version(self, code):
- return "1.24wmf6"
- | Update mw version 1.24wmf11 derived from super class | ## Code Before:
__version__ = '$Id$'
from pywikibot import family
# Outreach wiki custom family
class Family(family.WikimediaFamily):
def __init__(self):
super(Family, self).__init__()
self.name = u'outreach'
self.langs = {
'outreach': 'outreach.wikimedia.org',
}
self.interwiki_forward = 'wikipedia'
def version(self, code):
return "1.24wmf6"
## Instruction:
Update mw version 1.24wmf11 derived from super class
## Code After:
__version__ = '$Id$'
from pywikibot import family
# Outreach wiki custom family
class Family(family.WikimediaFamily):
def __init__(self):
super(Family, self).__init__()
self.name = u'outreach'
self.langs = {
'outreach': 'outreach.wikimedia.org',
}
self.interwiki_forward = 'wikipedia'
| # ... existing code ...
}
self.interwiki_forward = 'wikipedia'
# ... rest of the code ... |
befe47c35c68e17231e21febbf52041f245b8985 | django_mailer/managers.py | django_mailer/managers.py | from django.db import models
from django_mailer import constants
class QueueManager(models.Manager):
use_for_related_fields = True
def high_priority(self):
"""
Return a QuerySet of high priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_HIGH)
def normal_priority(self):
"""
Return a QuerySet of normal priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_NORMAL)
def low_priority(self):
"""
Return a QuerySet of low priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_LOW)
def non_deferred(self):
"""
Return a QuerySet containing all non-deferred queued messages.
"""
return self.filter(deferred=False)
def deferred(self):
"""
Return a QuerySet of all deferred messages in the queue.
"""
return self.filter(deferred=True)
def retry_deferred(self, new_priority=None):
"""
Reset the deferred flag for all deferred messages so they will be
retried.
"""
count = self.deferred().count()
update_kwargs = dict(deferred=False)
if new_priority is not None:
update_kwargs['priority'] = new_priority
self.deferred().update(**update_kwargs)
return count
| from django.db import models
from django_mailer import constants
class QueueManager(models.Manager):
use_for_related_fields = True
def high_priority(self):
"""
Return a QuerySet of high priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_HIGH)
def normal_priority(self):
"""
Return a QuerySet of normal priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_NORMAL)
def low_priority(self):
"""
Return a QuerySet of low priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_LOW)
def non_deferred(self):
"""
Return a QuerySet containing all non-deferred queued messages.
"""
return self.filter(deferred=False)
def deferred(self):
"""
Return a QuerySet of all deferred messages in the queue.
"""
return self.filter(deferred=True)
def retry_deferred(self, new_priority=None):
"""
Reset the deferred flag for all deferred messages so they will be
retried.
"""
count = self.deferred().count()
update_kwargs = dict(deferred=False, retries=models.F('retries')+1)
if new_priority is not None:
update_kwargs['priority'] = new_priority
self.deferred().update(**update_kwargs)
return count
| Update the retries count of a queued message when it is changed back from deferred | Update the retries count of a queued message when it is changed back from deferred
| Python | mit | APSL/django-mailer-2,Giftovus/django-mailer-2,davidmarble/django-mailer-2,SmileyChris/django-mailer-2,kvh/django-mailer-2,maykinmedia/django-mailer-2,PSyton/django-mailer-2,APSL/django-mailer-2,colinhowe/django-mailer-2,rofrankel/django-mailer-2,maykinmedia/django-mailer-2,APSL/django-mailer-2,GreenLightGo/django-mailer-2,morenopc/django-mailer-2,shn/django-mailer-2,maykinmedia/django-mailer-2,mfwarren/django-mailer-2,mrbox/django-mailer-2,tachang/django-mailer-2,damkop/django-mailer-2,danfairs/django-mailer-2,tclancy/django-mailer-2,tsanders-kalloop/django-mailer-2,fenginx/django-mailer-2,victorfontes/django-mailer-2,k1000/django-mailer-2,pegler/django-mailer-2,torchbox/django-mailer-2 | from django.db import models
from django_mailer import constants
class QueueManager(models.Manager):
use_for_related_fields = True
def high_priority(self):
"""
Return a QuerySet of high priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_HIGH)
def normal_priority(self):
"""
Return a QuerySet of normal priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_NORMAL)
def low_priority(self):
"""
Return a QuerySet of low priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_LOW)
def non_deferred(self):
"""
Return a QuerySet containing all non-deferred queued messages.
"""
return self.filter(deferred=False)
def deferred(self):
"""
Return a QuerySet of all deferred messages in the queue.
"""
return self.filter(deferred=True)
def retry_deferred(self, new_priority=None):
"""
Reset the deferred flag for all deferred messages so they will be
retried.
"""
count = self.deferred().count()
- update_kwargs = dict(deferred=False)
+ update_kwargs = dict(deferred=False, retries=models.F('retries')+1)
if new_priority is not None:
update_kwargs['priority'] = new_priority
self.deferred().update(**update_kwargs)
return count
| Update the retries count of a queued message when it is changed back from deferred | ## Code Before:
from django.db import models
from django_mailer import constants
class QueueManager(models.Manager):
use_for_related_fields = True
def high_priority(self):
"""
Return a QuerySet of high priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_HIGH)
def normal_priority(self):
"""
Return a QuerySet of normal priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_NORMAL)
def low_priority(self):
"""
Return a QuerySet of low priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_LOW)
def non_deferred(self):
"""
Return a QuerySet containing all non-deferred queued messages.
"""
return self.filter(deferred=False)
def deferred(self):
"""
Return a QuerySet of all deferred messages in the queue.
"""
return self.filter(deferred=True)
def retry_deferred(self, new_priority=None):
"""
Reset the deferred flag for all deferred messages so they will be
retried.
"""
count = self.deferred().count()
update_kwargs = dict(deferred=False)
if new_priority is not None:
update_kwargs['priority'] = new_priority
self.deferred().update(**update_kwargs)
return count
## Instruction:
Update the retries count of a queued message when it is changed back from deferred
## Code After:
from django.db import models
from django_mailer import constants
class QueueManager(models.Manager):
use_for_related_fields = True
def high_priority(self):
"""
Return a QuerySet of high priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_HIGH)
def normal_priority(self):
"""
Return a QuerySet of normal priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_NORMAL)
def low_priority(self):
"""
Return a QuerySet of low priority queued messages.
"""
return self.filter(priority=constants.PRIORITY_LOW)
def non_deferred(self):
"""
Return a QuerySet containing all non-deferred queued messages.
"""
return self.filter(deferred=False)
def deferred(self):
"""
Return a QuerySet of all deferred messages in the queue.
"""
return self.filter(deferred=True)
def retry_deferred(self, new_priority=None):
"""
Reset the deferred flag for all deferred messages so they will be
retried.
"""
count = self.deferred().count()
update_kwargs = dict(deferred=False, retries=models.F('retries')+1)
if new_priority is not None:
update_kwargs['priority'] = new_priority
self.deferred().update(**update_kwargs)
return count
| ...
"""
count = self.deferred().count()
update_kwargs = dict(deferred=False, retries=models.F('retries')+1)
if new_priority is not None:
update_kwargs['priority'] = new_priority
... |
8af1f7a0525f69a6e2ee6c5cfd7d6a923873a7ec | froide/helper/auth.py | froide/helper/auth.py | from django.contrib.auth.backends import ModelBackend
from django.core.validators import email_re
from django.contrib.auth import models, load_backend, login
from django.conf import settings
class EmailBackend(ModelBackend):
def authenticate(self, username=None, password=None):
if email_re.search(username):
try:
user = models.User.objects.get(email=username)
if user.check_password(password):
return user
except models.User.DoesNotExist:
return None
return None
def login_user(request, user):
if not hasattr(user, 'backend'):
for backend in settings.AUTHENTICATION_BACKENDS:
if user == load_backend(backend).get_user(user.pk):
user.backend = backend
break
if hasattr(user, 'backend'):
return login(request, user)
| from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.contrib.auth import models, load_backend, login
from django.conf import settings
class EmailBackend(ModelBackend):
def authenticate(self, username=None, password=None):
try:
validate_email(username)
except ValidationError:
return None
try:
user = models.User.objects.get(email=username)
if user.check_password(password):
return user
except models.User.DoesNotExist:
return None
return None
def login_user(request, user):
if not hasattr(user, 'backend'):
for backend in settings.AUTHENTICATION_BACKENDS:
if user == load_backend(backend).get_user(user.pk):
user.backend = backend
break
if hasattr(user, 'backend'):
return login(request, user)
| Validate email the correct way | Validate email the correct way | Python | mit | catcosmo/froide,ryankanno/froide,okfse/froide,fin/froide,LilithWittmann/froide,fin/froide,ryankanno/froide,CodeforHawaii/froide,stefanw/froide,okfse/froide,LilithWittmann/froide,ryankanno/froide,LilithWittmann/froide,okfse/froide,stefanw/froide,CodeforHawaii/froide,catcosmo/froide,CodeforHawaii/froide,ryankanno/froide,ryankanno/froide,stefanw/froide,fin/froide,catcosmo/froide,LilithWittmann/froide,CodeforHawaii/froide,CodeforHawaii/froide,fin/froide,stefanw/froide,okfse/froide,stefanw/froide,okfse/froide,LilithWittmann/froide,catcosmo/froide,catcosmo/froide | from django.contrib.auth.backends import ModelBackend
+ from django.core.exceptions import ValidationError
- from django.core.validators import email_re
+ from django.core.validators import validate_email
from django.contrib.auth import models, load_backend, login
from django.conf import settings
class EmailBackend(ModelBackend):
def authenticate(self, username=None, password=None):
- if email_re.search(username):
- try:
+ try:
+ validate_email(username)
+ except ValidationError:
+ return None
+ try:
- user = models.User.objects.get(email=username)
+ user = models.User.objects.get(email=username)
- if user.check_password(password):
+ if user.check_password(password):
- return user
+ return user
- except models.User.DoesNotExist:
+ except models.User.DoesNotExist:
- return None
+ return None
return None
def login_user(request, user):
if not hasattr(user, 'backend'):
for backend in settings.AUTHENTICATION_BACKENDS:
if user == load_backend(backend).get_user(user.pk):
user.backend = backend
break
if hasattr(user, 'backend'):
return login(request, user)
| Validate email the correct way | ## Code Before:
from django.contrib.auth.backends import ModelBackend
from django.core.validators import email_re
from django.contrib.auth import models, load_backend, login
from django.conf import settings
class EmailBackend(ModelBackend):
def authenticate(self, username=None, password=None):
if email_re.search(username):
try:
user = models.User.objects.get(email=username)
if user.check_password(password):
return user
except models.User.DoesNotExist:
return None
return None
def login_user(request, user):
if not hasattr(user, 'backend'):
for backend in settings.AUTHENTICATION_BACKENDS:
if user == load_backend(backend).get_user(user.pk):
user.backend = backend
break
if hasattr(user, 'backend'):
return login(request, user)
## Instruction:
Validate email the correct way
## Code After:
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.contrib.auth import models, load_backend, login
from django.conf import settings
class EmailBackend(ModelBackend):
def authenticate(self, username=None, password=None):
try:
validate_email(username)
except ValidationError:
return None
try:
user = models.User.objects.get(email=username)
if user.check_password(password):
return user
except models.User.DoesNotExist:
return None
return None
def login_user(request, user):
if not hasattr(user, 'backend'):
for backend in settings.AUTHENTICATION_BACKENDS:
if user == load_backend(backend).get_user(user.pk):
user.backend = backend
break
if hasattr(user, 'backend'):
return login(request, user)
| # ... existing code ...
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.contrib.auth import models, load_backend, login
from django.conf import settings
# ... modified code ...
class EmailBackend(ModelBackend):
def authenticate(self, username=None, password=None):
try:
validate_email(username)
except ValidationError:
return None
try:
user = models.User.objects.get(email=username)
if user.check_password(password):
return user
except models.User.DoesNotExist:
return None
return None
# ... rest of the code ... |
22a024856b6fa602ee9d6fd7fb6031dde359cc9c | pytablewriter/writer/text/_csv.py | pytablewriter/writer/text/_csv.py | from typing import List
import typepy
from ._text_writer import TextTableWriter
class CsvTableWriter(TextTableWriter):
"""
A table writer class for character separated values format.
The default separated character is a comma (``","``).
:Example:
:ref:`example-csv-table-writer`
"""
FORMAT_NAME = "csv"
@property
def format_name(self) -> str:
return self.FORMAT_NAME
@property
def support_split_write(self) -> bool:
return True
def __init__(self) -> None:
super().__init__()
self.indent_string = ""
self.column_delimiter = ","
self.is_padding = False
self.is_formatting_float = False
self.is_write_header_separator_row = False
self._quoting_flags[typepy.Typecode.NULL_STRING] = False
def _write_header(self) -> None:
if typepy.is_empty_sequence(self.headers):
return
super()._write_header()
def _get_opening_row_items(self) -> List[str]:
return []
def _get_value_row_separator_items(self) -> List[str]:
return []
def _get_closing_row_items(self) -> List[str]:
return []
| from typing import List
import typepy
from ._text_writer import TextTableWriter
class CsvTableWriter(TextTableWriter):
"""
A table writer class for character separated values format.
The default separated character is a comma (``","``).
:Example:
:ref:`example-csv-table-writer`
"""
FORMAT_NAME = "csv"
@property
def format_name(self) -> str:
return self.FORMAT_NAME
@property
def support_split_write(self) -> bool:
return True
def __init__(self) -> None:
super().__init__()
self._set_chars("")
self.indent_string = ""
self.column_delimiter = ","
self.is_padding = False
self.is_formatting_float = False
self.is_write_header_separator_row = False
self._quoting_flags[typepy.Typecode.NULL_STRING] = False
def _write_header(self) -> None:
if typepy.is_empty_sequence(self.headers):
return
super()._write_header()
def _get_opening_row_items(self) -> List[str]:
return []
def _get_value_row_separator_items(self) -> List[str]:
return []
def _get_closing_row_items(self) -> List[str]:
return []
| Modify initialization to be more properly for CsvTableWriter class | Modify initialization to be more properly for CsvTableWriter class
| Python | mit | thombashi/pytablewriter | from typing import List
import typepy
from ._text_writer import TextTableWriter
class CsvTableWriter(TextTableWriter):
"""
A table writer class for character separated values format.
The default separated character is a comma (``","``).
:Example:
:ref:`example-csv-table-writer`
"""
FORMAT_NAME = "csv"
@property
def format_name(self) -> str:
return self.FORMAT_NAME
@property
def support_split_write(self) -> bool:
return True
def __init__(self) -> None:
super().__init__()
+ self._set_chars("")
self.indent_string = ""
self.column_delimiter = ","
+
self.is_padding = False
self.is_formatting_float = False
self.is_write_header_separator_row = False
self._quoting_flags[typepy.Typecode.NULL_STRING] = False
def _write_header(self) -> None:
if typepy.is_empty_sequence(self.headers):
return
super()._write_header()
def _get_opening_row_items(self) -> List[str]:
return []
def _get_value_row_separator_items(self) -> List[str]:
return []
def _get_closing_row_items(self) -> List[str]:
return []
| Modify initialization to be more properly for CsvTableWriter class | ## Code Before:
from typing import List
import typepy
from ._text_writer import TextTableWriter
class CsvTableWriter(TextTableWriter):
"""
A table writer class for character separated values format.
The default separated character is a comma (``","``).
:Example:
:ref:`example-csv-table-writer`
"""
FORMAT_NAME = "csv"
@property
def format_name(self) -> str:
return self.FORMAT_NAME
@property
def support_split_write(self) -> bool:
return True
def __init__(self) -> None:
super().__init__()
self.indent_string = ""
self.column_delimiter = ","
self.is_padding = False
self.is_formatting_float = False
self.is_write_header_separator_row = False
self._quoting_flags[typepy.Typecode.NULL_STRING] = False
def _write_header(self) -> None:
if typepy.is_empty_sequence(self.headers):
return
super()._write_header()
def _get_opening_row_items(self) -> List[str]:
return []
def _get_value_row_separator_items(self) -> List[str]:
return []
def _get_closing_row_items(self) -> List[str]:
return []
## Instruction:
Modify initialization to be more properly for CsvTableWriter class
## Code After:
from typing import List
import typepy
from ._text_writer import TextTableWriter
class CsvTableWriter(TextTableWriter):
"""
A table writer class for character separated values format.
The default separated character is a comma (``","``).
:Example:
:ref:`example-csv-table-writer`
"""
FORMAT_NAME = "csv"
@property
def format_name(self) -> str:
return self.FORMAT_NAME
@property
def support_split_write(self) -> bool:
return True
def __init__(self) -> None:
super().__init__()
self._set_chars("")
self.indent_string = ""
self.column_delimiter = ","
self.is_padding = False
self.is_formatting_float = False
self.is_write_header_separator_row = False
self._quoting_flags[typepy.Typecode.NULL_STRING] = False
def _write_header(self) -> None:
if typepy.is_empty_sequence(self.headers):
return
super()._write_header()
def _get_opening_row_items(self) -> List[str]:
return []
def _get_value_row_separator_items(self) -> List[str]:
return []
def _get_closing_row_items(self) -> List[str]:
return []
| # ... existing code ...
super().__init__()
self._set_chars("")
self.indent_string = ""
self.column_delimiter = ","
self.is_padding = False
self.is_formatting_float = False
# ... rest of the code ... |
b0824da73317bae42cb39fad5cfc95574548594a | accounts/models.py | accounts/models.py |
from __future__ import unicode_literals
from django.contrib.auth.models import AbstractUser, UserManager
from django.db.models import BooleanField
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ungettext_lazy
from mptt.fields import TreeForeignKey
from mptt.managers import TreeManager
from mptt.models import MPTTModel
from cache_tools import cached_ugettext_lazy as _
class HierarchicUserManager(TreeManager, UserManager):
pass
@python_2_unicode_compatible
class HierarchicUser(MPTTModel, AbstractUser):
mentor = TreeForeignKey(
'self', null=True, blank=True, related_name='disciples',
verbose_name=_('mentor'),
limit_choices_to={'willing_to_be_mentor__exact': True})
willing_to_be_mentor = BooleanField(
_('Veut être mentor'), default=False)
objects = HierarchicUserManager()
class MPTTMeta(object):
parent_attr = 'mentor'
order_insertion_by = ('username',)
class Meta(object):
verbose_name = ungettext_lazy('utilisateur', 'utilisateurs', 1)
verbose_name_plural = ungettext_lazy('utilisateur', 'utilisateurs', 2)
def __str__(self):
return self.get_full_name() or self.get_username()
|
from __future__ import unicode_literals
from django.contrib.auth.models import AbstractUser, UserManager
from django.db.models import BooleanField
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ungettext_lazy
from mptt.fields import TreeForeignKey
from mptt.managers import TreeManager
from mptt.models import MPTTModel
from cache_tools import cached_ugettext_lazy as _
class HierarchicUserManager(TreeManager, UserManager):
pass
@python_2_unicode_compatible
class HierarchicUser(MPTTModel, AbstractUser):
mentor = TreeForeignKey(
'self', null=True, blank=True, related_name='disciples',
verbose_name=_('mentor'),
limit_choices_to={'willing_to_be_mentor__exact': True})
willing_to_be_mentor = BooleanField(
_('Veut être mentor'), default=False)
objects = HierarchicUserManager()
class MPTTMeta(object):
parent_attr = 'mentor'
order_insertion_by = ('last_name', 'first_name', 'username')
class Meta(object):
verbose_name = ungettext_lazy('utilisateur', 'utilisateurs', 1)
verbose_name_plural = ungettext_lazy('utilisateur', 'utilisateurs', 2)
def __str__(self):
return self.get_full_name() or self.get_username()
| Change l'ordre d'insertion des utilisateurs. | Change l'ordre d'insertion des utilisateurs.
| Python | bsd-3-clause | dezede/dezede,dezede/dezede,dezede/dezede,dezede/dezede |
from __future__ import unicode_literals
from django.contrib.auth.models import AbstractUser, UserManager
from django.db.models import BooleanField
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ungettext_lazy
from mptt.fields import TreeForeignKey
from mptt.managers import TreeManager
from mptt.models import MPTTModel
from cache_tools import cached_ugettext_lazy as _
class HierarchicUserManager(TreeManager, UserManager):
pass
@python_2_unicode_compatible
class HierarchicUser(MPTTModel, AbstractUser):
mentor = TreeForeignKey(
'self', null=True, blank=True, related_name='disciples',
verbose_name=_('mentor'),
limit_choices_to={'willing_to_be_mentor__exact': True})
willing_to_be_mentor = BooleanField(
_('Veut être mentor'), default=False)
objects = HierarchicUserManager()
class MPTTMeta(object):
parent_attr = 'mentor'
- order_insertion_by = ('username',)
+ order_insertion_by = ('last_name', 'first_name', 'username')
class Meta(object):
verbose_name = ungettext_lazy('utilisateur', 'utilisateurs', 1)
verbose_name_plural = ungettext_lazy('utilisateur', 'utilisateurs', 2)
def __str__(self):
return self.get_full_name() or self.get_username()
| Change l'ordre d'insertion des utilisateurs. | ## Code Before:
from __future__ import unicode_literals
from django.contrib.auth.models import AbstractUser, UserManager
from django.db.models import BooleanField
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ungettext_lazy
from mptt.fields import TreeForeignKey
from mptt.managers import TreeManager
from mptt.models import MPTTModel
from cache_tools import cached_ugettext_lazy as _
class HierarchicUserManager(TreeManager, UserManager):
pass
@python_2_unicode_compatible
class HierarchicUser(MPTTModel, AbstractUser):
mentor = TreeForeignKey(
'self', null=True, blank=True, related_name='disciples',
verbose_name=_('mentor'),
limit_choices_to={'willing_to_be_mentor__exact': True})
willing_to_be_mentor = BooleanField(
_('Veut être mentor'), default=False)
objects = HierarchicUserManager()
class MPTTMeta(object):
parent_attr = 'mentor'
order_insertion_by = ('username',)
class Meta(object):
verbose_name = ungettext_lazy('utilisateur', 'utilisateurs', 1)
verbose_name_plural = ungettext_lazy('utilisateur', 'utilisateurs', 2)
def __str__(self):
return self.get_full_name() or self.get_username()
## Instruction:
Change l'ordre d'insertion des utilisateurs.
## Code After:
from __future__ import unicode_literals
from django.contrib.auth.models import AbstractUser, UserManager
from django.db.models import BooleanField
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ungettext_lazy
from mptt.fields import TreeForeignKey
from mptt.managers import TreeManager
from mptt.models import MPTTModel
from cache_tools import cached_ugettext_lazy as _
class HierarchicUserManager(TreeManager, UserManager):
pass
@python_2_unicode_compatible
class HierarchicUser(MPTTModel, AbstractUser):
mentor = TreeForeignKey(
'self', null=True, blank=True, related_name='disciples',
verbose_name=_('mentor'),
limit_choices_to={'willing_to_be_mentor__exact': True})
willing_to_be_mentor = BooleanField(
_('Veut être mentor'), default=False)
objects = HierarchicUserManager()
class MPTTMeta(object):
parent_attr = 'mentor'
order_insertion_by = ('last_name', 'first_name', 'username')
class Meta(object):
verbose_name = ungettext_lazy('utilisateur', 'utilisateurs', 1)
verbose_name_plural = ungettext_lazy('utilisateur', 'utilisateurs', 2)
def __str__(self):
return self.get_full_name() or self.get_username()
| # ... existing code ...
class MPTTMeta(object):
parent_attr = 'mentor'
order_insertion_by = ('last_name', 'first_name', 'username')
class Meta(object):
# ... rest of the code ... |
8d7f3320a9d3fd3b7365cad7631835a0a46f374e | planner/signals.py | planner/signals.py | from django.db.models.signals import m2m_changed
from django.dispatch import receiver
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from .models import Step
@receiver(m2m_changed, sender=Step.passengers.through)
def check_passengers(sender, **kwargs):
step = kwargs['instance']
if step.passengers.count() >= 8:
raise ValidationError(_("You exceeded passenger maximum number"))
| from django.db.models.signals import m2m_changed
from django.dispatch import receiver
from .models import Step
@receiver(m2m_changed, sender=Step.passengers.through)
def check_passengers(sender, **kwargs):
step = kwargs['instance']
if kwargs['action'] == 'post_add':
if step.passengers.count() >= step.trip.max_num_passengers:
step.trip.is_joinable = False
elif kwargs['action'] == 'post_remove':
step.trip.is_joinable = True
| Make is_joinable automatic based of passenger number | Make is_joinable automatic based of passenger number
| Python | mit | livingsilver94/getaride,livingsilver94/getaride,livingsilver94/getaride | from django.db.models.signals import m2m_changed
from django.dispatch import receiver
- from django.core.exceptions import ValidationError
- from django.utils.translation import ugettext_lazy as _
from .models import Step
@receiver(m2m_changed, sender=Step.passengers.through)
def check_passengers(sender, **kwargs):
step = kwargs['instance']
- if step.passengers.count() >= 8:
- raise ValidationError(_("You exceeded passenger maximum number"))
+ if kwargs['action'] == 'post_add':
+ if step.passengers.count() >= step.trip.max_num_passengers:
+ step.trip.is_joinable = False
+ elif kwargs['action'] == 'post_remove':
+ step.trip.is_joinable = True
| Make is_joinable automatic based of passenger number | ## Code Before:
from django.db.models.signals import m2m_changed
from django.dispatch import receiver
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from .models import Step
@receiver(m2m_changed, sender=Step.passengers.through)
def check_passengers(sender, **kwargs):
step = kwargs['instance']
if step.passengers.count() >= 8:
raise ValidationError(_("You exceeded passenger maximum number"))
## Instruction:
Make is_joinable automatic based of passenger number
## Code After:
from django.db.models.signals import m2m_changed
from django.dispatch import receiver
from .models import Step
@receiver(m2m_changed, sender=Step.passengers.through)
def check_passengers(sender, **kwargs):
step = kwargs['instance']
if kwargs['action'] == 'post_add':
if step.passengers.count() >= step.trip.max_num_passengers:
step.trip.is_joinable = False
elif kwargs['action'] == 'post_remove':
step.trip.is_joinable = True
| ...
from django.db.models.signals import m2m_changed
from django.dispatch import receiver
from .models import Step
...
def check_passengers(sender, **kwargs):
step = kwargs['instance']
if kwargs['action'] == 'post_add':
if step.passengers.count() >= step.trip.max_num_passengers:
step.trip.is_joinable = False
elif kwargs['action'] == 'post_remove':
step.trip.is_joinable = True
... |
30b6d886670b7ba65aee9b130ec50d577c778649 | run_server.py | run_server.py | import subprocess
import sys
def main():
ip = '127.0.0.1'
port = 5000
workers_count = 4
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
if ':' in arg:
ip, port = arg.split(':')
port = int(port)
break
if '.' in arg:
ip = arg
if arg.isdigit():
port = int(arg)
subprocess.run('gunicorn -w {workers_count} -b {ip}:{port} flucalc.server:app'.format(
workers_count=workers_count, ip=ip, port=port
), shell=True)
if __name__ == '__main__':
main()
| import subprocess
import sys
def main():
ip = '127.0.0.1'
port = 5000
workers_count = 4
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
if ':' in arg:
ip, port = arg.split(':')
port = int(port)
break
if '.' in arg:
ip = arg
if arg.isdigit():
port = int(arg)
print('FluCalc started on {ip}:{port}'.format(ip=ip, port=port))
subprocess.run('gunicorn -w {workers_count} -b {ip}:{port} flucalc.server:app'.format(
workers_count=workers_count, ip=ip, port=port
), shell=True)
if __name__ == '__main__':
main()
| Add a message with a socket on server start | Add a message with a socket on server start
| Python | mit | bondarevts/flucalc,bondarevts/flucalc,bondarevts/flucalc | import subprocess
import sys
def main():
ip = '127.0.0.1'
port = 5000
workers_count = 4
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
if ':' in arg:
ip, port = arg.split(':')
port = int(port)
break
if '.' in arg:
ip = arg
if arg.isdigit():
port = int(arg)
+ print('FluCalc started on {ip}:{port}'.format(ip=ip, port=port))
subprocess.run('gunicorn -w {workers_count} -b {ip}:{port} flucalc.server:app'.format(
workers_count=workers_count, ip=ip, port=port
), shell=True)
if __name__ == '__main__':
main()
| Add a message with a socket on server start | ## Code Before:
import subprocess
import sys
def main():
ip = '127.0.0.1'
port = 5000
workers_count = 4
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
if ':' in arg:
ip, port = arg.split(':')
port = int(port)
break
if '.' in arg:
ip = arg
if arg.isdigit():
port = int(arg)
subprocess.run('gunicorn -w {workers_count} -b {ip}:{port} flucalc.server:app'.format(
workers_count=workers_count, ip=ip, port=port
), shell=True)
if __name__ == '__main__':
main()
## Instruction:
Add a message with a socket on server start
## Code After:
import subprocess
import sys
def main():
ip = '127.0.0.1'
port = 5000
workers_count = 4
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
if ':' in arg:
ip, port = arg.split(':')
port = int(port)
break
if '.' in arg:
ip = arg
if arg.isdigit():
port = int(arg)
print('FluCalc started on {ip}:{port}'.format(ip=ip, port=port))
subprocess.run('gunicorn -w {workers_count} -b {ip}:{port} flucalc.server:app'.format(
workers_count=workers_count, ip=ip, port=port
), shell=True)
if __name__ == '__main__':
main()
| // ... existing code ...
port = int(arg)
print('FluCalc started on {ip}:{port}'.format(ip=ip, port=port))
subprocess.run('gunicorn -w {workers_count} -b {ip}:{port} flucalc.server:app'.format(
workers_count=workers_count, ip=ip, port=port
// ... rest of the code ... |
c99ea848a39d22cb4347606b6cba97b98ce627fd | timesketch/api/v1/resources/information.py | timesketch/api/v1/resources/information.py | """Information API for version 1 of the Timesketch API."""
from flask import jsonify
from flask_restful import Resource
from flask_login import login_required
from timesketch import version
from timesketch.api.v1 import resources
from timesketch.lib.definitions import HTTP_STATUS_CODE_OK
class VersionResource(resources.ResourceMixin, Resource):
"""Resource to get Timesketch API version information."""
@login_required
def get(self):
"""Handles GET request to the resource.
Returns:
List of usernames
"""
schema = {
'meta': {
'version': version.get_version()
},
'objects': []
}
response = jsonify(schema)
response.status_code = HTTP_STATUS_CODE_OK
return response
| """Information API for version 1 of the Timesketch API."""
from flask import jsonify
from flask_restful import Resource
from flask_login import login_required
from timesketch import version
from timesketch.api.v1 import resources
from timesketch.lib.definitions import HTTP_STATUS_CODE_OK
class VersionResource(resources.ResourceMixin, Resource):
"""Resource to get Timesketch API version information."""
@login_required
def get(self):
"""Handles GET request to the resource.
Returns:
JSON object including version info
"""
schema = {
'meta': {
'version': version.get_version()
},
'objects': []
}
response = jsonify(schema)
response.status_code = HTTP_STATUS_CODE_OK
return response
| Fix method docstring (copy paste error) | Fix method docstring (copy paste error)
Guess there was a copy paste error in this PR: https://github.com/google/timesketch/commit/64157452b7b8285ea928e4949434d46592791d47
As the method does not return user info. | Python | apache-2.0 | google/timesketch,google/timesketch,google/timesketch,google/timesketch | """Information API for version 1 of the Timesketch API."""
from flask import jsonify
from flask_restful import Resource
from flask_login import login_required
from timesketch import version
from timesketch.api.v1 import resources
from timesketch.lib.definitions import HTTP_STATUS_CODE_OK
class VersionResource(resources.ResourceMixin, Resource):
"""Resource to get Timesketch API version information."""
@login_required
def get(self):
"""Handles GET request to the resource.
Returns:
- List of usernames
+ JSON object including version info
"""
schema = {
'meta': {
'version': version.get_version()
},
'objects': []
}
response = jsonify(schema)
response.status_code = HTTP_STATUS_CODE_OK
return response
| Fix method docstring (copy paste error) | ## Code Before:
"""Information API for version 1 of the Timesketch API."""
from flask import jsonify
from flask_restful import Resource
from flask_login import login_required
from timesketch import version
from timesketch.api.v1 import resources
from timesketch.lib.definitions import HTTP_STATUS_CODE_OK
class VersionResource(resources.ResourceMixin, Resource):
"""Resource to get Timesketch API version information."""
@login_required
def get(self):
"""Handles GET request to the resource.
Returns:
List of usernames
"""
schema = {
'meta': {
'version': version.get_version()
},
'objects': []
}
response = jsonify(schema)
response.status_code = HTTP_STATUS_CODE_OK
return response
## Instruction:
Fix method docstring (copy paste error)
## Code After:
"""Information API for version 1 of the Timesketch API."""
from flask import jsonify
from flask_restful import Resource
from flask_login import login_required
from timesketch import version
from timesketch.api.v1 import resources
from timesketch.lib.definitions import HTTP_STATUS_CODE_OK
class VersionResource(resources.ResourceMixin, Resource):
"""Resource to get Timesketch API version information."""
@login_required
def get(self):
"""Handles GET request to the resource.
Returns:
JSON object including version info
"""
schema = {
'meta': {
'version': version.get_version()
},
'objects': []
}
response = jsonify(schema)
response.status_code = HTTP_STATUS_CODE_OK
return response
| ...
Returns:
JSON object including version info
"""
schema = {
... |
2459239188b4a6f9e46363ef84fc9dc252793774 | trie_search/record_trie.py | trie_search/record_trie.py | from marisa_trie import RecordTrie
from .trie import TrieSearch
class RecordTrieSearch(RecordTrie, TrieSearch):
def __init__(self, record_format, records=None, filepath=None):
super(RecordTrieSearch, self).__init__(record_format, records)
if filepath:
self.load(filepath)
def search_all_patterns(self, text, splitter=u' ', min_weight=0.0):
for pattern, start_idx in super(
RecordTrie, self).search_all_patterns(text, splitter):
weight = self[pattern][0][0]
if weight < min_weight:
continue
yield pattern, start_idx, weight
def search_longest_patterns(self, text, splitter=u' ', min_weight=0.0):
all_patterns = self.search_all_patterns(text, splitter, min_weight)
check_field = [0] * len(text)
for pattern, start_idx, weight in sorted(
all_patterns,
key=lambda x: len(x[0].split(splitter)),
reverse=True):
target_field = check_field[start_idx:start_idx + len(pattern)]
check_sum = sum(target_field)
if check_sum != len(target_field):
for i in range(len(pattern)):
check_field[start_idx + i] = 1
yield pattern, start_idx, weight
| from marisa_trie import RecordTrie
from .trie import TrieSearch
class RecordTrieSearch(RecordTrie, TrieSearch):
def __init__(self, record_format, records=None, filepath=None):
super(RecordTrieSearch, self).__init__(record_format, records)
if filepath:
self.load(filepath)
def search_all_patterns(self, text, splitter=u' ', min_weight=0.0):
for pattern, start_idx in super(
RecordTrie, self).search_all_patterns(text, splitter):
weight = self[pattern][0][0]
if weight < min_weight:
continue
yield pattern, start_idx, weight
def search_longest_patterns(self, text, splitter=u' ', min_weight=0.0):
all_patterns = self.search_all_patterns(text, splitter, min_weight)
check_field = [0] * len(text)
for pattern, start_idx, weight in sorted(
all_patterns, key=lambda x: len(x[0]), reverse=True):
target_field = check_field[start_idx:start_idx + len(pattern)]
check_sum = sum(target_field)
if check_sum != len(target_field):
for i in range(len(pattern)):
check_field[start_idx + i] = 1
yield pattern, start_idx, weight
| Modify the condition for selection of longest patterns | Modify the condition for selection of longest patterns
| Python | mit | nkmrtty/trie-search | from marisa_trie import RecordTrie
from .trie import TrieSearch
class RecordTrieSearch(RecordTrie, TrieSearch):
def __init__(self, record_format, records=None, filepath=None):
super(RecordTrieSearch, self).__init__(record_format, records)
if filepath:
self.load(filepath)
def search_all_patterns(self, text, splitter=u' ', min_weight=0.0):
for pattern, start_idx in super(
RecordTrie, self).search_all_patterns(text, splitter):
weight = self[pattern][0][0]
if weight < min_weight:
continue
yield pattern, start_idx, weight
def search_longest_patterns(self, text, splitter=u' ', min_weight=0.0):
all_patterns = self.search_all_patterns(text, splitter, min_weight)
check_field = [0] * len(text)
for pattern, start_idx, weight in sorted(
+ all_patterns, key=lambda x: len(x[0]), reverse=True):
- all_patterns,
- key=lambda x: len(x[0].split(splitter)),
- reverse=True):
target_field = check_field[start_idx:start_idx + len(pattern)]
check_sum = sum(target_field)
if check_sum != len(target_field):
for i in range(len(pattern)):
check_field[start_idx + i] = 1
yield pattern, start_idx, weight
| Modify the condition for selection of longest patterns | ## Code Before:
from marisa_trie import RecordTrie
from .trie import TrieSearch
class RecordTrieSearch(RecordTrie, TrieSearch):
def __init__(self, record_format, records=None, filepath=None):
super(RecordTrieSearch, self).__init__(record_format, records)
if filepath:
self.load(filepath)
def search_all_patterns(self, text, splitter=u' ', min_weight=0.0):
for pattern, start_idx in super(
RecordTrie, self).search_all_patterns(text, splitter):
weight = self[pattern][0][0]
if weight < min_weight:
continue
yield pattern, start_idx, weight
def search_longest_patterns(self, text, splitter=u' ', min_weight=0.0):
all_patterns = self.search_all_patterns(text, splitter, min_weight)
check_field = [0] * len(text)
for pattern, start_idx, weight in sorted(
all_patterns,
key=lambda x: len(x[0].split(splitter)),
reverse=True):
target_field = check_field[start_idx:start_idx + len(pattern)]
check_sum = sum(target_field)
if check_sum != len(target_field):
for i in range(len(pattern)):
check_field[start_idx + i] = 1
yield pattern, start_idx, weight
## Instruction:
Modify the condition for selection of longest patterns
## Code After:
from marisa_trie import RecordTrie
from .trie import TrieSearch
class RecordTrieSearch(RecordTrie, TrieSearch):
def __init__(self, record_format, records=None, filepath=None):
super(RecordTrieSearch, self).__init__(record_format, records)
if filepath:
self.load(filepath)
def search_all_patterns(self, text, splitter=u' ', min_weight=0.0):
for pattern, start_idx in super(
RecordTrie, self).search_all_patterns(text, splitter):
weight = self[pattern][0][0]
if weight < min_weight:
continue
yield pattern, start_idx, weight
def search_longest_patterns(self, text, splitter=u' ', min_weight=0.0):
all_patterns = self.search_all_patterns(text, splitter, min_weight)
check_field = [0] * len(text)
for pattern, start_idx, weight in sorted(
all_patterns, key=lambda x: len(x[0]), reverse=True):
target_field = check_field[start_idx:start_idx + len(pattern)]
check_sum = sum(target_field)
if check_sum != len(target_field):
for i in range(len(pattern)):
check_field[start_idx + i] = 1
yield pattern, start_idx, weight
| // ... existing code ...
check_field = [0] * len(text)
for pattern, start_idx, weight in sorted(
all_patterns, key=lambda x: len(x[0]), reverse=True):
target_field = check_field[start_idx:start_idx + len(pattern)]
check_sum = sum(target_field)
// ... rest of the code ... |
fe6c924532750f646303fe82728795717b830819 | piper/version.py | piper/version.py | from piper.abc import DynamicItem
from piper.utils import oneshot
class Version(DynamicItem):
"""
Base for versioning classes
"""
def __str__(self): # pragma: nocover
return self.get_version()
def get_version(self):
raise NotImplementedError()
class StaticVersion(Version):
"""
Static versioning, set inside the piper.yml configuration file
"""
@property
def schema(self):
if not hasattr(self, '_schema'):
self._schema = super(StaticVersion, self).schema
self._schema['required'].append('version')
self._schema['properties']['version'] = {
'description': 'Static version to use',
'type': 'string',
}
return self._schema
def get_version(self):
return self.config.version
class GitVersion(Version):
"""
Versioning based on the output of `git describe`
"""
def __init__(self, ns, config):
super(GitVersion, self).__init__(ns, config)
if 'arguments' not in config:
self.config.arguments = None
@property
def schema(self):
if not hasattr(self, '_schema'):
self._schema = super(GitVersion, self).schema
self._schema['properties']['arguments'] = {
'description':
'Space separated arguments passed directly to the '
'`git describe` call.',
'default': "--tags",
'type': 'string',
}
return self._schema
def get_version(self):
cmd = 'git describe'
if self.config.arguments:
cmd += ' ' + self.config.arguments
return oneshot(cmd)
| from piper.abc import DynamicItem
from piper.utils import oneshot
class Version(DynamicItem):
"""
Base for versioning classes
"""
def __str__(self): # pragma: nocover
return self.get_version()
def get_version(self):
raise NotImplementedError()
class StaticVersion(Version):
"""
Static versioning, set inside the piper.yml configuration file
"""
@property
def schema(self):
if not hasattr(self, '_schema'):
self._schema = super(StaticVersion, self).schema
self._schema['required'].append('version')
self._schema['properties']['version'] = {
'description': 'Static version to use',
'type': 'string',
}
return self._schema
def get_version(self):
return self.config.version
class GitVersion(Version):
"""
Versioning based on the output of `git describe`
"""
@property
def schema(self):
if not hasattr(self, '_schema'):
self._schema = super(GitVersion, self).schema
self._schema['properties']['arguments'] = {
'description':
'Space separated arguments passed directly to the '
'`git describe` call.',
'default': "--tags",
'type': 'string',
}
return self._schema
def get_version(self):
cmd = 'git describe'
if self.config.arguments:
cmd += ' ' + self.config.arguments
return oneshot(cmd)
| Remove argument defaulting from Version() | Remove argument defaulting from Version()
It was moved to the ABC and subsequently the check was left behind.
| Python | mit | thiderman/piper | from piper.abc import DynamicItem
from piper.utils import oneshot
class Version(DynamicItem):
"""
Base for versioning classes
"""
def __str__(self): # pragma: nocover
return self.get_version()
def get_version(self):
raise NotImplementedError()
class StaticVersion(Version):
"""
Static versioning, set inside the piper.yml configuration file
"""
@property
def schema(self):
if not hasattr(self, '_schema'):
self._schema = super(StaticVersion, self).schema
self._schema['required'].append('version')
self._schema['properties']['version'] = {
'description': 'Static version to use',
'type': 'string',
}
return self._schema
def get_version(self):
return self.config.version
class GitVersion(Version):
"""
Versioning based on the output of `git describe`
"""
- def __init__(self, ns, config):
- super(GitVersion, self).__init__(ns, config)
- if 'arguments' not in config:
- self.config.arguments = None
-
@property
def schema(self):
if not hasattr(self, '_schema'):
self._schema = super(GitVersion, self).schema
self._schema['properties']['arguments'] = {
'description':
'Space separated arguments passed directly to the '
'`git describe` call.',
'default': "--tags",
'type': 'string',
}
return self._schema
def get_version(self):
cmd = 'git describe'
if self.config.arguments:
cmd += ' ' + self.config.arguments
return oneshot(cmd)
| Remove argument defaulting from Version() | ## Code Before:
from piper.abc import DynamicItem
from piper.utils import oneshot
class Version(DynamicItem):
"""
Base for versioning classes
"""
def __str__(self): # pragma: nocover
return self.get_version()
def get_version(self):
raise NotImplementedError()
class StaticVersion(Version):
"""
Static versioning, set inside the piper.yml configuration file
"""
@property
def schema(self):
if not hasattr(self, '_schema'):
self._schema = super(StaticVersion, self).schema
self._schema['required'].append('version')
self._schema['properties']['version'] = {
'description': 'Static version to use',
'type': 'string',
}
return self._schema
def get_version(self):
return self.config.version
class GitVersion(Version):
"""
Versioning based on the output of `git describe`
"""
def __init__(self, ns, config):
super(GitVersion, self).__init__(ns, config)
if 'arguments' not in config:
self.config.arguments = None
@property
def schema(self):
if not hasattr(self, '_schema'):
self._schema = super(GitVersion, self).schema
self._schema['properties']['arguments'] = {
'description':
'Space separated arguments passed directly to the '
'`git describe` call.',
'default': "--tags",
'type': 'string',
}
return self._schema
def get_version(self):
cmd = 'git describe'
if self.config.arguments:
cmd += ' ' + self.config.arguments
return oneshot(cmd)
## Instruction:
Remove argument defaulting from Version()
## Code After:
from piper.abc import DynamicItem
from piper.utils import oneshot
class Version(DynamicItem):
"""
Base for versioning classes
"""
def __str__(self): # pragma: nocover
return self.get_version()
def get_version(self):
raise NotImplementedError()
class StaticVersion(Version):
"""
Static versioning, set inside the piper.yml configuration file
"""
@property
def schema(self):
if not hasattr(self, '_schema'):
self._schema = super(StaticVersion, self).schema
self._schema['required'].append('version')
self._schema['properties']['version'] = {
'description': 'Static version to use',
'type': 'string',
}
return self._schema
def get_version(self):
return self.config.version
class GitVersion(Version):
"""
Versioning based on the output of `git describe`
"""
@property
def schema(self):
if not hasattr(self, '_schema'):
self._schema = super(GitVersion, self).schema
self._schema['properties']['arguments'] = {
'description':
'Space separated arguments passed directly to the '
'`git describe` call.',
'default': "--tags",
'type': 'string',
}
return self._schema
def get_version(self):
cmd = 'git describe'
if self.config.arguments:
cmd += ' ' + self.config.arguments
return oneshot(cmd)
| # ... existing code ...
"""
@property
def schema(self):
# ... rest of the code ... |
a2e63f05d7992058b09a3d8e72b91e022cb94ef1 | core/urls.py | core/urls.py | from django.conf.urls import include, url
from django.views.generic import TemplateView
from tastypie.api import Api
from .api import ImageResource, ThumbnailResource, PinResource, UserResource
v1_api = Api(api_name='v1')
v1_api.register(ImageResource())
v1_api.register(ThumbnailResource())
v1_api.register(PinResource())
v1_api.register(UserResource())
urlpatterns = [
url(r'^api/', include(v1_api.urls, namespace='api')),
url(r'^pins/pin-form/$', TemplateView.as_view(template_name='core/pin_form.html'),
name='pin-form'),
url(r'^pins/tags/(?P<tag>(\w|-)+)/$', TemplateView.as_view(template_name='core/pins.html'),
name='tag-pins'),
url(r'^pins/users/(?P<user>(\w|-)+)/$', TemplateView.as_view(template_name='core/pins.html'),
name='user-pins'),
url(r'^(?P<pin>[0-9]+)/$', TemplateView.as_view(template_name='core/pins.html'),
name='recent-pins'),
url(r'^$', TemplateView.as_view(template_name='core/pins.html'),
name='recent-pins'),
]
| from django.conf.urls import include, url
from django.views.generic import TemplateView
from tastypie.api import Api
from .api import ImageResource, ThumbnailResource, PinResource, UserResource
v1_api = Api(api_name='v1')
v1_api.register(ImageResource())
v1_api.register(ThumbnailResource())
v1_api.register(PinResource())
v1_api.register(UserResource())
urlpatterns = [
url(r'^api/', include(v1_api.urls, namespace='api')),
url(r'^pins/pin-form/$', TemplateView.as_view(template_name='core/pin_form.html'),
name='pin-form'),
url(r'^pins/tags/(?P<tag>(\w|-)+)/$', TemplateView.as_view(template_name='core/pins.html'),
name='tag-pins'),
url(r'^pins/users/(?P<user>(\w|-)+)/$', TemplateView.as_view(template_name='core/pins.html'),
name='user-pins'),
url(r'^(?P<pin>[0-9]+)/$', TemplateView.as_view(template_name='core/pins.html'),
name='pin-detail'),
url(r'^$', TemplateView.as_view(template_name='core/pins.html'),
name='recent-pins'),
]
| Correct the name for specified pin | Fix: Correct the name for specified pin
| Python | bsd-2-clause | pinry/pinry,lapo-luchini/pinry,lapo-luchini/pinry,pinry/pinry,pinry/pinry,pinry/pinry,lapo-luchini/pinry,lapo-luchini/pinry | from django.conf.urls import include, url
from django.views.generic import TemplateView
from tastypie.api import Api
from .api import ImageResource, ThumbnailResource, PinResource, UserResource
v1_api = Api(api_name='v1')
v1_api.register(ImageResource())
v1_api.register(ThumbnailResource())
v1_api.register(PinResource())
v1_api.register(UserResource())
urlpatterns = [
url(r'^api/', include(v1_api.urls, namespace='api')),
url(r'^pins/pin-form/$', TemplateView.as_view(template_name='core/pin_form.html'),
name='pin-form'),
url(r'^pins/tags/(?P<tag>(\w|-)+)/$', TemplateView.as_view(template_name='core/pins.html'),
name='tag-pins'),
url(r'^pins/users/(?P<user>(\w|-)+)/$', TemplateView.as_view(template_name='core/pins.html'),
name='user-pins'),
url(r'^(?P<pin>[0-9]+)/$', TemplateView.as_view(template_name='core/pins.html'),
- name='recent-pins'),
+ name='pin-detail'),
url(r'^$', TemplateView.as_view(template_name='core/pins.html'),
name='recent-pins'),
]
| Correct the name for specified pin | ## Code Before:
from django.conf.urls import include, url
from django.views.generic import TemplateView
from tastypie.api import Api
from .api import ImageResource, ThumbnailResource, PinResource, UserResource
v1_api = Api(api_name='v1')
v1_api.register(ImageResource())
v1_api.register(ThumbnailResource())
v1_api.register(PinResource())
v1_api.register(UserResource())
urlpatterns = [
url(r'^api/', include(v1_api.urls, namespace='api')),
url(r'^pins/pin-form/$', TemplateView.as_view(template_name='core/pin_form.html'),
name='pin-form'),
url(r'^pins/tags/(?P<tag>(\w|-)+)/$', TemplateView.as_view(template_name='core/pins.html'),
name='tag-pins'),
url(r'^pins/users/(?P<user>(\w|-)+)/$', TemplateView.as_view(template_name='core/pins.html'),
name='user-pins'),
url(r'^(?P<pin>[0-9]+)/$', TemplateView.as_view(template_name='core/pins.html'),
name='recent-pins'),
url(r'^$', TemplateView.as_view(template_name='core/pins.html'),
name='recent-pins'),
]
## Instruction:
Correct the name for specified pin
## Code After:
from django.conf.urls import include, url
from django.views.generic import TemplateView
from tastypie.api import Api
from .api import ImageResource, ThumbnailResource, PinResource, UserResource
v1_api = Api(api_name='v1')
v1_api.register(ImageResource())
v1_api.register(ThumbnailResource())
v1_api.register(PinResource())
v1_api.register(UserResource())
urlpatterns = [
url(r'^api/', include(v1_api.urls, namespace='api')),
url(r'^pins/pin-form/$', TemplateView.as_view(template_name='core/pin_form.html'),
name='pin-form'),
url(r'^pins/tags/(?P<tag>(\w|-)+)/$', TemplateView.as_view(template_name='core/pins.html'),
name='tag-pins'),
url(r'^pins/users/(?P<user>(\w|-)+)/$', TemplateView.as_view(template_name='core/pins.html'),
name='user-pins'),
url(r'^(?P<pin>[0-9]+)/$', TemplateView.as_view(template_name='core/pins.html'),
name='pin-detail'),
url(r'^$', TemplateView.as_view(template_name='core/pins.html'),
name='recent-pins'),
]
| # ... existing code ...
name='user-pins'),
url(r'^(?P<pin>[0-9]+)/$', TemplateView.as_view(template_name='core/pins.html'),
name='pin-detail'),
url(r'^$', TemplateView.as_view(template_name='core/pins.html'),
name='recent-pins'),
# ... rest of the code ... |
eca73e0c57042593f7e65446e26e63790c5cf2aa | notes/admin.py | notes/admin.py |
from snowy.accounts.models import UserProfile
from snowy.notes.models import Note, NoteTag
from reversion.admin import VersionAdmin
from django.contrib import admin
class NoteAdmin(VersionAdmin):
list_display = ('created', 'author', 'title')
search_fields = ['content', 'title']
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Note, NoteAdmin)
admin.site.register(NoteTag)
admin.site.register(UserProfile)
|
from snowy.accounts.models import UserProfile
from snowy.notes.models import Note, NoteTag
#from reversion.admin import VersionAdmin
from django.contrib import admin
#class NoteAdmin(VersionAdmin):
class NoteAdmin(admin.ModelAdmin):
list_display = ('created', 'author', 'title')
search_fields = ['content', 'title']
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Note, NoteAdmin)
admin.site.register(NoteTag)
admin.site.register(UserProfile)
| Complete removal of reversion usage | Complete removal of reversion usage
| Python | agpl-3.0 | leonhandreke/snowy,NoUsername/PrivateNotesExperimental,jaredjennings/snowy,GNOME/snowy,sandyarmstrong/snowy,syskill/snowy,syskill/snowy,NoUsername/PrivateNotesExperimental,sandyarmstrong/snowy,jaredjennings/snowy,jaredjennings/snowy,widox/snowy,jaredjennings/snowy,nekohayo/snowy,nekohayo/snowy,widox/snowy,GNOME/snowy,leonhandreke/snowy |
from snowy.accounts.models import UserProfile
from snowy.notes.models import Note, NoteTag
- from reversion.admin import VersionAdmin
+ #from reversion.admin import VersionAdmin
from django.contrib import admin
- class NoteAdmin(VersionAdmin):
+ #class NoteAdmin(VersionAdmin):
+ class NoteAdmin(admin.ModelAdmin):
list_display = ('created', 'author', 'title')
search_fields = ['content', 'title']
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Note, NoteAdmin)
admin.site.register(NoteTag)
admin.site.register(UserProfile)
| Complete removal of reversion usage | ## Code Before:
from snowy.accounts.models import UserProfile
from snowy.notes.models import Note, NoteTag
from reversion.admin import VersionAdmin
from django.contrib import admin
class NoteAdmin(VersionAdmin):
list_display = ('created', 'author', 'title')
search_fields = ['content', 'title']
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Note, NoteAdmin)
admin.site.register(NoteTag)
admin.site.register(UserProfile)
## Instruction:
Complete removal of reversion usage
## Code After:
from snowy.accounts.models import UserProfile
from snowy.notes.models import Note, NoteTag
#from reversion.admin import VersionAdmin
from django.contrib import admin
#class NoteAdmin(VersionAdmin):
class NoteAdmin(admin.ModelAdmin):
list_display = ('created', 'author', 'title')
search_fields = ['content', 'title']
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Note, NoteAdmin)
admin.site.register(NoteTag)
admin.site.register(UserProfile)
| # ... existing code ...
from snowy.accounts.models import UserProfile
from snowy.notes.models import Note, NoteTag
#from reversion.admin import VersionAdmin
from django.contrib import admin
#class NoteAdmin(VersionAdmin):
class NoteAdmin(admin.ModelAdmin):
list_display = ('created', 'author', 'title')
search_fields = ['content', 'title']
# ... rest of the code ... |
9d7beff62a3555aa4be51cefb2f54681070d1305 | ircstat/plugins/__init__.py | ircstat/plugins/__init__.py |
import importlib
import os
from functools import lru_cache
from os import path
from .base import Plugin
@lru_cache()
def load_plugins(config):
"""Import all the plugins, and return a set of plugin instances, filtering
out any plugin whose name appears in the configurable blacklist."""
cwd = path.abspath(path.dirname(__file__))
files = os.listdir(cwd)
for filename in files:
name, ext = path.splitext(filename)
if name.startswith('_'):
continue
if ext == '.py':
importlib.import_module('ircstat.plugins.' + name)
plugins = set(plugin() for plugin in Plugin.subclasses())
for plugin in plugins:
if plugin.name in config.plugin_blacklist:
plugins.remove(plugin)
return plugins
|
import importlib
import os
from functools import lru_cache
from os import path
from .base import Plugin
@lru_cache()
def load_plugins(config):
"""Import all the plugins, and return a set of plugin instances, filtering
out any plugin whose name appears in the configurable blacklist."""
plugins = set(plugin(config=config) for plugin in Plugin.subclasses())
for plugin in plugins:
if plugin.name in config.plugin_blacklist:
plugins.remove(plugin)
return plugins
# import plugins
cwd = path.abspath(path.dirname(__file__))
files = os.listdir(cwd)
for filename in files:
name, ext = path.splitext(filename)
if name.startswith('_'):
continue
if ext == '.py':
module = importlib.import_module('ircstat.plugins.' + name)
for name, item in module.__dict__.items():
if type(item) == type and issubclass(item, Plugin):
item.name = item.__name__
if item.name.endswith('Plugin'):
item.name = item.name[:-6]
| Make sure plugins' .name property gets set | Make sure plugins' .name property gets set
| Python | mit | jreese/ircstat,jreese/ircstat |
import importlib
import os
from functools import lru_cache
from os import path
from .base import Plugin
@lru_cache()
def load_plugins(config):
"""Import all the plugins, and return a set of plugin instances, filtering
out any plugin whose name appears in the configurable blacklist."""
- cwd = path.abspath(path.dirname(__file__))
- files = os.listdir(cwd)
-
- for filename in files:
- name, ext = path.splitext(filename)
-
- if name.startswith('_'):
- continue
-
- if ext == '.py':
- importlib.import_module('ircstat.plugins.' + name)
-
- plugins = set(plugin() for plugin in Plugin.subclasses())
+ plugins = set(plugin(config=config) for plugin in Plugin.subclasses())
for plugin in plugins:
if plugin.name in config.plugin_blacklist:
plugins.remove(plugin)
return plugins
+ # import plugins
+
+ cwd = path.abspath(path.dirname(__file__))
+ files = os.listdir(cwd)
+
+ for filename in files:
+ name, ext = path.splitext(filename)
+
+ if name.startswith('_'):
+ continue
+
+ if ext == '.py':
+ module = importlib.import_module('ircstat.plugins.' + name)
+ for name, item in module.__dict__.items():
+ if type(item) == type and issubclass(item, Plugin):
+ item.name = item.__name__
+ if item.name.endswith('Plugin'):
+ item.name = item.name[:-6]
+ | Make sure plugins' .name property gets set | ## Code Before:
import importlib
import os
from functools import lru_cache
from os import path
from .base import Plugin
@lru_cache()
def load_plugins(config):
"""Import all the plugins, and return a set of plugin instances, filtering
out any plugin whose name appears in the configurable blacklist."""
cwd = path.abspath(path.dirname(__file__))
files = os.listdir(cwd)
for filename in files:
name, ext = path.splitext(filename)
if name.startswith('_'):
continue
if ext == '.py':
importlib.import_module('ircstat.plugins.' + name)
plugins = set(plugin() for plugin in Plugin.subclasses())
for plugin in plugins:
if plugin.name in config.plugin_blacklist:
plugins.remove(plugin)
return plugins
## Instruction:
Make sure plugins' .name property gets set
## Code After:
import importlib
import os
from functools import lru_cache
from os import path
from .base import Plugin
@lru_cache()
def load_plugins(config):
"""Import all the plugins, and return a set of plugin instances, filtering
out any plugin whose name appears in the configurable blacklist."""
plugins = set(plugin(config=config) for plugin in Plugin.subclasses())
for plugin in plugins:
if plugin.name in config.plugin_blacklist:
plugins.remove(plugin)
return plugins
# import plugins
cwd = path.abspath(path.dirname(__file__))
files = os.listdir(cwd)
for filename in files:
name, ext = path.splitext(filename)
if name.startswith('_'):
continue
if ext == '.py':
module = importlib.import_module('ircstat.plugins.' + name)
for name, item in module.__dict__.items():
if type(item) == type and issubclass(item, Plugin):
item.name = item.__name__
if item.name.endswith('Plugin'):
item.name = item.name[:-6]
| # ... existing code ...
out any plugin whose name appears in the configurable blacklist."""
plugins = set(plugin(config=config) for plugin in Plugin.subclasses())
for plugin in plugins:
# ... modified code ...
return plugins
# import plugins
cwd = path.abspath(path.dirname(__file__))
files = os.listdir(cwd)
for filename in files:
name, ext = path.splitext(filename)
if name.startswith('_'):
continue
if ext == '.py':
module = importlib.import_module('ircstat.plugins.' + name)
for name, item in module.__dict__.items():
if type(item) == type and issubclass(item, Plugin):
item.name = item.__name__
if item.name.endswith('Plugin'):
item.name = item.name[:-6]
# ... rest of the code ... |
8d235a76120aadcd555da3d641f509541f525eb8 | csunplugged/utils/retrieve_query_parameter.py | csunplugged/utils/retrieve_query_parameter.py | """Module for retrieving a GET request query parameter."""
from django.http import Http404
def retrieve_query_parameter(request, parameter, valid_options=None):
"""Retrieve the query parameter.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
String value of parameter.
"""
value = request.get(parameter, None)
if value is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options and value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return value
| """Module for retrieving a GET request query parameter."""
from django.http import Http404
def retrieve_query_parameter(request, parameter, valid_options=None):
"""Retrieve the query parameter.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
String value of parameter.
"""
value = request.get(parameter, None)
if value is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options and value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return value
def retrieve_query_parameter_list(request, parameter, valid_options=None):
"""Retrieve the query parameter list.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
List of strings of values of parameter.
"""
values = request.getlist(parameter, None)
if values is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options:
for value in values:
if value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return values
| Add function to get list of parameters | Add function to get list of parameters
| Python | mit | uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged | """Module for retrieving a GET request query parameter."""
from django.http import Http404
def retrieve_query_parameter(request, parameter, valid_options=None):
"""Retrieve the query parameter.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
String value of parameter.
"""
value = request.get(parameter, None)
if value is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options and value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return value
+
+ def retrieve_query_parameter_list(request, parameter, valid_options=None):
+ """Retrieve the query parameter list.
+
+ If the parameter cannot be found, or is not found in the list of
+ valid options, then a 404 error is raised.
+
+ Args:
+ request: Request object (Request).
+ parameter: Parameter to retrieve (str).
+ valid_options: If provided, a list of valid options (list of str).
+
+ Returns:
+ List of strings of values of parameter.
+ """
+ values = request.getlist(parameter, None)
+ if values is None:
+ raise Http404("{} parameter not specified.".format(parameter))
+ if valid_options:
+ for value in values:
+ if value not in valid_options:
+ raise Http404("{} parameter not valid.".format(parameter))
+ return values
+ | Add function to get list of parameters | ## Code Before:
"""Module for retrieving a GET request query parameter."""
from django.http import Http404
def retrieve_query_parameter(request, parameter, valid_options=None):
"""Retrieve the query parameter.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
String value of parameter.
"""
value = request.get(parameter, None)
if value is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options and value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return value
## Instruction:
Add function to get list of parameters
## Code After:
"""Module for retrieving a GET request query parameter."""
from django.http import Http404
def retrieve_query_parameter(request, parameter, valid_options=None):
"""Retrieve the query parameter.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
String value of parameter.
"""
value = request.get(parameter, None)
if value is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options and value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return value
def retrieve_query_parameter_list(request, parameter, valid_options=None):
"""Retrieve the query parameter list.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
List of strings of values of parameter.
"""
values = request.getlist(parameter, None)
if values is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options:
for value in values:
if value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return values
| # ... existing code ...
raise Http404("{} parameter not valid.".format(parameter))
return value
def retrieve_query_parameter_list(request, parameter, valid_options=None):
"""Retrieve the query parameter list.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
List of strings of values of parameter.
"""
values = request.getlist(parameter, None)
if values is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options:
for value in values:
if value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return values
# ... rest of the code ... |
b33b063e49b394265bc890f6d3b39da08e355416 | blogs/tests/test_parser.py | blogs/tests/test_parser.py | from unittest import TestCase
from ..parser import get_all_entries
from .utils import get_test_rss_path
class BlogParserTest(TestCase):
def setUp(self):
self.test_file_path = get_test_rss_path()
self.entries = get_all_entries("file://{}".format(self.test_file_path))
def test_entries(self):
""" Make sure we can parse RSS entries """
self.assertEqual(len(self.entries), 25)
| import datetime
import unittest
from ..parser import get_all_entries
from .utils import get_test_rss_path
class BlogParserTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.test_file_path = get_test_rss_path()
cls.entries = get_all_entries("file://{}".format(cls.test_file_path))
def test_entries(self):
self.assertEqual(len(self.entries), 25)
self.assertEqual(
self.entries[0]['title'],
'Introducing Electronic Contributor Agreements'
)
self.assertIn(
"We're happy to announce the new way to file a contributor "
"agreement: on the web at",
self.entries[0]['summary']
)
self.assertIsInstance(self.entries[0]['pub_date'], datetime.datetime)
self.assertEqual(
self.entries[0]['url'],
'http://feedproxy.google.com/~r/PythonInsider/~3/tGNCqyOiun4/introducing-electronic-contributor.html'
)
| Add some tests to make sure we can parse RSS feeds | Add some tests to make sure we can parse RSS feeds
| Python | apache-2.0 | manhhomienbienthuy/pythondotorg,proevo/pythondotorg,manhhomienbienthuy/pythondotorg,proevo/pythondotorg,Mariatta/pythondotorg,Mariatta/pythondotorg,proevo/pythondotorg,python/pythondotorg,manhhomienbienthuy/pythondotorg,python/pythondotorg,Mariatta/pythondotorg,manhhomienbienthuy/pythondotorg,Mariatta/pythondotorg,python/pythondotorg,proevo/pythondotorg,python/pythondotorg | - from unittest import TestCase
+ import datetime
+ import unittest
from ..parser import get_all_entries
from .utils import get_test_rss_path
- class BlogParserTest(TestCase):
+ class BlogParserTest(unittest.TestCase):
+ @classmethod
- def setUp(self):
+ def setUpClass(cls):
- self.test_file_path = get_test_rss_path()
+ cls.test_file_path = get_test_rss_path()
- self.entries = get_all_entries("file://{}".format(self.test_file_path))
+ cls.entries = get_all_entries("file://{}".format(cls.test_file_path))
def test_entries(self):
- """ Make sure we can parse RSS entries """
self.assertEqual(len(self.entries), 25)
+ self.assertEqual(
+ self.entries[0]['title'],
+ 'Introducing Electronic Contributor Agreements'
+ )
+ self.assertIn(
+ "We're happy to announce the new way to file a contributor "
+ "agreement: on the web at",
+ self.entries[0]['summary']
+ )
+ self.assertIsInstance(self.entries[0]['pub_date'], datetime.datetime)
+ self.assertEqual(
+ self.entries[0]['url'],
+ 'http://feedproxy.google.com/~r/PythonInsider/~3/tGNCqyOiun4/introducing-electronic-contributor.html'
+ )
| Add some tests to make sure we can parse RSS feeds | ## Code Before:
from unittest import TestCase
from ..parser import get_all_entries
from .utils import get_test_rss_path
class BlogParserTest(TestCase):
def setUp(self):
self.test_file_path = get_test_rss_path()
self.entries = get_all_entries("file://{}".format(self.test_file_path))
def test_entries(self):
""" Make sure we can parse RSS entries """
self.assertEqual(len(self.entries), 25)
## Instruction:
Add some tests to make sure we can parse RSS feeds
## Code After:
import datetime
import unittest
from ..parser import get_all_entries
from .utils import get_test_rss_path
class BlogParserTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.test_file_path = get_test_rss_path()
cls.entries = get_all_entries("file://{}".format(cls.test_file_path))
def test_entries(self):
self.assertEqual(len(self.entries), 25)
self.assertEqual(
self.entries[0]['title'],
'Introducing Electronic Contributor Agreements'
)
self.assertIn(
"We're happy to announce the new way to file a contributor "
"agreement: on the web at",
self.entries[0]['summary']
)
self.assertIsInstance(self.entries[0]['pub_date'], datetime.datetime)
self.assertEqual(
self.entries[0]['url'],
'http://feedproxy.google.com/~r/PythonInsider/~3/tGNCqyOiun4/introducing-electronic-contributor.html'
)
| // ... existing code ...
import datetime
import unittest
from ..parser import get_all_entries
// ... modified code ...
class BlogParserTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.test_file_path = get_test_rss_path()
cls.entries = get_all_entries("file://{}".format(cls.test_file_path))
def test_entries(self):
self.assertEqual(len(self.entries), 25)
self.assertEqual(
self.entries[0]['title'],
'Introducing Electronic Contributor Agreements'
)
self.assertIn(
"We're happy to announce the new way to file a contributor "
"agreement: on the web at",
self.entries[0]['summary']
)
self.assertIsInstance(self.entries[0]['pub_date'], datetime.datetime)
self.assertEqual(
self.entries[0]['url'],
'http://feedproxy.google.com/~r/PythonInsider/~3/tGNCqyOiun4/introducing-electronic-contributor.html'
)
// ... rest of the code ... |
64d75740c485b8e3ac3108b916cdf72ad41b0611 | nacl/__init__.py | nacl/__init__.py | from . import hash # pylint: disable=W0622
| from . import __about__
from . import hash # pylint: disable=W0622
__all__ = ["hash"] + __about__.__all__
# - Meta Information -
# This is pretty ugly
for attr in __about__.__all__:
if hasattr(__about__, attr):
globals()[attr] = getattr(__about__, attr)
# - End Meta Information -
| Add meta information to the nacl package | Add meta information to the nacl package
| Python | mit | dstufft/pynacl,ucoin-bot/cutecoin,hoffmabc/pynacl,Insoleet/cutecoin,xueyumusic/pynacl,scholarly/pynacl,ucoin-io/cutecoin,dstufft/pynacl,lmctv/pynacl,JackWink/pynacl,JackWink/pynacl,xueyumusic/pynacl,pyca/pynacl,reaperhulk/pynacl,scholarly/pynacl,lmctv/pynacl,ucoin-io/cutecoin,alex/pynacl,pyca/pynacl,xueyumusic/pynacl,alex/pynacl,pyca/pynacl,pyca/pynacl,dstufft/pynacl,alex/pynacl,reaperhulk/pynacl,hoffmabc/pynacl,JackWink/pynacl,lmctv/pynacl,hoffmabc/pynacl,pyca/pynacl,reaperhulk/pynacl,lmctv/pynacl,scholarly/pynacl,scholarly/pynacl,reaperhulk/pynacl,alex/pynacl,reaperhulk/pynacl,JackWink/pynacl,ucoin-io/cutecoin,xueyumusic/pynacl,dstufft/pynacl,lmctv/pynacl | + from . import __about__
from . import hash # pylint: disable=W0622
+
+ __all__ = ["hash"] + __about__.__all__
+
+
+ # - Meta Information -
+ # This is pretty ugly
+ for attr in __about__.__all__:
+ if hasattr(__about__, attr):
+ globals()[attr] = getattr(__about__, attr)
+ # - End Meta Information -
+ | Add meta information to the nacl package | ## Code Before:
from . import hash # pylint: disable=W0622
## Instruction:
Add meta information to the nacl package
## Code After:
from . import __about__
from . import hash # pylint: disable=W0622
__all__ = ["hash"] + __about__.__all__
# - Meta Information -
# This is pretty ugly
for attr in __about__.__all__:
if hasattr(__about__, attr):
globals()[attr] = getattr(__about__, attr)
# - End Meta Information -
| # ... existing code ...
from . import __about__
from . import hash # pylint: disable=W0622
__all__ = ["hash"] + __about__.__all__
# - Meta Information -
# This is pretty ugly
for attr in __about__.__all__:
if hasattr(__about__, attr):
globals()[attr] = getattr(__about__, attr)
# - End Meta Information -
# ... rest of the code ... |
b5fbaafddf41f4efc1a4841a8a35f2fda094e60a | js2py/prototypes/jsfunction.py | js2py/prototypes/jsfunction.py | import six
if six.PY3:
basestring = str
long = int
xrange = range
unicode = str
# todo fix apply and bind
class FunctionPrototype:
def toString():
if not this.is_callable():
raise TypeError('toString is not generic!')
args = ', '.join(this.code.__code__.co_varnames[:this.argcount])
return 'function %s(%s) ' % (this.func_name, args) + this.source
def call():
arguments_ = arguments
if not len(arguments):
obj = this.Js(None)
else:
obj = arguments[0]
if len(arguments) <= 1:
args = ()
else:
args = tuple([arguments_[e] for e in xrange(1, len(arguments_))])
return this.call(obj, args)
def apply():
if not len(arguments):
obj = this.Js(None)
else:
obj = arguments[0]
if len(arguments) <= 1:
args = ()
else:
appl = arguments[1]
args = tuple([appl[e] for e in xrange(len(appl))])
return this.call(obj, args)
def bind(thisArg):
target = this
if not target.is_callable():
raise this.MakeError(
'Object must be callable in order to be used with bind method')
if len(arguments) <= 1:
args = ()
else:
args = tuple([arguments[e] for e in xrange(1, len(arguments))])
return this.PyJsBoundFunction(target, thisArg, args)
| import six
if six.PY3:
basestring = str
long = int
xrange = range
unicode = str
class FunctionPrototype:
def toString():
if not this.is_callable():
raise TypeError('toString is not generic!')
args = ', '.join(this.code.__code__.co_varnames[:this.argcount])
return 'function %s(%s) ' % (this.func_name, args) + this.source
def call():
arguments_ = arguments
if not len(arguments):
obj = this.Js(None)
else:
obj = arguments[0]
if len(arguments) <= 1:
args = ()
else:
args = tuple([arguments_[e] for e in xrange(1, len(arguments_))])
return this.call(obj, args)
def apply():
if not len(arguments):
obj = this.Js(None)
else:
obj = arguments[0]
if len(arguments) <= 1:
args = ()
else:
appl = arguments[1]
args = tuple([appl[e] for e in xrange(len(appl))])
return this.call(obj, args)
def bind(thisArg):
arguments_ = arguments
target = this
if not target.is_callable():
raise this.MakeError(
'Object must be callable in order to be used with bind method')
if len(arguments) <= 1:
args = ()
else:
args = tuple([arguments_[e] for e in xrange(1, len(arguments_))])
return this.PyJsBoundFunction(target, thisArg, args)
| Fix injected local 'arguments' not working in list comprehension in bind. | Fix injected local 'arguments' not working in list comprehension in bind.
| Python | mit | PiotrDabkowski/Js2Py,PiotrDabkowski/Js2Py,PiotrDabkowski/Js2Py | import six
if six.PY3:
basestring = str
long = int
xrange = range
unicode = str
-
- # todo fix apply and bind
class FunctionPrototype:
def toString():
if not this.is_callable():
raise TypeError('toString is not generic!')
args = ', '.join(this.code.__code__.co_varnames[:this.argcount])
return 'function %s(%s) ' % (this.func_name, args) + this.source
def call():
arguments_ = arguments
if not len(arguments):
obj = this.Js(None)
else:
obj = arguments[0]
if len(arguments) <= 1:
args = ()
else:
args = tuple([arguments_[e] for e in xrange(1, len(arguments_))])
return this.call(obj, args)
def apply():
if not len(arguments):
obj = this.Js(None)
else:
obj = arguments[0]
if len(arguments) <= 1:
args = ()
else:
appl = arguments[1]
args = tuple([appl[e] for e in xrange(len(appl))])
return this.call(obj, args)
def bind(thisArg):
+ arguments_ = arguments
target = this
if not target.is_callable():
raise this.MakeError(
'Object must be callable in order to be used with bind method')
if len(arguments) <= 1:
args = ()
else:
- args = tuple([arguments[e] for e in xrange(1, len(arguments))])
+ args = tuple([arguments_[e] for e in xrange(1, len(arguments_))])
return this.PyJsBoundFunction(target, thisArg, args)
| Fix injected local 'arguments' not working in list comprehension in bind. | ## Code Before:
import six
if six.PY3:
basestring = str
long = int
xrange = range
unicode = str
# todo fix apply and bind
class FunctionPrototype:
def toString():
if not this.is_callable():
raise TypeError('toString is not generic!')
args = ', '.join(this.code.__code__.co_varnames[:this.argcount])
return 'function %s(%s) ' % (this.func_name, args) + this.source
def call():
arguments_ = arguments
if not len(arguments):
obj = this.Js(None)
else:
obj = arguments[0]
if len(arguments) <= 1:
args = ()
else:
args = tuple([arguments_[e] for e in xrange(1, len(arguments_))])
return this.call(obj, args)
def apply():
if not len(arguments):
obj = this.Js(None)
else:
obj = arguments[0]
if len(arguments) <= 1:
args = ()
else:
appl = arguments[1]
args = tuple([appl[e] for e in xrange(len(appl))])
return this.call(obj, args)
def bind(thisArg):
target = this
if not target.is_callable():
raise this.MakeError(
'Object must be callable in order to be used with bind method')
if len(arguments) <= 1:
args = ()
else:
args = tuple([arguments[e] for e in xrange(1, len(arguments))])
return this.PyJsBoundFunction(target, thisArg, args)
## Instruction:
Fix injected local 'arguments' not working in list comprehension in bind.
## Code After:
import six
if six.PY3:
basestring = str
long = int
xrange = range
unicode = str
class FunctionPrototype:
def toString():
if not this.is_callable():
raise TypeError('toString is not generic!')
args = ', '.join(this.code.__code__.co_varnames[:this.argcount])
return 'function %s(%s) ' % (this.func_name, args) + this.source
def call():
arguments_ = arguments
if not len(arguments):
obj = this.Js(None)
else:
obj = arguments[0]
if len(arguments) <= 1:
args = ()
else:
args = tuple([arguments_[e] for e in xrange(1, len(arguments_))])
return this.call(obj, args)
def apply():
if not len(arguments):
obj = this.Js(None)
else:
obj = arguments[0]
if len(arguments) <= 1:
args = ()
else:
appl = arguments[1]
args = tuple([appl[e] for e in xrange(len(appl))])
return this.call(obj, args)
def bind(thisArg):
arguments_ = arguments
target = this
if not target.is_callable():
raise this.MakeError(
'Object must be callable in order to be used with bind method')
if len(arguments) <= 1:
args = ()
else:
args = tuple([arguments_[e] for e in xrange(1, len(arguments_))])
return this.PyJsBoundFunction(target, thisArg, args)
| // ... existing code ...
xrange = range
unicode = str
// ... modified code ...
def bind(thisArg):
arguments_ = arguments
target = this
if not target.is_callable():
...
args = ()
else:
args = tuple([arguments_[e] for e in xrange(1, len(arguments_))])
return this.PyJsBoundFunction(target, thisArg, args)
// ... rest of the code ... |
6155cfa0d16bfde8b412a3b2c68983ef939d518c | synapse/tests/test_init.py | synapse/tests/test_init.py | import os
import imp
import synapse
from synapse.tests.common import *
class InitTest(SynTest):
def test_init_modules(self):
os.environ['SYN_MODULES'] = 'fakenotrealmod , badnothere,math'
msg = 'SYN_MODULES failed: badnothere (NoSuchDyn: name=\'badnothere\')'
with self.getLoggerStream('synapse', msg) as stream:
imp.reload(synapse)
self.true(stream.wait(10))
stream.seek(0)
self.isin(msg, stream.read())
self.isin(('math', 2.0, None), synapse.lib.modules.call('sqrt', 4))
| import os
import imp
import synapse
from synapse.tests.common import *
class InitTest(SynTest):
pass
'''
def test_init_modules(self):
os.environ['SYN_MODULES'] = 'fakenotrealmod , badnothere,math'
msg = 'SYN_MODULES failed: badnothere (NoSuchDyn: name=\'badnothere\')'
with self.getLoggerStream('synapse', msg) as stream:
imp.reload(synapse)
self.true(stream.wait(10))
stream.seek(0)
self.isin(msg, stream.read())
self.isin(('math', 2.0, None), synapse.lib.modules.call('sqrt', 4))
'''
| Comment out broken init test | Comment out broken init test
| Python | apache-2.0 | vertexproject/synapse,vertexproject/synapse,vivisect/synapse,vertexproject/synapse | import os
import imp
import synapse
from synapse.tests.common import *
class InitTest(SynTest):
+ pass
+ '''
def test_init_modules(self):
os.environ['SYN_MODULES'] = 'fakenotrealmod , badnothere,math'
msg = 'SYN_MODULES failed: badnothere (NoSuchDyn: name=\'badnothere\')'
with self.getLoggerStream('synapse', msg) as stream:
imp.reload(synapse)
self.true(stream.wait(10))
stream.seek(0)
self.isin(msg, stream.read())
self.isin(('math', 2.0, None), synapse.lib.modules.call('sqrt', 4))
+ '''
| Comment out broken init test | ## Code Before:
import os
import imp
import synapse
from synapse.tests.common import *
class InitTest(SynTest):
def test_init_modules(self):
os.environ['SYN_MODULES'] = 'fakenotrealmod , badnothere,math'
msg = 'SYN_MODULES failed: badnothere (NoSuchDyn: name=\'badnothere\')'
with self.getLoggerStream('synapse', msg) as stream:
imp.reload(synapse)
self.true(stream.wait(10))
stream.seek(0)
self.isin(msg, stream.read())
self.isin(('math', 2.0, None), synapse.lib.modules.call('sqrt', 4))
## Instruction:
Comment out broken init test
## Code After:
import os
import imp
import synapse
from synapse.tests.common import *
class InitTest(SynTest):
pass
'''
def test_init_modules(self):
os.environ['SYN_MODULES'] = 'fakenotrealmod , badnothere,math'
msg = 'SYN_MODULES failed: badnothere (NoSuchDyn: name=\'badnothere\')'
with self.getLoggerStream('synapse', msg) as stream:
imp.reload(synapse)
self.true(stream.wait(10))
stream.seek(0)
self.isin(msg, stream.read())
self.isin(('math', 2.0, None), synapse.lib.modules.call('sqrt', 4))
'''
| # ... existing code ...
class InitTest(SynTest):
pass
'''
def test_init_modules(self):
os.environ['SYN_MODULES'] = 'fakenotrealmod , badnothere,math'
# ... modified code ...
self.isin(msg, stream.read())
self.isin(('math', 2.0, None), synapse.lib.modules.call('sqrt', 4))
'''
# ... rest of the code ... |
c13fb7a0decf8b5beb0399523f4e9b9b7b71b361 | opps/core/tags/views.py | opps/core/tags/views.py | from django.utils import timezone
from django.contrib.sites.models import get_current_site
from opps.views.generic.list import ListView
from opps.containers.models import Container
class TagList(ListView):
model = Container
template_name_suffix = '_tags'
def get_context_data(self, **kwargs):
context = super(TagList, self).get_context_data(**kwargs)
context['tag'] = self.kwargs['tag']
return context
def get_queryset(self):
self.site = get_current_site(self.request)
self.long_slug = self.kwargs['tag']
self.containers = self.model.objects.filter(
site_domain=self.site,
tags__icontains=self.long_slug,
date_available__lte=timezone.now(),
published=True)
return self.containers
| from django.utils import timezone
from django.contrib.sites.models import get_current_site
from django.core.cache import cache
from django.conf import settings
from opps.views.generic.list import ListView
from opps.containers.models import Container
from .models import Tag
class TagList(ListView):
model = Container
template_name_suffix = '_tags'
def get_context_data(self, **kwargs):
context = super(TagList, self).get_context_data(**kwargs)
context['tag'] = self.kwargs['tag']
return context
def get_queryset(self):
self.site = get_current_site(self.request)
# without the long_slug, the queryset will cause an error
self.long_slug = 'tags'
self.tag = self.kwargs['tag']
cache_key = 'taglist-{}'.format(self.tag)
if cache.get(cache_key):
return cache.get(cache_key)
tags = Tag.objects.filter(slug=self.tag).values_list('name') or []
tags_names = []
if tags:
tags_names = [i[0] for i in tags]
ids = []
for tag in tags_names:
result = self.containers = self.model.objects.filter(
site_domain=self.site,
tags__contains=tag,
date_available__lte=timezone.now(),
published=True
)
if result.exists():
ids.extend([i.id for i in result])
# remove the repeated
ids = list(set(ids))
# grab the containers
self.containers = self.model.objects.filter(id__in=ids)
expires = getattr(settings, 'OPPS_CACHE_EXPIRE', 3600)
cache.set(cache_key, list(self.containers), expires)
return self.containers
| Add new approach on taglist get_queryset | Add new approach on taglist get_queryset
| Python | mit | jeanmask/opps,YACOWS/opps,opps/opps,opps/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,williamroot/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,opps/opps,williamroot/opps,YACOWS/opps,opps/opps,YACOWS/opps | from django.utils import timezone
from django.contrib.sites.models import get_current_site
+ from django.core.cache import cache
+ from django.conf import settings
from opps.views.generic.list import ListView
from opps.containers.models import Container
+
+ from .models import Tag
class TagList(ListView):
model = Container
template_name_suffix = '_tags'
def get_context_data(self, **kwargs):
context = super(TagList, self).get_context_data(**kwargs)
context['tag'] = self.kwargs['tag']
return context
def get_queryset(self):
self.site = get_current_site(self.request)
+ # without the long_slug, the queryset will cause an error
+ self.long_slug = 'tags'
- self.long_slug = self.kwargs['tag']
+ self.tag = self.kwargs['tag']
+
+ cache_key = 'taglist-{}'.format(self.tag)
+ if cache.get(cache_key):
+ return cache.get(cache_key)
+
+ tags = Tag.objects.filter(slug=self.tag).values_list('name') or []
+ tags_names = []
+ if tags:
+ tags_names = [i[0] for i in tags]
+
+ ids = []
+ for tag in tags_names:
- self.containers = self.model.objects.filter(
+ result = self.containers = self.model.objects.filter(
- site_domain=self.site,
+ site_domain=self.site,
- tags__icontains=self.long_slug,
+ tags__contains=tag,
- date_available__lte=timezone.now(),
+ date_available__lte=timezone.now(),
- published=True)
+ published=True
+ )
+ if result.exists():
+ ids.extend([i.id for i in result])
+
+ # remove the repeated
+ ids = list(set(ids))
+
+ # grab the containers
+ self.containers = self.model.objects.filter(id__in=ids)
+ expires = getattr(settings, 'OPPS_CACHE_EXPIRE', 3600)
+ cache.set(cache_key, list(self.containers), expires)
return self.containers
| Add new approach on taglist get_queryset | ## Code Before:
from django.utils import timezone
from django.contrib.sites.models import get_current_site
from opps.views.generic.list import ListView
from opps.containers.models import Container
class TagList(ListView):
model = Container
template_name_suffix = '_tags'
def get_context_data(self, **kwargs):
context = super(TagList, self).get_context_data(**kwargs)
context['tag'] = self.kwargs['tag']
return context
def get_queryset(self):
self.site = get_current_site(self.request)
self.long_slug = self.kwargs['tag']
self.containers = self.model.objects.filter(
site_domain=self.site,
tags__icontains=self.long_slug,
date_available__lte=timezone.now(),
published=True)
return self.containers
## Instruction:
Add new approach on taglist get_queryset
## Code After:
from django.utils import timezone
from django.contrib.sites.models import get_current_site
from django.core.cache import cache
from django.conf import settings
from opps.views.generic.list import ListView
from opps.containers.models import Container
from .models import Tag
class TagList(ListView):
model = Container
template_name_suffix = '_tags'
def get_context_data(self, **kwargs):
context = super(TagList, self).get_context_data(**kwargs)
context['tag'] = self.kwargs['tag']
return context
def get_queryset(self):
self.site = get_current_site(self.request)
# without the long_slug, the queryset will cause an error
self.long_slug = 'tags'
self.tag = self.kwargs['tag']
cache_key = 'taglist-{}'.format(self.tag)
if cache.get(cache_key):
return cache.get(cache_key)
tags = Tag.objects.filter(slug=self.tag).values_list('name') or []
tags_names = []
if tags:
tags_names = [i[0] for i in tags]
ids = []
for tag in tags_names:
result = self.containers = self.model.objects.filter(
site_domain=self.site,
tags__contains=tag,
date_available__lte=timezone.now(),
published=True
)
if result.exists():
ids.extend([i.id for i in result])
# remove the repeated
ids = list(set(ids))
# grab the containers
self.containers = self.model.objects.filter(id__in=ids)
expires = getattr(settings, 'OPPS_CACHE_EXPIRE', 3600)
cache.set(cache_key, list(self.containers), expires)
return self.containers
| ...
from django.utils import timezone
from django.contrib.sites.models import get_current_site
from django.core.cache import cache
from django.conf import settings
from opps.views.generic.list import ListView
from opps.containers.models import Container
from .models import Tag
...
def get_queryset(self):
self.site = get_current_site(self.request)
# without the long_slug, the queryset will cause an error
self.long_slug = 'tags'
self.tag = self.kwargs['tag']
cache_key = 'taglist-{}'.format(self.tag)
if cache.get(cache_key):
return cache.get(cache_key)
tags = Tag.objects.filter(slug=self.tag).values_list('name') or []
tags_names = []
if tags:
tags_names = [i[0] for i in tags]
ids = []
for tag in tags_names:
result = self.containers = self.model.objects.filter(
site_domain=self.site,
tags__contains=tag,
date_available__lte=timezone.now(),
published=True
)
if result.exists():
ids.extend([i.id for i in result])
# remove the repeated
ids = list(set(ids))
# grab the containers
self.containers = self.model.objects.filter(id__in=ids)
expires = getattr(settings, 'OPPS_CACHE_EXPIRE', 3600)
cache.set(cache_key, list(self.containers), expires)
return self.containers
... |
2a0c9cc447e1dffe2eb03c49c0c6801f4303a620 | plugins/imagetypes.py | plugins/imagetypes.py |
from rbuild import pluginapi
from rbuild.pluginapi import command
class ListImageTypesCommand(command.ListCommand):
help = "List image types"
resource = "imagetypes"
listFields = ("description", "name")
class ImageTypes(pluginapi.Plugin):
name = 'imagetypes'
def initialize(self):
for command, subcommand, commandClass in (
('list', 'imagetypes', ListImageTypesCommand),
):
cmd = self.handle.Commands.getCommandClass(command)
cmd.registerSubCommand(subcommand, commandClass)
def list(self):
rb = self.handle.facade.rbuilder
return [type for type in rb.getImageTypes() if type.name]
|
from rbuild import pluginapi
from rbuild.pluginapi import command
class ListImageTypesCommand(command.ListCommand):
help = "List image types"
resource = "imagetypes"
listFields = ("name", "description")
class ImageTypes(pluginapi.Plugin):
name = 'imagetypes'
def initialize(self):
for command, subcommand, commandClass in (
('list', 'imagetypes', ListImageTypesCommand),
):
cmd = self.handle.Commands.getCommandClass(command)
cmd.registerSubCommand(subcommand, commandClass)
def list(self):
rb = self.handle.facade.rbuilder
return [type for type in rb.getImageTypes() if type.name]
| Swap order of name and description when listing image types | Swap order of name and description when listing image types
Uses the same order as target types, which puts the most important information,
the name, in front.
Refs APPENG-3419
| Python | apache-2.0 | sassoftware/rbuild,sassoftware/rbuild |
from rbuild import pluginapi
from rbuild.pluginapi import command
class ListImageTypesCommand(command.ListCommand):
help = "List image types"
resource = "imagetypes"
- listFields = ("description", "name")
+ listFields = ("name", "description")
class ImageTypes(pluginapi.Plugin):
name = 'imagetypes'
def initialize(self):
for command, subcommand, commandClass in (
('list', 'imagetypes', ListImageTypesCommand),
):
cmd = self.handle.Commands.getCommandClass(command)
cmd.registerSubCommand(subcommand, commandClass)
def list(self):
rb = self.handle.facade.rbuilder
return [type for type in rb.getImageTypes() if type.name]
| Swap order of name and description when listing image types | ## Code Before:
from rbuild import pluginapi
from rbuild.pluginapi import command
class ListImageTypesCommand(command.ListCommand):
help = "List image types"
resource = "imagetypes"
listFields = ("description", "name")
class ImageTypes(pluginapi.Plugin):
name = 'imagetypes'
def initialize(self):
for command, subcommand, commandClass in (
('list', 'imagetypes', ListImageTypesCommand),
):
cmd = self.handle.Commands.getCommandClass(command)
cmd.registerSubCommand(subcommand, commandClass)
def list(self):
rb = self.handle.facade.rbuilder
return [type for type in rb.getImageTypes() if type.name]
## Instruction:
Swap order of name and description when listing image types
## Code After:
from rbuild import pluginapi
from rbuild.pluginapi import command
class ListImageTypesCommand(command.ListCommand):
help = "List image types"
resource = "imagetypes"
listFields = ("name", "description")
class ImageTypes(pluginapi.Plugin):
name = 'imagetypes'
def initialize(self):
for command, subcommand, commandClass in (
('list', 'imagetypes', ListImageTypesCommand),
):
cmd = self.handle.Commands.getCommandClass(command)
cmd.registerSubCommand(subcommand, commandClass)
def list(self):
rb = self.handle.facade.rbuilder
return [type for type in rb.getImageTypes() if type.name]
| // ... existing code ...
help = "List image types"
resource = "imagetypes"
listFields = ("name", "description")
// ... rest of the code ... |
e27f04e9c8d5d74afdd9cd7d6990cad5ff6f6cb5 | api/v330/docking_event/serializers.py | api/v330/docking_event/serializers.py | from api.v330.common.serializers import *
class SpacecraftFlightSerializerForDockingEvent(serializers.HyperlinkedModelSerializer):
spacecraft = SpacecraftSerializer(read_only=True, many=False)
class Meta:
model = SpacecraftFlight
fields = ('id', 'url', 'destination', 'splashdown', 'spacecraft')
class DockingEventSerializer(serializers.HyperlinkedModelSerializer):
flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True)
docking_location = serializers.StringRelatedField(many=False, read_only=True)
class Meta:
model = DockingEvent
fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location')
class DockingEventDetailedSerializer(serializers.HyperlinkedModelSerializer):
flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True, many=False)
docking_location = serializers.StringRelatedField(many=False, read_only=True)
class Meta:
model = DockingEvent
fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location')
| from api.v330.common.serializers import *
class SpacecraftFlightSerializerForDockingEvent(serializers.HyperlinkedModelSerializer):
spacecraft = SpacecraftSerializer(read_only=True, many=False)
class Meta:
model = SpacecraftFlight
fields = ('id', 'url', 'destination', 'splashdown', 'spacecraft')
class SpaceStationSerializerForDockingEvent(serializers.HyperlinkedModelSerializer):
class Meta:
model = SpaceStation
fields = ('id', 'url', 'name', 'image_url')
class DockingEventSerializer(serializers.HyperlinkedModelSerializer):
flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True)
docking_location = serializers.StringRelatedField(many=False, read_only=True)
class Meta:
model = DockingEvent
fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location')
class DockingEventDetailedSerializer(serializers.HyperlinkedModelSerializer):
flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True, many=False)
docking_location = serializers.StringRelatedField(many=False, read_only=True)
space_station = SpaceStationSerializerForDockingEvent(many=False, read_only=True)
class Meta:
model = DockingEvent
fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location', 'space_station')
| Add space_station field to detailed docking event | Add space_station field to detailed docking event
| Python | apache-2.0 | ItsCalebJones/SpaceLaunchNow-Server,ItsCalebJones/SpaceLaunchNow-Server,ItsCalebJones/SpaceLaunchNow-Server | from api.v330.common.serializers import *
class SpacecraftFlightSerializerForDockingEvent(serializers.HyperlinkedModelSerializer):
spacecraft = SpacecraftSerializer(read_only=True, many=False)
class Meta:
model = SpacecraftFlight
fields = ('id', 'url', 'destination', 'splashdown', 'spacecraft')
+
+
+ class SpaceStationSerializerForDockingEvent(serializers.HyperlinkedModelSerializer):
+ class Meta:
+ model = SpaceStation
+ fields = ('id', 'url', 'name', 'image_url')
class DockingEventSerializer(serializers.HyperlinkedModelSerializer):
flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True)
docking_location = serializers.StringRelatedField(many=False, read_only=True)
class Meta:
model = DockingEvent
fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location')
class DockingEventDetailedSerializer(serializers.HyperlinkedModelSerializer):
flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True, many=False)
docking_location = serializers.StringRelatedField(many=False, read_only=True)
+ space_station = SpaceStationSerializerForDockingEvent(many=False, read_only=True)
class Meta:
model = DockingEvent
- fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location')
+ fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location', 'space_station')
| Add space_station field to detailed docking event | ## Code Before:
from api.v330.common.serializers import *
class SpacecraftFlightSerializerForDockingEvent(serializers.HyperlinkedModelSerializer):
spacecraft = SpacecraftSerializer(read_only=True, many=False)
class Meta:
model = SpacecraftFlight
fields = ('id', 'url', 'destination', 'splashdown', 'spacecraft')
class DockingEventSerializer(serializers.HyperlinkedModelSerializer):
flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True)
docking_location = serializers.StringRelatedField(many=False, read_only=True)
class Meta:
model = DockingEvent
fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location')
class DockingEventDetailedSerializer(serializers.HyperlinkedModelSerializer):
flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True, many=False)
docking_location = serializers.StringRelatedField(many=False, read_only=True)
class Meta:
model = DockingEvent
fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location')
## Instruction:
Add space_station field to detailed docking event
## Code After:
from api.v330.common.serializers import *
class SpacecraftFlightSerializerForDockingEvent(serializers.HyperlinkedModelSerializer):
spacecraft = SpacecraftSerializer(read_only=True, many=False)
class Meta:
model = SpacecraftFlight
fields = ('id', 'url', 'destination', 'splashdown', 'spacecraft')
class SpaceStationSerializerForDockingEvent(serializers.HyperlinkedModelSerializer):
class Meta:
model = SpaceStation
fields = ('id', 'url', 'name', 'image_url')
class DockingEventSerializer(serializers.HyperlinkedModelSerializer):
flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True)
docking_location = serializers.StringRelatedField(many=False, read_only=True)
class Meta:
model = DockingEvent
fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location')
class DockingEventDetailedSerializer(serializers.HyperlinkedModelSerializer):
flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True, many=False)
docking_location = serializers.StringRelatedField(many=False, read_only=True)
space_station = SpaceStationSerializerForDockingEvent(many=False, read_only=True)
class Meta:
model = DockingEvent
fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location', 'space_station')
| ...
model = SpacecraftFlight
fields = ('id', 'url', 'destination', 'splashdown', 'spacecraft')
class SpaceStationSerializerForDockingEvent(serializers.HyperlinkedModelSerializer):
class Meta:
model = SpaceStation
fields = ('id', 'url', 'name', 'image_url')
...
flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True, many=False)
docking_location = serializers.StringRelatedField(many=False, read_only=True)
space_station = SpaceStationSerializerForDockingEvent(many=False, read_only=True)
class Meta:
model = DockingEvent
fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location', 'space_station')
... |
63ad1bc8f237a90975c7fa883143021faa679efd | pkit/__init__.py | pkit/__init__.py | version = (0, 1, 0)
__title__ = "Process Kit"
__author__ = "Oleiade"
__license__ = "MIT"
__version__ = '.'.join(map(str, version))
from pkit.process import Process
| version = (0, 1, 0)
__title__ = "Process Kit"
__author__ = "Oleiade"
__license__ = "MIT"
__version__ = '.'.join(map(str, version))
| Add a wait option to Process.terminate | Add a wait option to Process.terminate
| Python | mit | botify-labs/process-kit | version = (0, 1, 0)
__title__ = "Process Kit"
__author__ = "Oleiade"
__license__ = "MIT"
__version__ = '.'.join(map(str, version))
- from pkit.process import Process
- | Add a wait option to Process.terminate | ## Code Before:
version = (0, 1, 0)
__title__ = "Process Kit"
__author__ = "Oleiade"
__license__ = "MIT"
__version__ = '.'.join(map(str, version))
from pkit.process import Process
## Instruction:
Add a wait option to Process.terminate
## Code After:
version = (0, 1, 0)
__title__ = "Process Kit"
__author__ = "Oleiade"
__license__ = "MIT"
__version__ = '.'.join(map(str, version))
| // ... existing code ...
__version__ = '.'.join(map(str, version))
// ... rest of the code ... |
df45251622e6b935b27022e36fcbd79e9228f989 | bonobo/commands/init.py | bonobo/commands/init.py | import os
def execute(name, branch, overwrite_if_exists=False):
try:
from cookiecutter.main import cookiecutter
except ImportError as exc:
raise ImportError(
'You must install "cookiecutter" to use this command.\n\n $ pip install cookiecutter\n'
) from exc
if os.listdir(os.getcwd()) == []:
overwrite_if_exists = True
return cookiecutter(
'https://github.com/python-bonobo/cookiecutter-bonobo.git',
extra_context={'name': name},
no_input=True,
checkout=branch,
overwrite_if_exists=overwrite_if_exists
)
def register(parser):
parser.add_argument('name')
parser.add_argument('--branch', '-b', default='master')
return execute
| import os
def execute(name, branch):
try:
from cookiecutter.main import cookiecutter
except ImportError as exc:
raise ImportError(
'You must install "cookiecutter" to use this command.\n\n $ pip install cookiecutter\n'
) from exc
overwrite_if_exists = False
project_path = os.path.join(os.getcwd(), name)
if os.path.isdir(project_path) and not os.listdir(project_path):
overwrite_if_exists = True
return cookiecutter(
'https://github.com/python-bonobo/cookiecutter-bonobo.git',
extra_context={'name': name},
no_input=True,
checkout=branch,
overwrite_if_exists=overwrite_if_exists
)
def register(parser):
parser.add_argument('name')
parser.add_argument('--branch', '-b', default='master')
return execute
| Check if target directory is empty instead of current directory and remove overwrite_if_exists argument | Check if target directory is empty instead of current directory and remove overwrite_if_exists argument
| Python | apache-2.0 | hartym/bonobo,python-bonobo/bonobo,hartym/bonobo,hartym/bonobo,python-bonobo/bonobo,python-bonobo/bonobo | import os
- def execute(name, branch, overwrite_if_exists=False):
+ def execute(name, branch):
try:
from cookiecutter.main import cookiecutter
except ImportError as exc:
raise ImportError(
'You must install "cookiecutter" to use this command.\n\n $ pip install cookiecutter\n'
) from exc
- if os.listdir(os.getcwd()) == []:
+ overwrite_if_exists = False
+ project_path = os.path.join(os.getcwd(), name)
+ if os.path.isdir(project_path) and not os.listdir(project_path):
overwrite_if_exists = True
return cookiecutter(
'https://github.com/python-bonobo/cookiecutter-bonobo.git',
extra_context={'name': name},
no_input=True,
checkout=branch,
overwrite_if_exists=overwrite_if_exists
)
def register(parser):
parser.add_argument('name')
parser.add_argument('--branch', '-b', default='master')
return execute
| Check if target directory is empty instead of current directory and remove overwrite_if_exists argument | ## Code Before:
import os
def execute(name, branch, overwrite_if_exists=False):
try:
from cookiecutter.main import cookiecutter
except ImportError as exc:
raise ImportError(
'You must install "cookiecutter" to use this command.\n\n $ pip install cookiecutter\n'
) from exc
if os.listdir(os.getcwd()) == []:
overwrite_if_exists = True
return cookiecutter(
'https://github.com/python-bonobo/cookiecutter-bonobo.git',
extra_context={'name': name},
no_input=True,
checkout=branch,
overwrite_if_exists=overwrite_if_exists
)
def register(parser):
parser.add_argument('name')
parser.add_argument('--branch', '-b', default='master')
return execute
## Instruction:
Check if target directory is empty instead of current directory and remove overwrite_if_exists argument
## Code After:
import os
def execute(name, branch):
try:
from cookiecutter.main import cookiecutter
except ImportError as exc:
raise ImportError(
'You must install "cookiecutter" to use this command.\n\n $ pip install cookiecutter\n'
) from exc
overwrite_if_exists = False
project_path = os.path.join(os.getcwd(), name)
if os.path.isdir(project_path) and not os.listdir(project_path):
overwrite_if_exists = True
return cookiecutter(
'https://github.com/python-bonobo/cookiecutter-bonobo.git',
extra_context={'name': name},
no_input=True,
checkout=branch,
overwrite_if_exists=overwrite_if_exists
)
def register(parser):
parser.add_argument('name')
parser.add_argument('--branch', '-b', default='master')
return execute
| // ... existing code ...
import os
def execute(name, branch):
try:
from cookiecutter.main import cookiecutter
// ... modified code ...
) from exc
overwrite_if_exists = False
project_path = os.path.join(os.getcwd(), name)
if os.path.isdir(project_path) and not os.listdir(project_path):
overwrite_if_exists = True
// ... rest of the code ... |
f9d17e97115d914c9ed231630d01a6d724378f15 | zou/app/blueprints/source/csv/persons.py | zou/app/blueprints/source/csv/persons.py | from zou.app.blueprints.source.csv.base import BaseCsvImportResource
from zou.app.models.person import Person
from zou.app.utils import auth, permissions
from sqlalchemy.exc import IntegrityError
class PersonsCsvImportResource(BaseCsvImportResource):
def check_permissions(self):
return permissions.check_admin_permissions()
def import_row(self, row):
first_name = row["First Name"]
last_name = row["Last Name"]
email = row["Email"]
phone = row["Phone"]
try:
password = auth.encrypt_password("default")
person = Person.get_by(email=email)
if person is None:
person = Person.create(
email=email,
password=password,
first_name=first_name,
last_name=last_name,
phone=phone
)
else:
person.update({
"first_name": first_name,
"last_name": last_name,
"phone": phone
})
except IntegrityError:
person = Person.get_by(email=email)
return person.serialize_safe()
| from zou.app.blueprints.source.csv.base import BaseCsvImportResource
from zou.app.models.person import Person
from zou.app.utils import auth, permissions
from sqlalchemy.exc import IntegrityError
class PersonsCsvImportResource(BaseCsvImportResource):
def check_permissions(self):
return permissions.check_admin_permissions()
def import_row(self, row):
first_name = row["First Name"]
last_name = row["Last Name"]
email = row["Email"]
phone = row["Phone"]
role = row.get("Role", None)
if role == "Studio Manager":
role = "admin"
elif role == "Supervisor":
role = "manager"
elif role == "Client":
role = "client"
if role is not None and \
len(role) > 0 and \
role not in ["admin", "manager"]:
role = "user"
try:
password = auth.encrypt_password("default")
person = Person.get_by(email=email)
if person is None:
person = Person.create(
email=email,
password=password,
first_name=first_name,
last_name=last_name,
phone=phone,
role=role
)
else:
data = {
"first_name": first_name,
"last_name": last_name,
"phone": phone
}
if role is not None and len(role) > 0:
data["role"] = role
person.update(data)
except IntegrityError:
person = Person.get_by(email=email)
return person.serialize_safe()
| Allow to import roles when importing people | Allow to import roles when importing people
| Python | agpl-3.0 | cgwire/zou | from zou.app.blueprints.source.csv.base import BaseCsvImportResource
from zou.app.models.person import Person
from zou.app.utils import auth, permissions
from sqlalchemy.exc import IntegrityError
class PersonsCsvImportResource(BaseCsvImportResource):
def check_permissions(self):
return permissions.check_admin_permissions()
def import_row(self, row):
first_name = row["First Name"]
last_name = row["Last Name"]
email = row["Email"]
phone = row["Phone"]
+ role = row.get("Role", None)
+
+ if role == "Studio Manager":
+ role = "admin"
+ elif role == "Supervisor":
+ role = "manager"
+ elif role == "Client":
+ role = "client"
+
+ if role is not None and \
+ len(role) > 0 and \
+ role not in ["admin", "manager"]:
+ role = "user"
try:
password = auth.encrypt_password("default")
person = Person.get_by(email=email)
if person is None:
person = Person.create(
email=email,
password=password,
first_name=first_name,
last_name=last_name,
- phone=phone
+ phone=phone,
+ role=role
)
else:
- person.update({
+ data = {
"first_name": first_name,
"last_name": last_name,
"phone": phone
- })
+ }
+ if role is not None and len(role) > 0:
+ data["role"] = role
+ person.update(data)
except IntegrityError:
person = Person.get_by(email=email)
return person.serialize_safe()
| Allow to import roles when importing people | ## Code Before:
from zou.app.blueprints.source.csv.base import BaseCsvImportResource
from zou.app.models.person import Person
from zou.app.utils import auth, permissions
from sqlalchemy.exc import IntegrityError
class PersonsCsvImportResource(BaseCsvImportResource):
def check_permissions(self):
return permissions.check_admin_permissions()
def import_row(self, row):
first_name = row["First Name"]
last_name = row["Last Name"]
email = row["Email"]
phone = row["Phone"]
try:
password = auth.encrypt_password("default")
person = Person.get_by(email=email)
if person is None:
person = Person.create(
email=email,
password=password,
first_name=first_name,
last_name=last_name,
phone=phone
)
else:
person.update({
"first_name": first_name,
"last_name": last_name,
"phone": phone
})
except IntegrityError:
person = Person.get_by(email=email)
return person.serialize_safe()
## Instruction:
Allow to import roles when importing people
## Code After:
from zou.app.blueprints.source.csv.base import BaseCsvImportResource
from zou.app.models.person import Person
from zou.app.utils import auth, permissions
from sqlalchemy.exc import IntegrityError
class PersonsCsvImportResource(BaseCsvImportResource):
def check_permissions(self):
return permissions.check_admin_permissions()
def import_row(self, row):
first_name = row["First Name"]
last_name = row["Last Name"]
email = row["Email"]
phone = row["Phone"]
role = row.get("Role", None)
if role == "Studio Manager":
role = "admin"
elif role == "Supervisor":
role = "manager"
elif role == "Client":
role = "client"
if role is not None and \
len(role) > 0 and \
role not in ["admin", "manager"]:
role = "user"
try:
password = auth.encrypt_password("default")
person = Person.get_by(email=email)
if person is None:
person = Person.create(
email=email,
password=password,
first_name=first_name,
last_name=last_name,
phone=phone,
role=role
)
else:
data = {
"first_name": first_name,
"last_name": last_name,
"phone": phone
}
if role is not None and len(role) > 0:
data["role"] = role
person.update(data)
except IntegrityError:
person = Person.get_by(email=email)
return person.serialize_safe()
| # ... existing code ...
email = row["Email"]
phone = row["Phone"]
role = row.get("Role", None)
if role == "Studio Manager":
role = "admin"
elif role == "Supervisor":
role = "manager"
elif role == "Client":
role = "client"
if role is not None and \
len(role) > 0 and \
role not in ["admin", "manager"]:
role = "user"
try:
# ... modified code ...
first_name=first_name,
last_name=last_name,
phone=phone,
role=role
)
else:
data = {
"first_name": first_name,
"last_name": last_name,
"phone": phone
}
if role is not None and len(role) > 0:
data["role"] = role
person.update(data)
except IntegrityError:
person = Person.get_by(email=email)
# ... rest of the code ... |
582edd6bd36e8b40a37a8aaaa013704b5cd73ad6 | dotbot/config.py | dotbot/config.py | import yaml
import json
import os.path
from .util import string
class ConfigReader(object):
def __init__(self, config_file_path):
self._config = self._read(config_file_path)
def _read(self, config_file_path):
try:
_, ext = os.path.splitext(config_file_path)
with open(config_file_path) as fin:
print ext
if ext == '.json':
data = json.load(fin)
else:
data = yaml.safe_load(fin)
return data
except Exception as e:
msg = string.indent_lines(str(e))
raise ReadingError('Could not read config file:\n%s' % msg)
def get_config(self):
return self._config
class ReadingError(Exception):
pass
| import yaml
import json
import os.path
from .util import string
class ConfigReader(object):
def __init__(self, config_file_path):
self._config = self._read(config_file_path)
def _read(self, config_file_path):
try:
_, ext = os.path.splitext(config_file_path)
with open(config_file_path) as fin:
if ext == '.json':
data = json.load(fin)
else:
data = yaml.safe_load(fin)
return data
except Exception as e:
msg = string.indent_lines(str(e))
raise ReadingError('Could not read config file:\n%s' % msg)
def get_config(self):
return self._config
class ReadingError(Exception):
pass
| Fix compatibility with Python 3 | Fix compatibility with Python 3
This patch removes a stray print statement that was causing problems
with Python 3.
| Python | mit | bchretien/dotbot,imattman/dotbot,imattman/dotbot,anishathalye/dotbot,anishathalye/dotbot,bchretien/dotbot,bchretien/dotbot,imattman/dotbot | import yaml
import json
import os.path
from .util import string
class ConfigReader(object):
def __init__(self, config_file_path):
self._config = self._read(config_file_path)
def _read(self, config_file_path):
try:
_, ext = os.path.splitext(config_file_path)
with open(config_file_path) as fin:
- print ext
if ext == '.json':
data = json.load(fin)
else:
data = yaml.safe_load(fin)
return data
except Exception as e:
msg = string.indent_lines(str(e))
raise ReadingError('Could not read config file:\n%s' % msg)
def get_config(self):
return self._config
class ReadingError(Exception):
pass
| Fix compatibility with Python 3 | ## Code Before:
import yaml
import json
import os.path
from .util import string
class ConfigReader(object):
def __init__(self, config_file_path):
self._config = self._read(config_file_path)
def _read(self, config_file_path):
try:
_, ext = os.path.splitext(config_file_path)
with open(config_file_path) as fin:
print ext
if ext == '.json':
data = json.load(fin)
else:
data = yaml.safe_load(fin)
return data
except Exception as e:
msg = string.indent_lines(str(e))
raise ReadingError('Could not read config file:\n%s' % msg)
def get_config(self):
return self._config
class ReadingError(Exception):
pass
## Instruction:
Fix compatibility with Python 3
## Code After:
import yaml
import json
import os.path
from .util import string
class ConfigReader(object):
def __init__(self, config_file_path):
self._config = self._read(config_file_path)
def _read(self, config_file_path):
try:
_, ext = os.path.splitext(config_file_path)
with open(config_file_path) as fin:
if ext == '.json':
data = json.load(fin)
else:
data = yaml.safe_load(fin)
return data
except Exception as e:
msg = string.indent_lines(str(e))
raise ReadingError('Could not read config file:\n%s' % msg)
def get_config(self):
return self._config
class ReadingError(Exception):
pass
| // ... existing code ...
_, ext = os.path.splitext(config_file_path)
with open(config_file_path) as fin:
if ext == '.json':
data = json.load(fin)
// ... rest of the code ... |
78032531e9fe1ab99f6c0e021250754fe5375ab9 | src/zeit/content/article/edit/browser/tests/test_sync.py | src/zeit/content/article/edit/browser/tests/test_sync.py | import zeit.content.article.edit.browser.testing
class Supertitle(zeit.content.article.edit.browser.testing.EditorTestCase):
supertitle = 'article-content-head.supertitle'
teaser_supertitle = 'teaser-supertitle.teaserSupertitle'
layer = zeit.content.article.testing.WEBDRIVER_LAYER
def setUp(self):
super(Supertitle, self).setUp()
self.open('/repository/online/2007/01/Somalia/@@checkout')
self.selenium.waitForElementPresent('id=%s' % self.teaser_supertitle)
def test_teaser_supertitle_is_copied_to_article_supertitle_if_empty(self):
s = self.selenium
self.eval('document.getElementById("%s").value = ""' % self.supertitle)
s.click('//a[@href="edit-form-teaser"]')
s.type('id=%s' % self.teaser_supertitle, 'super\t')
# XXX There's nothing asynchronous going on here, but with a direct
# assert, the test fails with "Element is no longer attached to the
# DOM" (at least on WS's machine).
s.waitForValue('id=%s' % self.supertitle, 'super')
| import zeit.content.article.edit.browser.testing
import time
class Supertitle(zeit.content.article.edit.browser.testing.EditorTestCase):
supertitle = 'article-content-head.supertitle'
teaser_supertitle = 'teaser-supertitle.teaserSupertitle'
layer = zeit.content.article.testing.WEBDRIVER_LAYER
def setUp(self):
super(Supertitle, self).setUp()
self.open('/repository/online/2007/01/Somalia/@@checkout')
self.selenium.waitForElementPresent('id=%s' % self.teaser_supertitle)
def test_teaser_supertitle_is_copied_to_article_supertitle_if_empty(self):
s = self.selenium
self.eval('document.getElementById("%s").value = ""' % self.supertitle)
s.click('//a[@href="edit-form-teaser"]')
s.type('id=%s' % self.teaser_supertitle, 'super\t')
# We cannot use waitForValue, since the DOM element changes in-between
# but Selenium retrieves the element once and only checks the value
# repeatedly, thus leading to an error that DOM is no longer attached
for i in range(10):
try:
s.assertValue('id=%s' % self.supertitle, 'super')
break
except:
time.sleep(0.1)
continue
s.assertValue('id=%s' % self.supertitle, 'super')
| Fix test that may break with DOM element no longer attached, since the DOM element in question is reloaded. | Fix test that may break with DOM element no longer attached, since the DOM element in question is reloaded.
| Python | bsd-3-clause | ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article | import zeit.content.article.edit.browser.testing
+ import time
class Supertitle(zeit.content.article.edit.browser.testing.EditorTestCase):
supertitle = 'article-content-head.supertitle'
teaser_supertitle = 'teaser-supertitle.teaserSupertitle'
layer = zeit.content.article.testing.WEBDRIVER_LAYER
def setUp(self):
super(Supertitle, self).setUp()
self.open('/repository/online/2007/01/Somalia/@@checkout')
self.selenium.waitForElementPresent('id=%s' % self.teaser_supertitle)
def test_teaser_supertitle_is_copied_to_article_supertitle_if_empty(self):
s = self.selenium
self.eval('document.getElementById("%s").value = ""' % self.supertitle)
s.click('//a[@href="edit-form-teaser"]')
s.type('id=%s' % self.teaser_supertitle, 'super\t')
- # XXX There's nothing asynchronous going on here, but with a direct
- # assert, the test fails with "Element is no longer attached to the
- # DOM" (at least on WS's machine).
- s.waitForValue('id=%s' % self.supertitle, 'super')
+ # We cannot use waitForValue, since the DOM element changes in-between
+ # but Selenium retrieves the element once and only checks the value
+ # repeatedly, thus leading to an error that DOM is no longer attached
+ for i in range(10):
+ try:
+ s.assertValue('id=%s' % self.supertitle, 'super')
+ break
+ except:
+ time.sleep(0.1)
+ continue
+ s.assertValue('id=%s' % self.supertitle, 'super')
+ | Fix test that may break with DOM element no longer attached, since the DOM element in question is reloaded. | ## Code Before:
import zeit.content.article.edit.browser.testing
class Supertitle(zeit.content.article.edit.browser.testing.EditorTestCase):
supertitle = 'article-content-head.supertitle'
teaser_supertitle = 'teaser-supertitle.teaserSupertitle'
layer = zeit.content.article.testing.WEBDRIVER_LAYER
def setUp(self):
super(Supertitle, self).setUp()
self.open('/repository/online/2007/01/Somalia/@@checkout')
self.selenium.waitForElementPresent('id=%s' % self.teaser_supertitle)
def test_teaser_supertitle_is_copied_to_article_supertitle_if_empty(self):
s = self.selenium
self.eval('document.getElementById("%s").value = ""' % self.supertitle)
s.click('//a[@href="edit-form-teaser"]')
s.type('id=%s' % self.teaser_supertitle, 'super\t')
# XXX There's nothing asynchronous going on here, but with a direct
# assert, the test fails with "Element is no longer attached to the
# DOM" (at least on WS's machine).
s.waitForValue('id=%s' % self.supertitle, 'super')
## Instruction:
Fix test that may break with DOM element no longer attached, since the DOM element in question is reloaded.
## Code After:
import zeit.content.article.edit.browser.testing
import time
class Supertitle(zeit.content.article.edit.browser.testing.EditorTestCase):
supertitle = 'article-content-head.supertitle'
teaser_supertitle = 'teaser-supertitle.teaserSupertitle'
layer = zeit.content.article.testing.WEBDRIVER_LAYER
def setUp(self):
super(Supertitle, self).setUp()
self.open('/repository/online/2007/01/Somalia/@@checkout')
self.selenium.waitForElementPresent('id=%s' % self.teaser_supertitle)
def test_teaser_supertitle_is_copied_to_article_supertitle_if_empty(self):
s = self.selenium
self.eval('document.getElementById("%s").value = ""' % self.supertitle)
s.click('//a[@href="edit-form-teaser"]')
s.type('id=%s' % self.teaser_supertitle, 'super\t')
# We cannot use waitForValue, since the DOM element changes in-between
# but Selenium retrieves the element once and only checks the value
# repeatedly, thus leading to an error that DOM is no longer attached
for i in range(10):
try:
s.assertValue('id=%s' % self.supertitle, 'super')
break
except:
time.sleep(0.1)
continue
s.assertValue('id=%s' % self.supertitle, 'super')
| # ... existing code ...
import zeit.content.article.edit.browser.testing
import time
# ... modified code ...
s.click('//a[@href="edit-form-teaser"]')
s.type('id=%s' % self.teaser_supertitle, 'super\t')
# We cannot use waitForValue, since the DOM element changes in-between
# but Selenium retrieves the element once and only checks the value
# repeatedly, thus leading to an error that DOM is no longer attached
for i in range(10):
try:
s.assertValue('id=%s' % self.supertitle, 'super')
break
except:
time.sleep(0.1)
continue
s.assertValue('id=%s' % self.supertitle, 'super')
# ... rest of the code ... |
ff2def37816fbf1a8cf726914368036c0081e869 | tests/integration/shared.py | tests/integration/shared.py |
class ServiceTests(object):
def test_bash(self):
return self.check(
input='bc -q\n1+1\nquit()',
type='org.tyrion.service.bash',
output='2',
error='',
code='0',
)
def test_python(self):
return self.check(
input='print 1+1',
type='org.tyrion.service.python',
output='2',
error='',
code='0',
)
def test_ruby(self):
return self.check(
input='puts 1+1',
type='org.tyrion.service.ruby',
output='2',
error='',
code='0',
)
def test_timeout_error(self):
return self.check(
input='sleep 10',
type='org.tyrion.service.bash',
output='',
error=None,
code='15',
timeout=2,
)
|
class ServiceTests(object):
def test_bash(self):
return self.check(
input='bc -q\n1+1\nquit()',
type='org.tyrion.service.bash',
output='2',
error='',
code='0',
)
def test_python(self):
return self.check(
input='print 1+1',
type='org.tyrion.service.python',
output='2',
error='',
code='0',
)
def test_ruby(self):
return self.check(
input='puts 1+1',
type='org.tyrion.service.ruby',
output='2',
error='',
code='0',
)
def test_timeout_error(self):
return self.check(
input='echo test\nsleep 10',
type='org.tyrion.service.bash',
output='test',
error=None,
code='15',
timeout=1,
)
| Tweak integration timeout test to match gtest | Tweak integration timeout test to match gtest
| Python | mit | silas/tyrion,silas/tyrion,silas/tyrion,silas/tyrion,silas/tyrion |
class ServiceTests(object):
def test_bash(self):
return self.check(
input='bc -q\n1+1\nquit()',
type='org.tyrion.service.bash',
output='2',
error='',
code='0',
)
def test_python(self):
return self.check(
input='print 1+1',
type='org.tyrion.service.python',
output='2',
error='',
code='0',
)
def test_ruby(self):
return self.check(
input='puts 1+1',
type='org.tyrion.service.ruby',
output='2',
error='',
code='0',
)
def test_timeout_error(self):
return self.check(
- input='sleep 10',
+ input='echo test\nsleep 10',
type='org.tyrion.service.bash',
- output='',
+ output='test',
error=None,
code='15',
- timeout=2,
+ timeout=1,
)
| Tweak integration timeout test to match gtest | ## Code Before:
class ServiceTests(object):
def test_bash(self):
return self.check(
input='bc -q\n1+1\nquit()',
type='org.tyrion.service.bash',
output='2',
error='',
code='0',
)
def test_python(self):
return self.check(
input='print 1+1',
type='org.tyrion.service.python',
output='2',
error='',
code='0',
)
def test_ruby(self):
return self.check(
input='puts 1+1',
type='org.tyrion.service.ruby',
output='2',
error='',
code='0',
)
def test_timeout_error(self):
return self.check(
input='sleep 10',
type='org.tyrion.service.bash',
output='',
error=None,
code='15',
timeout=2,
)
## Instruction:
Tweak integration timeout test to match gtest
## Code After:
class ServiceTests(object):
def test_bash(self):
return self.check(
input='bc -q\n1+1\nquit()',
type='org.tyrion.service.bash',
output='2',
error='',
code='0',
)
def test_python(self):
return self.check(
input='print 1+1',
type='org.tyrion.service.python',
output='2',
error='',
code='0',
)
def test_ruby(self):
return self.check(
input='puts 1+1',
type='org.tyrion.service.ruby',
output='2',
error='',
code='0',
)
def test_timeout_error(self):
return self.check(
input='echo test\nsleep 10',
type='org.tyrion.service.bash',
output='test',
error=None,
code='15',
timeout=1,
)
| # ... existing code ...
def test_timeout_error(self):
return self.check(
input='echo test\nsleep 10',
type='org.tyrion.service.bash',
output='test',
error=None,
code='15',
timeout=1,
)
# ... rest of the code ... |
876d995967c5f8e580fc8e89fff859860b648057 | wagtail/wagtailimages/backends/pillow.py | wagtail/wagtailimages/backends/pillow.py | from __future__ import absolute_import
import PIL.Image
from wagtail.wagtailimages.backends.base import BaseImageBackend
class PillowBackend(BaseImageBackend):
def __init__(self, params):
super(PillowBackend, self).__init__(params)
def open_image(self, input_file):
image = PIL.Image.open(input_file)
return image
def save_image(self, image, output, format):
image.save(output, format, quality=self.quality)
def resize(self, image, size):
if image.mode in ['1', 'P']:
image = image.convert('RGB')
return image.resize(size, PIL.Image.ANTIALIAS)
def crop(self, image, rect):
return image.crop(rect)
def image_data_as_rgb(self, image):
# https://github.com/thumbor/thumbor/blob/f52360dc96eedd9fc914fcf19eaf2358f7e2480c/thumbor/engines/pil.py#L206-L215
if image.mode not in ['RGB', 'RGBA']:
if 'A' in image.mode:
image = image.convert('RGBA')
else:
image = image.convert('RGB')
return image.mode, image.tostring()
| from __future__ import absolute_import
import PIL.Image
from wagtail.wagtailimages.backends.base import BaseImageBackend
class PillowBackend(BaseImageBackend):
def __init__(self, params):
super(PillowBackend, self).__init__(params)
def open_image(self, input_file):
image = PIL.Image.open(input_file)
return image
def save_image(self, image, output, format):
image.save(output, format, quality=self.quality)
def resize(self, image, size):
if image.mode in ['1', 'P']:
if 'transparency' in image.info:
image = image.convert('RGBA')
else:
image = image.convert('RGB')
return image.resize(size, PIL.Image.ANTIALIAS)
def crop(self, image, rect):
return image.crop(rect)
def image_data_as_rgb(self, image):
# https://github.com/thumbor/thumbor/blob/f52360dc96eedd9fc914fcf19eaf2358f7e2480c/thumbor/engines/pil.py#L206-L215
if image.mode not in ['RGB', 'RGBA']:
if 'A' in image.mode:
image = image.convert('RGBA')
else:
image = image.convert('RGB')
return image.mode, image.tostring()
| Convert P images with transparency into RGBA | Convert P images with transparency into RGBA
Fixes #800
| Python | bsd-3-clause | jorge-marques/wagtail,gasman/wagtail,mikedingjan/wagtail,takeflight/wagtail,nimasmi/wagtail,chimeno/wagtail,kurtrwall/wagtail,Pennebaker/wagtail,mephizzle/wagtail,zerolab/wagtail,gogobook/wagtail,inonit/wagtail,m-sanders/wagtail,mikedingjan/wagtail,nealtodd/wagtail,timorieber/wagtail,takeshineshiro/wagtail,nutztherookie/wagtail,zerolab/wagtail,JoshBarr/wagtail,thenewguy/wagtail,nilnvoid/wagtail,janusnic/wagtail,benjaoming/wagtail,jordij/wagtail,zerolab/wagtail,dresiu/wagtail,takeshineshiro/wagtail,jorge-marques/wagtail,rsalmaso/wagtail,tangentlabs/wagtail,mayapurmedia/wagtail,jorge-marques/wagtail,marctc/wagtail,marctc/wagtail,taedori81/wagtail,darith27/wagtail,nimasmi/wagtail,davecranwell/wagtail,davecranwell/wagtail,jorge-marques/wagtail,nealtodd/wagtail,chrxr/wagtail,rv816/wagtail,mayapurmedia/wagtail,serzans/wagtail,stevenewey/wagtail,mixxorz/wagtail,mayapurmedia/wagtail,torchbox/wagtail,thenewguy/wagtail,inonit/wagtail,kaedroho/wagtail,FlipperPA/wagtail,tangentlabs/wagtail,gogobook/wagtail,bjesus/wagtail,torchbox/wagtail,chrxr/wagtail,nimasmi/wagtail,kurtw/wagtail,wagtail/wagtail,WQuanfeng/wagtail,kurtw/wagtail,quru/wagtail,Tivix/wagtail,torchbox/wagtail,wagtail/wagtail,marctc/wagtail,WQuanfeng/wagtail,darith27/wagtail,kurtw/wagtail,mjec/wagtail,gasman/wagtail,mephizzle/wagtail,gasman/wagtail,nrsimha/wagtail,Toshakins/wagtail,JoshBarr/wagtail,Klaudit/wagtail,serzans/wagtail,Pennebaker/wagtail,Klaudit/wagtail,davecranwell/wagtail,stevenewey/wagtail,janusnic/wagtail,chimeno/wagtail,quru/wagtail,taedori81/wagtail,benjaoming/wagtail,jorge-marques/wagtail,mayapurmedia/wagtail,benjaoming/wagtail,iansprice/wagtail,JoshBarr/wagtail,nilnvoid/wagtail,mikedingjan/wagtail,hamsterbacke23/wagtail,gogobook/wagtail,kurtrwall/wagtail,m-sanders/wagtail,nimasmi/wagtail,kurtrwall/wagtail,inonit/wagtail,mephizzle/wagtail,chrxr/wagtail,Toshakins/wagtail,chimeno/wagtail,iansprice/wagtail,iho/wagtail,JoshBarr/wagtail,inonit/wagtail,tangentlabs/wagtail,takeflight/wagtail,wagtail/wagtail,rsalmaso/wagtail,hanpama/wagtail,WQuanfeng/wagtail,stevenewey/wagtail,Pennebaker/wagtail,jordij/wagtail,hanpama/wagtail,nilnvoid/wagtail,janusnic/wagtail,darith27/wagtail,kaedroho/wagtail,bjesus/wagtail,rv816/wagtail,torchbox/wagtail,rjsproxy/wagtail,mephizzle/wagtail,bjesus/wagtail,serzans/wagtail,taedori81/wagtail,kaedroho/wagtail,janusnic/wagtail,iansprice/wagtail,m-sanders/wagtail,mixxorz/wagtail,FlipperPA/wagtail,kaedroho/wagtail,iho/wagtail,stevenewey/wagtail,mjec/wagtail,iho/wagtail,dresiu/wagtail,chrxr/wagtail,Tivix/wagtail,chimeno/wagtail,quru/wagtail,wagtail/wagtail,mixxorz/wagtail,tangentlabs/wagtail,rjsproxy/wagtail,gogobook/wagtail,WQuanfeng/wagtail,dresiu/wagtail,taedori81/wagtail,FlipperPA/wagtail,benjaoming/wagtail,kaedroho/wagtail,nrsimha/wagtail,Toshakins/wagtail,Klaudit/wagtail,nrsimha/wagtail,mjec/wagtail,Pennebaker/wagtail,iho/wagtail,wagtail/wagtail,takeshineshiro/wagtail,rv816/wagtail,rjsproxy/wagtail,nutztherookie/wagtail,iansprice/wagtail,rsalmaso/wagtail,nutztherookie/wagtail,rsalmaso/wagtail,taedori81/wagtail,nealtodd/wagtail,zerolab/wagtail,thenewguy/wagtail,chimeno/wagtail,KimGlazebrook/wagtail-experiment,kurtw/wagtail,nutztherookie/wagtail,timorieber/wagtail,nilnvoid/wagtail,hamsterbacke23/wagtail,darith27/wagtail,hanpama/wagtail,KimGlazebrook/wagtail-experiment,hamsterbacke23/wagtail,jnns/wagtail,jordij/wagtail,rjsproxy/wagtail,mikedingjan/wagtail,marctc/wagtail,mjec/wagtail,rv816/wagtail,timorieber/wagtail,jnns/wagtail,mixxorz/wagtail,jnns/wagtail,serzans/wagtail,mixxorz/wagtail,nealtodd/wagtail,hanpama/wagtail,thenewguy/wagtail,m-sanders/wagtail,thenewguy/wagtail,nrsimha/wagtail,kurtrwall/wagtail,FlipperPA/wagtail,Klaudit/wagtail,dresiu/wagtail,gasman/wagtail,KimGlazebrook/wagtail-experiment,Tivix/wagtail,zerolab/wagtail,takeflight/wagtail,rsalmaso/wagtail,dresiu/wagtail,jordij/wagtail,Tivix/wagtail,takeshineshiro/wagtail,bjesus/wagtail,hamsterbacke23/wagtail,gasman/wagtail,timorieber/wagtail,jnns/wagtail,KimGlazebrook/wagtail-experiment,takeflight/wagtail,quru/wagtail,davecranwell/wagtail,Toshakins/wagtail | from __future__ import absolute_import
import PIL.Image
from wagtail.wagtailimages.backends.base import BaseImageBackend
class PillowBackend(BaseImageBackend):
def __init__(self, params):
super(PillowBackend, self).__init__(params)
def open_image(self, input_file):
image = PIL.Image.open(input_file)
return image
def save_image(self, image, output, format):
image.save(output, format, quality=self.quality)
def resize(self, image, size):
if image.mode in ['1', 'P']:
+ if 'transparency' in image.info:
+ image = image.convert('RGBA')
+ else:
- image = image.convert('RGB')
+ image = image.convert('RGB')
+
return image.resize(size, PIL.Image.ANTIALIAS)
def crop(self, image, rect):
return image.crop(rect)
def image_data_as_rgb(self, image):
# https://github.com/thumbor/thumbor/blob/f52360dc96eedd9fc914fcf19eaf2358f7e2480c/thumbor/engines/pil.py#L206-L215
if image.mode not in ['RGB', 'RGBA']:
if 'A' in image.mode:
image = image.convert('RGBA')
else:
image = image.convert('RGB')
return image.mode, image.tostring()
| Convert P images with transparency into RGBA | ## Code Before:
from __future__ import absolute_import
import PIL.Image
from wagtail.wagtailimages.backends.base import BaseImageBackend
class PillowBackend(BaseImageBackend):
def __init__(self, params):
super(PillowBackend, self).__init__(params)
def open_image(self, input_file):
image = PIL.Image.open(input_file)
return image
def save_image(self, image, output, format):
image.save(output, format, quality=self.quality)
def resize(self, image, size):
if image.mode in ['1', 'P']:
image = image.convert('RGB')
return image.resize(size, PIL.Image.ANTIALIAS)
def crop(self, image, rect):
return image.crop(rect)
def image_data_as_rgb(self, image):
# https://github.com/thumbor/thumbor/blob/f52360dc96eedd9fc914fcf19eaf2358f7e2480c/thumbor/engines/pil.py#L206-L215
if image.mode not in ['RGB', 'RGBA']:
if 'A' in image.mode:
image = image.convert('RGBA')
else:
image = image.convert('RGB')
return image.mode, image.tostring()
## Instruction:
Convert P images with transparency into RGBA
## Code After:
from __future__ import absolute_import
import PIL.Image
from wagtail.wagtailimages.backends.base import BaseImageBackend
class PillowBackend(BaseImageBackend):
def __init__(self, params):
super(PillowBackend, self).__init__(params)
def open_image(self, input_file):
image = PIL.Image.open(input_file)
return image
def save_image(self, image, output, format):
image.save(output, format, quality=self.quality)
def resize(self, image, size):
if image.mode in ['1', 'P']:
if 'transparency' in image.info:
image = image.convert('RGBA')
else:
image = image.convert('RGB')
return image.resize(size, PIL.Image.ANTIALIAS)
def crop(self, image, rect):
return image.crop(rect)
def image_data_as_rgb(self, image):
# https://github.com/thumbor/thumbor/blob/f52360dc96eedd9fc914fcf19eaf2358f7e2480c/thumbor/engines/pil.py#L206-L215
if image.mode not in ['RGB', 'RGBA']:
if 'A' in image.mode:
image = image.convert('RGBA')
else:
image = image.convert('RGB')
return image.mode, image.tostring()
| // ... existing code ...
def resize(self, image, size):
if image.mode in ['1', 'P']:
if 'transparency' in image.info:
image = image.convert('RGBA')
else:
image = image.convert('RGB')
return image.resize(size, PIL.Image.ANTIALIAS)
// ... rest of the code ... |
12791da5f9e4a19e670dcf8459572517d0f467cd | comics/urls.py | comics/urls.py | from __future__ import absolute_import
from django.conf import settings
from django.conf.urls import include, patterns
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.base import TemplateView
admin.autodiscover()
urlpatterns = patterns('',
# Robots not welcome
(r'^robots\.txt$', TemplateView.as_view(
template_name='robots.txt', content_type='text/plain')),
# User accounts management
(r'^account/', include('comics.accounts.urls')),
# API
(r'^api/', include('comics.api.urls')),
# Help, about and feedback
(r'^help/', include('comics.help.urls')),
# Comic crawler status
(r'^status/', include('comics.status.urls')),
# Django admin
(r'^admin/doc/', include('django.contrib.admindocs.urls')),
(r'^admin/', include(admin.site.urls)),
# Comics browsing. Must be last one included.
(r'^', include('comics.browser.urls')),
)
# Let Django host media if doing local development on runserver
if not settings.MEDIA_URL.startswith('http'):
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
urlpatterns += staticfiles_urlpatterns()
| from __future__ import absolute_import
from django.conf import settings
from django.conf.urls import include, patterns
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.base import TemplateView
admin.autodiscover()
urlpatterns = patterns(
'',
# Robots not welcome
(r'^robots\.txt$', TemplateView.as_view(
template_name='robots.txt', content_type='text/plain')),
# User accounts management
(r'^account/', include('comics.accounts.urls')),
# API
(r'^api/', include('comics.api.urls')),
# Help, about and feedback
(r'^help/', include('comics.help.urls')),
# Comic crawler status
(r'^status/', include('comics.status.urls')),
# Django admin
(r'^admin/doc/', include('django.contrib.admindocs.urls')),
(r'^admin/', include(admin.site.urls)),
# Comics browsing. Must be last one included.
(r'^', include('comics.browser.urls')),
)
# Let Django host media if doing local development on runserver
if not settings.MEDIA_URL.startswith('http'):
urlpatterns += patterns(
'',
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
urlpatterns += staticfiles_urlpatterns()
| Fix all warnings in top-level urlconf | flake8: Fix all warnings in top-level urlconf
| Python | agpl-3.0 | jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,datagutten/comics | from __future__ import absolute_import
from django.conf import settings
from django.conf.urls import include, patterns
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.base import TemplateView
admin.autodiscover()
- urlpatterns = patterns('',
+ urlpatterns = patterns(
+ '',
+
# Robots not welcome
(r'^robots\.txt$', TemplateView.as_view(
template_name='robots.txt', content_type='text/plain')),
# User accounts management
(r'^account/', include('comics.accounts.urls')),
# API
(r'^api/', include('comics.api.urls')),
# Help, about and feedback
(r'^help/', include('comics.help.urls')),
# Comic crawler status
(r'^status/', include('comics.status.urls')),
# Django admin
(r'^admin/doc/', include('django.contrib.admindocs.urls')),
(r'^admin/', include(admin.site.urls)),
# Comics browsing. Must be last one included.
(r'^', include('comics.browser.urls')),
)
# Let Django host media if doing local development on runserver
if not settings.MEDIA_URL.startswith('http'):
- urlpatterns += patterns('',
+ urlpatterns += patterns(
+ '',
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
urlpatterns += staticfiles_urlpatterns()
| Fix all warnings in top-level urlconf | ## Code Before:
from __future__ import absolute_import
from django.conf import settings
from django.conf.urls import include, patterns
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.base import TemplateView
admin.autodiscover()
urlpatterns = patterns('',
# Robots not welcome
(r'^robots\.txt$', TemplateView.as_view(
template_name='robots.txt', content_type='text/plain')),
# User accounts management
(r'^account/', include('comics.accounts.urls')),
# API
(r'^api/', include('comics.api.urls')),
# Help, about and feedback
(r'^help/', include('comics.help.urls')),
# Comic crawler status
(r'^status/', include('comics.status.urls')),
# Django admin
(r'^admin/doc/', include('django.contrib.admindocs.urls')),
(r'^admin/', include(admin.site.urls)),
# Comics browsing. Must be last one included.
(r'^', include('comics.browser.urls')),
)
# Let Django host media if doing local development on runserver
if not settings.MEDIA_URL.startswith('http'):
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
urlpatterns += staticfiles_urlpatterns()
## Instruction:
Fix all warnings in top-level urlconf
## Code After:
from __future__ import absolute_import
from django.conf import settings
from django.conf.urls import include, patterns
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.base import TemplateView
admin.autodiscover()
urlpatterns = patterns(
'',
# Robots not welcome
(r'^robots\.txt$', TemplateView.as_view(
template_name='robots.txt', content_type='text/plain')),
# User accounts management
(r'^account/', include('comics.accounts.urls')),
# API
(r'^api/', include('comics.api.urls')),
# Help, about and feedback
(r'^help/', include('comics.help.urls')),
# Comic crawler status
(r'^status/', include('comics.status.urls')),
# Django admin
(r'^admin/doc/', include('django.contrib.admindocs.urls')),
(r'^admin/', include(admin.site.urls)),
# Comics browsing. Must be last one included.
(r'^', include('comics.browser.urls')),
)
# Let Django host media if doing local development on runserver
if not settings.MEDIA_URL.startswith('http'):
urlpatterns += patterns(
'',
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
urlpatterns += staticfiles_urlpatterns()
| ...
admin.autodiscover()
urlpatterns = patterns(
'',
# Robots not welcome
(r'^robots\.txt$', TemplateView.as_view(
...
# Let Django host media if doing local development on runserver
if not settings.MEDIA_URL.startswith('http'):
urlpatterns += patterns(
'',
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
... |
7b4b2fcbcb9a95c07f09b71305afa0c5ce95fe99 | tenant_schemas/routers.py | tenant_schemas/routers.py | from django.conf import settings
class TenantSyncRouter(object):
"""
A router to control which applications will be synced,
depending if we are syncing the shared apps or the tenant apps.
"""
def allow_syncdb(self, db, model):
# the imports below need to be done here else django <1.5 goes crazy
# https://code.djangoproject.com/ticket/20704
from django.db import connection
from tenant_schemas.utils import get_public_schema_name, app_labels
if connection.schema_name == get_public_schema_name():
if model._meta.app_label not in app_labels(settings.SHARED_APPS):
return False
else:
if model._meta.app_label not in app_labels(settings.TENANT_APPS):
return False
return None
| from django.conf import settings
class TenantSyncRouter(object):
"""
A router to control which applications will be synced,
depending if we are syncing the shared apps or the tenant apps.
"""
def allow_migrate(self, db, model):
# the imports below need to be done here else django <1.5 goes crazy
# https://code.djangoproject.com/ticket/20704
from django.db import connection
from tenant_schemas.utils import get_public_schema_name, app_labels
if connection.schema_name == get_public_schema_name():
if model._meta.app_label not in app_labels(settings.SHARED_APPS):
return False
else:
if model._meta.app_label not in app_labels(settings.TENANT_APPS):
return False
return None
def allow_syncdb(self, db, model):
# allow_syncdb was changed to allow_migrate in django 1.7
return self.allow_migrate(db, model)
| Add database router allow_migrate() for Django 1.7 | Add database router allow_migrate() for Django 1.7
| Python | mit | goodtune/django-tenant-schemas,Mobytes/django-tenant-schemas,kajarenc/django-tenant-schemas,honur/django-tenant-schemas,mcanaves/django-tenant-schemas,ArtProcessors/django-tenant-schemas,goodtune/django-tenant-schemas,ArtProcessors/django-tenant-schemas,bernardopires/django-tenant-schemas,bernardopires/django-tenant-schemas,pombredanne/django-tenant-schemas | from django.conf import settings
class TenantSyncRouter(object):
"""
A router to control which applications will be synced,
depending if we are syncing the shared apps or the tenant apps.
"""
- def allow_syncdb(self, db, model):
+ def allow_migrate(self, db, model):
# the imports below need to be done here else django <1.5 goes crazy
# https://code.djangoproject.com/ticket/20704
from django.db import connection
from tenant_schemas.utils import get_public_schema_name, app_labels
if connection.schema_name == get_public_schema_name():
if model._meta.app_label not in app_labels(settings.SHARED_APPS):
return False
else:
if model._meta.app_label not in app_labels(settings.TENANT_APPS):
return False
return None
+ def allow_syncdb(self, db, model):
+ # allow_syncdb was changed to allow_migrate in django 1.7
+ return self.allow_migrate(db, model)
+ | Add database router allow_migrate() for Django 1.7 | ## Code Before:
from django.conf import settings
class TenantSyncRouter(object):
"""
A router to control which applications will be synced,
depending if we are syncing the shared apps or the tenant apps.
"""
def allow_syncdb(self, db, model):
# the imports below need to be done here else django <1.5 goes crazy
# https://code.djangoproject.com/ticket/20704
from django.db import connection
from tenant_schemas.utils import get_public_schema_name, app_labels
if connection.schema_name == get_public_schema_name():
if model._meta.app_label not in app_labels(settings.SHARED_APPS):
return False
else:
if model._meta.app_label not in app_labels(settings.TENANT_APPS):
return False
return None
## Instruction:
Add database router allow_migrate() for Django 1.7
## Code After:
from django.conf import settings
class TenantSyncRouter(object):
"""
A router to control which applications will be synced,
depending if we are syncing the shared apps or the tenant apps.
"""
def allow_migrate(self, db, model):
# the imports below need to be done here else django <1.5 goes crazy
# https://code.djangoproject.com/ticket/20704
from django.db import connection
from tenant_schemas.utils import get_public_schema_name, app_labels
if connection.schema_name == get_public_schema_name():
if model._meta.app_label not in app_labels(settings.SHARED_APPS):
return False
else:
if model._meta.app_label not in app_labels(settings.TENANT_APPS):
return False
return None
def allow_syncdb(self, db, model):
# allow_syncdb was changed to allow_migrate in django 1.7
return self.allow_migrate(db, model)
| // ... existing code ...
"""
def allow_migrate(self, db, model):
# the imports below need to be done here else django <1.5 goes crazy
# https://code.djangoproject.com/ticket/20704
// ... modified code ...
return None
def allow_syncdb(self, db, model):
# allow_syncdb was changed to allow_migrate in django 1.7
return self.allow_migrate(db, model)
// ... rest of the code ... |
8ce6aa788573aa10758375d58881f03ff438db16 | machete/base.py | machete/base.py | from datetime import datetime
from thunderdome.connection import setup
import thunderdome
setup(["localhost"], "machete")
class BaseVertex(thunderdome.Vertex):
created_at = thunderdome.DateTime(default=datetime.now)
class BaseEdge(thunderdome.Edge):
created_at = thunderdome.DateTime(default=datetime.now)
class CreatedBy(BaseEdge):
pass
| from datetime import datetime
from thunderdome.connection import setup
import thunderdome
setup(["localhost"], "machete")
class BaseVertex(thunderdome.Vertex):
created_at = thunderdome.DateTime(default=datetime.now)
def __repr__(self):
return "<{}:{}>".format(self.__class__.__name__, self.vid)
class BaseEdge(thunderdome.Edge):
created_at = thunderdome.DateTime(default=datetime.now)
def __repr__(self):
return "<{}:{}>".format(self.__class__.__name__, self.eid)
class CreatedBy(BaseEdge):
pass
| Add __repr__ To BaseVertex and BaseEdge | Add __repr__ To BaseVertex and BaseEdge
| Python | bsd-3-clause | rustyrazorblade/machete,rustyrazorblade/machete,rustyrazorblade/machete | from datetime import datetime
from thunderdome.connection import setup
import thunderdome
setup(["localhost"], "machete")
class BaseVertex(thunderdome.Vertex):
created_at = thunderdome.DateTime(default=datetime.now)
+ def __repr__(self):
+ return "<{}:{}>".format(self.__class__.__name__, self.vid)
+
class BaseEdge(thunderdome.Edge):
created_at = thunderdome.DateTime(default=datetime.now)
+
+ def __repr__(self):
+ return "<{}:{}>".format(self.__class__.__name__, self.eid)
class CreatedBy(BaseEdge):
pass
| Add __repr__ To BaseVertex and BaseEdge | ## Code Before:
from datetime import datetime
from thunderdome.connection import setup
import thunderdome
setup(["localhost"], "machete")
class BaseVertex(thunderdome.Vertex):
created_at = thunderdome.DateTime(default=datetime.now)
class BaseEdge(thunderdome.Edge):
created_at = thunderdome.DateTime(default=datetime.now)
class CreatedBy(BaseEdge):
pass
## Instruction:
Add __repr__ To BaseVertex and BaseEdge
## Code After:
from datetime import datetime
from thunderdome.connection import setup
import thunderdome
setup(["localhost"], "machete")
class BaseVertex(thunderdome.Vertex):
created_at = thunderdome.DateTime(default=datetime.now)
def __repr__(self):
return "<{}:{}>".format(self.__class__.__name__, self.vid)
class BaseEdge(thunderdome.Edge):
created_at = thunderdome.DateTime(default=datetime.now)
def __repr__(self):
return "<{}:{}>".format(self.__class__.__name__, self.eid)
class CreatedBy(BaseEdge):
pass
| # ... existing code ...
created_at = thunderdome.DateTime(default=datetime.now)
def __repr__(self):
return "<{}:{}>".format(self.__class__.__name__, self.vid)
class BaseEdge(thunderdome.Edge):
created_at = thunderdome.DateTime(default=datetime.now)
def __repr__(self):
return "<{}:{}>".format(self.__class__.__name__, self.eid)
# ... rest of the code ... |
cc754aeb16aa41f936d59a3b5746a3bec69489ef | sts/util/convenience.py | sts/util/convenience.py | import time
def timestamp_string():
return time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
def find(f, seq):
"""Return first item in sequence where f(item) == True."""
for item in seq:
if f(item):
return item
def find_index(f, seq):
"""Return the index of the first item in sequence where f(item) == True."""
for index, item in enumerate(seq):
if f(item):
return index
| import time
def is_sorted(l):
return all(l[i] <= l[i+1] for i in xrange(len(l)-1))
def is_strictly_sorted(l):
return all(l[i] < l[i+1] for i in xrange(len(l)-1))
def timestamp_string():
return time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
def find(f, seq):
"""Return first item in sequence where f(item) == True."""
for item in seq:
if f(item):
return item
def find_index(f, seq):
"""Return the index of the first item in sequence where f(item) == True."""
for index, item in enumerate(seq):
if f(item):
return index
| Add little functions for checking if a list is sorted without sorting it | Add little functions for checking if a list is sorted without sorting it
| Python | apache-2.0 | ucb-sts/sts,jmiserez/sts,jmiserez/sts,ucb-sts/sts | import time
+
+ def is_sorted(l):
+ return all(l[i] <= l[i+1] for i in xrange(len(l)-1))
+
+ def is_strictly_sorted(l):
+ return all(l[i] < l[i+1] for i in xrange(len(l)-1))
def timestamp_string():
return time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
def find(f, seq):
"""Return first item in sequence where f(item) == True."""
for item in seq:
if f(item):
return item
def find_index(f, seq):
"""Return the index of the first item in sequence where f(item) == True."""
for index, item in enumerate(seq):
if f(item):
return index
| Add little functions for checking if a list is sorted without sorting it | ## Code Before:
import time
def timestamp_string():
return time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
def find(f, seq):
"""Return first item in sequence where f(item) == True."""
for item in seq:
if f(item):
return item
def find_index(f, seq):
"""Return the index of the first item in sequence where f(item) == True."""
for index, item in enumerate(seq):
if f(item):
return index
## Instruction:
Add little functions for checking if a list is sorted without sorting it
## Code After:
import time
def is_sorted(l):
return all(l[i] <= l[i+1] for i in xrange(len(l)-1))
def is_strictly_sorted(l):
return all(l[i] < l[i+1] for i in xrange(len(l)-1))
def timestamp_string():
return time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
def find(f, seq):
"""Return first item in sequence where f(item) == True."""
for item in seq:
if f(item):
return item
def find_index(f, seq):
"""Return the index of the first item in sequence where f(item) == True."""
for index, item in enumerate(seq):
if f(item):
return index
| // ... existing code ...
import time
def is_sorted(l):
return all(l[i] <= l[i+1] for i in xrange(len(l)-1))
def is_strictly_sorted(l):
return all(l[i] < l[i+1] for i in xrange(len(l)-1))
def timestamp_string():
// ... rest of the code ... |
c08c437b22982667e8ed413739147caec6c5d1ca | api/preprints/urls.py | api/preprints/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.PreprintList.as_view(), name=views.PreprintList.view_name),
url(r'^(?P<node_id>\w+)/$', views.PreprintDetail.as_view(), name=views.PreprintDetail.view_name),
url(r'^(?P<node_id>\w+)/contributors/$', views.PreprintContributorsList.as_view(), name=views.PreprintContributorsList.view_name),
]
| from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.PreprintList.as_view(), name=views.PreprintList.view_name),
url(r'^(?P<node_id>\w+)/$', views.PreprintDetail.as_view(), name=views.PreprintDetail.view_name),
url(r'^(?P<node_id>\w+)/contributors/$', views.PreprintContributorsList.as_view(), name=views.PreprintContributorsList.view_name),
url(r'^(?P<node_id>\w+)/relationships/preprint_provider/$', views.PreprintToPreprintProviderRelationship.as_view(), name=views.PreprintToPreprintProviderRelationship.view_name),
]
| Add URL route for updating provider relationship | Add URL route for updating provider relationship
| Python | apache-2.0 | mluo613/osf.io,rdhyee/osf.io,samchrisinger/osf.io,leb2dg/osf.io,cslzchen/osf.io,chrisseto/osf.io,leb2dg/osf.io,binoculars/osf.io,mluo613/osf.io,Nesiehr/osf.io,Johnetordoff/osf.io,laurenrevere/osf.io,emetsger/osf.io,monikagrabowska/osf.io,rdhyee/osf.io,CenterForOpenScience/osf.io,binoculars/osf.io,icereval/osf.io,binoculars/osf.io,cslzchen/osf.io,caneruguz/osf.io,samchrisinger/osf.io,baylee-d/osf.io,TomBaxter/osf.io,crcresearch/osf.io,icereval/osf.io,laurenrevere/osf.io,CenterForOpenScience/osf.io,chennan47/osf.io,samchrisinger/osf.io,caseyrollins/osf.io,cslzchen/osf.io,mfraezz/osf.io,mattclark/osf.io,cwisecarver/osf.io,chennan47/osf.io,aaxelb/osf.io,erinspace/osf.io,emetsger/osf.io,rdhyee/osf.io,monikagrabowska/osf.io,alexschiller/osf.io,HalcyonChimera/osf.io,leb2dg/osf.io,brianjgeiger/osf.io,caneruguz/osf.io,saradbowman/osf.io,mfraezz/osf.io,erinspace/osf.io,sloria/osf.io,HalcyonChimera/osf.io,Johnetordoff/osf.io,chennan47/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,hmoco/osf.io,pattisdr/osf.io,caneruguz/osf.io,HalcyonChimera/osf.io,saradbowman/osf.io,brianjgeiger/osf.io,baylee-d/osf.io,acshi/osf.io,sloria/osf.io,mluo613/osf.io,Nesiehr/osf.io,alexschiller/osf.io,aaxelb/osf.io,TomBaxter/osf.io,mluo613/osf.io,brianjgeiger/osf.io,Nesiehr/osf.io,pattisdr/osf.io,leb2dg/osf.io,adlius/osf.io,caseyrollins/osf.io,chrisseto/osf.io,mfraezz/osf.io,caseyrollins/osf.io,crcresearch/osf.io,alexschiller/osf.io,felliott/osf.io,alexschiller/osf.io,alexschiller/osf.io,monikagrabowska/osf.io,adlius/osf.io,Johnetordoff/osf.io,monikagrabowska/osf.io,monikagrabowska/osf.io,CenterForOpenScience/osf.io,acshi/osf.io,rdhyee/osf.io,hmoco/osf.io,baylee-d/osf.io,cwisecarver/osf.io,mattclark/osf.io,cslzchen/osf.io,emetsger/osf.io,CenterForOpenScience/osf.io,brianjgeiger/osf.io,cwisecarver/osf.io,samchrisinger/osf.io,felliott/osf.io,caneruguz/osf.io,Nesiehr/osf.io,acshi/osf.io,mattclark/osf.io,felliott/osf.io,TomBaxter/osf.io,crcresearch/osf.io,acshi/osf.io,hmoco/osf.io,HalcyonChimera/osf.io,adlius/osf.io,mfraezz/osf.io,acshi/osf.io,emetsger/osf.io,sloria/osf.io,laurenrevere/osf.io,felliott/osf.io,chrisseto/osf.io,chrisseto/osf.io,aaxelb/osf.io,adlius/osf.io,icereval/osf.io,erinspace/osf.io,hmoco/osf.io,cwisecarver/osf.io,mluo613/osf.io,pattisdr/osf.io | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.PreprintList.as_view(), name=views.PreprintList.view_name),
url(r'^(?P<node_id>\w+)/$', views.PreprintDetail.as_view(), name=views.PreprintDetail.view_name),
url(r'^(?P<node_id>\w+)/contributors/$', views.PreprintContributorsList.as_view(), name=views.PreprintContributorsList.view_name),
+ url(r'^(?P<node_id>\w+)/relationships/preprint_provider/$', views.PreprintToPreprintProviderRelationship.as_view(), name=views.PreprintToPreprintProviderRelationship.view_name),
]
| Add URL route for updating provider relationship | ## Code Before:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.PreprintList.as_view(), name=views.PreprintList.view_name),
url(r'^(?P<node_id>\w+)/$', views.PreprintDetail.as_view(), name=views.PreprintDetail.view_name),
url(r'^(?P<node_id>\w+)/contributors/$', views.PreprintContributorsList.as_view(), name=views.PreprintContributorsList.view_name),
]
## Instruction:
Add URL route for updating provider relationship
## Code After:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.PreprintList.as_view(), name=views.PreprintList.view_name),
url(r'^(?P<node_id>\w+)/$', views.PreprintDetail.as_view(), name=views.PreprintDetail.view_name),
url(r'^(?P<node_id>\w+)/contributors/$', views.PreprintContributorsList.as_view(), name=views.PreprintContributorsList.view_name),
url(r'^(?P<node_id>\w+)/relationships/preprint_provider/$', views.PreprintToPreprintProviderRelationship.as_view(), name=views.PreprintToPreprintProviderRelationship.view_name),
]
| # ... existing code ...
url(r'^(?P<node_id>\w+)/$', views.PreprintDetail.as_view(), name=views.PreprintDetail.view_name),
url(r'^(?P<node_id>\w+)/contributors/$', views.PreprintContributorsList.as_view(), name=views.PreprintContributorsList.view_name),
url(r'^(?P<node_id>\w+)/relationships/preprint_provider/$', views.PreprintToPreprintProviderRelationship.as_view(), name=views.PreprintToPreprintProviderRelationship.view_name),
]
# ... rest of the code ... |
bee9373dcf852e7af9f0f1a78dcc17a0922f96fe | anchorhub/tests/test_main.py | anchorhub/tests/test_main.py | from nose.tools import *
import anchorhub.main as main
def test_one():
"""
main.py: Test defaults with local directory as input.
"""
main.main(['.'])
| from nose.tools import *
import anchorhub.main as main
from anchorhub.util.getanchorhubpath import get_anchorhub_path
from anchorhub.compatibility import get_path_separator
def test_one():
"""
main.py: Test defaults with local directory as input.
"""
main.main([get_anchorhub_path() + get_path_separator() +
'../sample/multi-file'])
| Modify main.py tests to use get_anchorhub_path() | Modify main.py tests to use get_anchorhub_path()
| Python | apache-2.0 | samjabrahams/anchorhub | from nose.tools import *
import anchorhub.main as main
+ from anchorhub.util.getanchorhubpath import get_anchorhub_path
+ from anchorhub.compatibility import get_path_separator
def test_one():
"""
main.py: Test defaults with local directory as input.
"""
- main.main(['.'])
+ main.main([get_anchorhub_path() + get_path_separator() +
+ '../sample/multi-file'])
| Modify main.py tests to use get_anchorhub_path() | ## Code Before:
from nose.tools import *
import anchorhub.main as main
def test_one():
"""
main.py: Test defaults with local directory as input.
"""
main.main(['.'])
## Instruction:
Modify main.py tests to use get_anchorhub_path()
## Code After:
from nose.tools import *
import anchorhub.main as main
from anchorhub.util.getanchorhubpath import get_anchorhub_path
from anchorhub.compatibility import get_path_separator
def test_one():
"""
main.py: Test defaults with local directory as input.
"""
main.main([get_anchorhub_path() + get_path_separator() +
'../sample/multi-file'])
| # ... existing code ...
import anchorhub.main as main
from anchorhub.util.getanchorhubpath import get_anchorhub_path
from anchorhub.compatibility import get_path_separator
# ... modified code ...
main.py: Test defaults with local directory as input.
"""
main.main([get_anchorhub_path() + get_path_separator() +
'../sample/multi-file'])
# ... rest of the code ... |
673d6cecfaeb0e919f30997f793ee2bb18e399ee | tempest/api_schema/response/compute/v2/hypervisors.py | tempest/api_schema/response/compute/v2/hypervisors.py |
import copy
from tempest.api_schema.response.compute import hypervisors
hypervisors_servers = copy.deepcopy(hypervisors.common_hypervisors_detail)
# Defining extra attributes for V3 show hypervisor schema
hypervisors_servers['response_body']['properties']['hypervisors']['items'][
'properties']['servers'] = {
'type': 'array',
'items': {
'type': 'object',
'properties': {
# NOTE: Now the type of 'id' is integer,
# but here allows 'string' also because we
# will be able to change it to 'uuid' in
# the future.
'id': {'type': ['integer', 'string']},
'name': {'type': 'string'}
}
}
}
# In V2 API, if there is no servers (VM) on the Hypervisor host then 'servers'
# attribute will not be present in response body So it is not 'required'.
|
import copy
from tempest.api_schema.response.compute import hypervisors
hypervisors_servers = copy.deepcopy(hypervisors.common_hypervisors_detail)
# Defining extra attributes for V3 show hypervisor schema
hypervisors_servers['response_body']['properties']['hypervisors']['items'][
'properties']['servers'] = {
'type': 'array',
'items': {
'type': 'object',
'properties': {
'uuid': {'type': 'string'},
'name': {'type': 'string'}
}
}
}
# In V2 API, if there is no servers (VM) on the Hypervisor host then 'servers'
# attribute will not be present in response body So it is not 'required'.
| Fix V2 hypervisor server schema attribute | Fix V2 hypervisor server schema attribute
Nova v2 hypervisor server API return attribute "uuid" in response's
server dict. Current response schema does not have this attribute instead
it contain "id" which is wrong.
This patch fix the above issue.
NOTE- "uuid" attribute in this API response is always a uuid.
Change-Id: I78c67834de930012b70874938f345524d69264ba
| Python | apache-2.0 | jaspreetw/tempest,openstack/tempest,Vaidyanath/tempest,vedujoshi/tempest,NexusIS/tempest,FujitsuEnablingSoftwareTechnologyGmbH/tempest,tonyli71/tempest,hayderimran7/tempest,xbezdick/tempest,akash1808/tempest,roopali8/tempest,tudorvio/tempest,alinbalutoiu/tempest,flyingfish007/tempest,manasi24/jiocloud-tempest-qatempest,flyingfish007/tempest,izadorozhna/tempest,afaheem88/tempest_neutron,queria/my-tempest,pczerkas/tempest,afaheem88/tempest,FujitsuEnablingSoftwareTechnologyGmbH/tempest,yamt/tempest,sebrandon1/tempest,bigswitch/tempest,masayukig/tempest,Tesora/tesora-tempest,manasi24/jiocloud-tempest-qatempest,hpcloud-mon/tempest,bigswitch/tempest,ebagdasa/tempest,openstack/tempest,neerja28/Tempest,izadorozhna/tempest,Tesora/tesora-tempest,NexusIS/tempest,jamielennox/tempest,eggmaster/tempest,roopali8/tempest,rzarzynski/tempest,yamt/tempest,queria/my-tempest,rzarzynski/tempest,vedujoshi/tempest,manasi24/tempest,redhat-cip/tempest,Juniper/tempest,varunarya10/tempest,redhat-cip/tempest,hpcloud-mon/tempest,rakeshmi/tempest,masayukig/tempest,JioCloud/tempest,Juniper/tempest,Juraci/tempest,cisco-openstack/tempest,dkalashnik/tempest,LIS/lis-tempest,rakeshmi/tempest,CiscoSystems/tempest,dkalashnik/tempest,nunogt/tempest,Lilywei123/tempest,tudorvio/tempest,tonyli71/tempest,pandeyop/tempest,danielmellado/tempest,neerja28/Tempest,Juraci/tempest,LIS/lis-tempest,JioCloud/tempest,danielmellado/tempest,zsoltdudas/lis-tempest,pczerkas/tempest,zsoltdudas/lis-tempest,eggmaster/tempest,manasi24/tempest,jamielennox/tempest,sebrandon1/tempest,afaheem88/tempest,varunarya10/tempest,afaheem88/tempest_neutron,Lilywei123/tempest,cisco-openstack/tempest,nunogt/tempest,pandeyop/tempest,hayderimran7/tempest,Vaidyanath/tempest,alinbalutoiu/tempest,ebagdasa/tempest,akash1808/tempest,xbezdick/tempest,jaspreetw/tempest,CiscoSystems/tempest |
import copy
from tempest.api_schema.response.compute import hypervisors
hypervisors_servers = copy.deepcopy(hypervisors.common_hypervisors_detail)
# Defining extra attributes for V3 show hypervisor schema
hypervisors_servers['response_body']['properties']['hypervisors']['items'][
'properties']['servers'] = {
'type': 'array',
'items': {
'type': 'object',
'properties': {
- # NOTE: Now the type of 'id' is integer,
- # but here allows 'string' also because we
- # will be able to change it to 'uuid' in
- # the future.
- 'id': {'type': ['integer', 'string']},
+ 'uuid': {'type': 'string'},
'name': {'type': 'string'}
}
}
}
# In V2 API, if there is no servers (VM) on the Hypervisor host then 'servers'
# attribute will not be present in response body So it is not 'required'.
| Fix V2 hypervisor server schema attribute | ## Code Before:
import copy
from tempest.api_schema.response.compute import hypervisors
hypervisors_servers = copy.deepcopy(hypervisors.common_hypervisors_detail)
# Defining extra attributes for V3 show hypervisor schema
hypervisors_servers['response_body']['properties']['hypervisors']['items'][
'properties']['servers'] = {
'type': 'array',
'items': {
'type': 'object',
'properties': {
# NOTE: Now the type of 'id' is integer,
# but here allows 'string' also because we
# will be able to change it to 'uuid' in
# the future.
'id': {'type': ['integer', 'string']},
'name': {'type': 'string'}
}
}
}
# In V2 API, if there is no servers (VM) on the Hypervisor host then 'servers'
# attribute will not be present in response body So it is not 'required'.
## Instruction:
Fix V2 hypervisor server schema attribute
## Code After:
import copy
from tempest.api_schema.response.compute import hypervisors
hypervisors_servers = copy.deepcopy(hypervisors.common_hypervisors_detail)
# Defining extra attributes for V3 show hypervisor schema
hypervisors_servers['response_body']['properties']['hypervisors']['items'][
'properties']['servers'] = {
'type': 'array',
'items': {
'type': 'object',
'properties': {
'uuid': {'type': 'string'},
'name': {'type': 'string'}
}
}
}
# In V2 API, if there is no servers (VM) on the Hypervisor host then 'servers'
# attribute will not be present in response body So it is not 'required'.
| ...
'type': 'object',
'properties': {
'uuid': {'type': 'string'},
'name': {'type': 'string'}
}
... |
6577b521ac8fd0f1c9007f819dc0c7ee27ef4955 | numba/typesystem/tests/test_type_properties.py | numba/typesystem/tests/test_type_properties.py | from numba.typesystem import *
assert int_.is_int
assert int_.is_numeric
assert long_.is_int
assert long_.is_numeric
assert not long_.is_long
assert float_.is_float
assert float_.is_numeric
assert double.is_float
assert double.is_numeric
assert not double.is_double
assert object_.is_object
assert list_.is_list
assert list_.is_object
assert list_type(int_, 2).is_list
assert list_type(int_, 2).is_object
assert function(void, [double]).is_function | from numba.typesystem import *
assert int_.is_int
assert int_.is_numeric
assert long_.is_int
assert long_.is_numeric
assert not long_.is_long
assert float_.is_float
assert float_.is_numeric
assert double.is_float
assert double.is_numeric
assert not double.is_double
assert object_.is_object
assert list_(int_, 2).is_list
assert list_(int_, 2).is_object
assert function(void, [double]).is_function | Update test for rename of list type | Update test for rename of list type
| Python | bsd-2-clause | gdementen/numba,GaZ3ll3/numba,stuartarchibald/numba,pitrou/numba,jriehl/numba,stefanseefeld/numba,ssarangi/numba,sklam/numba,IntelLabs/numba,gdementen/numba,jriehl/numba,stuartarchibald/numba,GaZ3ll3/numba,GaZ3ll3/numba,seibert/numba,numba/numba,pombredanne/numba,jriehl/numba,pitrou/numba,cpcloud/numba,gmarkall/numba,stefanseefeld/numba,pitrou/numba,gmarkall/numba,pitrou/numba,sklam/numba,pombredanne/numba,ssarangi/numba,jriehl/numba,gdementen/numba,pombredanne/numba,jriehl/numba,sklam/numba,cpcloud/numba,sklam/numba,numba/numba,gmarkall/numba,gdementen/numba,numba/numba,numba/numba,stonebig/numba,GaZ3ll3/numba,cpcloud/numba,IntelLabs/numba,GaZ3ll3/numba,ssarangi/numba,seibert/numba,gdementen/numba,sklam/numba,seibert/numba,pombredanne/numba,pitrou/numba,seibert/numba,stuartarchibald/numba,stonebig/numba,gmarkall/numba,seibert/numba,ssarangi/numba,stuartarchibald/numba,cpcloud/numba,cpcloud/numba,stefanseefeld/numba,stuartarchibald/numba,gmarkall/numba,IntelLabs/numba,stefanseefeld/numba,stonebig/numba,stonebig/numba,numba/numba,pombredanne/numba,stefanseefeld/numba,ssarangi/numba,stonebig/numba,IntelLabs/numba,IntelLabs/numba | from numba.typesystem import *
assert int_.is_int
assert int_.is_numeric
assert long_.is_int
assert long_.is_numeric
assert not long_.is_long
assert float_.is_float
assert float_.is_numeric
assert double.is_float
assert double.is_numeric
assert not double.is_double
assert object_.is_object
- assert list_.is_list
- assert list_.is_object
- assert list_type(int_, 2).is_list
+ assert list_(int_, 2).is_list
- assert list_type(int_, 2).is_object
+ assert list_(int_, 2).is_object
assert function(void, [double]).is_function | Update test for rename of list type | ## Code Before:
from numba.typesystem import *
assert int_.is_int
assert int_.is_numeric
assert long_.is_int
assert long_.is_numeric
assert not long_.is_long
assert float_.is_float
assert float_.is_numeric
assert double.is_float
assert double.is_numeric
assert not double.is_double
assert object_.is_object
assert list_.is_list
assert list_.is_object
assert list_type(int_, 2).is_list
assert list_type(int_, 2).is_object
assert function(void, [double]).is_function
## Instruction:
Update test for rename of list type
## Code After:
from numba.typesystem import *
assert int_.is_int
assert int_.is_numeric
assert long_.is_int
assert long_.is_numeric
assert not long_.is_long
assert float_.is_float
assert float_.is_numeric
assert double.is_float
assert double.is_numeric
assert not double.is_double
assert object_.is_object
assert list_(int_, 2).is_list
assert list_(int_, 2).is_object
assert function(void, [double]).is_function | ...
assert object_.is_object
assert list_(int_, 2).is_list
assert list_(int_, 2).is_object
assert function(void, [double]).is_function
... |
9ba9e26888578e66469a63e412f46cf151fbcfd7 | common/data_refinery_common/test_microarray.py | common/data_refinery_common/test_microarray.py | from unittest.mock import Mock, patch
from django.test import TestCase
from data_refinery_common import microarray
CEL_FILE_HUMAN = "test-files/C30057.CEL"
CEL_FILE_RAT = "test-files/SG2_u34a.CEL"
CEL_FILE_MOUSE = "test-files/97_(Mouse430_2).CEL"
CEL_FILE_ZEBRAFISH = "test-files/CONTROL6.cel"
class MicroarrayTestCase(TestCase):
def test_get_platform_from_CEL(self):
self.assertEqual("hgu95av2", microarray.get_platform_from_CEL(CEL_FILE_HUMAN))
self.assertEqual("rgu34a", microarray.get_platform_from_CEL(CEL_FILE_RAT))
self.assertEqual("mouse4302", microarray.get_platform_from_CEL(CEL_FILE_MOUSE))
self.assertEqual("zebgene11st", microarray.get_platform_from_CEL(CEL_FILE_ZEBRAFISH))
| from unittest.mock import Mock, patch
from django.test import TestCase
from data_refinery_common import microarray
CEL_FILE_HUMAN = "test-files/C30057.CEL.gz"
CEL_FILE_RAT = "test-files/SG2_u34a.CEL.gz"
CEL_FILE_MOUSE = "test-files/97_(Mouse430_2).CEL.gz"
CEL_FILE_ZEBRAFISH = "test-files/CONTROL6.cel.gz"
class MicroarrayTestCase(TestCase):
def test_get_platform_from_CEL(self):
self.assertEqual("hgu95av2", microarray.get_platform_from_CEL(CEL_FILE_HUMAN))
self.assertEqual("rgu34a", microarray.get_platform_from_CEL(CEL_FILE_RAT))
self.assertEqual("mouse4302", microarray.get_platform_from_CEL(CEL_FILE_MOUSE))
self.assertEqual("zebgene11st", microarray.get_platform_from_CEL(CEL_FILE_ZEBRAFISH))
| Update test file paths for common to point to compressed versions. | Update test file paths for common to point to compressed versions.
| Python | bsd-3-clause | data-refinery/data_refinery,data-refinery/data_refinery,data-refinery/data_refinery | from unittest.mock import Mock, patch
from django.test import TestCase
from data_refinery_common import microarray
- CEL_FILE_HUMAN = "test-files/C30057.CEL"
+ CEL_FILE_HUMAN = "test-files/C30057.CEL.gz"
- CEL_FILE_RAT = "test-files/SG2_u34a.CEL"
+ CEL_FILE_RAT = "test-files/SG2_u34a.CEL.gz"
- CEL_FILE_MOUSE = "test-files/97_(Mouse430_2).CEL"
+ CEL_FILE_MOUSE = "test-files/97_(Mouse430_2).CEL.gz"
- CEL_FILE_ZEBRAFISH = "test-files/CONTROL6.cel"
+ CEL_FILE_ZEBRAFISH = "test-files/CONTROL6.cel.gz"
class MicroarrayTestCase(TestCase):
def test_get_platform_from_CEL(self):
self.assertEqual("hgu95av2", microarray.get_platform_from_CEL(CEL_FILE_HUMAN))
self.assertEqual("rgu34a", microarray.get_platform_from_CEL(CEL_FILE_RAT))
self.assertEqual("mouse4302", microarray.get_platform_from_CEL(CEL_FILE_MOUSE))
self.assertEqual("zebgene11st", microarray.get_platform_from_CEL(CEL_FILE_ZEBRAFISH))
| Update test file paths for common to point to compressed versions. | ## Code Before:
from unittest.mock import Mock, patch
from django.test import TestCase
from data_refinery_common import microarray
CEL_FILE_HUMAN = "test-files/C30057.CEL"
CEL_FILE_RAT = "test-files/SG2_u34a.CEL"
CEL_FILE_MOUSE = "test-files/97_(Mouse430_2).CEL"
CEL_FILE_ZEBRAFISH = "test-files/CONTROL6.cel"
class MicroarrayTestCase(TestCase):
def test_get_platform_from_CEL(self):
self.assertEqual("hgu95av2", microarray.get_platform_from_CEL(CEL_FILE_HUMAN))
self.assertEqual("rgu34a", microarray.get_platform_from_CEL(CEL_FILE_RAT))
self.assertEqual("mouse4302", microarray.get_platform_from_CEL(CEL_FILE_MOUSE))
self.assertEqual("zebgene11st", microarray.get_platform_from_CEL(CEL_FILE_ZEBRAFISH))
## Instruction:
Update test file paths for common to point to compressed versions.
## Code After:
from unittest.mock import Mock, patch
from django.test import TestCase
from data_refinery_common import microarray
CEL_FILE_HUMAN = "test-files/C30057.CEL.gz"
CEL_FILE_RAT = "test-files/SG2_u34a.CEL.gz"
CEL_FILE_MOUSE = "test-files/97_(Mouse430_2).CEL.gz"
CEL_FILE_ZEBRAFISH = "test-files/CONTROL6.cel.gz"
class MicroarrayTestCase(TestCase):
def test_get_platform_from_CEL(self):
self.assertEqual("hgu95av2", microarray.get_platform_from_CEL(CEL_FILE_HUMAN))
self.assertEqual("rgu34a", microarray.get_platform_from_CEL(CEL_FILE_RAT))
self.assertEqual("mouse4302", microarray.get_platform_from_CEL(CEL_FILE_MOUSE))
self.assertEqual("zebgene11st", microarray.get_platform_from_CEL(CEL_FILE_ZEBRAFISH))
| ...
from data_refinery_common import microarray
CEL_FILE_HUMAN = "test-files/C30057.CEL.gz"
CEL_FILE_RAT = "test-files/SG2_u34a.CEL.gz"
CEL_FILE_MOUSE = "test-files/97_(Mouse430_2).CEL.gz"
CEL_FILE_ZEBRAFISH = "test-files/CONTROL6.cel.gz"
... |
33505f9b4dfeead0b01ee1b8cf3f8f228476e866 | openpassword/crypt_utils.py | openpassword/crypt_utils.py | from Crypto.Cipher import AES
def decrypt(data, key_iv):
key = key_iv[0:16]
iv = key_iv[16:]
print(data)
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.decrypt(data)
def encrypt(data, key_iv):
key = key_iv[0:16]
iv = key_iv[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.encrypt(data)
| from Crypto.Cipher import AES
def decrypt(data, key_iv):
key = key_iv[0:16]
iv = key_iv[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.decrypt(data)
def encrypt(data, key_iv):
key = key_iv[0:16]
iv = key_iv[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.encrypt(data)
| Remove print statement from crypto utils... | Remove print statement from crypto utils...
| Python | mit | openpassword/blimey,openpassword/blimey | from Crypto.Cipher import AES
def decrypt(data, key_iv):
key = key_iv[0:16]
iv = key_iv[16:]
- print(data)
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.decrypt(data)
def encrypt(data, key_iv):
key = key_iv[0:16]
iv = key_iv[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.encrypt(data)
| Remove print statement from crypto utils... | ## Code Before:
from Crypto.Cipher import AES
def decrypt(data, key_iv):
key = key_iv[0:16]
iv = key_iv[16:]
print(data)
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.decrypt(data)
def encrypt(data, key_iv):
key = key_iv[0:16]
iv = key_iv[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.encrypt(data)
## Instruction:
Remove print statement from crypto utils...
## Code After:
from Crypto.Cipher import AES
def decrypt(data, key_iv):
key = key_iv[0:16]
iv = key_iv[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.decrypt(data)
def encrypt(data, key_iv):
key = key_iv[0:16]
iv = key_iv[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.encrypt(data)
| # ... existing code ...
key = key_iv[0:16]
iv = key_iv[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.decrypt(data)
# ... rest of the code ... |
8fb574900a6680f8342487e32979829efa33a11a | spacy/about.py | spacy/about.py | __title__ = "spacy"
__version__ = "3.0.0.dev14"
__release__ = True
__download_url__ = "https://github.com/explosion/spacy-models/releases/download"
__compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
__shortcuts__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/shortcuts-v2.json"
__projects__ = "https://github.com/explosion/spacy-boilerplates"
| __title__ = "spacy_nightly"
__version__ = "3.0.0a0"
__release__ = True
__download_url__ = "https://github.com/explosion/spacy-models/releases/download"
__compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
__shortcuts__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/shortcuts-v2.json"
__projects__ = "https://github.com/explosion/spacy-boilerplates"
| Update parent package and version | Update parent package and version
| Python | mit | explosion/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy | - __title__ = "spacy"
+ __title__ = "spacy_nightly"
- __version__ = "3.0.0.dev14"
+ __version__ = "3.0.0a0"
__release__ = True
__download_url__ = "https://github.com/explosion/spacy-models/releases/download"
__compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
__shortcuts__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/shortcuts-v2.json"
__projects__ = "https://github.com/explosion/spacy-boilerplates"
| Update parent package and version | ## Code Before:
__title__ = "spacy"
__version__ = "3.0.0.dev14"
__release__ = True
__download_url__ = "https://github.com/explosion/spacy-models/releases/download"
__compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
__shortcuts__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/shortcuts-v2.json"
__projects__ = "https://github.com/explosion/spacy-boilerplates"
## Instruction:
Update parent package and version
## Code After:
__title__ = "spacy_nightly"
__version__ = "3.0.0a0"
__release__ = True
__download_url__ = "https://github.com/explosion/spacy-models/releases/download"
__compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
__shortcuts__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/shortcuts-v2.json"
__projects__ = "https://github.com/explosion/spacy-boilerplates"
| // ... existing code ...
__title__ = "spacy_nightly"
__version__ = "3.0.0a0"
__release__ = True
__download_url__ = "https://github.com/explosion/spacy-models/releases/download"
// ... rest of the code ... |
df038a485a2aaf80bcfbd872e94ffb87bcb5b33c | testinfra/__init__.py | testinfra/__init__.py |
from __future__ import unicode_literals
from testinfra.host import get_host
from testinfra.host import get_hosts
__all__ = ['get_host', 'get_hosts']
|
from __future__ import unicode_literals
import sys
from testinfra.host import get_host
from testinfra.host import get_hosts
__all__ = ['get_host', 'get_hosts']
if sys.version_info[0] == 2:
import warnings
class TestinfraDeprecationWarning(Warning):
pass
warnings.simplefilter("default", TestinfraDeprecationWarning)
warnings.warn(
'DEPRECATION: testinfra python2 support is unmaintained, please '
'upgrade to python3', category=TestinfraDeprecationWarning,
stacklevel=1)
| Add warning about unmaintained python2 | Add warning about unmaintained python2
| Python | apache-2.0 | philpep/testinfra |
from __future__ import unicode_literals
+ import sys
from testinfra.host import get_host
from testinfra.host import get_hosts
__all__ = ['get_host', 'get_hosts']
+ if sys.version_info[0] == 2:
+ import warnings
+
+ class TestinfraDeprecationWarning(Warning):
+ pass
+
+ warnings.simplefilter("default", TestinfraDeprecationWarning)
+ warnings.warn(
+ 'DEPRECATION: testinfra python2 support is unmaintained, please '
+ 'upgrade to python3', category=TestinfraDeprecationWarning,
+ stacklevel=1)
+ | Add warning about unmaintained python2 | ## Code Before:
from __future__ import unicode_literals
from testinfra.host import get_host
from testinfra.host import get_hosts
__all__ = ['get_host', 'get_hosts']
## Instruction:
Add warning about unmaintained python2
## Code After:
from __future__ import unicode_literals
import sys
from testinfra.host import get_host
from testinfra.host import get_hosts
__all__ = ['get_host', 'get_hosts']
if sys.version_info[0] == 2:
import warnings
class TestinfraDeprecationWarning(Warning):
pass
warnings.simplefilter("default", TestinfraDeprecationWarning)
warnings.warn(
'DEPRECATION: testinfra python2 support is unmaintained, please '
'upgrade to python3', category=TestinfraDeprecationWarning,
stacklevel=1)
| ...
from __future__ import unicode_literals
import sys
from testinfra.host import get_host
from testinfra.host import get_hosts
...
__all__ = ['get_host', 'get_hosts']
if sys.version_info[0] == 2:
import warnings
class TestinfraDeprecationWarning(Warning):
pass
warnings.simplefilter("default", TestinfraDeprecationWarning)
warnings.warn(
'DEPRECATION: testinfra python2 support is unmaintained, please '
'upgrade to python3', category=TestinfraDeprecationWarning,
stacklevel=1)
... |
d68935dfb34f7c5fc463f94e49f0c060717b17b8 | cmsplugin_contact_plus/checks.py | cmsplugin_contact_plus/checks.py | from django.core.checks import Warning, register
def warn_1_3_changes(app_configs, **kwargs):
return [
Warning(
'cmsplugin-contact-plus >= 1.3 has renamed the "input" field. Do not forget to migrate your '
'database and update your templates',
hint=None,
obj=None,
id='cmsplugin_contact_plus.W001',
)
]
def register_checks():
for check in [
warn_1_3_changes,
]:
register(check)
| from django.core.checks import Warning, register
def warn_1_3_changes(app_configs, **kwargs):
return [
Warning(
'cmsplugin-contact-plus >= 1.3 has renamed the "input" field. Do not forget to migrate your '
'database and update your templates',
hint=None,
obj=None,
id='cmsplugin_contact_plus.W001',
)
]
def register_checks():
for check in [
# warn_1_3_changes, # Might be more annoying than useful
]:
register(check)
| Comment out warning for renamed field | Comment out warning for renamed field
| Python | bsd-3-clause | arteria/cmsplugin-contact-plus,arteria/cmsplugin-contact-plus,worthwhile/cmsplugin-remote-form,worthwhile/cmsplugin-remote-form | from django.core.checks import Warning, register
def warn_1_3_changes(app_configs, **kwargs):
return [
Warning(
'cmsplugin-contact-plus >= 1.3 has renamed the "input" field. Do not forget to migrate your '
'database and update your templates',
hint=None,
obj=None,
id='cmsplugin_contact_plus.W001',
)
]
def register_checks():
for check in [
- warn_1_3_changes,
+ # warn_1_3_changes, # Might be more annoying than useful
]:
register(check)
| Comment out warning for renamed field | ## Code Before:
from django.core.checks import Warning, register
def warn_1_3_changes(app_configs, **kwargs):
return [
Warning(
'cmsplugin-contact-plus >= 1.3 has renamed the "input" field. Do not forget to migrate your '
'database and update your templates',
hint=None,
obj=None,
id='cmsplugin_contact_plus.W001',
)
]
def register_checks():
for check in [
warn_1_3_changes,
]:
register(check)
## Instruction:
Comment out warning for renamed field
## Code After:
from django.core.checks import Warning, register
def warn_1_3_changes(app_configs, **kwargs):
return [
Warning(
'cmsplugin-contact-plus >= 1.3 has renamed the "input" field. Do not forget to migrate your '
'database and update your templates',
hint=None,
obj=None,
id='cmsplugin_contact_plus.W001',
)
]
def register_checks():
for check in [
# warn_1_3_changes, # Might be more annoying than useful
]:
register(check)
| // ... existing code ...
def register_checks():
for check in [
# warn_1_3_changes, # Might be more annoying than useful
]:
register(check)
// ... rest of the code ... |
fc6aae454464aa31f1be401148645310ea9ee2b9 | cloud4rpi/errors.py | cloud4rpi/errors.py |
import subprocess
TYPE_WARN_MSG = 'WARNING! A string "%s" passed to a numeric variable. ' \
'Change the variable type or the passed value.' \
class InvalidTokenError(Exception):
pass
class InvalidConfigError(TypeError):
pass
class UnexpectedVariableTypeError(TypeError):
pass
class UnexpectedVariableValueTypeError(TypeError):
pass
class MqttConnectionError(Exception):
def __init__(self, code):
super(MqttConnectionError, self).__init__()
self.code = code
class NotSupportedError(Exception):
pass
__messages = {
KeyboardInterrupt: 'Interrupted',
subprocess.CalledProcessError: 'Try run with sudo',
InvalidTokenError:
'Device token {0} is invalid. Please verify it.',
InvalidConfigError:
'Configuration is invalid. It must be an array.',
UnexpectedVariableTypeError:
('Unexpected type for the "{0}" variable. '
'It must be "bool", "numeric", "string" or "location".'),
UnexpectedVariableValueTypeError:
'Unexpected value type for variable: {0}'
}
def get_error_message(e):
return __messages.get(type(e), 'Unexpected error: {0}').format(e.message)
|
import subprocess
TYPE_WARN_MSG = 'WARNING! A string "%s" passed to a numeric variable. ' \
'Change the variable type or the passed value.' \
class InvalidTokenError(Exception):
pass
class InvalidConfigError(TypeError):
pass
class UnexpectedVariableTypeError(TypeError):
pass
class UnexpectedVariableValueTypeError(TypeError):
pass
class MqttConnectionError(Exception):
def __init__(self, code):
super(MqttConnectionError, self).__init__()
self.code = code
class NotSupportedError(Exception):
pass
__messages = {
KeyboardInterrupt: 'Interrupted',
subprocess.CalledProcessError: 'Try run with sudo',
InvalidTokenError:
'Device token {0} is invalid. Please verify it.',
InvalidConfigError:
'Configuration is invalid. It must be an array.',
UnexpectedVariableTypeError:
('Unexpected type for the "{0}" variable. '
'It must be "bool", "numeric", "string" or "location".'),
UnexpectedVariableValueTypeError:
'Unexpected value type for variable: {0}'
}
def get_error_message(e):
return __messages.get(type(e), 'Unexpected error: {0}').format(str(type(e)) + str(e.args))
| Fix receiving an error message for python2 & 3 | Fix receiving an error message for python2 & 3
| Python | mit | cloud4rpi/cloud4rpi |
import subprocess
TYPE_WARN_MSG = 'WARNING! A string "%s" passed to a numeric variable. ' \
'Change the variable type or the passed value.' \
class InvalidTokenError(Exception):
pass
class InvalidConfigError(TypeError):
pass
class UnexpectedVariableTypeError(TypeError):
pass
class UnexpectedVariableValueTypeError(TypeError):
pass
class MqttConnectionError(Exception):
def __init__(self, code):
super(MqttConnectionError, self).__init__()
self.code = code
class NotSupportedError(Exception):
pass
__messages = {
KeyboardInterrupt: 'Interrupted',
subprocess.CalledProcessError: 'Try run with sudo',
InvalidTokenError:
'Device token {0} is invalid. Please verify it.',
InvalidConfigError:
'Configuration is invalid. It must be an array.',
UnexpectedVariableTypeError:
('Unexpected type for the "{0}" variable. '
'It must be "bool", "numeric", "string" or "location".'),
UnexpectedVariableValueTypeError:
'Unexpected value type for variable: {0}'
}
def get_error_message(e):
- return __messages.get(type(e), 'Unexpected error: {0}').format(e.message)
+ return __messages.get(type(e), 'Unexpected error: {0}').format(str(type(e)) + str(e.args))
| Fix receiving an error message for python2 & 3 | ## Code Before:
import subprocess
TYPE_WARN_MSG = 'WARNING! A string "%s" passed to a numeric variable. ' \
'Change the variable type or the passed value.' \
class InvalidTokenError(Exception):
pass
class InvalidConfigError(TypeError):
pass
class UnexpectedVariableTypeError(TypeError):
pass
class UnexpectedVariableValueTypeError(TypeError):
pass
class MqttConnectionError(Exception):
def __init__(self, code):
super(MqttConnectionError, self).__init__()
self.code = code
class NotSupportedError(Exception):
pass
__messages = {
KeyboardInterrupt: 'Interrupted',
subprocess.CalledProcessError: 'Try run with sudo',
InvalidTokenError:
'Device token {0} is invalid. Please verify it.',
InvalidConfigError:
'Configuration is invalid. It must be an array.',
UnexpectedVariableTypeError:
('Unexpected type for the "{0}" variable. '
'It must be "bool", "numeric", "string" or "location".'),
UnexpectedVariableValueTypeError:
'Unexpected value type for variable: {0}'
}
def get_error_message(e):
return __messages.get(type(e), 'Unexpected error: {0}').format(e.message)
## Instruction:
Fix receiving an error message for python2 & 3
## Code After:
import subprocess
TYPE_WARN_MSG = 'WARNING! A string "%s" passed to a numeric variable. ' \
'Change the variable type or the passed value.' \
class InvalidTokenError(Exception):
pass
class InvalidConfigError(TypeError):
pass
class UnexpectedVariableTypeError(TypeError):
pass
class UnexpectedVariableValueTypeError(TypeError):
pass
class MqttConnectionError(Exception):
def __init__(self, code):
super(MqttConnectionError, self).__init__()
self.code = code
class NotSupportedError(Exception):
pass
__messages = {
KeyboardInterrupt: 'Interrupted',
subprocess.CalledProcessError: 'Try run with sudo',
InvalidTokenError:
'Device token {0} is invalid. Please verify it.',
InvalidConfigError:
'Configuration is invalid. It must be an array.',
UnexpectedVariableTypeError:
('Unexpected type for the "{0}" variable. '
'It must be "bool", "numeric", "string" or "location".'),
UnexpectedVariableValueTypeError:
'Unexpected value type for variable: {0}'
}
def get_error_message(e):
return __messages.get(type(e), 'Unexpected error: {0}').format(str(type(e)) + str(e.args))
| // ... existing code ...
def get_error_message(e):
return __messages.get(type(e), 'Unexpected error: {0}').format(str(type(e)) + str(e.args))
// ... rest of the code ... |
81908e5f6304cc1c8e8627b0d4c859df194cc36d | ynr/apps/resultsbot/management/commands/store_modgov_urls.py | ynr/apps/resultsbot/management/commands/store_modgov_urls.py | import csv
import os
from django.core.management.base import BaseCommand
import resultsbot
from elections.models import Election
class Command(BaseCommand):
def handle(self, **options):
"""
Stores possible modgov urls stored in CSV file against the related election objects
"""
path = os.path.join(
os.path.dirname(resultsbot.__file__), "election_id_to_url.csv"
)
with open(path) as f:
csv_file = csv.reader(f)
for line in csv_file:
try:
election = Election.objects.get(slug=line[0])
election.modgov_url = line[1]
election.save()
except (IndexError, Election.DoesNotExist):
continue
| import csv
import os
from django.core.management.base import BaseCommand
import resultsbot
from elections.models import Election
class Command(BaseCommand):
def handle(self, **options):
"""
Stores possible modgov urls stored in CSV file against the related election objects
"""
# remove existing values first as this allows us to remove bad urls from the csv file
Election.objects.update(modgov_url=None)
path = os.path.join(
os.path.dirname(resultsbot.__file__), "election_id_to_url.csv"
)
with open(path) as f:
csv_file = csv.reader(f)
for line in csv_file:
try:
election = Election.objects.get(slug=line[0])
election.modgov_url = line[1]
election.save()
except (IndexError, Election.DoesNotExist):
continue
| Delete existing urls before each run | Delete existing urls before each run
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative | import csv
import os
from django.core.management.base import BaseCommand
import resultsbot
from elections.models import Election
class Command(BaseCommand):
def handle(self, **options):
"""
Stores possible modgov urls stored in CSV file against the related election objects
"""
+
+ # remove existing values first as this allows us to remove bad urls from the csv file
+ Election.objects.update(modgov_url=None)
+
path = os.path.join(
os.path.dirname(resultsbot.__file__), "election_id_to_url.csv"
)
with open(path) as f:
csv_file = csv.reader(f)
for line in csv_file:
try:
election = Election.objects.get(slug=line[0])
election.modgov_url = line[1]
election.save()
except (IndexError, Election.DoesNotExist):
continue
| Delete existing urls before each run | ## Code Before:
import csv
import os
from django.core.management.base import BaseCommand
import resultsbot
from elections.models import Election
class Command(BaseCommand):
def handle(self, **options):
"""
Stores possible modgov urls stored in CSV file against the related election objects
"""
path = os.path.join(
os.path.dirname(resultsbot.__file__), "election_id_to_url.csv"
)
with open(path) as f:
csv_file = csv.reader(f)
for line in csv_file:
try:
election = Election.objects.get(slug=line[0])
election.modgov_url = line[1]
election.save()
except (IndexError, Election.DoesNotExist):
continue
## Instruction:
Delete existing urls before each run
## Code After:
import csv
import os
from django.core.management.base import BaseCommand
import resultsbot
from elections.models import Election
class Command(BaseCommand):
def handle(self, **options):
"""
Stores possible modgov urls stored in CSV file against the related election objects
"""
# remove existing values first as this allows us to remove bad urls from the csv file
Election.objects.update(modgov_url=None)
path = os.path.join(
os.path.dirname(resultsbot.__file__), "election_id_to_url.csv"
)
with open(path) as f:
csv_file = csv.reader(f)
for line in csv_file:
try:
election = Election.objects.get(slug=line[0])
election.modgov_url = line[1]
election.save()
except (IndexError, Election.DoesNotExist):
continue
| ...
Stores possible modgov urls stored in CSV file against the related election objects
"""
# remove existing values first as this allows us to remove bad urls from the csv file
Election.objects.update(modgov_url=None)
path = os.path.join(
os.path.dirname(resultsbot.__file__), "election_id_to_url.csv"
... |
ad4b972667e9111c403c1d3726b2cde87fcbc88e | setup.py | setup.py |
from distutils.core import setup
setup(name='natural',
version='0.1.4',
description='Convert data to their natural (human-readable) format',
long_description='''
Example Usage
=============
Basic usage::
>>> from natural.file import accessed
>>> print accessed(__file__)
just now
We speak your language (with `your support`_)::
>>> import locale
>>> locale.setlocale(locale.LC_MESSAGES, 'nl_NL')
>>> print accessed(__file__)
zojuist
Bugs/Features
=============
You can issue a ticket in GitHub: https://github.com/tehmaze/natural/issues
Documentation
=============
The project documentation can be found at http://natural.rtfd.org/
.. _your support: http://natural.readthedocs.org/en/latest/locales.html
''',
author='Wijnand Modderman-Lenstra',
author_email='[email protected]',
license='MIT',
keywords='natural data date file number size',
url='https://github.com/tehmaze/natural',
packages=['natural'],
package_data={'natural': ['locale/*/LC_MESSAGES/*.mo']},
)
|
from distutils.core import setup
setup(name='natural',
version='0.1.4',
description='Convert data to their natural (human-readable) format',
long_description='''
Example Usage
=============
Basic usage::
>>> from natural.file import accessed
>>> print accessed(__file__)
just now
We speak your language (with `your support`_)::
>>> import locale
>>> locale.setlocale(locale.LC_MESSAGES, 'nl_NL')
>>> print accessed(__file__)
zojuist
Bugs/Features
=============
You can issue a ticket in GitHub: https://github.com/tehmaze/natural/issues
Documentation
=============
The project documentation can be found at http://natural.rtfd.org/
.. _your support: http://natural.readthedocs.org/en/latest/locales.html
''',
author='Wijnand Modderman-Lenstra',
author_email='[email protected]',
license='MIT',
keywords='natural data date file number size',
url='https://github.com/tehmaze/natural',
packages=['natural'],
package_data={'natural': ['locale/*/LC_MESSAGES/*.mo']},
use_2to3=True,
)
| Use 2to3 for Python 3 | Use 2to3 for Python 3
| Python | mit | tehmaze/natural |
from distutils.core import setup
setup(name='natural',
version='0.1.4',
description='Convert data to their natural (human-readable) format',
long_description='''
Example Usage
=============
Basic usage::
>>> from natural.file import accessed
>>> print accessed(__file__)
just now
We speak your language (with `your support`_)::
>>> import locale
>>> locale.setlocale(locale.LC_MESSAGES, 'nl_NL')
>>> print accessed(__file__)
zojuist
Bugs/Features
=============
You can issue a ticket in GitHub: https://github.com/tehmaze/natural/issues
Documentation
=============
The project documentation can be found at http://natural.rtfd.org/
.. _your support: http://natural.readthedocs.org/en/latest/locales.html
''',
author='Wijnand Modderman-Lenstra',
author_email='[email protected]',
license='MIT',
keywords='natural data date file number size',
url='https://github.com/tehmaze/natural',
packages=['natural'],
package_data={'natural': ['locale/*/LC_MESSAGES/*.mo']},
+ use_2to3=True,
)
| Use 2to3 for Python 3 | ## Code Before:
from distutils.core import setup
setup(name='natural',
version='0.1.4',
description='Convert data to their natural (human-readable) format',
long_description='''
Example Usage
=============
Basic usage::
>>> from natural.file import accessed
>>> print accessed(__file__)
just now
We speak your language (with `your support`_)::
>>> import locale
>>> locale.setlocale(locale.LC_MESSAGES, 'nl_NL')
>>> print accessed(__file__)
zojuist
Bugs/Features
=============
You can issue a ticket in GitHub: https://github.com/tehmaze/natural/issues
Documentation
=============
The project documentation can be found at http://natural.rtfd.org/
.. _your support: http://natural.readthedocs.org/en/latest/locales.html
''',
author='Wijnand Modderman-Lenstra',
author_email='[email protected]',
license='MIT',
keywords='natural data date file number size',
url='https://github.com/tehmaze/natural',
packages=['natural'],
package_data={'natural': ['locale/*/LC_MESSAGES/*.mo']},
)
## Instruction:
Use 2to3 for Python 3
## Code After:
from distutils.core import setup
setup(name='natural',
version='0.1.4',
description='Convert data to their natural (human-readable) format',
long_description='''
Example Usage
=============
Basic usage::
>>> from natural.file import accessed
>>> print accessed(__file__)
just now
We speak your language (with `your support`_)::
>>> import locale
>>> locale.setlocale(locale.LC_MESSAGES, 'nl_NL')
>>> print accessed(__file__)
zojuist
Bugs/Features
=============
You can issue a ticket in GitHub: https://github.com/tehmaze/natural/issues
Documentation
=============
The project documentation can be found at http://natural.rtfd.org/
.. _your support: http://natural.readthedocs.org/en/latest/locales.html
''',
author='Wijnand Modderman-Lenstra',
author_email='[email protected]',
license='MIT',
keywords='natural data date file number size',
url='https://github.com/tehmaze/natural',
packages=['natural'],
package_data={'natural': ['locale/*/LC_MESSAGES/*.mo']},
use_2to3=True,
)
| // ... existing code ...
packages=['natural'],
package_data={'natural': ['locale/*/LC_MESSAGES/*.mo']},
use_2to3=True,
)
// ... rest of the code ... |
810961f65c37d27c5e2d99cf102064d0b4e300f3 | project/apiv2/views.py | project/apiv2/views.py | from django.db.models import Q
from django.shortcuts import render
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework.generics import ListAPIView
from rest_framework_json_api.renderers import JSONRenderer
from rest_framework.generics import RetrieveUpdateDestroyAPIView
from bookmarks.models import Bookmark
from bookmarks.serializers import BookmarkSerializer
class BookmarkListCreateAPIView(ListAPIView):
queryset = Bookmark.objects.all()
serializer_class = BookmarkSerializer
resource_name = 'bookmark'
action = 'list'
renderer_classes = (JSONRenderer,)
filter_backends = (SearchFilter, OrderingFilter)
search_fields = ('url', 'title')
ordering_fields = ('id', 'url', 'title', 'bookmarked_at')
class BookmarkRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView):
queryset = Bookmark.objects.all()
serializer_class = BookmarkSerializer
lookup_field = 'bookmark_id'
| from django.db.models import Q
from django.shortcuts import render
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework_json_api.renderers import JSONRenderer
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
from bookmarks.models import Bookmark
from bookmarks.serializers import BookmarkSerializer
class BookmarkListCreateAPIView(ListCreateAPIView):
queryset = Bookmark.objects.all()
serializer_class = BookmarkSerializer
resource_name = 'bookmark'
action = 'list'
renderer_classes = (JSONRenderer,)
filter_backends = (SearchFilter, OrderingFilter)
search_fields = ('url', 'title')
ordering_fields = ('id', 'url', 'title', 'bookmarked_at')
class BookmarkRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView):
queryset = Bookmark.objects.all()
serializer_class = BookmarkSerializer
lookup_field = 'bookmark_id'
| Use ListCreateAPIView as base class to support bookmark creation | Use ListCreateAPIView as base class to support bookmark creation
| Python | mit | hnakamur/django-bootstrap-table-example,hnakamur/django-bootstrap-table-example,hnakamur/django-bootstrap-table-example | from django.db.models import Q
from django.shortcuts import render
from rest_framework.filters import OrderingFilter, SearchFilter
- from rest_framework.generics import ListAPIView
from rest_framework_json_api.renderers import JSONRenderer
- from rest_framework.generics import RetrieveUpdateDestroyAPIView
+ from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
from bookmarks.models import Bookmark
from bookmarks.serializers import BookmarkSerializer
- class BookmarkListCreateAPIView(ListAPIView):
+ class BookmarkListCreateAPIView(ListCreateAPIView):
queryset = Bookmark.objects.all()
serializer_class = BookmarkSerializer
resource_name = 'bookmark'
action = 'list'
renderer_classes = (JSONRenderer,)
filter_backends = (SearchFilter, OrderingFilter)
search_fields = ('url', 'title')
ordering_fields = ('id', 'url', 'title', 'bookmarked_at')
class BookmarkRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView):
queryset = Bookmark.objects.all()
serializer_class = BookmarkSerializer
lookup_field = 'bookmark_id'
| Use ListCreateAPIView as base class to support bookmark creation | ## Code Before:
from django.db.models import Q
from django.shortcuts import render
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework.generics import ListAPIView
from rest_framework_json_api.renderers import JSONRenderer
from rest_framework.generics import RetrieveUpdateDestroyAPIView
from bookmarks.models import Bookmark
from bookmarks.serializers import BookmarkSerializer
class BookmarkListCreateAPIView(ListAPIView):
queryset = Bookmark.objects.all()
serializer_class = BookmarkSerializer
resource_name = 'bookmark'
action = 'list'
renderer_classes = (JSONRenderer,)
filter_backends = (SearchFilter, OrderingFilter)
search_fields = ('url', 'title')
ordering_fields = ('id', 'url', 'title', 'bookmarked_at')
class BookmarkRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView):
queryset = Bookmark.objects.all()
serializer_class = BookmarkSerializer
lookup_field = 'bookmark_id'
## Instruction:
Use ListCreateAPIView as base class to support bookmark creation
## Code After:
from django.db.models import Q
from django.shortcuts import render
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework_json_api.renderers import JSONRenderer
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
from bookmarks.models import Bookmark
from bookmarks.serializers import BookmarkSerializer
class BookmarkListCreateAPIView(ListCreateAPIView):
queryset = Bookmark.objects.all()
serializer_class = BookmarkSerializer
resource_name = 'bookmark'
action = 'list'
renderer_classes = (JSONRenderer,)
filter_backends = (SearchFilter, OrderingFilter)
search_fields = ('url', 'title')
ordering_fields = ('id', 'url', 'title', 'bookmarked_at')
class BookmarkRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView):
queryset = Bookmark.objects.all()
serializer_class = BookmarkSerializer
lookup_field = 'bookmark_id'
| ...
from django.shortcuts import render
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework_json_api.renderers import JSONRenderer
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
from bookmarks.models import Bookmark
...
from bookmarks.serializers import BookmarkSerializer
class BookmarkListCreateAPIView(ListCreateAPIView):
queryset = Bookmark.objects.all()
serializer_class = BookmarkSerializer
... |
678e872de192b09c1bafc7a26dc67d7737a14e20 | altair/examples/us_population_over_time.py | altair/examples/us_population_over_time.py | # category: case studies
import altair as alt
from vega_datasets import data
source = data.population.url
pink_blue = alt.Scale(domain=('Male', 'Female'),
range=["steelblue", "salmon"])
slider = alt.binding_range(min=1900, max=2000, step=10)
select_year = alt.selection_single(name="year", fields=['year'],
bind=slider, init={'year': 2000})
alt.Chart(source).mark_bar().encode(
x=alt.X('sex:N', title=None),
y=alt.Y('people:Q', scale=alt.Scale(domain=(0, 12000000))),
color=alt.Color('sex:N', scale=pink_blue),
column='age:O'
).properties(
width=20
).add_selection(
select_year
).transform_calculate(
"sex", alt.expr.if_(alt.datum.sex == 1, "Male", "Female")
).transform_filter(
select_year
).configure_facet(
spacing=8
)
| # category: case studies
import altair as alt
from vega_datasets import data
source = data.population.url
select_year = alt.selection_single(
name="Year",
fields=["year"],
bind=alt.binding_range(min=1900, max=2000, step=10, name="Year"),
init={"year": 2000},
)
alt.Chart(source).mark_bar().encode(
x=alt.X("sex:N", axis=alt.Axis(labels=False, title=None, ticks=False)),
y=alt.Y("people:Q", scale=alt.Scale(domain=(0, 12000000)), title="Population"),
color=alt.Color(
"sex:N",
scale=alt.Scale(domain=("Male", "Female"), range=["steelblue", "salmon"]),
title="Sex",
),
column=alt.Column("age:O", title="Age"),
).properties(width=20, title="U.S. Population by Age and Sex").add_selection(
select_year
).transform_calculate(
"sex", alt.expr.if_(alt.datum.sex == 1, "Male", "Female")
).transform_filter(
select_year
).configure_facet(
spacing=8
)
| Tidy up U.S. Population by Age and Sex | Tidy up U.S. Population by Age and Sex | Python | bsd-3-clause | altair-viz/altair | # category: case studies
import altair as alt
from vega_datasets import data
source = data.population.url
- pink_blue = alt.Scale(domain=('Male', 'Female'),
- range=["steelblue", "salmon"])
-
+ select_year = alt.selection_single(
+ name="Year",
+ fields=["year"],
- slider = alt.binding_range(min=1900, max=2000, step=10)
+ bind=alt.binding_range(min=1900, max=2000, step=10, name="Year"),
- select_year = alt.selection_single(name="year", fields=['year'],
- bind=slider, init={'year': 2000})
+ init={"year": 2000},
+ )
alt.Chart(source).mark_bar().encode(
- x=alt.X('sex:N', title=None),
+ x=alt.X("sex:N", axis=alt.Axis(labels=False, title=None, ticks=False)),
- y=alt.Y('people:Q', scale=alt.Scale(domain=(0, 12000000))),
+ y=alt.Y("people:Q", scale=alt.Scale(domain=(0, 12000000)), title="Population"),
- color=alt.Color('sex:N', scale=pink_blue),
- column='age:O'
- ).properties(
- width=20
- ).add_selection(
+ color=alt.Color(
+ "sex:N",
+ scale=alt.Scale(domain=("Male", "Female"), range=["steelblue", "salmon"]),
+ title="Sex",
+ ),
+ column=alt.Column("age:O", title="Age"),
+ ).properties(width=20, title="U.S. Population by Age and Sex").add_selection(
select_year
).transform_calculate(
"sex", alt.expr.if_(alt.datum.sex == 1, "Male", "Female")
).transform_filter(
select_year
).configure_facet(
spacing=8
)
| Tidy up U.S. Population by Age and Sex | ## Code Before:
# category: case studies
import altair as alt
from vega_datasets import data
source = data.population.url
pink_blue = alt.Scale(domain=('Male', 'Female'),
range=["steelblue", "salmon"])
slider = alt.binding_range(min=1900, max=2000, step=10)
select_year = alt.selection_single(name="year", fields=['year'],
bind=slider, init={'year': 2000})
alt.Chart(source).mark_bar().encode(
x=alt.X('sex:N', title=None),
y=alt.Y('people:Q', scale=alt.Scale(domain=(0, 12000000))),
color=alt.Color('sex:N', scale=pink_blue),
column='age:O'
).properties(
width=20
).add_selection(
select_year
).transform_calculate(
"sex", alt.expr.if_(alt.datum.sex == 1, "Male", "Female")
).transform_filter(
select_year
).configure_facet(
spacing=8
)
## Instruction:
Tidy up U.S. Population by Age and Sex
## Code After:
# category: case studies
import altair as alt
from vega_datasets import data
source = data.population.url
select_year = alt.selection_single(
name="Year",
fields=["year"],
bind=alt.binding_range(min=1900, max=2000, step=10, name="Year"),
init={"year": 2000},
)
alt.Chart(source).mark_bar().encode(
x=alt.X("sex:N", axis=alt.Axis(labels=False, title=None, ticks=False)),
y=alt.Y("people:Q", scale=alt.Scale(domain=(0, 12000000)), title="Population"),
color=alt.Color(
"sex:N",
scale=alt.Scale(domain=("Male", "Female"), range=["steelblue", "salmon"]),
title="Sex",
),
column=alt.Column("age:O", title="Age"),
).properties(width=20, title="U.S. Population by Age and Sex").add_selection(
select_year
).transform_calculate(
"sex", alt.expr.if_(alt.datum.sex == 1, "Male", "Female")
).transform_filter(
select_year
).configure_facet(
spacing=8
)
| ...
source = data.population.url
select_year = alt.selection_single(
name="Year",
fields=["year"],
bind=alt.binding_range(min=1900, max=2000, step=10, name="Year"),
init={"year": 2000},
)
alt.Chart(source).mark_bar().encode(
x=alt.X("sex:N", axis=alt.Axis(labels=False, title=None, ticks=False)),
y=alt.Y("people:Q", scale=alt.Scale(domain=(0, 12000000)), title="Population"),
color=alt.Color(
"sex:N",
scale=alt.Scale(domain=("Male", "Female"), range=["steelblue", "salmon"]),
title="Sex",
),
column=alt.Column("age:O", title="Age"),
).properties(width=20, title="U.S. Population by Age and Sex").add_selection(
select_year
).transform_calculate(
... |
68b52fedf5b22891a4fc9cf121417ced38d0ea00 | rolepermissions/utils.py | rolepermissions/utils.py | from __future__ import unicode_literals
import re
import collections
def user_is_authenticated(user):
if isinstance(user.is_authenticated, collections.Callable):
authenticated = user.is_authenticated()
else:
authenticated = user.is_authenticated
return authenticated
def camelToSnake(s):
"""
https://gist.github.com/jaytaylor/3660565
Is it ironic that this function is written in camel case, yet it
converts to snake case? hmm..
"""
_underscorer1 = re.compile(r'(.)([A-Z][a-z]+)')
_underscorer2 = re.compile('([a-z0-9])([A-Z])')
subbed = _underscorer1.sub(r'\1_\2', s)
return _underscorer2.sub(r'\1_\2', subbed).lower()
def snake_to_title(s):
return ' '.join(x.capitalize() for x in s.split('_'))
def camel_or_snake_to_title(s):
return snake_to_title(camelToSnake(s))
| from __future__ import unicode_literals
import re
try:
from collections.abc import Callable
except ImportError:
from collections import Callable
def user_is_authenticated(user):
if isinstance(user.is_authenticated, Callable):
authenticated = user.is_authenticated()
else:
authenticated = user.is_authenticated
return authenticated
def camelToSnake(s):
"""
https://gist.github.com/jaytaylor/3660565
Is it ironic that this function is written in camel case, yet it
converts to snake case? hmm..
"""
_underscorer1 = re.compile(r'(.)([A-Z][a-z]+)')
_underscorer2 = re.compile('([a-z0-9])([A-Z])')
subbed = _underscorer1.sub(r'\1_\2', s)
return _underscorer2.sub(r'\1_\2', subbed).lower()
def snake_to_title(s):
return ' '.join(x.capitalize() for x in s.split('_'))
def camel_or_snake_to_title(s):
return snake_to_title(camelToSnake(s))
| Fix import of Callable for Python 3.9 | Fix import of Callable for Python 3.9
Python 3.3 moved Callable to collections.abc and Python 3.9 removes Callable from collections module | Python | mit | vintasoftware/django-role-permissions | from __future__ import unicode_literals
import re
- import collections
+ try:
+ from collections.abc import Callable
+ except ImportError:
+ from collections import Callable
def user_is_authenticated(user):
- if isinstance(user.is_authenticated, collections.Callable):
+ if isinstance(user.is_authenticated, Callable):
authenticated = user.is_authenticated()
else:
authenticated = user.is_authenticated
return authenticated
def camelToSnake(s):
"""
https://gist.github.com/jaytaylor/3660565
Is it ironic that this function is written in camel case, yet it
converts to snake case? hmm..
"""
_underscorer1 = re.compile(r'(.)([A-Z][a-z]+)')
_underscorer2 = re.compile('([a-z0-9])([A-Z])')
subbed = _underscorer1.sub(r'\1_\2', s)
return _underscorer2.sub(r'\1_\2', subbed).lower()
def snake_to_title(s):
return ' '.join(x.capitalize() for x in s.split('_'))
def camel_or_snake_to_title(s):
return snake_to_title(camelToSnake(s))
| Fix import of Callable for Python 3.9 | ## Code Before:
from __future__ import unicode_literals
import re
import collections
def user_is_authenticated(user):
if isinstance(user.is_authenticated, collections.Callable):
authenticated = user.is_authenticated()
else:
authenticated = user.is_authenticated
return authenticated
def camelToSnake(s):
"""
https://gist.github.com/jaytaylor/3660565
Is it ironic that this function is written in camel case, yet it
converts to snake case? hmm..
"""
_underscorer1 = re.compile(r'(.)([A-Z][a-z]+)')
_underscorer2 = re.compile('([a-z0-9])([A-Z])')
subbed = _underscorer1.sub(r'\1_\2', s)
return _underscorer2.sub(r'\1_\2', subbed).lower()
def snake_to_title(s):
return ' '.join(x.capitalize() for x in s.split('_'))
def camel_or_snake_to_title(s):
return snake_to_title(camelToSnake(s))
## Instruction:
Fix import of Callable for Python 3.9
## Code After:
from __future__ import unicode_literals
import re
try:
from collections.abc import Callable
except ImportError:
from collections import Callable
def user_is_authenticated(user):
if isinstance(user.is_authenticated, Callable):
authenticated = user.is_authenticated()
else:
authenticated = user.is_authenticated
return authenticated
def camelToSnake(s):
"""
https://gist.github.com/jaytaylor/3660565
Is it ironic that this function is written in camel case, yet it
converts to snake case? hmm..
"""
_underscorer1 = re.compile(r'(.)([A-Z][a-z]+)')
_underscorer2 = re.compile('([a-z0-9])([A-Z])')
subbed = _underscorer1.sub(r'\1_\2', s)
return _underscorer2.sub(r'\1_\2', subbed).lower()
def snake_to_title(s):
return ' '.join(x.capitalize() for x in s.split('_'))
def camel_or_snake_to_title(s):
return snake_to_title(camelToSnake(s))
| // ... existing code ...
import re
try:
from collections.abc import Callable
except ImportError:
from collections import Callable
def user_is_authenticated(user):
if isinstance(user.is_authenticated, Callable):
authenticated = user.is_authenticated()
else:
// ... rest of the code ... |
a06c3845b2e827ff34bdd34844db39a74826f123 | meteocalc/mimicfloat.py | meteocalc/mimicfloat.py | import operator
def math_method(name, right=False):
def wrapper(self, other):
value = self.value
math_func = getattr(operator, name)
if right:
value, other = other, value
result = math_func(value, other)
return type(self)(result, units=self.units)
return wrapper
class MimicFloat(type):
overrride_methods = ('__add__', '__sub__', '__mul__', '__truediv__')
overrride_rmethods = ('__radd__', '__rsub__', '__rmul__', '__rtruediv__')
def __new__(cls, name, bases, namespace):
for method in cls.overrride_methods:
namespace[method] = math_method(method)
for rmethod in cls.overrride_rmethods:
method = rmethod.replace('__r', '__')
namespace[rmethod] = math_method(method, right=True)
return super(MimicFloat, cls).__new__(cls, name, bases, namespace)
| from functools import wraps
import operator
def math_method(name, right=False):
math_func = getattr(operator, name)
@wraps(math_func)
def wrapper(self, other):
value = self.value
if right:
value, other = other, value
result = math_func(value, other)
return type(self)(result, units=self.units)
return wrapper
class MimicFloat(type):
math_methods = ('__add__', '__sub__', '__mul__', '__truediv__')
math_rmethods = ('__radd__', '__rsub__', '__rmul__', '__rtruediv__')
def __new__(cls, name, bases, namespace):
for method in cls.math_methods:
namespace[method] = math_method(method)
for rmethod in cls.math_rmethods:
method = rmethod.replace('__r', '__')
namespace[rmethod] = math_method(method, right=True)
return super(MimicFloat, cls).__new__(cls, name, bases, namespace)
| Make math method wrapping nicer | Make math method wrapping nicer
| Python | mit | malexer/meteocalc | + from functools import wraps
import operator
def math_method(name, right=False):
+ math_func = getattr(operator, name)
+
+ @wraps(math_func)
def wrapper(self, other):
value = self.value
- math_func = getattr(operator, name)
if right:
value, other = other, value
result = math_func(value, other)
return type(self)(result, units=self.units)
return wrapper
class MimicFloat(type):
- overrride_methods = ('__add__', '__sub__', '__mul__', '__truediv__')
+ math_methods = ('__add__', '__sub__', '__mul__', '__truediv__')
- overrride_rmethods = ('__radd__', '__rsub__', '__rmul__', '__rtruediv__')
+ math_rmethods = ('__radd__', '__rsub__', '__rmul__', '__rtruediv__')
def __new__(cls, name, bases, namespace):
- for method in cls.overrride_methods:
+ for method in cls.math_methods:
namespace[method] = math_method(method)
- for rmethod in cls.overrride_rmethods:
+ for rmethod in cls.math_rmethods:
method = rmethod.replace('__r', '__')
namespace[rmethod] = math_method(method, right=True)
return super(MimicFloat, cls).__new__(cls, name, bases, namespace)
| Make math method wrapping nicer | ## Code Before:
import operator
def math_method(name, right=False):
def wrapper(self, other):
value = self.value
math_func = getattr(operator, name)
if right:
value, other = other, value
result = math_func(value, other)
return type(self)(result, units=self.units)
return wrapper
class MimicFloat(type):
overrride_methods = ('__add__', '__sub__', '__mul__', '__truediv__')
overrride_rmethods = ('__radd__', '__rsub__', '__rmul__', '__rtruediv__')
def __new__(cls, name, bases, namespace):
for method in cls.overrride_methods:
namespace[method] = math_method(method)
for rmethod in cls.overrride_rmethods:
method = rmethod.replace('__r', '__')
namespace[rmethod] = math_method(method, right=True)
return super(MimicFloat, cls).__new__(cls, name, bases, namespace)
## Instruction:
Make math method wrapping nicer
## Code After:
from functools import wraps
import operator
def math_method(name, right=False):
math_func = getattr(operator, name)
@wraps(math_func)
def wrapper(self, other):
value = self.value
if right:
value, other = other, value
result = math_func(value, other)
return type(self)(result, units=self.units)
return wrapper
class MimicFloat(type):
math_methods = ('__add__', '__sub__', '__mul__', '__truediv__')
math_rmethods = ('__radd__', '__rsub__', '__rmul__', '__rtruediv__')
def __new__(cls, name, bases, namespace):
for method in cls.math_methods:
namespace[method] = math_method(method)
for rmethod in cls.math_rmethods:
method = rmethod.replace('__r', '__')
namespace[rmethod] = math_method(method, right=True)
return super(MimicFloat, cls).__new__(cls, name, bases, namespace)
| ...
from functools import wraps
import operator
...
def math_method(name, right=False):
math_func = getattr(operator, name)
@wraps(math_func)
def wrapper(self, other):
value = self.value
if right:
...
class MimicFloat(type):
math_methods = ('__add__', '__sub__', '__mul__', '__truediv__')
math_rmethods = ('__radd__', '__rsub__', '__rmul__', '__rtruediv__')
def __new__(cls, name, bases, namespace):
for method in cls.math_methods:
namespace[method] = math_method(method)
for rmethod in cls.math_rmethods:
method = rmethod.replace('__r', '__')
namespace[rmethod] = math_method(method, right=True)
... |
cd5bfa0fb09835e4e33236ec4292a16ed5556088 | tests/parser.py | tests/parser.py | from spec import Spec, skip, ok_, eq_, raises
from invoke.parser import Parser, Context, Argument
from invoke.collection import Collection
class Parser_(Spec):
def has_and_requires_initial_context(self):
c = Context()
p = Parser(initial=c)
eq_(p.initial, c)
def may_also_take_additional_contexts(self):
c1 = Context('foo')
c2 = Context('bar')
p = Parser(initial=Context(), contexts=[c1, c2])
eq_(p.contexts['foo'], c1)
eq_(p.contexts['bar'], c2)
@raises(ValueError)
def raises_ValueError_for_unnamed_Contexts_in_contexts(self):
Parser(initial=Context(), contexts=[Context()])
class parse_argv:
def parses_sys_argv_style_list_of_strings(self):
"parses sys.argv-style list of strings"
# Doesn't-blow-up tests FTL
mytask = Context(name='mytask')
mytask.add_arg('--arg')
p = Parser(contexts=[mytask])
p.parse_argv(['mytask', '--arg'])
def returns_ordered_list_of_tasks_and_their_args(self):
skip()
def returns_remainder(self):
"returns -- style remainder string chunk"
skip()
| from spec import Spec, skip, ok_, eq_, raises
from invoke.parser import Parser, Context, Argument
from invoke.collection import Collection
class Parser_(Spec):
def can_take_initial_context(self):
c = Context()
p = Parser(initial=c)
eq_(p.initial, c)
def can_take_initial_and_other_contexts(self):
c1 = Context('foo')
c2 = Context('bar')
p = Parser(initial=Context(), contexts=[c1, c2])
eq_(p.contexts['foo'], c1)
eq_(p.contexts['bar'], c2)
def can_take_just_other_contexts(self):
c = Context('foo')
p = Parser(contexts=[c])
eq_(p.contexts['foo'], c)
@raises(ValueError)
def raises_ValueError_for_unnamed_Contexts_in_contexts(self):
Parser(initial=Context(), contexts=[Context()])
class parse_argv:
def parses_sys_argv_style_list_of_strings(self):
"parses sys.argv-style list of strings"
# Doesn't-blow-up tests FTL
mytask = Context(name='mytask')
mytask.add_arg('--arg')
p = Parser(contexts=[mytask])
p.parse_argv(['mytask', '--arg'])
def returns_ordered_list_of_tasks_and_their_args(self):
skip()
def returns_remainder(self):
"returns -- style remainder string chunk"
skip()
| Update tests to explicitly account for previous | Update tests to explicitly account for previous
| Python | bsd-2-clause | mattrobenolt/invoke,frol/invoke,sophacles/invoke,pyinvoke/invoke,tyewang/invoke,frol/invoke,mattrobenolt/invoke,pfmoore/invoke,singingwolfboy/invoke,kejbaly2/invoke,pfmoore/invoke,pyinvoke/invoke,mkusz/invoke,alex/invoke,mkusz/invoke,kejbaly2/invoke | from spec import Spec, skip, ok_, eq_, raises
from invoke.parser import Parser, Context, Argument
from invoke.collection import Collection
class Parser_(Spec):
- def has_and_requires_initial_context(self):
+ def can_take_initial_context(self):
c = Context()
p = Parser(initial=c)
eq_(p.initial, c)
- def may_also_take_additional_contexts(self):
+ def can_take_initial_and_other_contexts(self):
c1 = Context('foo')
c2 = Context('bar')
p = Parser(initial=Context(), contexts=[c1, c2])
eq_(p.contexts['foo'], c1)
eq_(p.contexts['bar'], c2)
+
+ def can_take_just_other_contexts(self):
+ c = Context('foo')
+ p = Parser(contexts=[c])
+ eq_(p.contexts['foo'], c)
@raises(ValueError)
def raises_ValueError_for_unnamed_Contexts_in_contexts(self):
Parser(initial=Context(), contexts=[Context()])
class parse_argv:
def parses_sys_argv_style_list_of_strings(self):
"parses sys.argv-style list of strings"
# Doesn't-blow-up tests FTL
mytask = Context(name='mytask')
mytask.add_arg('--arg')
p = Parser(contexts=[mytask])
p.parse_argv(['mytask', '--arg'])
def returns_ordered_list_of_tasks_and_their_args(self):
skip()
def returns_remainder(self):
"returns -- style remainder string chunk"
skip()
| Update tests to explicitly account for previous | ## Code Before:
from spec import Spec, skip, ok_, eq_, raises
from invoke.parser import Parser, Context, Argument
from invoke.collection import Collection
class Parser_(Spec):
def has_and_requires_initial_context(self):
c = Context()
p = Parser(initial=c)
eq_(p.initial, c)
def may_also_take_additional_contexts(self):
c1 = Context('foo')
c2 = Context('bar')
p = Parser(initial=Context(), contexts=[c1, c2])
eq_(p.contexts['foo'], c1)
eq_(p.contexts['bar'], c2)
@raises(ValueError)
def raises_ValueError_for_unnamed_Contexts_in_contexts(self):
Parser(initial=Context(), contexts=[Context()])
class parse_argv:
def parses_sys_argv_style_list_of_strings(self):
"parses sys.argv-style list of strings"
# Doesn't-blow-up tests FTL
mytask = Context(name='mytask')
mytask.add_arg('--arg')
p = Parser(contexts=[mytask])
p.parse_argv(['mytask', '--arg'])
def returns_ordered_list_of_tasks_and_their_args(self):
skip()
def returns_remainder(self):
"returns -- style remainder string chunk"
skip()
## Instruction:
Update tests to explicitly account for previous
## Code After:
from spec import Spec, skip, ok_, eq_, raises
from invoke.parser import Parser, Context, Argument
from invoke.collection import Collection
class Parser_(Spec):
def can_take_initial_context(self):
c = Context()
p = Parser(initial=c)
eq_(p.initial, c)
def can_take_initial_and_other_contexts(self):
c1 = Context('foo')
c2 = Context('bar')
p = Parser(initial=Context(), contexts=[c1, c2])
eq_(p.contexts['foo'], c1)
eq_(p.contexts['bar'], c2)
def can_take_just_other_contexts(self):
c = Context('foo')
p = Parser(contexts=[c])
eq_(p.contexts['foo'], c)
@raises(ValueError)
def raises_ValueError_for_unnamed_Contexts_in_contexts(self):
Parser(initial=Context(), contexts=[Context()])
class parse_argv:
def parses_sys_argv_style_list_of_strings(self):
"parses sys.argv-style list of strings"
# Doesn't-blow-up tests FTL
mytask = Context(name='mytask')
mytask.add_arg('--arg')
p = Parser(contexts=[mytask])
p.parse_argv(['mytask', '--arg'])
def returns_ordered_list_of_tasks_and_their_args(self):
skip()
def returns_remainder(self):
"returns -- style remainder string chunk"
skip()
| ...
class Parser_(Spec):
def can_take_initial_context(self):
c = Context()
p = Parser(initial=c)
...
eq_(p.initial, c)
def can_take_initial_and_other_contexts(self):
c1 = Context('foo')
c2 = Context('bar')
...
eq_(p.contexts['foo'], c1)
eq_(p.contexts['bar'], c2)
def can_take_just_other_contexts(self):
c = Context('foo')
p = Parser(contexts=[c])
eq_(p.contexts['foo'], c)
@raises(ValueError)
... |
199aee78cb494169eb8b73fbb65de5ae40a5d436 | other/wrapping-cpp/swig/c++/test_mylib.py | other/wrapping-cpp/swig/c++/test_mylib.py | import os
import mylib
os.system('make all')
def test_squared():
assert 16. == mylib.squared(4)
def test_myfunction():
assert 16. == mylib.myfunction(mylib.squared, 4)
os.system('make clean')
| import os
import pytest
@pytest.fixture
def setup(request):
def teardown():
print("Running make clean")
os.system('make clean')
print("Completed finaliser")
request.addfinalizer(teardown)
os.system('make clean')
os.system('make all')
def test_squared(setup):
import mylib
assert 16. == mylib.squared(4)
def test_myfunction(setup):
import mylib
assert 16. == mylib.myfunction(mylib.squared, 4)
| Use pytest fixture to deal with compilation | Use pytest fixture to deal with compilation
| Python | bsd-2-clause | fangohr/oommf-python,ryanpepper/oommf-python,ryanpepper/oommf-python,fangohr/oommf-python,ryanpepper/oommf-python,ryanpepper/oommf-python,fangohr/oommf-python | import os
- import mylib
+
+ import pytest
+
+ @pytest.fixture
+ def setup(request):
+ def teardown():
+ print("Running make clean")
+ os.system('make clean')
+ print("Completed finaliser")
+ request.addfinalizer(teardown)
+ os.system('make clean')
- os.system('make all')
+ os.system('make all')
- def test_squared():
+ def test_squared(setup):
+ import mylib
assert 16. == mylib.squared(4)
- def test_myfunction():
+ def test_myfunction(setup):
+ import mylib
assert 16. == mylib.myfunction(mylib.squared, 4)
- os.system('make clean')
- | Use pytest fixture to deal with compilation | ## Code Before:
import os
import mylib
os.system('make all')
def test_squared():
assert 16. == mylib.squared(4)
def test_myfunction():
assert 16. == mylib.myfunction(mylib.squared, 4)
os.system('make clean')
## Instruction:
Use pytest fixture to deal with compilation
## Code After:
import os
import pytest
@pytest.fixture
def setup(request):
def teardown():
print("Running make clean")
os.system('make clean')
print("Completed finaliser")
request.addfinalizer(teardown)
os.system('make clean')
os.system('make all')
def test_squared(setup):
import mylib
assert 16. == mylib.squared(4)
def test_myfunction(setup):
import mylib
assert 16. == mylib.myfunction(mylib.squared, 4)
| ...
import os
import pytest
@pytest.fixture
def setup(request):
def teardown():
print("Running make clean")
os.system('make clean')
print("Completed finaliser")
request.addfinalizer(teardown)
os.system('make clean')
os.system('make all')
def test_squared(setup):
import mylib
assert 16. == mylib.squared(4)
def test_myfunction(setup):
import mylib
assert 16. == mylib.myfunction(mylib.squared, 4)
... |
eaa4de2ecbcf29c9e56ebf2fa69099055e469fbc | tests/test_conversion.py | tests/test_conversion.py | from asciisciit import conversions as conv
import numpy as np
def test_lookup_method_equivalency():
img = np.random.randint(0, 255, (300,300), dtype=np.uint8)
pil_ascii = conv.apply_lut_pil(img)
np_ascii = conv.apply_lut_numpy(img)
assert(pil_ascii == np_ascii)
pil_ascii = conv.apply_lut_pil(img, "binary")
np_ascii = conv.apply_lut_numpy(img, "binary")
assert(pil_ascii == np_ascii) | import itertools
from asciisciit import conversions as conv
import numpy as np
import pytest
@pytest.mark.parametrize("invert,equalize,lut,lookup_func",
itertools.product((True, False),
(True, False),
("simple", "binary"),
(None, conv.apply_lut_pil)))
def test_pil_to_ascii(invert, equalize, lut, lookup_func):
img = np.random.randint(0, 255, (480, 640), dtype=np.uint8)
h, w = img.shape
expected_len = int(h*0.5*conv.ASPECTCORRECTIONFACTOR)*(int(w*0.5)+1)+1
img = conv.numpy_to_pil(img)
text = conv.pil_to_ascii(img, 0.5, invert, equalize, lut, lookup_func)
assert(len(text) == expected_len)
@pytest.mark.parametrize("invert,equalize,lut",
itertools.product((True, False),
(True, False),
("simple", "binary")))
def test_numpy_to_ascii(invert, equalize, lut):
img = np.random.randint(0, 255, (480, 640), dtype=np.uint8)
h, w = img.shape
expected_len = int(h*0.5*conv.ASPECTCORRECTIONFACTOR)*(int(w*0.5)+1)+1
text = conv.numpy_to_ascii(img, 0.5, invert, equalize, lut)
assert(len(text) == expected_len)
def test_lookup_method_equivalency():
img = np.random.randint(0, 255, (300,300), dtype=np.uint8)
pil_ascii = conv.apply_lut_pil(img)
np_ascii = conv.apply_lut_numpy(img)
assert(pil_ascii == np_ascii)
pil_ascii = conv.apply_lut_pil(img, "binary")
np_ascii = conv.apply_lut_numpy(img, "binary")
assert(pil_ascii == np_ascii)
| Add tests to minimally exercise basic conversion functionality | Add tests to minimally exercise basic conversion functionality
| Python | mit | derricw/asciisciit | + import itertools
from asciisciit import conversions as conv
import numpy as np
+ import pytest
+
+
+ @pytest.mark.parametrize("invert,equalize,lut,lookup_func",
+ itertools.product((True, False),
+ (True, False),
+ ("simple", "binary"),
+ (None, conv.apply_lut_pil)))
+ def test_pil_to_ascii(invert, equalize, lut, lookup_func):
+ img = np.random.randint(0, 255, (480, 640), dtype=np.uint8)
+ h, w = img.shape
+ expected_len = int(h*0.5*conv.ASPECTCORRECTIONFACTOR)*(int(w*0.5)+1)+1
+ img = conv.numpy_to_pil(img)
+ text = conv.pil_to_ascii(img, 0.5, invert, equalize, lut, lookup_func)
+ assert(len(text) == expected_len)
+
+
+ @pytest.mark.parametrize("invert,equalize,lut",
+ itertools.product((True, False),
+ (True, False),
+ ("simple", "binary")))
+ def test_numpy_to_ascii(invert, equalize, lut):
+ img = np.random.randint(0, 255, (480, 640), dtype=np.uint8)
+ h, w = img.shape
+ expected_len = int(h*0.5*conv.ASPECTCORRECTIONFACTOR)*(int(w*0.5)+1)+1
+ text = conv.numpy_to_ascii(img, 0.5, invert, equalize, lut)
+ assert(len(text) == expected_len)
def test_lookup_method_equivalency():
img = np.random.randint(0, 255, (300,300), dtype=np.uint8)
pil_ascii = conv.apply_lut_pil(img)
np_ascii = conv.apply_lut_numpy(img)
assert(pil_ascii == np_ascii)
pil_ascii = conv.apply_lut_pil(img, "binary")
np_ascii = conv.apply_lut_numpy(img, "binary")
assert(pil_ascii == np_ascii)
+ | Add tests to minimally exercise basic conversion functionality | ## Code Before:
from asciisciit import conversions as conv
import numpy as np
def test_lookup_method_equivalency():
img = np.random.randint(0, 255, (300,300), dtype=np.uint8)
pil_ascii = conv.apply_lut_pil(img)
np_ascii = conv.apply_lut_numpy(img)
assert(pil_ascii == np_ascii)
pil_ascii = conv.apply_lut_pil(img, "binary")
np_ascii = conv.apply_lut_numpy(img, "binary")
assert(pil_ascii == np_ascii)
## Instruction:
Add tests to minimally exercise basic conversion functionality
## Code After:
import itertools
from asciisciit import conversions as conv
import numpy as np
import pytest
@pytest.mark.parametrize("invert,equalize,lut,lookup_func",
itertools.product((True, False),
(True, False),
("simple", "binary"),
(None, conv.apply_lut_pil)))
def test_pil_to_ascii(invert, equalize, lut, lookup_func):
img = np.random.randint(0, 255, (480, 640), dtype=np.uint8)
h, w = img.shape
expected_len = int(h*0.5*conv.ASPECTCORRECTIONFACTOR)*(int(w*0.5)+1)+1
img = conv.numpy_to_pil(img)
text = conv.pil_to_ascii(img, 0.5, invert, equalize, lut, lookup_func)
assert(len(text) == expected_len)
@pytest.mark.parametrize("invert,equalize,lut",
itertools.product((True, False),
(True, False),
("simple", "binary")))
def test_numpy_to_ascii(invert, equalize, lut):
img = np.random.randint(0, 255, (480, 640), dtype=np.uint8)
h, w = img.shape
expected_len = int(h*0.5*conv.ASPECTCORRECTIONFACTOR)*(int(w*0.5)+1)+1
text = conv.numpy_to_ascii(img, 0.5, invert, equalize, lut)
assert(len(text) == expected_len)
def test_lookup_method_equivalency():
img = np.random.randint(0, 255, (300,300), dtype=np.uint8)
pil_ascii = conv.apply_lut_pil(img)
np_ascii = conv.apply_lut_numpy(img)
assert(pil_ascii == np_ascii)
pil_ascii = conv.apply_lut_pil(img, "binary")
np_ascii = conv.apply_lut_numpy(img, "binary")
assert(pil_ascii == np_ascii)
| # ... existing code ...
import itertools
from asciisciit import conversions as conv
import numpy as np
import pytest
@pytest.mark.parametrize("invert,equalize,lut,lookup_func",
itertools.product((True, False),
(True, False),
("simple", "binary"),
(None, conv.apply_lut_pil)))
def test_pil_to_ascii(invert, equalize, lut, lookup_func):
img = np.random.randint(0, 255, (480, 640), dtype=np.uint8)
h, w = img.shape
expected_len = int(h*0.5*conv.ASPECTCORRECTIONFACTOR)*(int(w*0.5)+1)+1
img = conv.numpy_to_pil(img)
text = conv.pil_to_ascii(img, 0.5, invert, equalize, lut, lookup_func)
assert(len(text) == expected_len)
@pytest.mark.parametrize("invert,equalize,lut",
itertools.product((True, False),
(True, False),
("simple", "binary")))
def test_numpy_to_ascii(invert, equalize, lut):
img = np.random.randint(0, 255, (480, 640), dtype=np.uint8)
h, w = img.shape
expected_len = int(h*0.5*conv.ASPECTCORRECTIONFACTOR)*(int(w*0.5)+1)+1
text = conv.numpy_to_ascii(img, 0.5, invert, equalize, lut)
assert(len(text) == expected_len)
# ... rest of the code ... |
638901243c060b243ebf046304c06ea14a98dbe8 | dynochemy/errors.py | dynochemy/errors.py | import json
class Error(Exception):
"""This is an ambiguous error that occured."""
pass
class SyncUnallowedError(Error): pass
class DuplicateBatchItemError(Error): pass
class IncompleteSolventError(Error): pass
class ExceededBatchRequestsError(Error): pass
class ItemNotFoundError(Error): pass
class DynamoDBError(Error): pass
class ProvisionedThroughputError(DynamoDBError): pass
class UnprocessedItemError(DynamoDBError): pass
def parse_error(raw_error):
"""Parse the error we get out of Boto into something we can code around"""
if isinstance(raw_error, Error):
return raw_error
error_data = json.loads(raw_error.data)
if 'ProvisionedThroughputExceededException' in error_data['__type']:
return ProvisionedThroughputError(error_data['message'])
else:
return DynamoDBError(error_data['message'], error_data['__type'])
__all__ = ["Error", "SyncUnallowedError", "DuplicateBatchItemError", "DynamoDBError", "ProvisionedThroughputError", "ItemNotFoundError"]
| import json
class Error(Exception):
"""This is an ambiguous error that occured."""
pass
class SyncUnallowedError(Error): pass
class DuplicateBatchItemError(Error): pass
class IncompleteSolventError(Error): pass
class ExceededBatchRequestsError(Error): pass
class ItemNotFoundError(Error): pass
class DynamoDBError(Error): pass
class ProvisionedThroughputError(DynamoDBError): pass
class UnprocessedItemError(DynamoDBError): pass
def parse_error(raw_error):
"""Parse the error we get out of Boto into something we can code around"""
if isinstance(raw_error, Error):
return raw_error
if 'ProvisionedThroughputExceededException' in raw_error.error_code:
return ProvisionedThroughputError(raw_error.error_message)
else:
return DynamoDBError(raw_error.error_message, raw_error.error_code)
__all__ = ["Error", "SyncUnallowedError", "DuplicateBatchItemError", "DynamoDBError", "ProvisionedThroughputError", "ItemNotFoundError"]
| Handle updated boto exception format. | Handle updated boto exception format.
See https://github.com/boto/boto/issues/625
| Python | isc | rhettg/Dynochemy | import json
class Error(Exception):
"""This is an ambiguous error that occured."""
pass
class SyncUnallowedError(Error): pass
class DuplicateBatchItemError(Error): pass
class IncompleteSolventError(Error): pass
class ExceededBatchRequestsError(Error): pass
class ItemNotFoundError(Error): pass
class DynamoDBError(Error): pass
class ProvisionedThroughputError(DynamoDBError): pass
class UnprocessedItemError(DynamoDBError): pass
def parse_error(raw_error):
"""Parse the error we get out of Boto into something we can code around"""
if isinstance(raw_error, Error):
return raw_error
- error_data = json.loads(raw_error.data)
- if 'ProvisionedThroughputExceededException' in error_data['__type']:
+ if 'ProvisionedThroughputExceededException' in raw_error.error_code:
- return ProvisionedThroughputError(error_data['message'])
+ return ProvisionedThroughputError(raw_error.error_message)
else:
- return DynamoDBError(error_data['message'], error_data['__type'])
+ return DynamoDBError(raw_error.error_message, raw_error.error_code)
__all__ = ["Error", "SyncUnallowedError", "DuplicateBatchItemError", "DynamoDBError", "ProvisionedThroughputError", "ItemNotFoundError"]
| Handle updated boto exception format. | ## Code Before:
import json
class Error(Exception):
"""This is an ambiguous error that occured."""
pass
class SyncUnallowedError(Error): pass
class DuplicateBatchItemError(Error): pass
class IncompleteSolventError(Error): pass
class ExceededBatchRequestsError(Error): pass
class ItemNotFoundError(Error): pass
class DynamoDBError(Error): pass
class ProvisionedThroughputError(DynamoDBError): pass
class UnprocessedItemError(DynamoDBError): pass
def parse_error(raw_error):
"""Parse the error we get out of Boto into something we can code around"""
if isinstance(raw_error, Error):
return raw_error
error_data = json.loads(raw_error.data)
if 'ProvisionedThroughputExceededException' in error_data['__type']:
return ProvisionedThroughputError(error_data['message'])
else:
return DynamoDBError(error_data['message'], error_data['__type'])
__all__ = ["Error", "SyncUnallowedError", "DuplicateBatchItemError", "DynamoDBError", "ProvisionedThroughputError", "ItemNotFoundError"]
## Instruction:
Handle updated boto exception format.
## Code After:
import json
class Error(Exception):
"""This is an ambiguous error that occured."""
pass
class SyncUnallowedError(Error): pass
class DuplicateBatchItemError(Error): pass
class IncompleteSolventError(Error): pass
class ExceededBatchRequestsError(Error): pass
class ItemNotFoundError(Error): pass
class DynamoDBError(Error): pass
class ProvisionedThroughputError(DynamoDBError): pass
class UnprocessedItemError(DynamoDBError): pass
def parse_error(raw_error):
"""Parse the error we get out of Boto into something we can code around"""
if isinstance(raw_error, Error):
return raw_error
if 'ProvisionedThroughputExceededException' in raw_error.error_code:
return ProvisionedThroughputError(raw_error.error_message)
else:
return DynamoDBError(raw_error.error_message, raw_error.error_code)
__all__ = ["Error", "SyncUnallowedError", "DuplicateBatchItemError", "DynamoDBError", "ProvisionedThroughputError", "ItemNotFoundError"]
| // ... existing code ...
return raw_error
if 'ProvisionedThroughputExceededException' in raw_error.error_code:
return ProvisionedThroughputError(raw_error.error_message)
else:
return DynamoDBError(raw_error.error_message, raw_error.error_code)
// ... rest of the code ... |
2794f71e1a4c9ac8aa70f22ce3c9d01bf2d7737a | humanize/__init__.py | humanize/__init__.py | __version__ = VERSION = (0, 5, 1)
from humanize.time import *
from humanize.number import *
from humanize.filesize import *
from humanize.i18n import activate, deactivate
__all__ = ['__version__', 'VERSION', 'naturalday', 'naturaltime', 'ordinal', 'intword',
'naturaldelta', 'intcomma', 'apnumber', 'fractional', 'naturalsize',
'activate', 'deactivate', 'naturaldate']
| __version__ = VERSION = (0, 5, 1)
from humanize.time import *
from humanize.number import *
from humanize.filesize import *
from humanize.i18n import activate, deactivate
__all__ = [
"__version__",
"activate",
"apnumber",
"deactivate",
"fractional",
"intcomma",
"intword",
"naturaldate",
"naturalday",
"naturaldelta",
"naturalsize",
"naturaltime",
"ordinal",
"VERSION",
]
| Format with Black and sort | Format with Black and sort
| Python | mit | jmoiron/humanize,jmoiron/humanize | __version__ = VERSION = (0, 5, 1)
from humanize.time import *
from humanize.number import *
from humanize.filesize import *
from humanize.i18n import activate, deactivate
- __all__ = ['__version__', 'VERSION', 'naturalday', 'naturaltime', 'ordinal', 'intword',
- 'naturaldelta', 'intcomma', 'apnumber', 'fractional', 'naturalsize',
- 'activate', 'deactivate', 'naturaldate']
+ __all__ = [
+ "__version__",
+ "activate",
+ "apnumber",
+ "deactivate",
+ "fractional",
+ "intcomma",
+ "intword",
+ "naturaldate",
+ "naturalday",
+ "naturaldelta",
+ "naturalsize",
+ "naturaltime",
+ "ordinal",
+ "VERSION",
+ ]
| Format with Black and sort | ## Code Before:
__version__ = VERSION = (0, 5, 1)
from humanize.time import *
from humanize.number import *
from humanize.filesize import *
from humanize.i18n import activate, deactivate
__all__ = ['__version__', 'VERSION', 'naturalday', 'naturaltime', 'ordinal', 'intword',
'naturaldelta', 'intcomma', 'apnumber', 'fractional', 'naturalsize',
'activate', 'deactivate', 'naturaldate']
## Instruction:
Format with Black and sort
## Code After:
__version__ = VERSION = (0, 5, 1)
from humanize.time import *
from humanize.number import *
from humanize.filesize import *
from humanize.i18n import activate, deactivate
__all__ = [
"__version__",
"activate",
"apnumber",
"deactivate",
"fractional",
"intcomma",
"intword",
"naturaldate",
"naturalday",
"naturaldelta",
"naturalsize",
"naturaltime",
"ordinal",
"VERSION",
]
| ...
from humanize.i18n import activate, deactivate
__all__ = [
"__version__",
"activate",
"apnumber",
"deactivate",
"fractional",
"intcomma",
"intword",
"naturaldate",
"naturalday",
"naturaldelta",
"naturalsize",
"naturaltime",
"ordinal",
"VERSION",
]
... |
b86c53c388c39baee1ddfe3a615cdad20d272055 | antcolony/util.py | antcolony/util.py | import json
def avg(iterable):
return sum(iterable) / len(iterable)
def nice_json_dump(data, filepath):
with open(filepath, 'w') as f:
json.dump(data, f, sort_keys=True, indent=4, separators=(',', ': '))
| import json
def avg(iterable):
sum_ = 0
element_count = 0
for element in iterable:
sum_ += element
element_count += 1
return sum_ / element_count
def nice_json_dump(data, filepath):
with open(filepath, 'w') as f:
json.dump(data, f, sort_keys=True, indent=4, separators=(',', ': '))
| Make avg() work with iterators | Make avg() work with iterators
| Python | bsd-3-clause | ppolewicz/ant-colony,ppolewicz/ant-colony | import json
def avg(iterable):
- return sum(iterable) / len(iterable)
+ sum_ = 0
+ element_count = 0
+ for element in iterable:
+ sum_ += element
+ element_count += 1
+ return sum_ / element_count
def nice_json_dump(data, filepath):
with open(filepath, 'w') as f:
json.dump(data, f, sort_keys=True, indent=4, separators=(',', ': '))
| Make avg() work with iterators | ## Code Before:
import json
def avg(iterable):
return sum(iterable) / len(iterable)
def nice_json_dump(data, filepath):
with open(filepath, 'w') as f:
json.dump(data, f, sort_keys=True, indent=4, separators=(',', ': '))
## Instruction:
Make avg() work with iterators
## Code After:
import json
def avg(iterable):
sum_ = 0
element_count = 0
for element in iterable:
sum_ += element
element_count += 1
return sum_ / element_count
def nice_json_dump(data, filepath):
with open(filepath, 'w') as f:
json.dump(data, f, sort_keys=True, indent=4, separators=(',', ': '))
| ...
def avg(iterable):
sum_ = 0
element_count = 0
for element in iterable:
sum_ += element
element_count += 1
return sum_ / element_count
def nice_json_dump(data, filepath):
... |
67d08d61186f7d9bc0026c1d867039f58872fee7 | main.py | main.py | import cmd
import argparse
from Interface import *
class Lexeme(cmd.Cmd):
intro = "Welcome to Lexeme! Input '?' for help and commands."
prompt = "Enter command: "
def do_list(self, arg):
'List word database.'
listwords()
def do_quit(self, arg):
quit()
def do_add(self, arg):
add()
def do_decline(self, arg):
decline()
def do_statistics(self, arg):
statistics()
def do_search(self, arg):
search()
def do_generate(self, arg):
generate()
def do_export(self, arg):
export()
def do_batch(self, arg):
batchgenerate()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--database", help="set database file")
parser.add_argument("--config", help="set configuration file")
args = parser.parse_args()
if args.database is not None:
Library.loadDatabase(args.database)
else:
Library.loadDatabase()
if args.config is not None:
loadData(args.config)
else:
loadData()
Lexeme().cmdloop()
| import cmd
import argparse
from Interface import *
class Lexeme(cmd.Cmd):
intro = "Welcome to Lexeme! Input '?' for help and commands."
prompt = "Enter command: "
def do_list(self, arg):
'List word database.'
listwords()
def do_quit(self, arg):
quit()
def do_add(self, arg):
add()
def do_decline(self, arg):
decline()
def do_statistics(self, arg):
statistics()
def do_search(self, arg):
search()
def do_generate(self, arg):
generate()
def do_export(self, arg):
export()
def do_batch(self, arg):
batchgenerate()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--database", help="set database file")
parser.add_argument("--config", help="set configuration file")
args = parser.parse_args()
if args.database is not None:
Library.loadDatabase(args.database)
else:
Library.loadDatabase()
if args.config is not None:
loadData(args.config)
else:
loadData()
clearScreen()
Lexeme().cmdloop()
| Clear screen at start of program | Clear screen at start of program
| Python | mit | kdelwat/Lexeme | import cmd
import argparse
from Interface import *
class Lexeme(cmd.Cmd):
intro = "Welcome to Lexeme! Input '?' for help and commands."
prompt = "Enter command: "
def do_list(self, arg):
'List word database.'
listwords()
def do_quit(self, arg):
quit()
def do_add(self, arg):
add()
def do_decline(self, arg):
decline()
def do_statistics(self, arg):
statistics()
def do_search(self, arg):
search()
def do_generate(self, arg):
generate()
def do_export(self, arg):
export()
def do_batch(self, arg):
batchgenerate()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--database", help="set database file")
parser.add_argument("--config", help="set configuration file")
args = parser.parse_args()
if args.database is not None:
Library.loadDatabase(args.database)
else:
Library.loadDatabase()
if args.config is not None:
loadData(args.config)
else:
loadData()
+ clearScreen()
+
Lexeme().cmdloop()
| Clear screen at start of program | ## Code Before:
import cmd
import argparse
from Interface import *
class Lexeme(cmd.Cmd):
intro = "Welcome to Lexeme! Input '?' for help and commands."
prompt = "Enter command: "
def do_list(self, arg):
'List word database.'
listwords()
def do_quit(self, arg):
quit()
def do_add(self, arg):
add()
def do_decline(self, arg):
decline()
def do_statistics(self, arg):
statistics()
def do_search(self, arg):
search()
def do_generate(self, arg):
generate()
def do_export(self, arg):
export()
def do_batch(self, arg):
batchgenerate()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--database", help="set database file")
parser.add_argument("--config", help="set configuration file")
args = parser.parse_args()
if args.database is not None:
Library.loadDatabase(args.database)
else:
Library.loadDatabase()
if args.config is not None:
loadData(args.config)
else:
loadData()
Lexeme().cmdloop()
## Instruction:
Clear screen at start of program
## Code After:
import cmd
import argparse
from Interface import *
class Lexeme(cmd.Cmd):
intro = "Welcome to Lexeme! Input '?' for help and commands."
prompt = "Enter command: "
def do_list(self, arg):
'List word database.'
listwords()
def do_quit(self, arg):
quit()
def do_add(self, arg):
add()
def do_decline(self, arg):
decline()
def do_statistics(self, arg):
statistics()
def do_search(self, arg):
search()
def do_generate(self, arg):
generate()
def do_export(self, arg):
export()
def do_batch(self, arg):
batchgenerate()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--database", help="set database file")
parser.add_argument("--config", help="set configuration file")
args = parser.parse_args()
if args.database is not None:
Library.loadDatabase(args.database)
else:
Library.loadDatabase()
if args.config is not None:
loadData(args.config)
else:
loadData()
clearScreen()
Lexeme().cmdloop()
| // ... existing code ...
loadData()
clearScreen()
Lexeme().cmdloop()
// ... rest of the code ... |
e03cf2206733dc9f005375abef78238cf4011b50 | dashi/config.py | dashi/config.py | import json
import logging
import os
LOGGER = logging.getLogger(__name__)
class User():
def __init__(self, config):
self.config = config
@property
def aliases(self):
return [self.config['name']] + self.config.get('aliases', [])
def _load_config():
for path in ['dashi.conf', os.path.join(os.environ['HOME'], '.dashi'), '/etc/dashi.conf']:
try:
with open(path, 'r') as f:
return json.load(f)
except FileNotFoundError:
LOGGER.info("Unable to read config file at %s", path)
except ValueError as e:
LOGGER.warning("Failed to parse config file %s: %s", path, e)
raise Exception("Unable to load any configuration files")
def parse():
config = _load_config()
config['users'] = [User(c) for c in config['users']]
return config
| import json
import logging
import os
LOGGER = logging.getLogger(__name__)
class User():
def __init__(self, config):
self.config = config
@property
def aliases(self):
return [self.config['name']] + self.config.get('aliases', [])
@property
def first_name(self):
return self.config['name'].partition(' ')[0]
def __str__(self):
return 'User {}'.format(self.config['name'])
def __repr__(self):
return str(self)
def _load_config():
for path in ['dashi.conf', os.path.join(os.environ['HOME'], '.dashi'), '/etc/dashi.conf']:
try:
with open(path, 'r') as f:
return json.load(f)
except FileNotFoundError:
LOGGER.info("Unable to read config file at %s", path)
except ValueError as e:
LOGGER.warning("Failed to parse config file %s: %s", path, e)
raise Exception("Unable to load any configuration files")
def parse():
config = _load_config()
config['users'] = [User(c) for c in config['users']]
return config
def get_user(config, username):
matches = []
for user in config['users']:
for alias in user.aliases:
if username in alias and user not in matches:
matches.append(user)
if len(matches) == 1:
return matches[0]
elif len(matches) > 1:
raise Exception("Username '{}' matched {}".format(username, ', '.join([m['name'] for m in matches])))
else:
raise Exception("Unable to match user '{}'".format(username))
| Add the ability to get users and represent them | Add the ability to get users and represent them
Also added a handy first name property for easy table display
| Python | mit | EliRibble/dashi,EliRibble/dashi | import json
import logging
import os
LOGGER = logging.getLogger(__name__)
class User():
def __init__(self, config):
self.config = config
@property
def aliases(self):
return [self.config['name']] + self.config.get('aliases', [])
+
+ @property
+ def first_name(self):
+ return self.config['name'].partition(' ')[0]
+
+ def __str__(self):
+ return 'User {}'.format(self.config['name'])
+
+ def __repr__(self):
+ return str(self)
def _load_config():
for path in ['dashi.conf', os.path.join(os.environ['HOME'], '.dashi'), '/etc/dashi.conf']:
try:
with open(path, 'r') as f:
return json.load(f)
except FileNotFoundError:
LOGGER.info("Unable to read config file at %s", path)
except ValueError as e:
LOGGER.warning("Failed to parse config file %s: %s", path, e)
raise Exception("Unable to load any configuration files")
def parse():
config = _load_config()
config['users'] = [User(c) for c in config['users']]
return config
+ def get_user(config, username):
+ matches = []
+ for user in config['users']:
+ for alias in user.aliases:
+ if username in alias and user not in matches:
+ matches.append(user)
+ if len(matches) == 1:
+ return matches[0]
+ elif len(matches) > 1:
+ raise Exception("Username '{}' matched {}".format(username, ', '.join([m['name'] for m in matches])))
+ else:
+ raise Exception("Unable to match user '{}'".format(username))
+
+
+ | Add the ability to get users and represent them | ## Code Before:
import json
import logging
import os
LOGGER = logging.getLogger(__name__)
class User():
def __init__(self, config):
self.config = config
@property
def aliases(self):
return [self.config['name']] + self.config.get('aliases', [])
def _load_config():
for path in ['dashi.conf', os.path.join(os.environ['HOME'], '.dashi'), '/etc/dashi.conf']:
try:
with open(path, 'r') as f:
return json.load(f)
except FileNotFoundError:
LOGGER.info("Unable to read config file at %s", path)
except ValueError as e:
LOGGER.warning("Failed to parse config file %s: %s", path, e)
raise Exception("Unable to load any configuration files")
def parse():
config = _load_config()
config['users'] = [User(c) for c in config['users']]
return config
## Instruction:
Add the ability to get users and represent them
## Code After:
import json
import logging
import os
LOGGER = logging.getLogger(__name__)
class User():
def __init__(self, config):
self.config = config
@property
def aliases(self):
return [self.config['name']] + self.config.get('aliases', [])
@property
def first_name(self):
return self.config['name'].partition(' ')[0]
def __str__(self):
return 'User {}'.format(self.config['name'])
def __repr__(self):
return str(self)
def _load_config():
for path in ['dashi.conf', os.path.join(os.environ['HOME'], '.dashi'), '/etc/dashi.conf']:
try:
with open(path, 'r') as f:
return json.load(f)
except FileNotFoundError:
LOGGER.info("Unable to read config file at %s", path)
except ValueError as e:
LOGGER.warning("Failed to parse config file %s: %s", path, e)
raise Exception("Unable to load any configuration files")
def parse():
config = _load_config()
config['users'] = [User(c) for c in config['users']]
return config
def get_user(config, username):
matches = []
for user in config['users']:
for alias in user.aliases:
if username in alias and user not in matches:
matches.append(user)
if len(matches) == 1:
return matches[0]
elif len(matches) > 1:
raise Exception("Username '{}' matched {}".format(username, ', '.join([m['name'] for m in matches])))
else:
raise Exception("Unable to match user '{}'".format(username))
| // ... existing code ...
def aliases(self):
return [self.config['name']] + self.config.get('aliases', [])
@property
def first_name(self):
return self.config['name'].partition(' ')[0]
def __str__(self):
return 'User {}'.format(self.config['name'])
def __repr__(self):
return str(self)
def _load_config():
// ... modified code ...
return config
def get_user(config, username):
matches = []
for user in config['users']:
for alias in user.aliases:
if username in alias and user not in matches:
matches.append(user)
if len(matches) == 1:
return matches[0]
elif len(matches) > 1:
raise Exception("Username '{}' matched {}".format(username, ', '.join([m['name'] for m in matches])))
else:
raise Exception("Unable to match user '{}'".format(username))
// ... rest of the code ... |
791d378d1c5cb2e9729877bc70261b9354bdb590 | testsuite/cases/pillow_rotate_right.py | testsuite/cases/pillow_rotate_right.py |
from __future__ import print_function, unicode_literals, absolute_import
from PIL import Image
from .base import rpartial
from .pillow import PillowTestCase
class RotateRightCase(PillowTestCase):
def handle_args(self, name, transposition):
self.name = name
self.transposition = transposition
def runner(self, im):
im.transpose(self.transposition)
def readable_args(self):
return [self.name]
cases = [
rpartial(RotateRightCase, 'Flop', Image.FLIP_LEFT_RIGHT),
rpartial(RotateRightCase, 'Flip', Image.FLIP_TOP_BOTTOM),
rpartial(RotateRightCase, 'Rotate 90', Image.ROTATE_90),
rpartial(RotateRightCase, 'Rotate 180', Image.ROTATE_180),
rpartial(RotateRightCase, 'Rotate 270', Image.ROTATE_270),
]
if hasattr(Image, 'TRANSPOSE'):
cases.append(rpartial(RotateRightCase, 'Transpose', Image.TRANSPOSE))
|
from __future__ import print_function, unicode_literals, absolute_import
from PIL import Image
from .base import rpartial
from .pillow import PillowTestCase
class RotateRightCase(PillowTestCase):
def handle_args(self, name, transposition):
self.name = name
self.transposition = transposition
def runner(self, im):
for trans in self.transposition:
im = im.transpose(trans)
def readable_args(self):
return [self.name]
cases = [
rpartial(RotateRightCase, 'Flop', [Image.FLIP_LEFT_RIGHT]),
rpartial(RotateRightCase, 'Flip', [Image.FLIP_TOP_BOTTOM]),
rpartial(RotateRightCase, 'Rotate 90', [Image.ROTATE_90]),
rpartial(RotateRightCase, 'Rotate 180', [Image.ROTATE_180]),
rpartial(RotateRightCase, 'Rotate 270', [Image.ROTATE_270]),
rpartial(RotateRightCase, 'Transpose',
[Image.TRANSPOSE]
if hasattr(Image, 'TRANSPOSE')
else [Image.ROTATE_90, Image.FLIP_LEFT_RIGHT]),
rpartial(RotateRightCase, 'Transpose180',
[Image.TRANSPOSE_ROTATE_180]
if hasattr(Image, 'TRANSPOSE_ROTATE_180')
else [Image.ROTATE_270, Image.FLIP_LEFT_RIGHT]),
]
| Transpose and Transpose180 for all Pillow versions | Transpose and Transpose180 for all Pillow versions
| Python | mit | python-pillow/pillow-perf,python-pillow/pillow-perf |
from __future__ import print_function, unicode_literals, absolute_import
from PIL import Image
from .base import rpartial
from .pillow import PillowTestCase
class RotateRightCase(PillowTestCase):
def handle_args(self, name, transposition):
self.name = name
self.transposition = transposition
def runner(self, im):
- im.transpose(self.transposition)
+ for trans in self.transposition:
+ im = im.transpose(trans)
def readable_args(self):
return [self.name]
cases = [
- rpartial(RotateRightCase, 'Flop', Image.FLIP_LEFT_RIGHT),
+ rpartial(RotateRightCase, 'Flop', [Image.FLIP_LEFT_RIGHT]),
- rpartial(RotateRightCase, 'Flip', Image.FLIP_TOP_BOTTOM),
+ rpartial(RotateRightCase, 'Flip', [Image.FLIP_TOP_BOTTOM]),
- rpartial(RotateRightCase, 'Rotate 90', Image.ROTATE_90),
+ rpartial(RotateRightCase, 'Rotate 90', [Image.ROTATE_90]),
- rpartial(RotateRightCase, 'Rotate 180', Image.ROTATE_180),
+ rpartial(RotateRightCase, 'Rotate 180', [Image.ROTATE_180]),
- rpartial(RotateRightCase, 'Rotate 270', Image.ROTATE_270),
+ rpartial(RotateRightCase, 'Rotate 270', [Image.ROTATE_270]),
+ rpartial(RotateRightCase, 'Transpose',
+ [Image.TRANSPOSE]
+ if hasattr(Image, 'TRANSPOSE')
+ else [Image.ROTATE_90, Image.FLIP_LEFT_RIGHT]),
+ rpartial(RotateRightCase, 'Transpose180',
+ [Image.TRANSPOSE_ROTATE_180]
+ if hasattr(Image, 'TRANSPOSE_ROTATE_180')
+ else [Image.ROTATE_270, Image.FLIP_LEFT_RIGHT]),
]
- if hasattr(Image, 'TRANSPOSE'):
- cases.append(rpartial(RotateRightCase, 'Transpose', Image.TRANSPOSE))
- | Transpose and Transpose180 for all Pillow versions | ## Code Before:
from __future__ import print_function, unicode_literals, absolute_import
from PIL import Image
from .base import rpartial
from .pillow import PillowTestCase
class RotateRightCase(PillowTestCase):
def handle_args(self, name, transposition):
self.name = name
self.transposition = transposition
def runner(self, im):
im.transpose(self.transposition)
def readable_args(self):
return [self.name]
cases = [
rpartial(RotateRightCase, 'Flop', Image.FLIP_LEFT_RIGHT),
rpartial(RotateRightCase, 'Flip', Image.FLIP_TOP_BOTTOM),
rpartial(RotateRightCase, 'Rotate 90', Image.ROTATE_90),
rpartial(RotateRightCase, 'Rotate 180', Image.ROTATE_180),
rpartial(RotateRightCase, 'Rotate 270', Image.ROTATE_270),
]
if hasattr(Image, 'TRANSPOSE'):
cases.append(rpartial(RotateRightCase, 'Transpose', Image.TRANSPOSE))
## Instruction:
Transpose and Transpose180 for all Pillow versions
## Code After:
from __future__ import print_function, unicode_literals, absolute_import
from PIL import Image
from .base import rpartial
from .pillow import PillowTestCase
class RotateRightCase(PillowTestCase):
def handle_args(self, name, transposition):
self.name = name
self.transposition = transposition
def runner(self, im):
for trans in self.transposition:
im = im.transpose(trans)
def readable_args(self):
return [self.name]
cases = [
rpartial(RotateRightCase, 'Flop', [Image.FLIP_LEFT_RIGHT]),
rpartial(RotateRightCase, 'Flip', [Image.FLIP_TOP_BOTTOM]),
rpartial(RotateRightCase, 'Rotate 90', [Image.ROTATE_90]),
rpartial(RotateRightCase, 'Rotate 180', [Image.ROTATE_180]),
rpartial(RotateRightCase, 'Rotate 270', [Image.ROTATE_270]),
rpartial(RotateRightCase, 'Transpose',
[Image.TRANSPOSE]
if hasattr(Image, 'TRANSPOSE')
else [Image.ROTATE_90, Image.FLIP_LEFT_RIGHT]),
rpartial(RotateRightCase, 'Transpose180',
[Image.TRANSPOSE_ROTATE_180]
if hasattr(Image, 'TRANSPOSE_ROTATE_180')
else [Image.ROTATE_270, Image.FLIP_LEFT_RIGHT]),
]
| ...
def runner(self, im):
for trans in self.transposition:
im = im.transpose(trans)
def readable_args(self):
...
cases = [
rpartial(RotateRightCase, 'Flop', [Image.FLIP_LEFT_RIGHT]),
rpartial(RotateRightCase, 'Flip', [Image.FLIP_TOP_BOTTOM]),
rpartial(RotateRightCase, 'Rotate 90', [Image.ROTATE_90]),
rpartial(RotateRightCase, 'Rotate 180', [Image.ROTATE_180]),
rpartial(RotateRightCase, 'Rotate 270', [Image.ROTATE_270]),
rpartial(RotateRightCase, 'Transpose',
[Image.TRANSPOSE]
if hasattr(Image, 'TRANSPOSE')
else [Image.ROTATE_90, Image.FLIP_LEFT_RIGHT]),
rpartial(RotateRightCase, 'Transpose180',
[Image.TRANSPOSE_ROTATE_180]
if hasattr(Image, 'TRANSPOSE_ROTATE_180')
else [Image.ROTATE_270, Image.FLIP_LEFT_RIGHT]),
]
... |
1e16c3810e41df7a4d6273750c713c086ad82c14 | weaveserver/core/plugins/virtualenv.py | weaveserver/core/plugins/virtualenv.py | import os
import subprocess
import virtualenv
class VirtualEnvManager(object):
def __init__(self, path):
self.venv_home = path
def install(self, requirements_file=None):
if os.path.exists(self.venv_home):
return True
virtualenv.create_environment(self.venv_home)
if requirements_file:
args = [os.path.join(self.venv_home, 'bin/python'), '-m', 'pip',
'install', '-r', requirements_file]
try:
subprocess.check_call(args)
except subprocess.CalledProcessError:
return False
def activate(self):
script = os.path.join(self.venv_home, "bin", "activate_this.py")
execfile(script, dict(__file__=script))
def deactivate(self):
pass
| import os
import subprocess
import virtualenv
def execute_file(path):
global_vars = {"__file__": path}
with open(path, 'rb') as pyfile:
exec(compile(pyfile.read(), path, 'exec'), global_vars)
class VirtualEnvManager(object):
def __init__(self, path):
self.venv_home = path
def install(self, requirements_file=None):
if os.path.exists(self.venv_home):
return True
virtualenv.create_environment(self.venv_home)
if requirements_file:
args = [os.path.join(self.venv_home, 'bin/python'), '-m', 'pip',
'install', '-r', requirements_file]
try:
subprocess.check_call(args)
except subprocess.CalledProcessError:
return False
def activate(self):
script = os.path.join(self.venv_home, "bin", "activate_this.py")
execute_file(script)
def deactivate(self):
pass
| Replace execfile with something compatible with both Py2/3. | Replace execfile with something compatible with both Py2/3.
| Python | mit | supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer | import os
import subprocess
import virtualenv
+
+
+ def execute_file(path):
+ global_vars = {"__file__": path}
+ with open(path, 'rb') as pyfile:
+ exec(compile(pyfile.read(), path, 'exec'), global_vars)
class VirtualEnvManager(object):
def __init__(self, path):
self.venv_home = path
def install(self, requirements_file=None):
if os.path.exists(self.venv_home):
return True
virtualenv.create_environment(self.venv_home)
if requirements_file:
args = [os.path.join(self.venv_home, 'bin/python'), '-m', 'pip',
'install', '-r', requirements_file]
try:
subprocess.check_call(args)
except subprocess.CalledProcessError:
return False
def activate(self):
script = os.path.join(self.venv_home, "bin", "activate_this.py")
- execfile(script, dict(__file__=script))
+ execute_file(script)
def deactivate(self):
pass
| Replace execfile with something compatible with both Py2/3. | ## Code Before:
import os
import subprocess
import virtualenv
class VirtualEnvManager(object):
def __init__(self, path):
self.venv_home = path
def install(self, requirements_file=None):
if os.path.exists(self.venv_home):
return True
virtualenv.create_environment(self.venv_home)
if requirements_file:
args = [os.path.join(self.venv_home, 'bin/python'), '-m', 'pip',
'install', '-r', requirements_file]
try:
subprocess.check_call(args)
except subprocess.CalledProcessError:
return False
def activate(self):
script = os.path.join(self.venv_home, "bin", "activate_this.py")
execfile(script, dict(__file__=script))
def deactivate(self):
pass
## Instruction:
Replace execfile with something compatible with both Py2/3.
## Code After:
import os
import subprocess
import virtualenv
def execute_file(path):
global_vars = {"__file__": path}
with open(path, 'rb') as pyfile:
exec(compile(pyfile.read(), path, 'exec'), global_vars)
class VirtualEnvManager(object):
def __init__(self, path):
self.venv_home = path
def install(self, requirements_file=None):
if os.path.exists(self.venv_home):
return True
virtualenv.create_environment(self.venv_home)
if requirements_file:
args = [os.path.join(self.venv_home, 'bin/python'), '-m', 'pip',
'install', '-r', requirements_file]
try:
subprocess.check_call(args)
except subprocess.CalledProcessError:
return False
def activate(self):
script = os.path.join(self.venv_home, "bin", "activate_this.py")
execute_file(script)
def deactivate(self):
pass
| # ... existing code ...
import virtualenv
def execute_file(path):
global_vars = {"__file__": path}
with open(path, 'rb') as pyfile:
exec(compile(pyfile.read(), path, 'exec'), global_vars)
# ... modified code ...
def activate(self):
script = os.path.join(self.venv_home, "bin", "activate_this.py")
execute_file(script)
def deactivate(self):
# ... rest of the code ... |
6422f6057d43dfb5259028291991f39c5b81b446 | spreadflow_core/flow.py | spreadflow_core/flow.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from collections import defaultdict
class Flowmap(dict):
def __init__(self):
super(Flowmap, self).__init__()
self.decorators = []
self.annotations = {}
def graph(self):
result = defaultdict(set)
backlog = set()
processed = set()
for port_out, port_in in self.iteritems():
result[port_out].add(port_in)
backlog.add(port_in)
while len(backlog):
node = backlog.pop()
if node in processed:
continue
else:
processed.add(node)
try:
arcs = tuple(node.dependencies)
except AttributeError:
continue
for port_out, port_in in arcs:
result[port_out].add(port_in)
backlog.add(port_out)
backlog.add(port_in)
return result
| from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from collections import defaultdict, MutableMapping
class Flowmap(MutableMapping):
def __init__(self):
super(Flowmap, self).__init__()
self.annotations = {}
self.connections = {}
self.decorators = []
def __getitem__(self, key):
return self.connections[key]
def __setitem__(self, key, value):
self.connections[key] = value
def __delitem__(self, key):
del self.connections[key]
def __iter__(self):
return iter(self.connections)
def __len__(self):
return len(self.connections)
def graph(self):
result = defaultdict(set)
backlog = set()
processed = set()
for port_out, port_in in self.iteritems():
result[port_out].add(port_in)
backlog.add(port_in)
while len(backlog):
node = backlog.pop()
if node in processed:
continue
else:
processed.add(node)
try:
arcs = tuple(node.dependencies)
except AttributeError:
continue
for port_out, port_in in arcs:
result[port_out].add(port_in)
backlog.add(port_out)
backlog.add(port_in)
return result
| Refactor Flowmap into a MutableMapping | Refactor Flowmap into a MutableMapping
| Python | mit | spreadflow/spreadflow-core,znerol/spreadflow-core | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
- from collections import defaultdict
+ from collections import defaultdict, MutableMapping
- class Flowmap(dict):
+ class Flowmap(MutableMapping):
def __init__(self):
super(Flowmap, self).__init__()
+ self.annotations = {}
+ self.connections = {}
self.decorators = []
- self.annotations = {}
+
+ def __getitem__(self, key):
+ return self.connections[key]
+
+ def __setitem__(self, key, value):
+ self.connections[key] = value
+
+ def __delitem__(self, key):
+ del self.connections[key]
+
+ def __iter__(self):
+ return iter(self.connections)
+
+ def __len__(self):
+ return len(self.connections)
def graph(self):
result = defaultdict(set)
backlog = set()
processed = set()
for port_out, port_in in self.iteritems():
result[port_out].add(port_in)
backlog.add(port_in)
while len(backlog):
node = backlog.pop()
if node in processed:
continue
else:
processed.add(node)
try:
arcs = tuple(node.dependencies)
except AttributeError:
continue
for port_out, port_in in arcs:
result[port_out].add(port_in)
backlog.add(port_out)
backlog.add(port_in)
return result
| Refactor Flowmap into a MutableMapping | ## Code Before:
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from collections import defaultdict
class Flowmap(dict):
def __init__(self):
super(Flowmap, self).__init__()
self.decorators = []
self.annotations = {}
def graph(self):
result = defaultdict(set)
backlog = set()
processed = set()
for port_out, port_in in self.iteritems():
result[port_out].add(port_in)
backlog.add(port_in)
while len(backlog):
node = backlog.pop()
if node in processed:
continue
else:
processed.add(node)
try:
arcs = tuple(node.dependencies)
except AttributeError:
continue
for port_out, port_in in arcs:
result[port_out].add(port_in)
backlog.add(port_out)
backlog.add(port_in)
return result
## Instruction:
Refactor Flowmap into a MutableMapping
## Code After:
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from collections import defaultdict, MutableMapping
class Flowmap(MutableMapping):
def __init__(self):
super(Flowmap, self).__init__()
self.annotations = {}
self.connections = {}
self.decorators = []
def __getitem__(self, key):
return self.connections[key]
def __setitem__(self, key, value):
self.connections[key] = value
def __delitem__(self, key):
del self.connections[key]
def __iter__(self):
return iter(self.connections)
def __len__(self):
return len(self.connections)
def graph(self):
result = defaultdict(set)
backlog = set()
processed = set()
for port_out, port_in in self.iteritems():
result[port_out].add(port_in)
backlog.add(port_in)
while len(backlog):
node = backlog.pop()
if node in processed:
continue
else:
processed.add(node)
try:
arcs = tuple(node.dependencies)
except AttributeError:
continue
for port_out, port_in in arcs:
result[port_out].add(port_in)
backlog.add(port_out)
backlog.add(port_in)
return result
| // ... existing code ...
from __future__ import unicode_literals
from collections import defaultdict, MutableMapping
class Flowmap(MutableMapping):
def __init__(self):
super(Flowmap, self).__init__()
self.annotations = {}
self.connections = {}
self.decorators = []
def __getitem__(self, key):
return self.connections[key]
def __setitem__(self, key, value):
self.connections[key] = value
def __delitem__(self, key):
del self.connections[key]
def __iter__(self):
return iter(self.connections)
def __len__(self):
return len(self.connections)
def graph(self):
// ... rest of the code ... |
91b01e37897ea20f6486118e4dd595439f81006b | ktane/Model/Modules/WiresModule.py | ktane/Model/Modules/WiresModule.py | from enum import Enum
from .AbstractModule import AbstractModule, ModuleState
class WireColors(Enum):
MISSING = 'missing'
BLACK = 'black'
RED = 'red'
WHITE = 'white'
BLUE = 'blue'
YELLOW = 'yellow'
def get_correct_wire(sequence, boolpar):
wires_count = get_wires_count(sequence)
def get_wires_count(sequence):
return len([1 for x in sequence if x != WireColors.MISSING.value])
def get_nth_wire_position(sequence, n):
NotImplementedError
class WiresModule(AbstractModule):
def export_to_string(self):
raise NotImplementedError
def import_from_string(self, string):
raise NotImplementedError
def translate_to_commands(self):
raise NotImplementedError
def __init__(self):
super().__init__()
self.name = "WiresModule"
self.type_number = 10
self.state = ModuleState.Armed
| from enum import Enum
from .AbstractModule import AbstractModule, ModuleState
class WireColors(Enum):
MISSING = 'missing'
BLACK = 'black'
RED = 'red'
WHITE = 'white'
BLUE = 'blue'
YELLOW = 'yellow'
def get_correct_wire(sequence, boolpar):
wires_count = get_wires_count(sequence)
def get_wires_count(sequence):
return len([1 for x in sequence if x != WireColors.MISSING.value])
def get_nth_wire_position(sequence, n):
counter = 0
for idx, value in enumerate(sequence):
if value != WireColors.MISSING.value:
counter += 1
if counter == n:
return idx
return None
class WiresModule(AbstractModule):
def export_to_string(self):
raise NotImplementedError
def import_from_string(self, string):
raise NotImplementedError
def translate_to_commands(self):
raise NotImplementedError
def __init__(self):
super().__init__()
self.name = "WiresModule"
self.type_number = 10
self.state = ModuleState.Armed
| Implement Wires helper method get_nth_wire_position | Implement Wires helper method get_nth_wire_position
| Python | mit | hanzikl/ktane-controller | from enum import Enum
from .AbstractModule import AbstractModule, ModuleState
class WireColors(Enum):
MISSING = 'missing'
BLACK = 'black'
RED = 'red'
WHITE = 'white'
BLUE = 'blue'
YELLOW = 'yellow'
def get_correct_wire(sequence, boolpar):
wires_count = get_wires_count(sequence)
def get_wires_count(sequence):
return len([1 for x in sequence if x != WireColors.MISSING.value])
def get_nth_wire_position(sequence, n):
- NotImplementedError
+ counter = 0
+ for idx, value in enumerate(sequence):
+ if value != WireColors.MISSING.value:
+ counter += 1
+ if counter == n:
+ return idx
+
+ return None
class WiresModule(AbstractModule):
def export_to_string(self):
raise NotImplementedError
def import_from_string(self, string):
raise NotImplementedError
def translate_to_commands(self):
raise NotImplementedError
def __init__(self):
super().__init__()
self.name = "WiresModule"
self.type_number = 10
self.state = ModuleState.Armed
| Implement Wires helper method get_nth_wire_position | ## Code Before:
from enum import Enum
from .AbstractModule import AbstractModule, ModuleState
class WireColors(Enum):
MISSING = 'missing'
BLACK = 'black'
RED = 'red'
WHITE = 'white'
BLUE = 'blue'
YELLOW = 'yellow'
def get_correct_wire(sequence, boolpar):
wires_count = get_wires_count(sequence)
def get_wires_count(sequence):
return len([1 for x in sequence if x != WireColors.MISSING.value])
def get_nth_wire_position(sequence, n):
NotImplementedError
class WiresModule(AbstractModule):
def export_to_string(self):
raise NotImplementedError
def import_from_string(self, string):
raise NotImplementedError
def translate_to_commands(self):
raise NotImplementedError
def __init__(self):
super().__init__()
self.name = "WiresModule"
self.type_number = 10
self.state = ModuleState.Armed
## Instruction:
Implement Wires helper method get_nth_wire_position
## Code After:
from enum import Enum
from .AbstractModule import AbstractModule, ModuleState
class WireColors(Enum):
MISSING = 'missing'
BLACK = 'black'
RED = 'red'
WHITE = 'white'
BLUE = 'blue'
YELLOW = 'yellow'
def get_correct_wire(sequence, boolpar):
wires_count = get_wires_count(sequence)
def get_wires_count(sequence):
return len([1 for x in sequence if x != WireColors.MISSING.value])
def get_nth_wire_position(sequence, n):
counter = 0
for idx, value in enumerate(sequence):
if value != WireColors.MISSING.value:
counter += 1
if counter == n:
return idx
return None
class WiresModule(AbstractModule):
def export_to_string(self):
raise NotImplementedError
def import_from_string(self, string):
raise NotImplementedError
def translate_to_commands(self):
raise NotImplementedError
def __init__(self):
super().__init__()
self.name = "WiresModule"
self.type_number = 10
self.state = ModuleState.Armed
| ...
def get_nth_wire_position(sequence, n):
counter = 0
for idx, value in enumerate(sequence):
if value != WireColors.MISSING.value:
counter += 1
if counter == n:
return idx
return None
... |
400c8de8a3a714da21c0e2b175c6e4adad3677b9 | syft/__init__.py | syft/__init__.py | import importlib
import pkgutil
ignore_packages = set(['test'])
def import_submodules(package, recursive=True):
""" Import all submodules of a module, recursively, including subpackages
:param package: package (name or actual module)
:type package: str | module
:rtype: dict[str, types.ModuleType]
"""
if isinstance(package, str):
package = importlib.import_module(package)
results = {}
for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
if(name not in ignore_packages):
full_name = package.__name__ + '.' + name
results[full_name] = importlib.import_module(full_name)
if recursive and is_pkg:
results.update(import_submodules(full_name))
return results
# import submodules recursively
import_submodules(__name__)
| import importlib
import pkgutil
ignore_packages = set(['test'])
def import_submodules(package, recursive=True):
""" Import all submodules of a module, recursively, including subpackages
:param package: package (name or actual module)
:type package: str | module
:rtype: dict[str, types.ModuleType]
"""
if isinstance(package, str):
package = importlib.import_module(package)
results = {}
for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
# test submodule names are 'syft.test.*', so this matches the 'ignore_packages' above
if name.split('.')[1] not in ignore_packages:
full_name = package.__name__ + '.' + name
results[full_name] = importlib.import_module(full_name)
if recursive and is_pkg:
results.update(import_submodules(full_name))
return results
# import submodules recursively
import_submodules(__name__)
| Check for the name of the submodule we'd like to ignore in a more general way. | Check for the name of the submodule we'd like to ignore in a more general way.
| Python | apache-2.0 | aradhyamathur/PySyft,sajalsubodh22/PySyft,OpenMined/PySyft,dipanshunagar/PySyft,sajalsubodh22/PySyft,dipanshunagar/PySyft,joewie/PySyft,cypherai/PySyft,cypherai/PySyft,joewie/PySyft,aradhyamathur/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft | import importlib
import pkgutil
ignore_packages = set(['test'])
def import_submodules(package, recursive=True):
""" Import all submodules of a module, recursively, including subpackages
:param package: package (name or actual module)
:type package: str | module
:rtype: dict[str, types.ModuleType]
"""
if isinstance(package, str):
package = importlib.import_module(package)
results = {}
for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
+ # test submodule names are 'syft.test.*', so this matches the 'ignore_packages' above
- if(name not in ignore_packages):
+ if name.split('.')[1] not in ignore_packages:
full_name = package.__name__ + '.' + name
results[full_name] = importlib.import_module(full_name)
if recursive and is_pkg:
results.update(import_submodules(full_name))
return results
# import submodules recursively
import_submodules(__name__)
| Check for the name of the submodule we'd like to ignore in a more general way. | ## Code Before:
import importlib
import pkgutil
ignore_packages = set(['test'])
def import_submodules(package, recursive=True):
""" Import all submodules of a module, recursively, including subpackages
:param package: package (name or actual module)
:type package: str | module
:rtype: dict[str, types.ModuleType]
"""
if isinstance(package, str):
package = importlib.import_module(package)
results = {}
for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
if(name not in ignore_packages):
full_name = package.__name__ + '.' + name
results[full_name] = importlib.import_module(full_name)
if recursive and is_pkg:
results.update(import_submodules(full_name))
return results
# import submodules recursively
import_submodules(__name__)
## Instruction:
Check for the name of the submodule we'd like to ignore in a more general way.
## Code After:
import importlib
import pkgutil
ignore_packages = set(['test'])
def import_submodules(package, recursive=True):
""" Import all submodules of a module, recursively, including subpackages
:param package: package (name or actual module)
:type package: str | module
:rtype: dict[str, types.ModuleType]
"""
if isinstance(package, str):
package = importlib.import_module(package)
results = {}
for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
# test submodule names are 'syft.test.*', so this matches the 'ignore_packages' above
if name.split('.')[1] not in ignore_packages:
full_name = package.__name__ + '.' + name
results[full_name] = importlib.import_module(full_name)
if recursive and is_pkg:
results.update(import_submodules(full_name))
return results
# import submodules recursively
import_submodules(__name__)
| ...
results = {}
for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
# test submodule names are 'syft.test.*', so this matches the 'ignore_packages' above
if name.split('.')[1] not in ignore_packages:
full_name = package.__name__ + '.' + name
results[full_name] = importlib.import_module(full_name)
... |
dad86f0637ea94abf1cdbf6674b62696980d5589 | dont_tread_on_memes/__main__.py | dont_tread_on_memes/__main__.py | import dont_tread_on_memes
import click
@click.command()
@click.option("--message", prompt="Don't _____ me",
help=("The word or phrase to substitute for 'tread' in 'don't "
"tread on me'"))
@click.option("--save", default=None, help="Where to save the image")
def tread(message, save):
flag = dont_tread_on_memes.tread_on(message)
if save is not None:
flag.save(save)
else:
flag.show()
if __name__ == "__main__":
tread()
| import dont_tread_on_memes
import click
@click.command()
@click.option("--message", prompt="Don't _____ me",
help=("The word or phrase to substitute for 'tread' in 'don't "
"tread on me'"))
@click.option("--format/--no-format", default=True,
help=("Use the provided message as the entire caption instead of"
" formatting it as 'Don't [message] me'"))
@click.option("--save", default=None, help="Where to save the image")
def tread(message, format, save):
# Generate the flag
if format is True:
flag = dont_tread_on_memes.dont_me(message)
else:
flag = dont_tread_on_memes.tread_on(message)
# Save or show
if save is not None:
flag.save(save)
else:
flag.show()
if __name__ == "__main__":
tread()
| Allow 'raw' captioning via the --no-format flag | Allow 'raw' captioning via the --no-format flag
| Python | mit | controversial/dont-tread-on-memes | import dont_tread_on_memes
import click
@click.command()
@click.option("--message", prompt="Don't _____ me",
help=("The word or phrase to substitute for 'tread' in 'don't "
"tread on me'"))
+ @click.option("--format/--no-format", default=True,
+ help=("Use the provided message as the entire caption instead of"
+ " formatting it as 'Don't [message] me'"))
@click.option("--save", default=None, help="Where to save the image")
- def tread(message, save):
+ def tread(message, format, save):
+ # Generate the flag
+ if format is True:
+ flag = dont_tread_on_memes.dont_me(message)
+ else:
- flag = dont_tread_on_memes.tread_on(message)
+ flag = dont_tread_on_memes.tread_on(message)
+
+ # Save or show
if save is not None:
flag.save(save)
else:
flag.show()
if __name__ == "__main__":
tread()
| Allow 'raw' captioning via the --no-format flag | ## Code Before:
import dont_tread_on_memes
import click
@click.command()
@click.option("--message", prompt="Don't _____ me",
help=("The word or phrase to substitute for 'tread' in 'don't "
"tread on me'"))
@click.option("--save", default=None, help="Where to save the image")
def tread(message, save):
flag = dont_tread_on_memes.tread_on(message)
if save is not None:
flag.save(save)
else:
flag.show()
if __name__ == "__main__":
tread()
## Instruction:
Allow 'raw' captioning via the --no-format flag
## Code After:
import dont_tread_on_memes
import click
@click.command()
@click.option("--message", prompt="Don't _____ me",
help=("The word or phrase to substitute for 'tread' in 'don't "
"tread on me'"))
@click.option("--format/--no-format", default=True,
help=("Use the provided message as the entire caption instead of"
" formatting it as 'Don't [message] me'"))
@click.option("--save", default=None, help="Where to save the image")
def tread(message, format, save):
# Generate the flag
if format is True:
flag = dont_tread_on_memes.dont_me(message)
else:
flag = dont_tread_on_memes.tread_on(message)
# Save or show
if save is not None:
flag.save(save)
else:
flag.show()
if __name__ == "__main__":
tread()
| // ... existing code ...
help=("The word or phrase to substitute for 'tread' in 'don't "
"tread on me'"))
@click.option("--format/--no-format", default=True,
help=("Use the provided message as the entire caption instead of"
" formatting it as 'Don't [message] me'"))
@click.option("--save", default=None, help="Where to save the image")
def tread(message, format, save):
# Generate the flag
if format is True:
flag = dont_tread_on_memes.dont_me(message)
else:
flag = dont_tread_on_memes.tread_on(message)
# Save or show
if save is not None:
flag.save(save)
// ... rest of the code ... |
9ad5f279c33339ab00b1fcf90975c085afe0ab43 | mysite/extra_translations.py | mysite/extra_translations.py |
from __future__ import unicode_literals
from django.utils.translation import ugettext as _
# Labels for the extra fields which are defined in the database.
# Costa Rica:
_('Profession')
_('Important Roles')
_('Standing for re-election')
# Labels for the person fields which are setup in the database and it pulls
# the label text from the database
_('Name')
_('Family Name')
_('Given Name')
_('Additional Name')
_('Honorific Prefix')
_('Honorific Suffix')
_('Patronymic Name')
_('Sort Name')
_('Email')
_('Gender')
_('Birth Date')
_('Death Date')
_('Summary')
_('Biography')
_('National Identity')
|
from __future__ import unicode_literals
from django.utils.translation import ugettext as _
# Labels for the extra fields which are defined in the database.
# Costa Rica:
_('Profession')
_('Important Roles')
_('Standing for re-election')
# Labels for the person fields which are setup in the database and it pulls
# the label text from the database
_('Name')
_('Family Name')
_('Given Name')
_('Additional Name')
_('Honorific Prefix')
_('Honorific Suffix')
_('Patronymic Name')
_('Sort Name')
_('Email')
_('Gender')
_('Birth Date')
_('Death Date')
_('Summary')
_('Biography')
_('National Identity')
_('Title / pre-nominal honorific (e.g. Dr, Sir, etc.)')
_('Full name')
_('Post-nominal letters (e.g. CBE, DSO, etc.)')
_('Email')
_('Gender (e.g. “male”, “female”)')
_('Date of birth (a four digit year or a full date)')
_('User facing description of the information')
_('Name of the Popolo related type')
_('Type of HTML field the user will see')
_('Value to put in the info_type_key e.g. twitter')
_('Name of the field in the array that stores the value, e.g url for links, value for contact_type, identifier for identifiers')
_('Twitter username (e.g. democlub)')
_('Twitter username (e.g. democlub)')
_('Facebook page (e.g. for their campaign)')
_('Homepage URL')
_('Wikipedia URL')
_('LinkedIn URL')
_("The party's candidate page for this person")
| Add some more text used in migrations which need translation | Add some more text used in migrations which need translation
| Python | agpl-3.0 | mysociety/yournextrepresentative,neavouli/yournextrepresentative,DemocracyClub/yournextrepresentative,neavouli/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextmp-popit,mysociety/yournextmp-popit,neavouli/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextmp-popit,DemocracyClub/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextrepresentative |
from __future__ import unicode_literals
from django.utils.translation import ugettext as _
# Labels for the extra fields which are defined in the database.
# Costa Rica:
_('Profession')
_('Important Roles')
_('Standing for re-election')
# Labels for the person fields which are setup in the database and it pulls
# the label text from the database
_('Name')
_('Family Name')
_('Given Name')
_('Additional Name')
_('Honorific Prefix')
_('Honorific Suffix')
_('Patronymic Name')
_('Sort Name')
_('Email')
_('Gender')
_('Birth Date')
_('Death Date')
_('Summary')
_('Biography')
_('National Identity')
+ _('Title / pre-nominal honorific (e.g. Dr, Sir, etc.)')
+ _('Full name')
+ _('Post-nominal letters (e.g. CBE, DSO, etc.)')
+ _('Email')
+ _('Gender (e.g. “male”, “female”)')
+ _('Date of birth (a four digit year or a full date)')
+
+ _('User facing description of the information')
+ _('Name of the Popolo related type')
+ _('Type of HTML field the user will see')
+ _('Value to put in the info_type_key e.g. twitter')
+ _('Name of the field in the array that stores the value, e.g url for links, value for contact_type, identifier for identifiers')
+
+ _('Twitter username (e.g. democlub)')
+ _('Twitter username (e.g. democlub)')
+ _('Facebook page (e.g. for their campaign)')
+ _('Homepage URL')
+ _('Wikipedia URL')
+ _('LinkedIn URL')
+ _("The party's candidate page for this person")
+ | Add some more text used in migrations which need translation | ## Code Before:
from __future__ import unicode_literals
from django.utils.translation import ugettext as _
# Labels for the extra fields which are defined in the database.
# Costa Rica:
_('Profession')
_('Important Roles')
_('Standing for re-election')
# Labels for the person fields which are setup in the database and it pulls
# the label text from the database
_('Name')
_('Family Name')
_('Given Name')
_('Additional Name')
_('Honorific Prefix')
_('Honorific Suffix')
_('Patronymic Name')
_('Sort Name')
_('Email')
_('Gender')
_('Birth Date')
_('Death Date')
_('Summary')
_('Biography')
_('National Identity')
## Instruction:
Add some more text used in migrations which need translation
## Code After:
from __future__ import unicode_literals
from django.utils.translation import ugettext as _
# Labels for the extra fields which are defined in the database.
# Costa Rica:
_('Profession')
_('Important Roles')
_('Standing for re-election')
# Labels for the person fields which are setup in the database and it pulls
# the label text from the database
_('Name')
_('Family Name')
_('Given Name')
_('Additional Name')
_('Honorific Prefix')
_('Honorific Suffix')
_('Patronymic Name')
_('Sort Name')
_('Email')
_('Gender')
_('Birth Date')
_('Death Date')
_('Summary')
_('Biography')
_('National Identity')
_('Title / pre-nominal honorific (e.g. Dr, Sir, etc.)')
_('Full name')
_('Post-nominal letters (e.g. CBE, DSO, etc.)')
_('Email')
_('Gender (e.g. “male”, “female”)')
_('Date of birth (a four digit year or a full date)')
_('User facing description of the information')
_('Name of the Popolo related type')
_('Type of HTML field the user will see')
_('Value to put in the info_type_key e.g. twitter')
_('Name of the field in the array that stores the value, e.g url for links, value for contact_type, identifier for identifiers')
_('Twitter username (e.g. democlub)')
_('Twitter username (e.g. democlub)')
_('Facebook page (e.g. for their campaign)')
_('Homepage URL')
_('Wikipedia URL')
_('LinkedIn URL')
_("The party's candidate page for this person")
| ...
_('Biography')
_('National Identity')
_('Title / pre-nominal honorific (e.g. Dr, Sir, etc.)')
_('Full name')
_('Post-nominal letters (e.g. CBE, DSO, etc.)')
_('Email')
_('Gender (e.g. “male”, “female”)')
_('Date of birth (a four digit year or a full date)')
_('User facing description of the information')
_('Name of the Popolo related type')
_('Type of HTML field the user will see')
_('Value to put in the info_type_key e.g. twitter')
_('Name of the field in the array that stores the value, e.g url for links, value for contact_type, identifier for identifiers')
_('Twitter username (e.g. democlub)')
_('Twitter username (e.g. democlub)')
_('Facebook page (e.g. for their campaign)')
_('Homepage URL')
_('Wikipedia URL')
_('LinkedIn URL')
_("The party's candidate page for this person")
... |
c537f40c4c56dc8a52e284bd9c03d09d191e77eb | tests/test_dungeon.py | tests/test_dungeon.py | from game.models import (Dungeon,
Deck,
Player,
make_standard_deck)
import pytest
@pytest.fixture
def dungeon():
return Dungeon(make_standard_deck(), seed=123456789)
def test_dungeon_handle_input_valid(dungeon):
dungeon.handle_input('f')
| from game.models import (Dungeon,
Deck,
Player,
make_standard_deck)
import pytest
@pytest.fixture
def dungeon():
return Dungeon(make_standard_deck(), seed=123456789)
def test_deck_order(dungeon):
"""this check ensures that we can plan for the first three rooms having
known cards and thus we can check the availability of certain actions or
sequences of actions"""
cards = dungeon.deck.draw(12)
assert str(cards[0]) == "17 of Clubs"
assert str(cards[1]) == "11 of Diamonds"
assert str(cards[2]) == "8 of Diamonds"
assert str(cards[3]) == "7 of Spades"
assert str(cards[4]) == "5 of Clubs"
assert str(cards[5]) == "11 of Spades"
assert str(cards[6]) == "17 of Spades"
assert str(cards[7]) == "11 of Diamonds"
assert str(cards[8]) == "9 of Spades"
assert str(cards[9]) == "Joker"
assert str(cards[10]) == "6 of Spades"
assert str(cards[11]) == "2 of Diamonds"
def test_dungeon_valid_flee_unconditioned(dungeon):
dungeon.handle_input('f')
assert len(dungeon.room_history) == 2
def test_cannot_flee_twice(dungeon):
assert dungeon.room_history[-1].escapable() == True
dungeon.handle_input('f')
assert dungeon.player.escaped_last_room == True
assert dungeon.room_history[-1].escapable() == False
dungeon.handle_input('f')
assert len(dungeon.room_history) == 2
| Add tests for Dungeon class | Add tests for Dungeon class
| Python | mit | setphen/Donsol | from game.models import (Dungeon,
Deck,
Player,
make_standard_deck)
import pytest
@pytest.fixture
def dungeon():
return Dungeon(make_standard_deck(), seed=123456789)
- def test_dungeon_handle_input_valid(dungeon):
- dungeon.handle_input('f')
+ def test_deck_order(dungeon):
+ """this check ensures that we can plan for the first three rooms having
+ known cards and thus we can check the availability of certain actions or
+ sequences of actions"""
+ cards = dungeon.deck.draw(12)
+ assert str(cards[0]) == "17 of Clubs"
+ assert str(cards[1]) == "11 of Diamonds"
+ assert str(cards[2]) == "8 of Diamonds"
+ assert str(cards[3]) == "7 of Spades"
+ assert str(cards[4]) == "5 of Clubs"
+ assert str(cards[5]) == "11 of Spades"
+ assert str(cards[6]) == "17 of Spades"
+ assert str(cards[7]) == "11 of Diamonds"
+ assert str(cards[8]) == "9 of Spades"
+ assert str(cards[9]) == "Joker"
+ assert str(cards[10]) == "6 of Spades"
+ assert str(cards[11]) == "2 of Diamonds"
+ def test_dungeon_valid_flee_unconditioned(dungeon):
+ dungeon.handle_input('f')
+ assert len(dungeon.room_history) == 2
+
+
+ def test_cannot_flee_twice(dungeon):
+ assert dungeon.room_history[-1].escapable() == True
+ dungeon.handle_input('f')
+ assert dungeon.player.escaped_last_room == True
+ assert dungeon.room_history[-1].escapable() == False
+ dungeon.handle_input('f')
+ assert len(dungeon.room_history) == 2
+ | Add tests for Dungeon class | ## Code Before:
from game.models import (Dungeon,
Deck,
Player,
make_standard_deck)
import pytest
@pytest.fixture
def dungeon():
return Dungeon(make_standard_deck(), seed=123456789)
def test_dungeon_handle_input_valid(dungeon):
dungeon.handle_input('f')
## Instruction:
Add tests for Dungeon class
## Code After:
from game.models import (Dungeon,
Deck,
Player,
make_standard_deck)
import pytest
@pytest.fixture
def dungeon():
return Dungeon(make_standard_deck(), seed=123456789)
def test_deck_order(dungeon):
"""this check ensures that we can plan for the first three rooms having
known cards and thus we can check the availability of certain actions or
sequences of actions"""
cards = dungeon.deck.draw(12)
assert str(cards[0]) == "17 of Clubs"
assert str(cards[1]) == "11 of Diamonds"
assert str(cards[2]) == "8 of Diamonds"
assert str(cards[3]) == "7 of Spades"
assert str(cards[4]) == "5 of Clubs"
assert str(cards[5]) == "11 of Spades"
assert str(cards[6]) == "17 of Spades"
assert str(cards[7]) == "11 of Diamonds"
assert str(cards[8]) == "9 of Spades"
assert str(cards[9]) == "Joker"
assert str(cards[10]) == "6 of Spades"
assert str(cards[11]) == "2 of Diamonds"
def test_dungeon_valid_flee_unconditioned(dungeon):
dungeon.handle_input('f')
assert len(dungeon.room_history) == 2
def test_cannot_flee_twice(dungeon):
assert dungeon.room_history[-1].escapable() == True
dungeon.handle_input('f')
assert dungeon.player.escaped_last_room == True
assert dungeon.room_history[-1].escapable() == False
dungeon.handle_input('f')
assert len(dungeon.room_history) == 2
| ...
def test_deck_order(dungeon):
"""this check ensures that we can plan for the first three rooms having
known cards and thus we can check the availability of certain actions or
sequences of actions"""
cards = dungeon.deck.draw(12)
assert str(cards[0]) == "17 of Clubs"
assert str(cards[1]) == "11 of Diamonds"
assert str(cards[2]) == "8 of Diamonds"
assert str(cards[3]) == "7 of Spades"
assert str(cards[4]) == "5 of Clubs"
assert str(cards[5]) == "11 of Spades"
assert str(cards[6]) == "17 of Spades"
assert str(cards[7]) == "11 of Diamonds"
assert str(cards[8]) == "9 of Spades"
assert str(cards[9]) == "Joker"
assert str(cards[10]) == "6 of Spades"
assert str(cards[11]) == "2 of Diamonds"
def test_dungeon_valid_flee_unconditioned(dungeon):
dungeon.handle_input('f')
assert len(dungeon.room_history) == 2
def test_cannot_flee_twice(dungeon):
assert dungeon.room_history[-1].escapable() == True
dungeon.handle_input('f')
assert dungeon.player.escaped_last_room == True
assert dungeon.room_history[-1].escapable() == False
dungeon.handle_input('f')
assert len(dungeon.room_history) == 2
... |
ce939b6f03260a57268a8371a2e05e531b36bce2 | hoomd/typeparam.py | hoomd/typeparam.py | from hoomd.parameterdicts import AttachedTypeParameterDict
class TypeParameter:
def __init__(self, name, type_kind, param_dict):
self.name = name
self.type_kind = type_kind
self.param_dict = param_dict
def __getitem__(self, key):
return self.param_dict[key]
def __setitem__(self, key, value):
self.param_dict[key] = value
@property
def default(self):
return self.param_dict.default
@default.setter
def default(self, value):
self.param_dict.default = value
def attach(self, cpp_obj, sim):
self.param_dict = AttachedTypeParameterDict(cpp_obj,
self.name,
self.type_kind,
self.param_dict,
sim)
return self
def detach(self):
self.param_dict = self.param_dict.to_dettached()
return self
def to_dict(self):
return self.param_dict.to_dict()
def keys(self):
yield from self.param_dict.keys()
@property
def state(self):
state = self.to_dict()
if self.param_dict._len_keys > 1:
state = {str(key): value for key, value in state.items()}
state['__default'] = self.default
return state
| from hoomd.parameterdicts import AttachedTypeParameterDict
class TypeParameter:
def __init__(self, name, type_kind, param_dict):
self.name = name
self.type_kind = type_kind
self.param_dict = param_dict
def __getattr__(self, attr):
try:
return getattr(self.param_dict, attr)
except AttributeError:
raise AttributeError("'{}' object has no attribute "
"'{}'".format(type(self), attr))
def __getitem__(self, key):
return self.param_dict[key]
def __setitem__(self, key, value):
self.param_dict[key] = value
@property
def default(self):
return self.param_dict.default
@default.setter
def default(self, value):
self.param_dict.default = value
def attach(self, cpp_obj, sim):
self.param_dict = AttachedTypeParameterDict(cpp_obj,
self.name,
self.type_kind,
self.param_dict,
sim)
return self
def detach(self):
self.param_dict = self.param_dict.to_dettached()
return self
def to_dict(self):
return self.param_dict.to_dict()
def keys(self):
yield from self.param_dict.keys()
@property
def state(self):
state = self.to_dict()
if self.param_dict._len_keys > 1:
state = {str(key): value for key, value in state.items()}
state['__default'] = self.default
return state
| Allow TypeParameters to 'grap' attr from param_dict | Allow TypeParameters to 'grap' attr from param_dict
| Python | bsd-3-clause | joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue | from hoomd.parameterdicts import AttachedTypeParameterDict
class TypeParameter:
def __init__(self, name, type_kind, param_dict):
self.name = name
self.type_kind = type_kind
self.param_dict = param_dict
+
+ def __getattr__(self, attr):
+ try:
+ return getattr(self.param_dict, attr)
+ except AttributeError:
+ raise AttributeError("'{}' object has no attribute "
+ "'{}'".format(type(self), attr))
def __getitem__(self, key):
return self.param_dict[key]
def __setitem__(self, key, value):
self.param_dict[key] = value
@property
def default(self):
return self.param_dict.default
@default.setter
def default(self, value):
self.param_dict.default = value
def attach(self, cpp_obj, sim):
self.param_dict = AttachedTypeParameterDict(cpp_obj,
self.name,
self.type_kind,
self.param_dict,
sim)
return self
def detach(self):
self.param_dict = self.param_dict.to_dettached()
return self
def to_dict(self):
return self.param_dict.to_dict()
def keys(self):
yield from self.param_dict.keys()
@property
def state(self):
state = self.to_dict()
if self.param_dict._len_keys > 1:
state = {str(key): value for key, value in state.items()}
state['__default'] = self.default
return state
| Allow TypeParameters to 'grap' attr from param_dict | ## Code Before:
from hoomd.parameterdicts import AttachedTypeParameterDict
class TypeParameter:
def __init__(self, name, type_kind, param_dict):
self.name = name
self.type_kind = type_kind
self.param_dict = param_dict
def __getitem__(self, key):
return self.param_dict[key]
def __setitem__(self, key, value):
self.param_dict[key] = value
@property
def default(self):
return self.param_dict.default
@default.setter
def default(self, value):
self.param_dict.default = value
def attach(self, cpp_obj, sim):
self.param_dict = AttachedTypeParameterDict(cpp_obj,
self.name,
self.type_kind,
self.param_dict,
sim)
return self
def detach(self):
self.param_dict = self.param_dict.to_dettached()
return self
def to_dict(self):
return self.param_dict.to_dict()
def keys(self):
yield from self.param_dict.keys()
@property
def state(self):
state = self.to_dict()
if self.param_dict._len_keys > 1:
state = {str(key): value for key, value in state.items()}
state['__default'] = self.default
return state
## Instruction:
Allow TypeParameters to 'grap' attr from param_dict
## Code After:
from hoomd.parameterdicts import AttachedTypeParameterDict
class TypeParameter:
def __init__(self, name, type_kind, param_dict):
self.name = name
self.type_kind = type_kind
self.param_dict = param_dict
def __getattr__(self, attr):
try:
return getattr(self.param_dict, attr)
except AttributeError:
raise AttributeError("'{}' object has no attribute "
"'{}'".format(type(self), attr))
def __getitem__(self, key):
return self.param_dict[key]
def __setitem__(self, key, value):
self.param_dict[key] = value
@property
def default(self):
return self.param_dict.default
@default.setter
def default(self, value):
self.param_dict.default = value
def attach(self, cpp_obj, sim):
self.param_dict = AttachedTypeParameterDict(cpp_obj,
self.name,
self.type_kind,
self.param_dict,
sim)
return self
def detach(self):
self.param_dict = self.param_dict.to_dettached()
return self
def to_dict(self):
return self.param_dict.to_dict()
def keys(self):
yield from self.param_dict.keys()
@property
def state(self):
state = self.to_dict()
if self.param_dict._len_keys > 1:
state = {str(key): value for key, value in state.items()}
state['__default'] = self.default
return state
| ...
self.type_kind = type_kind
self.param_dict = param_dict
def __getattr__(self, attr):
try:
return getattr(self.param_dict, attr)
except AttributeError:
raise AttributeError("'{}' object has no attribute "
"'{}'".format(type(self), attr))
def __getitem__(self, key):
... |
1212d33d849155f8c1cdc6a610e893318937e7c5 | silk/webdoc/html/v5.py | silk/webdoc/html/v5.py |
from .common import *
del ACRONYM
del APPLET
del BASEFONT
del BIG
del CENTER
del DIR
del FONT
del FRAME
del FRAMESET
del NOFRAMES
del STRIKE
del TT
del U
|
from .common import ( # flake8: noqa
A,
ABBR,
# ACRONYM,
ADDRESS,
# APPLET,
AREA,
B,
BASE,
# BASEFONT,
BDO,
# BIG,
BLOCKQUOTE,
BODY,
BR,
BUTTON,
Body,
CAPTION,
CAT,
# CENTER,
CITE,
CODE,
COL,
COLGROUP,
COMMENT,
CONDITIONAL_COMMENT,
DD,
DEL,
DFN,
# DIR,
DIV,
DL,
DT,
EM,
FIELDSET,
# FONT,
FORM,
# FRAME,
# FRAMESET,
Form,
H1,
H2,
H3,
H4,
H5,
H6,
HEAD,
HR,
HTML,
HTMLDoc,
Hyper,
I,
IFRAME,
IMG,
INPUT,
INS,
Image,
Javascript,
KBD,
LABEL,
LEGEND,
LI,
LINK,
MAP,
MENU,
META,
NBSP,
# NOFRAMES,
NOSCRIPT,
OBJECT,
OL,
OPTGROUP,
OPTION,
P,
PARAM,
PRE,
Q,
S,
SAMP,
SCRIPT,
SELECT,
SMALL,
SPAN,
# STRIKE,
STRONG,
STYLE,
SUB,
SUP,
TABLE,
TBODY,
TD,
TEXTAREA,
TFOOT,
TH,
THEAD,
TITLE,
TR,
# TT,
# U,
UL,
VAR,
XML,
XMLEntity,
XMLNode,
XMP,
xmlescape,
xmlunescape
)
| Replace import * with explicit names | Replace import * with explicit names
| Python | bsd-3-clause | orbnauticus/silk |
- from .common import *
+ from .common import ( # flake8: noqa
+ A,
+ ABBR,
+ # ACRONYM,
+ ADDRESS,
+ # APPLET,
+ AREA,
+ B,
+ BASE,
+ # BASEFONT,
+ BDO,
+ # BIG,
+ BLOCKQUOTE,
+ BODY,
+ BR,
+ BUTTON,
+ Body,
+ CAPTION,
+ CAT,
+ # CENTER,
+ CITE,
+ CODE,
+ COL,
+ COLGROUP,
+ COMMENT,
+ CONDITIONAL_COMMENT,
+ DD,
+ DEL,
+ DFN,
+ # DIR,
+ DIV,
+ DL,
+ DT,
+ EM,
+ FIELDSET,
+ # FONT,
+ FORM,
+ # FRAME,
+ # FRAMESET,
+ Form,
+ H1,
+ H2,
+ H3,
+ H4,
+ H5,
+ H6,
+ HEAD,
+ HR,
+ HTML,
+ HTMLDoc,
+ Hyper,
+ I,
+ IFRAME,
+ IMG,
+ INPUT,
+ INS,
+ Image,
+ Javascript,
+ KBD,
+ LABEL,
+ LEGEND,
+ LI,
+ LINK,
+ MAP,
+ MENU,
+ META,
+ NBSP,
+ # NOFRAMES,
+ NOSCRIPT,
+ OBJECT,
+ OL,
+ OPTGROUP,
+ OPTION,
+ P,
+ PARAM,
+ PRE,
+ Q,
+ S,
+ SAMP,
+ SCRIPT,
+ SELECT,
+ SMALL,
+ SPAN,
+ # STRIKE,
+ STRONG,
+ STYLE,
+ SUB,
+ SUP,
+ TABLE,
+ TBODY,
+ TD,
+ TEXTAREA,
+ TFOOT,
+ TH,
+ THEAD,
+ TITLE,
+ TR,
+ # TT,
+ # U,
+ UL,
+ VAR,
+ XML,
+ XMLEntity,
+ XMLNode,
+ XMP,
+ xmlescape,
+ xmlunescape
+ )
- del ACRONYM
- del APPLET
- del BASEFONT
- del BIG
- del CENTER
- del DIR
- del FONT
- del FRAME
- del FRAMESET
- del NOFRAMES
- del STRIKE
- del TT
- del U
- | Replace import * with explicit names | ## Code Before:
from .common import *
del ACRONYM
del APPLET
del BASEFONT
del BIG
del CENTER
del DIR
del FONT
del FRAME
del FRAMESET
del NOFRAMES
del STRIKE
del TT
del U
## Instruction:
Replace import * with explicit names
## Code After:
from .common import ( # flake8: noqa
A,
ABBR,
# ACRONYM,
ADDRESS,
# APPLET,
AREA,
B,
BASE,
# BASEFONT,
BDO,
# BIG,
BLOCKQUOTE,
BODY,
BR,
BUTTON,
Body,
CAPTION,
CAT,
# CENTER,
CITE,
CODE,
COL,
COLGROUP,
COMMENT,
CONDITIONAL_COMMENT,
DD,
DEL,
DFN,
# DIR,
DIV,
DL,
DT,
EM,
FIELDSET,
# FONT,
FORM,
# FRAME,
# FRAMESET,
Form,
H1,
H2,
H3,
H4,
H5,
H6,
HEAD,
HR,
HTML,
HTMLDoc,
Hyper,
I,
IFRAME,
IMG,
INPUT,
INS,
Image,
Javascript,
KBD,
LABEL,
LEGEND,
LI,
LINK,
MAP,
MENU,
META,
NBSP,
# NOFRAMES,
NOSCRIPT,
OBJECT,
OL,
OPTGROUP,
OPTION,
P,
PARAM,
PRE,
Q,
S,
SAMP,
SCRIPT,
SELECT,
SMALL,
SPAN,
# STRIKE,
STRONG,
STYLE,
SUB,
SUP,
TABLE,
TBODY,
TD,
TEXTAREA,
TFOOT,
TH,
THEAD,
TITLE,
TR,
# TT,
# U,
UL,
VAR,
XML,
XMLEntity,
XMLNode,
XMP,
xmlescape,
xmlunescape
)
| // ... existing code ...
from .common import ( # flake8: noqa
A,
ABBR,
# ACRONYM,
ADDRESS,
# APPLET,
AREA,
B,
BASE,
# BASEFONT,
BDO,
# BIG,
BLOCKQUOTE,
BODY,
BR,
BUTTON,
Body,
CAPTION,
CAT,
# CENTER,
CITE,
CODE,
COL,
COLGROUP,
COMMENT,
CONDITIONAL_COMMENT,
DD,
DEL,
DFN,
# DIR,
DIV,
DL,
DT,
EM,
FIELDSET,
# FONT,
FORM,
# FRAME,
# FRAMESET,
Form,
H1,
H2,
H3,
H4,
H5,
H6,
HEAD,
HR,
HTML,
HTMLDoc,
Hyper,
I,
IFRAME,
IMG,
INPUT,
INS,
Image,
Javascript,
KBD,
LABEL,
LEGEND,
LI,
LINK,
MAP,
MENU,
META,
NBSP,
# NOFRAMES,
NOSCRIPT,
OBJECT,
OL,
OPTGROUP,
OPTION,
P,
PARAM,
PRE,
Q,
S,
SAMP,
SCRIPT,
SELECT,
SMALL,
SPAN,
# STRIKE,
STRONG,
STYLE,
SUB,
SUP,
TABLE,
TBODY,
TD,
TEXTAREA,
TFOOT,
TH,
THEAD,
TITLE,
TR,
# TT,
# U,
UL,
VAR,
XML,
XMLEntity,
XMLNode,
XMP,
xmlescape,
xmlunescape
)
// ... rest of the code ... |
6d18ff715a5fa3059ddb609c1abdbbb06b15ad63 | fuel/downloaders/celeba.py | fuel/downloaders/celeba.py | from fuel.downloaders.base import default_downloader
def fill_subparser(subparser):
"""Sets up a subparser to download the CelebA dataset file.
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `celeba` command.
"""
urls = ['https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AAB7G69NLjRNqv_tyiULHSVUa/list_attr_celeba.txt?dl=1',
'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AADVdnYbokd7TXhpvfWLL3sga/img_align_celeba.zip?dl=1']
filenames = ['list_attr_celeba.txt', 'img_align_celeba.zip']
subparser.set_defaults(urls=urls, filenames=filenames)
return default_downloader
| from fuel.downloaders.base import default_downloader
def fill_subparser(subparser):
"""Sets up a subparser to download the CelebA dataset file.
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `celeba` command.
"""
urls = ['https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AAC7-uCaJkmPmvLX2_P5qy0ga/Anno/list_attr_celeba.txt?dl=1',
'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AADIKlz8PR9zr6Y20qbkunrba/Img/img_align_celeba.zip?dl=1']
filenames = ['list_attr_celeba.txt', 'img_align_celeba.zip']
subparser.set_defaults(urls=urls, filenames=filenames)
return default_downloader
| Update download links for CelebA files | Update download links for CelebA files
| Python | mit | mila-udem/fuel,dmitriy-serdyuk/fuel,dmitriy-serdyuk/fuel,mila-udem/fuel,vdumoulin/fuel,vdumoulin/fuel | from fuel.downloaders.base import default_downloader
def fill_subparser(subparser):
"""Sets up a subparser to download the CelebA dataset file.
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `celeba` command.
"""
urls = ['https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
- 'AAB7G69NLjRNqv_tyiULHSVUa/list_attr_celeba.txt?dl=1',
+ 'AAC7-uCaJkmPmvLX2_P5qy0ga/Anno/list_attr_celeba.txt?dl=1',
'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
- 'AADVdnYbokd7TXhpvfWLL3sga/img_align_celeba.zip?dl=1']
+ 'AADIKlz8PR9zr6Y20qbkunrba/Img/img_align_celeba.zip?dl=1']
filenames = ['list_attr_celeba.txt', 'img_align_celeba.zip']
subparser.set_defaults(urls=urls, filenames=filenames)
return default_downloader
| Update download links for CelebA files | ## Code Before:
from fuel.downloaders.base import default_downloader
def fill_subparser(subparser):
"""Sets up a subparser to download the CelebA dataset file.
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `celeba` command.
"""
urls = ['https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AAB7G69NLjRNqv_tyiULHSVUa/list_attr_celeba.txt?dl=1',
'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AADVdnYbokd7TXhpvfWLL3sga/img_align_celeba.zip?dl=1']
filenames = ['list_attr_celeba.txt', 'img_align_celeba.zip']
subparser.set_defaults(urls=urls, filenames=filenames)
return default_downloader
## Instruction:
Update download links for CelebA files
## Code After:
from fuel.downloaders.base import default_downloader
def fill_subparser(subparser):
"""Sets up a subparser to download the CelebA dataset file.
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `celeba` command.
"""
urls = ['https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AAC7-uCaJkmPmvLX2_P5qy0ga/Anno/list_attr_celeba.txt?dl=1',
'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AADIKlz8PR9zr6Y20qbkunrba/Img/img_align_celeba.zip?dl=1']
filenames = ['list_attr_celeba.txt', 'img_align_celeba.zip']
subparser.set_defaults(urls=urls, filenames=filenames)
return default_downloader
| // ... existing code ...
"""
urls = ['https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AAC7-uCaJkmPmvLX2_P5qy0ga/Anno/list_attr_celeba.txt?dl=1',
'https://www.dropbox.com/sh/8oqt9vytwxb3s4r/'
'AADIKlz8PR9zr6Y20qbkunrba/Img/img_align_celeba.zip?dl=1']
filenames = ['list_attr_celeba.txt', 'img_align_celeba.zip']
subparser.set_defaults(urls=urls, filenames=filenames)
// ... rest of the code ... |
7278be28410c111280d4ccb566842419979843d3 | mla_game/apps/transcript/management/commands/fake_game_one_gameplay.py | mla_game/apps/transcript/management/commands/fake_game_one_gameplay.py | import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
class Command(BaseCommand):
help = 'Creates random votes for 5 phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript().first()
phrases = transcript.phrases.all()[:5]
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(
*[phrase.pk for phrase in phrases]
)
for phrase in phrases:
for user in users:
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
| import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
from ...tasks import update_transcript_stats
class Command(BaseCommand):
help = 'Creates random votes for 5 phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript(in_progress=False).first()
phrases = transcript.phrases.all()[:5]
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(
*[phrase.pk for phrase in phrases]
)
for phrase in phrases:
for user in users:
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
update_transcript_stats(transcript)
| Use an actually random transcript; update stats immediately | Use an actually random transcript; update stats immediately
| Python | mit | WGBH/FixIt,WGBH/FixIt,WGBH/FixIt | import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
+ from ...tasks import update_transcript_stats
class Command(BaseCommand):
help = 'Creates random votes for 5 phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
- transcript = Transcript.objects.random_transcript().first()
+ transcript = Transcript.objects.random_transcript(in_progress=False).first()
phrases = transcript.phrases.all()[:5]
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(
*[phrase.pk for phrase in phrases]
)
for phrase in phrases:
for user in users:
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
+ update_transcript_stats(transcript)
| Use an actually random transcript; update stats immediately | ## Code Before:
import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
class Command(BaseCommand):
help = 'Creates random votes for 5 phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript().first()
phrases = transcript.phrases.all()[:5]
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(
*[phrase.pk for phrase in phrases]
)
for phrase in phrases:
for user in users:
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
## Instruction:
Use an actually random transcript; update stats immediately
## Code After:
import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
from ...tasks import update_transcript_stats
class Command(BaseCommand):
help = 'Creates random votes for 5 phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript(in_progress=False).first()
phrases = transcript.phrases.all()[:5]
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(
*[phrase.pk for phrase in phrases]
)
for phrase in phrases:
for user in users:
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
update_transcript_stats(transcript)
| ...
Transcript, TranscriptPhraseDownvote
)
from ...tasks import update_transcript_stats
...
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript(in_progress=False).first()
phrases = transcript.phrases.all()[:5]
for user in users:
...
user=user
)
update_transcript_stats(transcript)
... |
fc8c7a62b737e4f291250c4d45bf34ae944ef6da | sweettooth/upload/urls.py | sweettooth/upload/urls.py |
from django.conf.urls.defaults import patterns, url
slug_charset = "[a-zA-Z0-9-_]"
urlpatterns = patterns('upload',
url(r'^$', 'views.upload_file', dict(slug=None), name='upload-file'),
url(r'(?P<slug>%s+)/$' % (slug_charset,), 'views.upload_file', name='upload-file'),
url(r'edit-data/$', 'views.upload_edit_data', name='upload-edit-data'),
)
|
from django.conf.urls.defaults import patterns, url
slug_charset = "[a-zA-Z0-9-_]"
urlpatterns = patterns('upload',
url(r'^$', 'views.upload_file', dict(slug=None), name='upload-file'),
url(r'new-version/(?P<slug>%s+)/$' % (slug_charset,), 'views.upload_file', name='upload-file'),
url(r'edit-data/$', 'views.upload_edit_data', name='upload-edit-data'),
)
| Adjust URL for new version upload, was competing with 'edit-data'. | Adjust URL for new version upload, was competing with 'edit-data'.
| Python | agpl-3.0 | magcius/sweettooth,GNOME/extensions-web,GNOME/extensions-web,GNOME/extensions-web,magcius/sweettooth,GNOME/extensions-web |
from django.conf.urls.defaults import patterns, url
slug_charset = "[a-zA-Z0-9-_]"
urlpatterns = patterns('upload',
url(r'^$', 'views.upload_file', dict(slug=None), name='upload-file'),
- url(r'(?P<slug>%s+)/$' % (slug_charset,), 'views.upload_file', name='upload-file'),
+ url(r'new-version/(?P<slug>%s+)/$' % (slug_charset,), 'views.upload_file', name='upload-file'),
url(r'edit-data/$', 'views.upload_edit_data', name='upload-edit-data'),
)
| Adjust URL for new version upload, was competing with 'edit-data'. | ## Code Before:
from django.conf.urls.defaults import patterns, url
slug_charset = "[a-zA-Z0-9-_]"
urlpatterns = patterns('upload',
url(r'^$', 'views.upload_file', dict(slug=None), name='upload-file'),
url(r'(?P<slug>%s+)/$' % (slug_charset,), 'views.upload_file', name='upload-file'),
url(r'edit-data/$', 'views.upload_edit_data', name='upload-edit-data'),
)
## Instruction:
Adjust URL for new version upload, was competing with 'edit-data'.
## Code After:
from django.conf.urls.defaults import patterns, url
slug_charset = "[a-zA-Z0-9-_]"
urlpatterns = patterns('upload',
url(r'^$', 'views.upload_file', dict(slug=None), name='upload-file'),
url(r'new-version/(?P<slug>%s+)/$' % (slug_charset,), 'views.upload_file', name='upload-file'),
url(r'edit-data/$', 'views.upload_edit_data', name='upload-edit-data'),
)
| # ... existing code ...
urlpatterns = patterns('upload',
url(r'^$', 'views.upload_file', dict(slug=None), name='upload-file'),
url(r'new-version/(?P<slug>%s+)/$' % (slug_charset,), 'views.upload_file', name='upload-file'),
url(r'edit-data/$', 'views.upload_edit_data', name='upload-edit-data'),
)
# ... rest of the code ... |
e97a1ed2015db2eb2d5fe6abe15af6d9020c16d9 | mbuild/tests/test_box.py | mbuild/tests/test_box.py | import pytest
import numpy as np
import mbuild as mb
from mbuild.tests.base_test import BaseTest
class TestBox(BaseTest):
def test_init_lengths(self):
box = mb.Box(lengths=np.ones(3))
assert np.array_equal(box.lengths, np.ones(3))
assert np.array_equal(box.mins, np.zeros(3))
assert np.array_equal(box.maxs, np.ones(3))
def test_init_bounds(self):
box = mb.Box(mins=np.zeros(3), maxs=np.ones(3))
assert np.array_equal(box.lengths, np.ones(3))
assert np.array_equal(box.mins, np.zeros(3))
assert np.array_equal(box.maxs, np.ones(3))
def test_scale(self):
box = mb.Box(lengths=np.ones(3))
scaling_factors = np.array([3, 4, 5])
box.scale(scaling_factors)
assert np.array_equal(box.lengths, scaling_factors)
assert np.array_equal(box.mins, (np.ones(3) / 2) - (scaling_factors / 2))
assert np.array_equal(box.maxs, (scaling_factors / 2) + (np.ones(3) / 2))
def test_center(self):
box = mb.Box(lengths=np.ones(3))
box.center()
assert np.array_equal(box.lengths, np.ones(3))
assert np.array_equal(box.mins, np.ones(3) * -0.5)
assert np.array_equal(box.maxs, np.ones(3) * 0.5)
| import pytest
import numpy as np
import mbuild as mb
from mbuild.tests.base_test import BaseTest
class TestBox(BaseTest):
def test_init_lengths(self):
box = mb.Box(lengths=np.ones(3))
assert np.array_equal(box.lengths, np.ones(3))
assert np.array_equal(box.mins, np.zeros(3))
assert np.array_equal(box.maxs, np.ones(3))
def test_init_bounds(self):
box = mb.Box(mins=np.zeros(3), maxs=np.ones(3))
assert np.array_equal(box.lengths, np.ones(3))
assert np.array_equal(box.mins, np.zeros(3))
assert np.array_equal(box.maxs, np.ones(3))
| Remove box tests for non-existant functionality | Remove box tests for non-existant functionality
| Python | mit | ctk3b/mbuild,iModels/mbuild,iModels/mbuild,ctk3b/mbuild,tcmoore3/mbuild,tcmoore3/mbuild,summeraz/mbuild,summeraz/mbuild | import pytest
import numpy as np
import mbuild as mb
from mbuild.tests.base_test import BaseTest
class TestBox(BaseTest):
def test_init_lengths(self):
box = mb.Box(lengths=np.ones(3))
assert np.array_equal(box.lengths, np.ones(3))
assert np.array_equal(box.mins, np.zeros(3))
assert np.array_equal(box.maxs, np.ones(3))
def test_init_bounds(self):
box = mb.Box(mins=np.zeros(3), maxs=np.ones(3))
assert np.array_equal(box.lengths, np.ones(3))
assert np.array_equal(box.mins, np.zeros(3))
assert np.array_equal(box.maxs, np.ones(3))
- def test_scale(self):
- box = mb.Box(lengths=np.ones(3))
- scaling_factors = np.array([3, 4, 5])
- box.scale(scaling_factors)
- assert np.array_equal(box.lengths, scaling_factors)
- assert np.array_equal(box.mins, (np.ones(3) / 2) - (scaling_factors / 2))
- assert np.array_equal(box.maxs, (scaling_factors / 2) + (np.ones(3) / 2))
-
- def test_center(self):
- box = mb.Box(lengths=np.ones(3))
- box.center()
- assert np.array_equal(box.lengths, np.ones(3))
- assert np.array_equal(box.mins, np.ones(3) * -0.5)
- assert np.array_equal(box.maxs, np.ones(3) * 0.5)
- | Remove box tests for non-existant functionality | ## Code Before:
import pytest
import numpy as np
import mbuild as mb
from mbuild.tests.base_test import BaseTest
class TestBox(BaseTest):
def test_init_lengths(self):
box = mb.Box(lengths=np.ones(3))
assert np.array_equal(box.lengths, np.ones(3))
assert np.array_equal(box.mins, np.zeros(3))
assert np.array_equal(box.maxs, np.ones(3))
def test_init_bounds(self):
box = mb.Box(mins=np.zeros(3), maxs=np.ones(3))
assert np.array_equal(box.lengths, np.ones(3))
assert np.array_equal(box.mins, np.zeros(3))
assert np.array_equal(box.maxs, np.ones(3))
def test_scale(self):
box = mb.Box(lengths=np.ones(3))
scaling_factors = np.array([3, 4, 5])
box.scale(scaling_factors)
assert np.array_equal(box.lengths, scaling_factors)
assert np.array_equal(box.mins, (np.ones(3) / 2) - (scaling_factors / 2))
assert np.array_equal(box.maxs, (scaling_factors / 2) + (np.ones(3) / 2))
def test_center(self):
box = mb.Box(lengths=np.ones(3))
box.center()
assert np.array_equal(box.lengths, np.ones(3))
assert np.array_equal(box.mins, np.ones(3) * -0.5)
assert np.array_equal(box.maxs, np.ones(3) * 0.5)
## Instruction:
Remove box tests for non-existant functionality
## Code After:
import pytest
import numpy as np
import mbuild as mb
from mbuild.tests.base_test import BaseTest
class TestBox(BaseTest):
def test_init_lengths(self):
box = mb.Box(lengths=np.ones(3))
assert np.array_equal(box.lengths, np.ones(3))
assert np.array_equal(box.mins, np.zeros(3))
assert np.array_equal(box.maxs, np.ones(3))
def test_init_bounds(self):
box = mb.Box(mins=np.zeros(3), maxs=np.ones(3))
assert np.array_equal(box.lengths, np.ones(3))
assert np.array_equal(box.mins, np.zeros(3))
assert np.array_equal(box.maxs, np.ones(3))
| # ... existing code ...
assert np.array_equal(box.mins, np.zeros(3))
assert np.array_equal(box.maxs, np.ones(3))
# ... rest of the code ... |
c383e06d51d4e59d400ab6fd62eff2359ab4e728 | python/the_birthday_bar.py | python/the_birthday_bar.py |
import itertools
import collections
def sliding_window(n, seq):
"""
Copied from toolz
https://toolz.readthedocs.io/en/latest/_modules/toolz/itertoolz.html#sliding_window
A sequence of overlapping subsequences
>>> list(sliding_window(2, [1, 2, 3, 4]))
[(1, 2), (2, 3), (3, 4)]
This function creates a sliding window suitable for transformations like
sliding means / smoothing
>>> mean = lambda seq: float(sum(seq)) / len(seq)
>>> list(map(mean, sliding_window(2, [1, 2, 3, 4])))
[1.5, 2.5, 3.5]
"""
return zip(*(collections.deque(itertools.islice(it, i), 0) or it
for i, it in enumerate(itertools.tee(seq, n))))
def birthday_chocolate(squares, day, month):
birthday_chocolates = 0
for piece in sliding_window(month, squares):
if sum(piece) == day:
birthday_chocolates += 1
return birthday_chocolates
_ = int(input().strip())
SQUARES = list(map(int, input().strip().split(' ')))
DAY, MONTH = map(int, input().strip().split(' '))
print(birthday_chocolate(SQUARES, DAY, MONTH))
|
import itertools
import collections
def sliding_window(n, seq):
"""
Copied from toolz
https://toolz.readthedocs.io/en/latest/_modules/toolz/itertoolz.html#sliding_window
A sequence of overlapping subsequences
>>> list(sliding_window(2, [1, 2, 3, 4]))
[(1, 2), (2, 3), (3, 4)]
This function creates a sliding window suitable for transformations like
sliding means / smoothing
>>> mean = lambda seq: float(sum(seq)) / len(seq)
>>> list(map(mean, sliding_window(2, [1, 2, 3, 4])))
[1.5, 2.5, 3.5]
"""
return zip(*(collections.deque(itertools.islice(it, i), 0) or it
for i, it in enumerate(itertools.tee(seq, n))))
def birthday_chocolate(squares, day, month):
consecutive_sums = map(lambda piece: sum(piece), sliding_window(month, squares))
birthday_bars = list(filter(lambda consecutive_sum: day == consecutive_sum,
consecutive_sums))
return len(birthday_bars)
_ = int(input().strip())
SQUARES = list(map(int, input().strip().split(' ')))
DAY, MONTH = map(int, input().strip().split(' '))
print(birthday_chocolate(SQUARES, DAY, MONTH))
| Refactor to use map and filter | Refactor to use map and filter
| Python | mit | rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank |
import itertools
import collections
def sliding_window(n, seq):
"""
Copied from toolz
https://toolz.readthedocs.io/en/latest/_modules/toolz/itertoolz.html#sliding_window
A sequence of overlapping subsequences
>>> list(sliding_window(2, [1, 2, 3, 4]))
[(1, 2), (2, 3), (3, 4)]
This function creates a sliding window suitable for transformations like
sliding means / smoothing
>>> mean = lambda seq: float(sum(seq)) / len(seq)
>>> list(map(mean, sliding_window(2, [1, 2, 3, 4])))
[1.5, 2.5, 3.5]
"""
return zip(*(collections.deque(itertools.islice(it, i), 0) or it
for i, it in enumerate(itertools.tee(seq, n))))
def birthday_chocolate(squares, day, month):
+ consecutive_sums = map(lambda piece: sum(piece), sliding_window(month, squares))
+ birthday_bars = list(filter(lambda consecutive_sum: day == consecutive_sum,
+ consecutive_sums))
+ return len(birthday_bars)
- birthday_chocolates = 0
- for piece in sliding_window(month, squares):
- if sum(piece) == day:
- birthday_chocolates += 1
- return birthday_chocolates
_ = int(input().strip())
SQUARES = list(map(int, input().strip().split(' ')))
DAY, MONTH = map(int, input().strip().split(' '))
print(birthday_chocolate(SQUARES, DAY, MONTH))
| Refactor to use map and filter | ## Code Before:
import itertools
import collections
def sliding_window(n, seq):
"""
Copied from toolz
https://toolz.readthedocs.io/en/latest/_modules/toolz/itertoolz.html#sliding_window
A sequence of overlapping subsequences
>>> list(sliding_window(2, [1, 2, 3, 4]))
[(1, 2), (2, 3), (3, 4)]
This function creates a sliding window suitable for transformations like
sliding means / smoothing
>>> mean = lambda seq: float(sum(seq)) / len(seq)
>>> list(map(mean, sliding_window(2, [1, 2, 3, 4])))
[1.5, 2.5, 3.5]
"""
return zip(*(collections.deque(itertools.islice(it, i), 0) or it
for i, it in enumerate(itertools.tee(seq, n))))
def birthday_chocolate(squares, day, month):
birthday_chocolates = 0
for piece in sliding_window(month, squares):
if sum(piece) == day:
birthday_chocolates += 1
return birthday_chocolates
_ = int(input().strip())
SQUARES = list(map(int, input().strip().split(' ')))
DAY, MONTH = map(int, input().strip().split(' '))
print(birthday_chocolate(SQUARES, DAY, MONTH))
## Instruction:
Refactor to use map and filter
## Code After:
import itertools
import collections
def sliding_window(n, seq):
"""
Copied from toolz
https://toolz.readthedocs.io/en/latest/_modules/toolz/itertoolz.html#sliding_window
A sequence of overlapping subsequences
>>> list(sliding_window(2, [1, 2, 3, 4]))
[(1, 2), (2, 3), (3, 4)]
This function creates a sliding window suitable for transformations like
sliding means / smoothing
>>> mean = lambda seq: float(sum(seq)) / len(seq)
>>> list(map(mean, sliding_window(2, [1, 2, 3, 4])))
[1.5, 2.5, 3.5]
"""
return zip(*(collections.deque(itertools.islice(it, i), 0) or it
for i, it in enumerate(itertools.tee(seq, n))))
def birthday_chocolate(squares, day, month):
consecutive_sums = map(lambda piece: sum(piece), sliding_window(month, squares))
birthday_bars = list(filter(lambda consecutive_sum: day == consecutive_sum,
consecutive_sums))
return len(birthday_bars)
_ = int(input().strip())
SQUARES = list(map(int, input().strip().split(' ')))
DAY, MONTH = map(int, input().strip().split(' '))
print(birthday_chocolate(SQUARES, DAY, MONTH))
| # ... existing code ...
def birthday_chocolate(squares, day, month):
consecutive_sums = map(lambda piece: sum(piece), sliding_window(month, squares))
birthday_bars = list(filter(lambda consecutive_sum: day == consecutive_sum,
consecutive_sums))
return len(birthday_bars)
_ = int(input().strip())
# ... rest of the code ... |
0b4097394fd05da204624d1c6093176feb158bb1 | ajaxuploader/backends/thumbnail.py | ajaxuploader/backends/thumbnail.py | import os
from sorl.thumbnail import get_thumbnail
from ajaxuploader.backends.local import LocalUploadBackend
class ThumbnailUploadBackend(LocalUploadBackend):
def __init__(self, dimension):
self._dimension = dimension
def upload_complete(self, request, filename):
thumbnail = get_thumbnail(self._filename, self._dimension)
os.unlink(self._filename)
return {"path": thumbnail.name}
| import os
from django.conf import settings
from sorl.thumbnail import get_thumbnail
from ajaxuploader.backends.local import LocalUploadBackend
class ThumbnailUploadBackend(LocalUploadBackend):
DIMENSION = "100x100"
def upload_complete(self, request, filename):
thumbnail = get_thumbnail(self._path, self.DIMENSION)
os.unlink(self._path)
return {"path": settings.MEDIA_URL + thumbnail.name}
| Use dimension as a constant, so we keep same interface for all backends; also returns full path to the place where image was saved | Use dimension as a constant, so we keep same interface for all backends; also returns full path to the place where image was saved
| Python | bsd-3-clause | OnlyInAmerica/django-ajax-uploader,derek-adair/django-ajax-uploader,derek-adair/django-ajax-uploader,skoczen/django-ajax-uploader,brilliant-org/django-ajax-uploader,derek-adair/django-ajax-uploader,brilliant-org/django-ajax-uploader,skoczen/django-ajax-uploader,OnlyInAmerica/django-ajax-uploader,brilliant-org/django-ajax-uploader | import os
+ from django.conf import settings
from sorl.thumbnail import get_thumbnail
from ajaxuploader.backends.local import LocalUploadBackend
class ThumbnailUploadBackend(LocalUploadBackend):
+ DIMENSION = "100x100"
+
- def __init__(self, dimension):
- self._dimension = dimension
-
def upload_complete(self, request, filename):
- thumbnail = get_thumbnail(self._filename, self._dimension)
+ thumbnail = get_thumbnail(self._path, self.DIMENSION)
- os.unlink(self._filename)
+ os.unlink(self._path)
- return {"path": thumbnail.name}
+ return {"path": settings.MEDIA_URL + thumbnail.name}
| Use dimension as a constant, so we keep same interface for all backends; also returns full path to the place where image was saved | ## Code Before:
import os
from sorl.thumbnail import get_thumbnail
from ajaxuploader.backends.local import LocalUploadBackend
class ThumbnailUploadBackend(LocalUploadBackend):
def __init__(self, dimension):
self._dimension = dimension
def upload_complete(self, request, filename):
thumbnail = get_thumbnail(self._filename, self._dimension)
os.unlink(self._filename)
return {"path": thumbnail.name}
## Instruction:
Use dimension as a constant, so we keep same interface for all backends; also returns full path to the place where image was saved
## Code After:
import os
from django.conf import settings
from sorl.thumbnail import get_thumbnail
from ajaxuploader.backends.local import LocalUploadBackend
class ThumbnailUploadBackend(LocalUploadBackend):
DIMENSION = "100x100"
def upload_complete(self, request, filename):
thumbnail = get_thumbnail(self._path, self.DIMENSION)
os.unlink(self._path)
return {"path": settings.MEDIA_URL + thumbnail.name}
| // ... existing code ...
import os
from django.conf import settings
from sorl.thumbnail import get_thumbnail
// ... modified code ...
class ThumbnailUploadBackend(LocalUploadBackend):
DIMENSION = "100x100"
def upload_complete(self, request, filename):
thumbnail = get_thumbnail(self._path, self.DIMENSION)
os.unlink(self._path)
return {"path": settings.MEDIA_URL + thumbnail.name}
// ... rest of the code ... |
d32710e53b89e1377a64427f934053c3b0d33802 | bin/intake_multiprocess.py | bin/intake_multiprocess.py | import json
import logging
import argparse
import numpy as np
import emission.pipeline.scheduler as eps
if __name__ == '__main__':
try:
intake_log_config = json.load(open("conf/log/intake.conf", "r"))
except:
intake_log_config = json.load(open("conf/log/intake.conf.sample", "r"))
intake_log_config["handlers"]["file"]["filename"] = intake_log_config["handlers"]["file"]["filename"].replace("intake", "intake_launcher")
intake_log_config["handlers"]["errors"]["filename"] = intake_log_config["handlers"]["errors"]["filename"].replace("intake", "intake_launcher")
logging.config.dictConfig(intake_log_config)
np.random.seed(61297777)
parser = argparse.ArgumentParser()
parser.add_argument("n_workers", type=int,
help="the number of worker processors to use")
parser.add_argument("-p", "--public", action="store_true",
help="pipeline for public (as opposed to regular) phones")
args = parser.parse_args()
split_lists = eps.get_split_uuid_lists(args.n_workers, args.public)
logging.info("Finished generating split lists %s" % split_lists)
eps.dispatch(split_lists, args.public)
| import json
import logging
import argparse
import numpy as np
import emission.pipeline.scheduler as eps
if __name__ == '__main__':
try:
intake_log_config = json.load(open("conf/log/intake.conf", "r"))
except:
intake_log_config = json.load(open("conf/log/intake.conf.sample", "r"))
parser = argparse.ArgumentParser()
parser.add_argument("n_workers", type=int,
help="the number of worker processors to use")
parser.add_argument("-p", "--public", action="store_true",
help="pipeline for public (as opposed to regular) phones")
args = parser.parse_args()
if args.public:
intake_log_config["handlers"]["file"]["filename"] = intake_log_config["handlers"]["file"]["filename"].replace("intake", "intake_launcher_public")
intake_log_config["handlers"]["errors"]["filename"] = intake_log_config["handlers"]["errors"]["filename"].replace("intake", "intake_launcher_public")
else:
intake_log_config["handlers"]["file"]["filename"] = intake_log_config["handlers"]["file"]["filename"].replace("intake", "intake_launcher")
intake_log_config["handlers"]["errors"]["filename"] = intake_log_config["handlers"]["errors"]["filename"].replace("intake", "intake_launcher")
logging.config.dictConfig(intake_log_config)
np.random.seed(61297777)
split_lists = eps.get_split_uuid_lists(args.n_workers, args.public)
logging.info("Finished generating split lists %s" % split_lists)
eps.dispatch(split_lists, args.public)
| Use a separate log file for the public launcher data | Use a separate log file for the public launcher data
Log files are not thread-safe
| Python | bsd-3-clause | sunil07t/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server | import json
import logging
import argparse
import numpy as np
import emission.pipeline.scheduler as eps
if __name__ == '__main__':
try:
intake_log_config = json.load(open("conf/log/intake.conf", "r"))
except:
intake_log_config = json.load(open("conf/log/intake.conf.sample", "r"))
- intake_log_config["handlers"]["file"]["filename"] = intake_log_config["handlers"]["file"]["filename"].replace("intake", "intake_launcher")
- intake_log_config["handlers"]["errors"]["filename"] = intake_log_config["handlers"]["errors"]["filename"].replace("intake", "intake_launcher")
-
- logging.config.dictConfig(intake_log_config)
- np.random.seed(61297777)
-
parser = argparse.ArgumentParser()
parser.add_argument("n_workers", type=int,
help="the number of worker processors to use")
parser.add_argument("-p", "--public", action="store_true",
help="pipeline for public (as opposed to regular) phones")
args = parser.parse_args()
+ if args.public:
+ intake_log_config["handlers"]["file"]["filename"] = intake_log_config["handlers"]["file"]["filename"].replace("intake", "intake_launcher_public")
+ intake_log_config["handlers"]["errors"]["filename"] = intake_log_config["handlers"]["errors"]["filename"].replace("intake", "intake_launcher_public")
+ else:
+ intake_log_config["handlers"]["file"]["filename"] = intake_log_config["handlers"]["file"]["filename"].replace("intake", "intake_launcher")
+ intake_log_config["handlers"]["errors"]["filename"] = intake_log_config["handlers"]["errors"]["filename"].replace("intake", "intake_launcher")
+
+ logging.config.dictConfig(intake_log_config)
+ np.random.seed(61297777)
+
split_lists = eps.get_split_uuid_lists(args.n_workers, args.public)
logging.info("Finished generating split lists %s" % split_lists)
eps.dispatch(split_lists, args.public)
| Use a separate log file for the public launcher data | ## Code Before:
import json
import logging
import argparse
import numpy as np
import emission.pipeline.scheduler as eps
if __name__ == '__main__':
try:
intake_log_config = json.load(open("conf/log/intake.conf", "r"))
except:
intake_log_config = json.load(open("conf/log/intake.conf.sample", "r"))
intake_log_config["handlers"]["file"]["filename"] = intake_log_config["handlers"]["file"]["filename"].replace("intake", "intake_launcher")
intake_log_config["handlers"]["errors"]["filename"] = intake_log_config["handlers"]["errors"]["filename"].replace("intake", "intake_launcher")
logging.config.dictConfig(intake_log_config)
np.random.seed(61297777)
parser = argparse.ArgumentParser()
parser.add_argument("n_workers", type=int,
help="the number of worker processors to use")
parser.add_argument("-p", "--public", action="store_true",
help="pipeline for public (as opposed to regular) phones")
args = parser.parse_args()
split_lists = eps.get_split_uuid_lists(args.n_workers, args.public)
logging.info("Finished generating split lists %s" % split_lists)
eps.dispatch(split_lists, args.public)
## Instruction:
Use a separate log file for the public launcher data
## Code After:
import json
import logging
import argparse
import numpy as np
import emission.pipeline.scheduler as eps
if __name__ == '__main__':
try:
intake_log_config = json.load(open("conf/log/intake.conf", "r"))
except:
intake_log_config = json.load(open("conf/log/intake.conf.sample", "r"))
parser = argparse.ArgumentParser()
parser.add_argument("n_workers", type=int,
help="the number of worker processors to use")
parser.add_argument("-p", "--public", action="store_true",
help="pipeline for public (as opposed to regular) phones")
args = parser.parse_args()
if args.public:
intake_log_config["handlers"]["file"]["filename"] = intake_log_config["handlers"]["file"]["filename"].replace("intake", "intake_launcher_public")
intake_log_config["handlers"]["errors"]["filename"] = intake_log_config["handlers"]["errors"]["filename"].replace("intake", "intake_launcher_public")
else:
intake_log_config["handlers"]["file"]["filename"] = intake_log_config["handlers"]["file"]["filename"].replace("intake", "intake_launcher")
intake_log_config["handlers"]["errors"]["filename"] = intake_log_config["handlers"]["errors"]["filename"].replace("intake", "intake_launcher")
logging.config.dictConfig(intake_log_config)
np.random.seed(61297777)
split_lists = eps.get_split_uuid_lists(args.n_workers, args.public)
logging.info("Finished generating split lists %s" % split_lists)
eps.dispatch(split_lists, args.public)
| ...
intake_log_config = json.load(open("conf/log/intake.conf.sample", "r"))
parser = argparse.ArgumentParser()
parser.add_argument("n_workers", type=int,
...
args = parser.parse_args()
if args.public:
intake_log_config["handlers"]["file"]["filename"] = intake_log_config["handlers"]["file"]["filename"].replace("intake", "intake_launcher_public")
intake_log_config["handlers"]["errors"]["filename"] = intake_log_config["handlers"]["errors"]["filename"].replace("intake", "intake_launcher_public")
else:
intake_log_config["handlers"]["file"]["filename"] = intake_log_config["handlers"]["file"]["filename"].replace("intake", "intake_launcher")
intake_log_config["handlers"]["errors"]["filename"] = intake_log_config["handlers"]["errors"]["filename"].replace("intake", "intake_launcher")
logging.config.dictConfig(intake_log_config)
np.random.seed(61297777)
split_lists = eps.get_split_uuid_lists(args.n_workers, args.public)
logging.info("Finished generating split lists %s" % split_lists)
... |
d2250ac74b0797d1662c054d2357573578caa251 | core/tasks.py | core/tasks.py | import os
import gzip
import urllib.request
from celery import shared_task
from django.core.mail import EmailMessage
from celery.task import periodic_task
from celery.schedules import crontab
@shared_task(name='deliver_email')
def deliver_email(subject=None, body=None, recipients=None):
#print("Entering core.tasks.deliver_email for ...", recipients)
if recipients:
for recipient in recipients:
#print("sending email to recipient: ", recipient)
email = EmailMessage(subject, body, to=[recipient])
email.send()
@periodic_task(bind=True, run_every=crontab(0, 0, day_of_month='7'))
def update_geolocation(self):
# Establish desired paths and directories
current_directory = os.path.dirname(__file__)
compressed_filepath = os.path.join(current_directory, 'GeoLite2-City.mmdb.gz')
uncompressed_filepath = os.path.join(current_directory, 'GeoLite2-City.mmdb')
# Pull down current database file
url = "http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz"
urllib.request.urlretrieve(url, compressed_filepath)
# Read and unzip compressed file to current directory
zipped = gzip.open(compressed_filepath, "rb")
uncompressed = open(uncompressed_filepath, "wb")
uncompressed.write(zipped.read())
zipped.close()
uncompressed.close()
# Remove zipped file
os.remove(compressed_filepath)
| import os
import gzip
import urllib.request
from celery import shared_task
from django.core.mail import EmailMessage
from celery.task import periodic_task
from celery.schedules import crontab
@shared_task(name='deliver_email')
def deliver_email(subject=None, body=None, recipients=None):
if recipients:
for recipient in recipients:
email = EmailMessage(subject, body, to=[recipient])
email.send()
@periodic_task(bind=True, run_every=crontab(0, 0, day_of_month='7'))
def update_geolocation(self):
# Establish desired paths and directories
current_directory = os.path.dirname(__file__)
compressed_filepath = os.path.join(current_directory, 'GeoLite2-City.mmdb.gz')
uncompressed_filepath = os.path.join(current_directory, 'GeoLite2-City.mmdb')
# Pull down current database file
url = "http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz"
urllib.request.urlretrieve(url, compressed_filepath)
# Read and unzip compressed file to current directory
zipped = gzip.open(compressed_filepath, "rb")
uncompressed = open(uncompressed_filepath, "wb")
uncompressed.write(zipped.read())
zipped.close()
uncompressed.close()
# Remove zipped file
os.remove(compressed_filepath) | Clean up code and remove print statements | Clean up code and remove print statements
| Python | mit | LindaTNguyen/RAPID,gdit-cnd/RAPID,LindaTNguyen/RAPID,gdit-cnd/RAPID,LindaTNguyen/RAPID,gdit-cnd/RAPID,gdit-cnd/RAPID,gdit-cnd/RAPID,LindaTNguyen/RAPID,LindaTNguyen/RAPID | import os
import gzip
import urllib.request
from celery import shared_task
from django.core.mail import EmailMessage
from celery.task import periodic_task
from celery.schedules import crontab
@shared_task(name='deliver_email')
def deliver_email(subject=None, body=None, recipients=None):
- #print("Entering core.tasks.deliver_email for ...", recipients)
if recipients:
for recipient in recipients:
- #print("sending email to recipient: ", recipient)
email = EmailMessage(subject, body, to=[recipient])
email.send()
+
@periodic_task(bind=True, run_every=crontab(0, 0, day_of_month='7'))
def update_geolocation(self):
+
# Establish desired paths and directories
current_directory = os.path.dirname(__file__)
compressed_filepath = os.path.join(current_directory, 'GeoLite2-City.mmdb.gz')
uncompressed_filepath = os.path.join(current_directory, 'GeoLite2-City.mmdb')
# Pull down current database file
url = "http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz"
urllib.request.urlretrieve(url, compressed_filepath)
# Read and unzip compressed file to current directory
zipped = gzip.open(compressed_filepath, "rb")
uncompressed = open(uncompressed_filepath, "wb")
uncompressed.write(zipped.read())
zipped.close()
uncompressed.close()
# Remove zipped file
os.remove(compressed_filepath)
- | Clean up code and remove print statements | ## Code Before:
import os
import gzip
import urllib.request
from celery import shared_task
from django.core.mail import EmailMessage
from celery.task import periodic_task
from celery.schedules import crontab
@shared_task(name='deliver_email')
def deliver_email(subject=None, body=None, recipients=None):
#print("Entering core.tasks.deliver_email for ...", recipients)
if recipients:
for recipient in recipients:
#print("sending email to recipient: ", recipient)
email = EmailMessage(subject, body, to=[recipient])
email.send()
@periodic_task(bind=True, run_every=crontab(0, 0, day_of_month='7'))
def update_geolocation(self):
# Establish desired paths and directories
current_directory = os.path.dirname(__file__)
compressed_filepath = os.path.join(current_directory, 'GeoLite2-City.mmdb.gz')
uncompressed_filepath = os.path.join(current_directory, 'GeoLite2-City.mmdb')
# Pull down current database file
url = "http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz"
urllib.request.urlretrieve(url, compressed_filepath)
# Read and unzip compressed file to current directory
zipped = gzip.open(compressed_filepath, "rb")
uncompressed = open(uncompressed_filepath, "wb")
uncompressed.write(zipped.read())
zipped.close()
uncompressed.close()
# Remove zipped file
os.remove(compressed_filepath)
## Instruction:
Clean up code and remove print statements
## Code After:
import os
import gzip
import urllib.request
from celery import shared_task
from django.core.mail import EmailMessage
from celery.task import periodic_task
from celery.schedules import crontab
@shared_task(name='deliver_email')
def deliver_email(subject=None, body=None, recipients=None):
if recipients:
for recipient in recipients:
email = EmailMessage(subject, body, to=[recipient])
email.send()
@periodic_task(bind=True, run_every=crontab(0, 0, day_of_month='7'))
def update_geolocation(self):
# Establish desired paths and directories
current_directory = os.path.dirname(__file__)
compressed_filepath = os.path.join(current_directory, 'GeoLite2-City.mmdb.gz')
uncompressed_filepath = os.path.join(current_directory, 'GeoLite2-City.mmdb')
# Pull down current database file
url = "http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz"
urllib.request.urlretrieve(url, compressed_filepath)
# Read and unzip compressed file to current directory
zipped = gzip.open(compressed_filepath, "rb")
uncompressed = open(uncompressed_filepath, "wb")
uncompressed.write(zipped.read())
zipped.close()
uncompressed.close()
# Remove zipped file
os.remove(compressed_filepath) | # ... existing code ...
@shared_task(name='deliver_email')
def deliver_email(subject=None, body=None, recipients=None):
if recipients:
# ... modified code ...
for recipient in recipients:
email = EmailMessage(subject, body, to=[recipient])
email.send()
...
@periodic_task(bind=True, run_every=crontab(0, 0, day_of_month='7'))
def update_geolocation(self):
# Establish desired paths and directories
current_directory = os.path.dirname(__file__)
# ... rest of the code ... |
f3b87dcad47e77a3383de6fef17080661471a4a3 | facturapdf/generators.py | facturapdf/generators.py | import re
from reportlab import platypus
from facturapdf import flowables, helper
def element(item):
elements = {
'framebreak': {'class': platypus.FrameBreak},
'simpleline': {'class': flowables.SimpleLine, 'cast': {0: float, 1: float}},
'paragraph': {'class': flowables.Paragraph},
'image': {'class': helper.get_image, 'cast': {1: float}},
'spacer': {'class': platypus.Spacer, 'cast': {0: float, 1: float}}
}
if isinstance(item, str):
match = re.search('(?P<name>\w+)(\[(?P<args>.+)\])?', item)
if match and match.group('name') in elements:
flowable = elements[match.group('name')]
args = [] if not match.group('args') else match.group('args').split('|')
if 'cast' in flowable:
for index, cls in flowable['cast'].iteritems():
args[index] = cls(args[index])
return flowable['class'](*args)
return item
def chapter(*args):
return [element(item) for item in args] | import re
from reportlab import platypus
from facturapdf import flowables, helper
def element(item):
elements = {
'framebreak': {'class': platypus.FrameBreak},
'simpleline': {'class': flowables.SimpleLine, 'cast': {0: float, 1: float}},
'paragraph': {'class': flowables.Paragraph},
'image': {'class': helper.get_image, 'cast': {1: float}},
'spacer': {'class': platypus.Spacer, 'cast': {0: float, 1: float}}
}
if isinstance(item, str):
match = re.search('(?P<name>\w+)(\[(?P<args>.+)\])?', item)
if match and match.group('name') in elements:
flowable = elements[match.group('name')]
args = [] if not match.group('args') else match.group('args').split('|')
if 'cast' in flowable:
for index, cls in iter(flowable['cast'].items()):
args[index] = cls(args[index])
return flowable['class'](*args)
return item
def chapter(*args):
return [element(item) for item in args] | Use dict iteration compatible with Python 2 and 3 | Use dict iteration compatible with Python 2 and 3
| Python | bsd-3-clause | initios/factura-pdf | import re
from reportlab import platypus
from facturapdf import flowables, helper
def element(item):
elements = {
'framebreak': {'class': platypus.FrameBreak},
'simpleline': {'class': flowables.SimpleLine, 'cast': {0: float, 1: float}},
'paragraph': {'class': flowables.Paragraph},
'image': {'class': helper.get_image, 'cast': {1: float}},
'spacer': {'class': platypus.Spacer, 'cast': {0: float, 1: float}}
}
if isinstance(item, str):
match = re.search('(?P<name>\w+)(\[(?P<args>.+)\])?', item)
if match and match.group('name') in elements:
flowable = elements[match.group('name')]
args = [] if not match.group('args') else match.group('args').split('|')
if 'cast' in flowable:
- for index, cls in flowable['cast'].iteritems():
+ for index, cls in iter(flowable['cast'].items()):
args[index] = cls(args[index])
return flowable['class'](*args)
return item
def chapter(*args):
return [element(item) for item in args] | Use dict iteration compatible with Python 2 and 3 | ## Code Before:
import re
from reportlab import platypus
from facturapdf import flowables, helper
def element(item):
elements = {
'framebreak': {'class': platypus.FrameBreak},
'simpleline': {'class': flowables.SimpleLine, 'cast': {0: float, 1: float}},
'paragraph': {'class': flowables.Paragraph},
'image': {'class': helper.get_image, 'cast': {1: float}},
'spacer': {'class': platypus.Spacer, 'cast': {0: float, 1: float}}
}
if isinstance(item, str):
match = re.search('(?P<name>\w+)(\[(?P<args>.+)\])?', item)
if match and match.group('name') in elements:
flowable = elements[match.group('name')]
args = [] if not match.group('args') else match.group('args').split('|')
if 'cast' in flowable:
for index, cls in flowable['cast'].iteritems():
args[index] = cls(args[index])
return flowable['class'](*args)
return item
def chapter(*args):
return [element(item) for item in args]
## Instruction:
Use dict iteration compatible with Python 2 and 3
## Code After:
import re
from reportlab import platypus
from facturapdf import flowables, helper
def element(item):
elements = {
'framebreak': {'class': platypus.FrameBreak},
'simpleline': {'class': flowables.SimpleLine, 'cast': {0: float, 1: float}},
'paragraph': {'class': flowables.Paragraph},
'image': {'class': helper.get_image, 'cast': {1: float}},
'spacer': {'class': platypus.Spacer, 'cast': {0: float, 1: float}}
}
if isinstance(item, str):
match = re.search('(?P<name>\w+)(\[(?P<args>.+)\])?', item)
if match and match.group('name') in elements:
flowable = elements[match.group('name')]
args = [] if not match.group('args') else match.group('args').split('|')
if 'cast' in flowable:
for index, cls in iter(flowable['cast'].items()):
args[index] = cls(args[index])
return flowable['class'](*args)
return item
def chapter(*args):
return [element(item) for item in args] | // ... existing code ...
if 'cast' in flowable:
for index, cls in iter(flowable['cast'].items()):
args[index] = cls(args[index])
// ... rest of the code ... |
442f21bfde16f72d4480fa7fd9dea2eac741a857 | src/analyses/views.py | src/analyses/views.py | from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.translation import ugettext_lazy as _
from django.views.generic import CreateView, TemplateView
from .forms import AbstractAnalysisCreateForm
from .pipelines import AVAILABLE_PIPELINES
User = get_user_model()
class SelectNewAnalysisTypeView(LoginRequiredMixin, TemplateView):
template_name = "analyses/new_analysis_by_type.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['available_pipelines'] = AVAILABLE_PIPELINES
return context
class AbstractAnalysisFormView(LoginRequiredMixin, CreateView):
form_class = AbstractAnalysisCreateForm
template_name = None
analysis_type = 'AbstractAnalysis'
analysis_description = ''
analysis_create_url = None
def get_form_kwargs(self):
"""Pass request object for form creation"""
kwargs = super().get_form_kwargs()
kwargs['request'] = self.request
return kwargs
def form_valid(self, form):
response = super().form_valid(form)
messages.add_message(
self.request, messages.INFO,
_('You just created a %(analysis_type)s analysis!') % {
'analysis_type': self.analysis_type
}
)
return response
| from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.translation import ugettext_lazy as _
from django.views.generic import CreateView, TemplateView
from .forms import AbstractAnalysisCreateForm
from .pipelines import AVAILABLE_PIPELINES
User = get_user_model()
class SelectNewAnalysisTypeView(LoginRequiredMixin, TemplateView):
template_name = "analyses/new_analysis_by_type.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['available_pipelines'] = AVAILABLE_PIPELINES
return context
class AbstractAnalysisFormView(LoginRequiredMixin, CreateView):
form_class = AbstractAnalysisCreateForm
template_name = None
analysis_type = 'AbstractAnalysis'
analysis_description = ''
analysis_create_url = None
def get_form_kwargs(self):
"""Pass request object for form creation"""
kwargs = super().get_form_kwargs()
kwargs['request'] = self.request
return kwargs
def form_valid(self, form):
response = super().form_valid(form)
messages.add_message(
self.request, messages.INFO,
_(
'You just created a %(analysis_type)s analysis! '
'View its detail <a href="%(analysis_detail_url)s">here</a>.'
) % {
'analysis_type': self.analysis_type,
'analysis_detail_url': self.object.get_absolute_url(),
},
extra_tags='safe',
)
return response
| Include analysis detail view URL in message | Include analysis detail view URL in message
| Python | mit | ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai | from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.translation import ugettext_lazy as _
from django.views.generic import CreateView, TemplateView
from .forms import AbstractAnalysisCreateForm
from .pipelines import AVAILABLE_PIPELINES
User = get_user_model()
class SelectNewAnalysisTypeView(LoginRequiredMixin, TemplateView):
template_name = "analyses/new_analysis_by_type.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['available_pipelines'] = AVAILABLE_PIPELINES
return context
class AbstractAnalysisFormView(LoginRequiredMixin, CreateView):
form_class = AbstractAnalysisCreateForm
template_name = None
analysis_type = 'AbstractAnalysis'
analysis_description = ''
analysis_create_url = None
def get_form_kwargs(self):
"""Pass request object for form creation"""
kwargs = super().get_form_kwargs()
kwargs['request'] = self.request
return kwargs
def form_valid(self, form):
response = super().form_valid(form)
messages.add_message(
self.request, messages.INFO,
+ _(
- _('You just created a %(analysis_type)s analysis!') % {
+ 'You just created a %(analysis_type)s analysis! '
+ 'View its detail <a href="%(analysis_detail_url)s">here</a>.'
+ ) % {
- 'analysis_type': self.analysis_type
+ 'analysis_type': self.analysis_type,
+ 'analysis_detail_url': self.object.get_absolute_url(),
- }
+ },
+ extra_tags='safe',
)
return response
| Include analysis detail view URL in message | ## Code Before:
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.translation import ugettext_lazy as _
from django.views.generic import CreateView, TemplateView
from .forms import AbstractAnalysisCreateForm
from .pipelines import AVAILABLE_PIPELINES
User = get_user_model()
class SelectNewAnalysisTypeView(LoginRequiredMixin, TemplateView):
template_name = "analyses/new_analysis_by_type.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['available_pipelines'] = AVAILABLE_PIPELINES
return context
class AbstractAnalysisFormView(LoginRequiredMixin, CreateView):
form_class = AbstractAnalysisCreateForm
template_name = None
analysis_type = 'AbstractAnalysis'
analysis_description = ''
analysis_create_url = None
def get_form_kwargs(self):
"""Pass request object for form creation"""
kwargs = super().get_form_kwargs()
kwargs['request'] = self.request
return kwargs
def form_valid(self, form):
response = super().form_valid(form)
messages.add_message(
self.request, messages.INFO,
_('You just created a %(analysis_type)s analysis!') % {
'analysis_type': self.analysis_type
}
)
return response
## Instruction:
Include analysis detail view URL in message
## Code After:
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.translation import ugettext_lazy as _
from django.views.generic import CreateView, TemplateView
from .forms import AbstractAnalysisCreateForm
from .pipelines import AVAILABLE_PIPELINES
User = get_user_model()
class SelectNewAnalysisTypeView(LoginRequiredMixin, TemplateView):
template_name = "analyses/new_analysis_by_type.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['available_pipelines'] = AVAILABLE_PIPELINES
return context
class AbstractAnalysisFormView(LoginRequiredMixin, CreateView):
form_class = AbstractAnalysisCreateForm
template_name = None
analysis_type = 'AbstractAnalysis'
analysis_description = ''
analysis_create_url = None
def get_form_kwargs(self):
"""Pass request object for form creation"""
kwargs = super().get_form_kwargs()
kwargs['request'] = self.request
return kwargs
def form_valid(self, form):
response = super().form_valid(form)
messages.add_message(
self.request, messages.INFO,
_(
'You just created a %(analysis_type)s analysis! '
'View its detail <a href="%(analysis_detail_url)s">here</a>.'
) % {
'analysis_type': self.analysis_type,
'analysis_detail_url': self.object.get_absolute_url(),
},
extra_tags='safe',
)
return response
| // ... existing code ...
messages.add_message(
self.request, messages.INFO,
_(
'You just created a %(analysis_type)s analysis! '
'View its detail <a href="%(analysis_detail_url)s">here</a>.'
) % {
'analysis_type': self.analysis_type,
'analysis_detail_url': self.object.get_absolute_url(),
},
extra_tags='safe',
)
return response
// ... rest of the code ... |
aaaaad4ea3109406268471b6605eb6078848db0d | falcom/api/uri/fake_mapping.py | falcom/api/uri/fake_mapping.py |
class FakeMappingThatRecordsAccessions:
def __init__ (self):
self.__set = set()
def __getitem__ (self, key):
self.__set.add(key)
return 0
def get_set (self):
return self.__set
def check_on_format_str (self, format_str):
format_str.format_map(self)
|
class FakeMappingThatRecordsAccessions:
def __init__ (self):
self.__set = set()
def __getitem__ (self, key):
self.__set.add(key)
return 0
def get_set (self):
return self.__set
def check_on_format_str (self, format_str):
format_str.format_map(self)
def get_expected_args_from_format_str (format_str):
mapping = FakeMappingThatRecordsAccessions()
format_str.format_map(mapping)
return mapping.get_set()
| Write function for getting expected args | Write function for getting expected args
| Python | bsd-3-clause | mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation |
class FakeMappingThatRecordsAccessions:
def __init__ (self):
self.__set = set()
def __getitem__ (self, key):
self.__set.add(key)
return 0
def get_set (self):
return self.__set
def check_on_format_str (self, format_str):
format_str.format_map(self)
+ def get_expected_args_from_format_str (format_str):
+ mapping = FakeMappingThatRecordsAccessions()
+ format_str.format_map(mapping)
+
+ return mapping.get_set()
+ | Write function for getting expected args | ## Code Before:
class FakeMappingThatRecordsAccessions:
def __init__ (self):
self.__set = set()
def __getitem__ (self, key):
self.__set.add(key)
return 0
def get_set (self):
return self.__set
def check_on_format_str (self, format_str):
format_str.format_map(self)
## Instruction:
Write function for getting expected args
## Code After:
class FakeMappingThatRecordsAccessions:
def __init__ (self):
self.__set = set()
def __getitem__ (self, key):
self.__set.add(key)
return 0
def get_set (self):
return self.__set
def check_on_format_str (self, format_str):
format_str.format_map(self)
def get_expected_args_from_format_str (format_str):
mapping = FakeMappingThatRecordsAccessions()
format_str.format_map(mapping)
return mapping.get_set()
| // ... existing code ...
def check_on_format_str (self, format_str):
format_str.format_map(self)
def get_expected_args_from_format_str (format_str):
mapping = FakeMappingThatRecordsAccessions()
format_str.format_map(mapping)
return mapping.get_set()
// ... rest of the code ... |
bc634d8c04bc15ca381019dda08982b9e1badd1c | sncosmo/tests/test_builtins.py | sncosmo/tests/test_builtins.py | import pytest
import sncosmo
@pytest.mark.might_download
def test_hst_bands():
""" check that the HST and JWST bands are accessible """
for bandname in ['f606w', 'uvf606w', 'f125w', 'f127m',
'f115w']: # jwst nircam
sncosmo.get_bandpass(bandname)
@pytest.mark.might_download
def test_jwst_miri_bands():
for bandname in ['f1130w']:
sncosmo.get_bandpass(bandname)
@pytest.mark.might_download
def test_ztf_bandpass():
bp = sncosmo.get_bandpass('ztfg')
@pytest.mark.might_download
def test_roman_bandpass():
sncosmo.get_bandpass('f062')
sncosmo.get_bandpass('f087')
sncosmo.get_bandpass('f106')
sncosmo.get_bandpass('f129')
sncosmo.get_bandpass('f158')
sncosmo.get_bandpass('f184')
sncosmo.get_bandpass('f213')
sncosmo.get_bandpass('f146')
| import pytest
import sncosmo
from sncosmo.bandpasses import _BANDPASSES, _BANDPASS_INTERPOLATORS
from sncosmo.magsystems import _MAGSYSTEMS
from sncosmo.models import _SOURCES
bandpasses = [i['name'] for i in _BANDPASSES.get_loaders_metadata()]
bandpass_interpolators = [i['name'] for i in
_BANDPASS_INTERPOLATORS.get_loaders_metadata()]
magsystems = [i['name'] for i in _MAGSYSTEMS.get_loaders_metadata()]
sources = [(i['name'], i['version']) for i in _SOURCES.get_loaders_metadata()]
@pytest.mark.might_download
@pytest.mark.parametrize("name", bandpasses)
def test_builtin_bandpass(name):
sncosmo.get_bandpass(name)
@pytest.mark.might_download
@pytest.mark.parametrize("name", bandpass_interpolators)
def test_builtin_bandpass_interpolator(name):
interpolator = _BANDPASS_INTERPOLATORS.retrieve(name)
interpolator.at(interpolator.minpos())
@pytest.mark.might_download
@pytest.mark.parametrize("name,version", sources)
def test_builtin_source(name, version):
sncosmo.get_source(name, version)
@pytest.mark.might_download
@pytest.mark.parametrize("name", magsystems)
def test_builtin_magsystem(name):
sncosmo.get_magsystem(name)
| Add tests for all builtins | Add tests for all builtins
| Python | bsd-3-clause | sncosmo/sncosmo,sncosmo/sncosmo,sncosmo/sncosmo | import pytest
import sncosmo
+ from sncosmo.bandpasses import _BANDPASSES, _BANDPASS_INTERPOLATORS
+ from sncosmo.magsystems import _MAGSYSTEMS
+ from sncosmo.models import _SOURCES
- @pytest.mark.might_download
- def test_hst_bands():
- """ check that the HST and JWST bands are accessible """
- for bandname in ['f606w', 'uvf606w', 'f125w', 'f127m',
- 'f115w']: # jwst nircam
- sncosmo.get_bandpass(bandname)
+
+ bandpasses = [i['name'] for i in _BANDPASSES.get_loaders_metadata()]
+ bandpass_interpolators = [i['name'] for i in
+ _BANDPASS_INTERPOLATORS.get_loaders_metadata()]
+ magsystems = [i['name'] for i in _MAGSYSTEMS.get_loaders_metadata()]
+ sources = [(i['name'], i['version']) for i in _SOURCES.get_loaders_metadata()]
@pytest.mark.might_download
- def test_jwst_miri_bands():
- for bandname in ['f1130w']:
+ @pytest.mark.parametrize("name", bandpasses)
+ def test_builtin_bandpass(name):
- sncosmo.get_bandpass(bandname)
+ sncosmo.get_bandpass(name)
@pytest.mark.might_download
- def test_ztf_bandpass():
- bp = sncosmo.get_bandpass('ztfg')
+ @pytest.mark.parametrize("name", bandpass_interpolators)
+ def test_builtin_bandpass_interpolator(name):
+ interpolator = _BANDPASS_INTERPOLATORS.retrieve(name)
+ interpolator.at(interpolator.minpos())
@pytest.mark.might_download
+ @pytest.mark.parametrize("name,version", sources)
+ def test_builtin_source(name, version):
+ sncosmo.get_source(name, version)
- def test_roman_bandpass():
- sncosmo.get_bandpass('f062')
- sncosmo.get_bandpass('f087')
- sncosmo.get_bandpass('f106')
- sncosmo.get_bandpass('f129')
- sncosmo.get_bandpass('f158')
- sncosmo.get_bandpass('f184')
- sncosmo.get_bandpass('f213')
- sncosmo.get_bandpass('f146')
+
+ @pytest.mark.might_download
+ @pytest.mark.parametrize("name", magsystems)
+ def test_builtin_magsystem(name):
+ sncosmo.get_magsystem(name)
+ | Add tests for all builtins | ## Code Before:
import pytest
import sncosmo
@pytest.mark.might_download
def test_hst_bands():
""" check that the HST and JWST bands are accessible """
for bandname in ['f606w', 'uvf606w', 'f125w', 'f127m',
'f115w']: # jwst nircam
sncosmo.get_bandpass(bandname)
@pytest.mark.might_download
def test_jwst_miri_bands():
for bandname in ['f1130w']:
sncosmo.get_bandpass(bandname)
@pytest.mark.might_download
def test_ztf_bandpass():
bp = sncosmo.get_bandpass('ztfg')
@pytest.mark.might_download
def test_roman_bandpass():
sncosmo.get_bandpass('f062')
sncosmo.get_bandpass('f087')
sncosmo.get_bandpass('f106')
sncosmo.get_bandpass('f129')
sncosmo.get_bandpass('f158')
sncosmo.get_bandpass('f184')
sncosmo.get_bandpass('f213')
sncosmo.get_bandpass('f146')
## Instruction:
Add tests for all builtins
## Code After:
import pytest
import sncosmo
from sncosmo.bandpasses import _BANDPASSES, _BANDPASS_INTERPOLATORS
from sncosmo.magsystems import _MAGSYSTEMS
from sncosmo.models import _SOURCES
bandpasses = [i['name'] for i in _BANDPASSES.get_loaders_metadata()]
bandpass_interpolators = [i['name'] for i in
_BANDPASS_INTERPOLATORS.get_loaders_metadata()]
magsystems = [i['name'] for i in _MAGSYSTEMS.get_loaders_metadata()]
sources = [(i['name'], i['version']) for i in _SOURCES.get_loaders_metadata()]
@pytest.mark.might_download
@pytest.mark.parametrize("name", bandpasses)
def test_builtin_bandpass(name):
sncosmo.get_bandpass(name)
@pytest.mark.might_download
@pytest.mark.parametrize("name", bandpass_interpolators)
def test_builtin_bandpass_interpolator(name):
interpolator = _BANDPASS_INTERPOLATORS.retrieve(name)
interpolator.at(interpolator.minpos())
@pytest.mark.might_download
@pytest.mark.parametrize("name,version", sources)
def test_builtin_source(name, version):
sncosmo.get_source(name, version)
@pytest.mark.might_download
@pytest.mark.parametrize("name", magsystems)
def test_builtin_magsystem(name):
sncosmo.get_magsystem(name)
| ...
import sncosmo
from sncosmo.bandpasses import _BANDPASSES, _BANDPASS_INTERPOLATORS
from sncosmo.magsystems import _MAGSYSTEMS
from sncosmo.models import _SOURCES
bandpasses = [i['name'] for i in _BANDPASSES.get_loaders_metadata()]
bandpass_interpolators = [i['name'] for i in
_BANDPASS_INTERPOLATORS.get_loaders_metadata()]
magsystems = [i['name'] for i in _MAGSYSTEMS.get_loaders_metadata()]
sources = [(i['name'], i['version']) for i in _SOURCES.get_loaders_metadata()]
@pytest.mark.might_download
@pytest.mark.parametrize("name", bandpasses)
def test_builtin_bandpass(name):
sncosmo.get_bandpass(name)
@pytest.mark.might_download
@pytest.mark.parametrize("name", bandpass_interpolators)
def test_builtin_bandpass_interpolator(name):
interpolator = _BANDPASS_INTERPOLATORS.retrieve(name)
interpolator.at(interpolator.minpos())
@pytest.mark.might_download
@pytest.mark.parametrize("name,version", sources)
def test_builtin_source(name, version):
sncosmo.get_source(name, version)
@pytest.mark.might_download
@pytest.mark.parametrize("name", magsystems)
def test_builtin_magsystem(name):
sncosmo.get_magsystem(name)
... |
95d71d5a84f05de7d655fd788a4139c3a1316d74 | text/__init__.py | text/__init__.py |
import os
def get_files(path, ext=None):
"""
Get all files in directory path, optionally with the specified extension
"""
if ext is None:
ext = ''
return [
os.path.abspath(fname)
for fname in os.listdir(path)
if os.path.isfile(fname)
if fname.endswith(ext)
]
|
import os
def get_files(path, ext=None):
"""
Get all files in directory path, optionally with the specified extension
"""
if ext is None:
ext = ''
return [
os.path.abspath(fname)
for fname in os.listdir(path)
if os.path.isfile(fname)
if fname.endswith(ext)
]
def blob_text(filenames):
"""
Create a blob of text by reading in all filenames into a string
"""
return '\n'.join([open(fname).read() for fname in filenames])
| Add function to generate a blob of text from a list of files | Add function to generate a blob of text from a list of files
| Python | mit | IanLee1521/utilities |
import os
def get_files(path, ext=None):
"""
Get all files in directory path, optionally with the specified extension
"""
if ext is None:
ext = ''
return [
os.path.abspath(fname)
for fname in os.listdir(path)
if os.path.isfile(fname)
if fname.endswith(ext)
]
+
+ def blob_text(filenames):
+ """
+ Create a blob of text by reading in all filenames into a string
+ """
+ return '\n'.join([open(fname).read() for fname in filenames])
+ | Add function to generate a blob of text from a list of files | ## Code Before:
import os
def get_files(path, ext=None):
"""
Get all files in directory path, optionally with the specified extension
"""
if ext is None:
ext = ''
return [
os.path.abspath(fname)
for fname in os.listdir(path)
if os.path.isfile(fname)
if fname.endswith(ext)
]
## Instruction:
Add function to generate a blob of text from a list of files
## Code After:
import os
def get_files(path, ext=None):
"""
Get all files in directory path, optionally with the specified extension
"""
if ext is None:
ext = ''
return [
os.path.abspath(fname)
for fname in os.listdir(path)
if os.path.isfile(fname)
if fname.endswith(ext)
]
def blob_text(filenames):
"""
Create a blob of text by reading in all filenames into a string
"""
return '\n'.join([open(fname).read() for fname in filenames])
| # ... existing code ...
if fname.endswith(ext)
]
def blob_text(filenames):
"""
Create a blob of text by reading in all filenames into a string
"""
return '\n'.join([open(fname).read() for fname in filenames])
# ... rest of the code ... |
527593c5f183054e330894e6b7161e24cca265a5 | lily/notes/factories.py | lily/notes/factories.py | import random
import factory
from factory.declarations import SubFactory, SelfAttribute, LazyAttribute
from factory.django import DjangoModelFactory
from faker.factory import Factory
from lily.accounts.factories import AccountFactory
from lily.contacts.factories import ContactFactory
from lily.users.factories import LilyUserFactory
from .models import Note
faker = Factory.create('nl_NL')
class NoteFactory(DjangoModelFactory):
content = LazyAttribute(lambda o: faker.text())
author = SubFactory(LilyUserFactory, tenant=SelfAttribute('..tenant'))
@factory.lazy_attribute
def subject(self):
SubjectFactory = random.choice([AccountFactory, ContactFactory])
return SubjectFactory(tenant=self.tenant)
class Meta:
model = Note
| import random
from datetime import datetime
import pytz
import factory
from factory.declarations import SubFactory, SelfAttribute, LazyAttribute
from factory.django import DjangoModelFactory
from faker.factory import Factory
from lily.accounts.factories import AccountFactory
from lily.contacts.factories import ContactFactory
from lily.users.factories import LilyUserFactory
from .models import Note
faker = Factory.create('nl_NL')
class NoteFactory(DjangoModelFactory):
content = LazyAttribute(lambda o: faker.text())
author = SubFactory(LilyUserFactory, tenant=SelfAttribute('..tenant'))
sort_by_date = LazyAttribute(lambda o: datetime.now(tz=pytz.utc))
@factory.lazy_attribute
def subject(self):
SubjectFactory = random.choice([AccountFactory, ContactFactory])
return SubjectFactory(tenant=self.tenant)
class Meta:
model = Note
| Fix so testdata can be loaded when setting up local environment | Fix so testdata can be loaded when setting up local environment
| Python | agpl-3.0 | HelloLily/hellolily,HelloLily/hellolily,HelloLily/hellolily,HelloLily/hellolily | import random
+ from datetime import datetime
+ import pytz
import factory
from factory.declarations import SubFactory, SelfAttribute, LazyAttribute
from factory.django import DjangoModelFactory
from faker.factory import Factory
from lily.accounts.factories import AccountFactory
from lily.contacts.factories import ContactFactory
from lily.users.factories import LilyUserFactory
from .models import Note
faker = Factory.create('nl_NL')
class NoteFactory(DjangoModelFactory):
content = LazyAttribute(lambda o: faker.text())
author = SubFactory(LilyUserFactory, tenant=SelfAttribute('..tenant'))
+ sort_by_date = LazyAttribute(lambda o: datetime.now(tz=pytz.utc))
@factory.lazy_attribute
def subject(self):
SubjectFactory = random.choice([AccountFactory, ContactFactory])
return SubjectFactory(tenant=self.tenant)
class Meta:
model = Note
| Fix so testdata can be loaded when setting up local environment | ## Code Before:
import random
import factory
from factory.declarations import SubFactory, SelfAttribute, LazyAttribute
from factory.django import DjangoModelFactory
from faker.factory import Factory
from lily.accounts.factories import AccountFactory
from lily.contacts.factories import ContactFactory
from lily.users.factories import LilyUserFactory
from .models import Note
faker = Factory.create('nl_NL')
class NoteFactory(DjangoModelFactory):
content = LazyAttribute(lambda o: faker.text())
author = SubFactory(LilyUserFactory, tenant=SelfAttribute('..tenant'))
@factory.lazy_attribute
def subject(self):
SubjectFactory = random.choice([AccountFactory, ContactFactory])
return SubjectFactory(tenant=self.tenant)
class Meta:
model = Note
## Instruction:
Fix so testdata can be loaded when setting up local environment
## Code After:
import random
from datetime import datetime
import pytz
import factory
from factory.declarations import SubFactory, SelfAttribute, LazyAttribute
from factory.django import DjangoModelFactory
from faker.factory import Factory
from lily.accounts.factories import AccountFactory
from lily.contacts.factories import ContactFactory
from lily.users.factories import LilyUserFactory
from .models import Note
faker = Factory.create('nl_NL')
class NoteFactory(DjangoModelFactory):
content = LazyAttribute(lambda o: faker.text())
author = SubFactory(LilyUserFactory, tenant=SelfAttribute('..tenant'))
sort_by_date = LazyAttribute(lambda o: datetime.now(tz=pytz.utc))
@factory.lazy_attribute
def subject(self):
SubjectFactory = random.choice([AccountFactory, ContactFactory])
return SubjectFactory(tenant=self.tenant)
class Meta:
model = Note
| ...
import random
from datetime import datetime
import pytz
import factory
from factory.declarations import SubFactory, SelfAttribute, LazyAttribute
...
content = LazyAttribute(lambda o: faker.text())
author = SubFactory(LilyUserFactory, tenant=SelfAttribute('..tenant'))
sort_by_date = LazyAttribute(lambda o: datetime.now(tz=pytz.utc))
@factory.lazy_attribute
... |
063d88ed5d5f48114cdf566433ae40d40a8674f4 | nbgrader/utils.py | nbgrader/utils.py | import hashlib
import autopep8
def is_grade(cell):
"""Returns True if the cell is a grade cell."""
if 'nbgrader' not in cell.metadata:
return False
return cell.metadata['nbgrader'].get('grade', False)
def is_solution(cell):
"""Returns True if the cell is a solution cell."""
if 'nbgrader' not in cell.metadata:
return False
return cell.metadata['nbgrader'].get('solution', False)
def determine_grade(cell):
if not is_grade(cell):
raise ValueError("cell is not a grade cell")
max_points = float(cell.metadata['nbgrader']['points'])
if cell.cell_type == 'code':
for output in cell.outputs:
if output.output_type == 'error':
return 0, max_points
return max_points, max_points
else:
return None, max_points
def compute_checksum(cell):
m = hashlib.md5()
# fix minor whitespace issues that might have been added and then
# add cell contents
m.update(autopep8.fix_code(cell.source).rstrip())
# include number of points that the cell is worth
if 'points' in cell.metadata.nbgrader:
m.update(cell.metadata.nbgrader['points'])
# include the grade_id
if 'grade_id' in cell.metadata.nbgrader:
m.update(cell.metadata.nbgrader['grade_id'])
return m.hexdigest()
| import hashlib
import autopep8
def is_grade(cell):
"""Returns True if the cell is a grade cell."""
if 'nbgrader' not in cell.metadata:
return False
return cell.metadata['nbgrader'].get('grade', False)
def is_solution(cell):
"""Returns True if the cell is a solution cell."""
if 'nbgrader' not in cell.metadata:
return False
return cell.metadata['nbgrader'].get('solution', False)
def determine_grade(cell):
if not is_grade(cell):
raise ValueError("cell is not a grade cell")
max_points = float(cell.metadata['nbgrader']['points'])
if cell.cell_type == 'code':
for output in cell.outputs:
if output.output_type == 'error':
return 0, max_points
return max_points, max_points
else:
return None, max_points
def compute_checksum(cell):
m = hashlib.md5()
# fix minor whitespace issues that might have been added and then
# add cell contents
m.update(autopep8.fix_code(cell.source).rstrip())
# include number of points that the cell is worth
if 'points' in cell.metadata.nbgrader:
m.update(str(float(cell.metadata.nbgrader['points'])))
# include the grade_id
if 'grade_id' in cell.metadata.nbgrader:
m.update(cell.metadata.nbgrader['grade_id'])
return m.hexdigest()
| Make sure points in checksum are consistent | Make sure points in checksum are consistent
| Python | bsd-3-clause | EdwardJKim/nbgrader,modulexcite/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,jdfreder/nbgrader,dementrock/nbgrader,ellisonbg/nbgrader,ellisonbg/nbgrader,ellisonbg/nbgrader,jhamrick/nbgrader,alope107/nbgrader,dementrock/nbgrader,MatKallada/nbgrader,EdwardJKim/nbgrader,ellisonbg/nbgrader,MatKallada/nbgrader,jdfreder/nbgrader,jupyter/nbgrader,jupyter/nbgrader,EdwardJKim/nbgrader,modulexcite/nbgrader,jupyter/nbgrader,alope107/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,EdwardJKim/nbgrader | import hashlib
import autopep8
def is_grade(cell):
"""Returns True if the cell is a grade cell."""
if 'nbgrader' not in cell.metadata:
return False
return cell.metadata['nbgrader'].get('grade', False)
def is_solution(cell):
"""Returns True if the cell is a solution cell."""
if 'nbgrader' not in cell.metadata:
return False
return cell.metadata['nbgrader'].get('solution', False)
def determine_grade(cell):
if not is_grade(cell):
raise ValueError("cell is not a grade cell")
max_points = float(cell.metadata['nbgrader']['points'])
if cell.cell_type == 'code':
for output in cell.outputs:
if output.output_type == 'error':
return 0, max_points
return max_points, max_points
else:
return None, max_points
def compute_checksum(cell):
m = hashlib.md5()
# fix minor whitespace issues that might have been added and then
# add cell contents
m.update(autopep8.fix_code(cell.source).rstrip())
# include number of points that the cell is worth
if 'points' in cell.metadata.nbgrader:
- m.update(cell.metadata.nbgrader['points'])
+ m.update(str(float(cell.metadata.nbgrader['points'])))
# include the grade_id
if 'grade_id' in cell.metadata.nbgrader:
m.update(cell.metadata.nbgrader['grade_id'])
return m.hexdigest()
| Make sure points in checksum are consistent | ## Code Before:
import hashlib
import autopep8
def is_grade(cell):
"""Returns True if the cell is a grade cell."""
if 'nbgrader' not in cell.metadata:
return False
return cell.metadata['nbgrader'].get('grade', False)
def is_solution(cell):
"""Returns True if the cell is a solution cell."""
if 'nbgrader' not in cell.metadata:
return False
return cell.metadata['nbgrader'].get('solution', False)
def determine_grade(cell):
if not is_grade(cell):
raise ValueError("cell is not a grade cell")
max_points = float(cell.metadata['nbgrader']['points'])
if cell.cell_type == 'code':
for output in cell.outputs:
if output.output_type == 'error':
return 0, max_points
return max_points, max_points
else:
return None, max_points
def compute_checksum(cell):
m = hashlib.md5()
# fix minor whitespace issues that might have been added and then
# add cell contents
m.update(autopep8.fix_code(cell.source).rstrip())
# include number of points that the cell is worth
if 'points' in cell.metadata.nbgrader:
m.update(cell.metadata.nbgrader['points'])
# include the grade_id
if 'grade_id' in cell.metadata.nbgrader:
m.update(cell.metadata.nbgrader['grade_id'])
return m.hexdigest()
## Instruction:
Make sure points in checksum are consistent
## Code After:
import hashlib
import autopep8
def is_grade(cell):
"""Returns True if the cell is a grade cell."""
if 'nbgrader' not in cell.metadata:
return False
return cell.metadata['nbgrader'].get('grade', False)
def is_solution(cell):
"""Returns True if the cell is a solution cell."""
if 'nbgrader' not in cell.metadata:
return False
return cell.metadata['nbgrader'].get('solution', False)
def determine_grade(cell):
if not is_grade(cell):
raise ValueError("cell is not a grade cell")
max_points = float(cell.metadata['nbgrader']['points'])
if cell.cell_type == 'code':
for output in cell.outputs:
if output.output_type == 'error':
return 0, max_points
return max_points, max_points
else:
return None, max_points
def compute_checksum(cell):
m = hashlib.md5()
# fix minor whitespace issues that might have been added and then
# add cell contents
m.update(autopep8.fix_code(cell.source).rstrip())
# include number of points that the cell is worth
if 'points' in cell.metadata.nbgrader:
m.update(str(float(cell.metadata.nbgrader['points'])))
# include the grade_id
if 'grade_id' in cell.metadata.nbgrader:
m.update(cell.metadata.nbgrader['grade_id'])
return m.hexdigest()
| # ... existing code ...
# include number of points that the cell is worth
if 'points' in cell.metadata.nbgrader:
m.update(str(float(cell.metadata.nbgrader['points'])))
# include the grade_id
# ... rest of the code ... |
1ce39741886cdce69e3801a1d0afb25c39a8b844 | fitbit/models.py | fitbit/models.py | from django.contrib.auth.models import User
from django.db import models
class Token(models.Model):
fitbit_id = models.CharField(max_length=50)
refresh_token = models.CharField(max_length=120)
| from django.contrib.auth.models import User
from django.db import models
class Token(models.Model):
fitbit_id = models.CharField(max_length=50)
refresh_token = models.CharField(max_length=120)
def __repr__(self):
return '<Token %s>' % self.fitbit_id
def __str__(self):
return self.fitbit_id
| Add repr and str to our token model | Add repr and str to our token model
| Python | apache-2.0 | Bachmann1234/fitbitSlackBot,Bachmann1234/fitbitSlackBot | from django.contrib.auth.models import User
from django.db import models
class Token(models.Model):
fitbit_id = models.CharField(max_length=50)
refresh_token = models.CharField(max_length=120)
+ def __repr__(self):
+ return '<Token %s>' % self.fitbit_id
+
+ def __str__(self):
+ return self.fitbit_id
+ | Add repr and str to our token model | ## Code Before:
from django.contrib.auth.models import User
from django.db import models
class Token(models.Model):
fitbit_id = models.CharField(max_length=50)
refresh_token = models.CharField(max_length=120)
## Instruction:
Add repr and str to our token model
## Code After:
from django.contrib.auth.models import User
from django.db import models
class Token(models.Model):
fitbit_id = models.CharField(max_length=50)
refresh_token = models.CharField(max_length=120)
def __repr__(self):
return '<Token %s>' % self.fitbit_id
def __str__(self):
return self.fitbit_id
| // ... existing code ...
fitbit_id = models.CharField(max_length=50)
refresh_token = models.CharField(max_length=120)
def __repr__(self):
return '<Token %s>' % self.fitbit_id
def __str__(self):
return self.fitbit_id
// ... rest of the code ... |
857cbff1e8ec6e4db4ac25ad10a41311f3afcd66 | pombola/core/migrations/0049_del_userprofile.py | pombola/core/migrations/0049_del_userprofile.py | import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from django.db.utils import DatabaseError
from django.contrib.contenttypes.models import ContentType
class Migration(SchemaMigration):
def forwards(self, orm):
# Do the deletes in a separate transaction, as database errors when
# deleting a table that does not exist would cause a transaction to be
# rolled back
db.start_transaction()
ContentType.objects.filter(app_label='user_profile').delete()
# Commit the deletes to the various tables.
db.commit_transaction()
try:
db.delete_table('user_profile_userprofile')
except DatabaseError:
# table does not exist to delete, probably because the database was
# not created at a time when the user_profile app was still in use.
pass
def backwards(self, orm):
# There is no backwards - to create the user_profile tables again add the app
# back in and letting its migrations do the work.
pass
models = {}
complete_apps = ['user_profile']
| import datetime
from south.db import db
from south.v2 import SchemaMigration
from south.models import MigrationHistory
from django.db import models
from django.db.utils import DatabaseError
from django.contrib.contenttypes.models import ContentType
class Migration(SchemaMigration):
def forwards(self, orm):
# Do the deletes in a separate transaction, as database errors when
# deleting a table that does not exist would cause a transaction to be
# rolled back
db.start_transaction()
ContentType.objects.filter(app_label='user_profile').delete()
# Remove the entries from South's tables as we don't want to leave
# incorrect entries in there.
MigrationHistory.objects.filter(app_name='user_profile').delete()
# Commit the deletes to the various tables.
db.commit_transaction()
try:
db.delete_table('user_profile_userprofile')
except DatabaseError:
# table does not exist to delete, probably because the database was
# not created at a time when the user_profile app was still in use.
pass
def backwards(self, orm):
# There is no backwards - to create the user_profile tables again add the app
# back in and letting its migrations do the work.
pass
models = {}
complete_apps = ['user_profile']
| Delete entries from the South migration history too | Delete entries from the South migration history too
| Python | agpl-3.0 | mysociety/pombola,mysociety/pombola,patricmutwiri/pombola,hzj123/56th,patricmutwiri/pombola,geoffkilpin/pombola,ken-muturi/pombola,mysociety/pombola,patricmutwiri/pombola,hzj123/56th,geoffkilpin/pombola,hzj123/56th,mysociety/pombola,ken-muturi/pombola,hzj123/56th,mysociety/pombola,patricmutwiri/pombola,ken-muturi/pombola,hzj123/56th,ken-muturi/pombola,patricmutwiri/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,patricmutwiri/pombola,mysociety/pombola,hzj123/56th,geoffkilpin/pombola,ken-muturi/pombola,ken-muturi/pombola | import datetime
from south.db import db
from south.v2 import SchemaMigration
+ from south.models import MigrationHistory
from django.db import models
from django.db.utils import DatabaseError
from django.contrib.contenttypes.models import ContentType
class Migration(SchemaMigration):
def forwards(self, orm):
# Do the deletes in a separate transaction, as database errors when
# deleting a table that does not exist would cause a transaction to be
# rolled back
db.start_transaction()
ContentType.objects.filter(app_label='user_profile').delete()
+
+ # Remove the entries from South's tables as we don't want to leave
+ # incorrect entries in there.
+ MigrationHistory.objects.filter(app_name='user_profile').delete()
# Commit the deletes to the various tables.
db.commit_transaction()
try:
db.delete_table('user_profile_userprofile')
except DatabaseError:
# table does not exist to delete, probably because the database was
# not created at a time when the user_profile app was still in use.
pass
def backwards(self, orm):
# There is no backwards - to create the user_profile tables again add the app
# back in and letting its migrations do the work.
pass
models = {}
complete_apps = ['user_profile']
| Delete entries from the South migration history too | ## Code Before:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from django.db.utils import DatabaseError
from django.contrib.contenttypes.models import ContentType
class Migration(SchemaMigration):
def forwards(self, orm):
# Do the deletes in a separate transaction, as database errors when
# deleting a table that does not exist would cause a transaction to be
# rolled back
db.start_transaction()
ContentType.objects.filter(app_label='user_profile').delete()
# Commit the deletes to the various tables.
db.commit_transaction()
try:
db.delete_table('user_profile_userprofile')
except DatabaseError:
# table does not exist to delete, probably because the database was
# not created at a time when the user_profile app was still in use.
pass
def backwards(self, orm):
# There is no backwards - to create the user_profile tables again add the app
# back in and letting its migrations do the work.
pass
models = {}
complete_apps = ['user_profile']
## Instruction:
Delete entries from the South migration history too
## Code After:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from south.models import MigrationHistory
from django.db import models
from django.db.utils import DatabaseError
from django.contrib.contenttypes.models import ContentType
class Migration(SchemaMigration):
def forwards(self, orm):
# Do the deletes in a separate transaction, as database errors when
# deleting a table that does not exist would cause a transaction to be
# rolled back
db.start_transaction()
ContentType.objects.filter(app_label='user_profile').delete()
# Remove the entries from South's tables as we don't want to leave
# incorrect entries in there.
MigrationHistory.objects.filter(app_name='user_profile').delete()
# Commit the deletes to the various tables.
db.commit_transaction()
try:
db.delete_table('user_profile_userprofile')
except DatabaseError:
# table does not exist to delete, probably because the database was
# not created at a time when the user_profile app was still in use.
pass
def backwards(self, orm):
# There is no backwards - to create the user_profile tables again add the app
# back in and letting its migrations do the work.
pass
models = {}
complete_apps = ['user_profile']
| // ... existing code ...
from south.db import db
from south.v2 import SchemaMigration
from south.models import MigrationHistory
from django.db import models
from django.db.utils import DatabaseError
// ... modified code ...
ContentType.objects.filter(app_label='user_profile').delete()
# Remove the entries from South's tables as we don't want to leave
# incorrect entries in there.
MigrationHistory.objects.filter(app_name='user_profile').delete()
# Commit the deletes to the various tables.
// ... rest of the code ... |
9a64f7b08704f2f343564698d83dd73bb1f0d4b2 | slackbot_settings.py | slackbot_settings.py | DEFAULT_REPLY = "Sorry, I did not understand you."
ERRORS_TO = 'general'
PLUGINS = [
'plugins.witai'
]
| DEFAULT_REPLY = "Sorry, I did not understand you."
PLUGINS = [
'plugins.witai'
]
| Remove sending error to general channel | Remove sending error to general channel
| Python | mit | sanjaybv/netbot | DEFAULT_REPLY = "Sorry, I did not understand you."
- ERRORS_TO = 'general'
PLUGINS = [
'plugins.witai'
]
| Remove sending error to general channel | ## Code Before:
DEFAULT_REPLY = "Sorry, I did not understand you."
ERRORS_TO = 'general'
PLUGINS = [
'plugins.witai'
]
## Instruction:
Remove sending error to general channel
## Code After:
DEFAULT_REPLY = "Sorry, I did not understand you."
PLUGINS = [
'plugins.witai'
]
| # ... existing code ...
DEFAULT_REPLY = "Sorry, I did not understand you."
PLUGINS = [
# ... rest of the code ... |
3075a10c56fb38611134aa15c06b6da8cc777868 | enthought/pyface/tasks/task_window_layout.py | enthought/pyface/tasks/task_window_layout.py | from enthought.traits.api import Dict, HasStrictTraits, Instance, List, Str, \
Tuple
# Local imports.
from task_layout import TaskLayout
class TaskWindowLayout(HasStrictTraits):
""" A picklable object that describes the layout and state of a TaskWindow.
"""
# The ID of the active task. If unspecified, the first task will be active.
active_task = Str
# The IDs of all the tasks attached to the window.
tasks = List(Str)
# The position of the window.
position = Tuple(-1, -1)
# The size of the window.
size = Tuple(800, 600)
# A map from task IDs to their respective layouts. Set by the framework.
layout_state = Dict(Str, Instance(TaskLayout))
| from enthought.traits.api import Dict, HasStrictTraits, Instance, List, Str, \
Tuple
# Local imports.
from task_layout import TaskLayout
class TaskWindowLayout(HasStrictTraits):
""" A picklable object that describes the layout and state of a TaskWindow.
"""
# The ID of the active task. If unspecified, the first task will be active.
active_task = Str
# The IDs of all the tasks attached to the window.
tasks = List(Str)
# The position of the window.
position = Tuple(-1, -1)
# The size of the window.
size = Tuple(800, 600)
# A map from task IDs to their respective layouts. Set by the framework.
layout_state = Dict(Str, Instance(TaskLayout))
def get_active_task(self):
""" Returns the ID of the active task in the layout, or None if there is
no active task.
"""
if self.active_task:
return self.active_task
elif self.tasks:
return self.tasks[0]
return None
def is_equivalent_to(self, layout):
""" Returns whether two layouts are equivalent, i.e. whether they
contain the same tasks.
"""
return isinstance(layout, TaskWindowLayout) and \
self.get_active_task() == layout.get_active_task() and \
self.tasks == layout.tasks
| Add a few useful utility methods to TaskWindowLayout. | Add a few useful utility methods to TaskWindowLayout.
| Python | bsd-3-clause | brett-patterson/pyface,pankajp/pyface,geggo/pyface,geggo/pyface,enthought/traitsgui | from enthought.traits.api import Dict, HasStrictTraits, Instance, List, Str, \
Tuple
# Local imports.
from task_layout import TaskLayout
class TaskWindowLayout(HasStrictTraits):
""" A picklable object that describes the layout and state of a TaskWindow.
"""
# The ID of the active task. If unspecified, the first task will be active.
active_task = Str
# The IDs of all the tasks attached to the window.
tasks = List(Str)
# The position of the window.
position = Tuple(-1, -1)
# The size of the window.
size = Tuple(800, 600)
# A map from task IDs to their respective layouts. Set by the framework.
layout_state = Dict(Str, Instance(TaskLayout))
+ def get_active_task(self):
+ """ Returns the ID of the active task in the layout, or None if there is
+ no active task.
+ """
+ if self.active_task:
+ return self.active_task
+ elif self.tasks:
+ return self.tasks[0]
+ return None
+
+ def is_equivalent_to(self, layout):
+ """ Returns whether two layouts are equivalent, i.e. whether they
+ contain the same tasks.
+ """
+ return isinstance(layout, TaskWindowLayout) and \
+ self.get_active_task() == layout.get_active_task() and \
+ self.tasks == layout.tasks
+ | Add a few useful utility methods to TaskWindowLayout. | ## Code Before:
from enthought.traits.api import Dict, HasStrictTraits, Instance, List, Str, \
Tuple
# Local imports.
from task_layout import TaskLayout
class TaskWindowLayout(HasStrictTraits):
""" A picklable object that describes the layout and state of a TaskWindow.
"""
# The ID of the active task. If unspecified, the first task will be active.
active_task = Str
# The IDs of all the tasks attached to the window.
tasks = List(Str)
# The position of the window.
position = Tuple(-1, -1)
# The size of the window.
size = Tuple(800, 600)
# A map from task IDs to their respective layouts. Set by the framework.
layout_state = Dict(Str, Instance(TaskLayout))
## Instruction:
Add a few useful utility methods to TaskWindowLayout.
## Code After:
from enthought.traits.api import Dict, HasStrictTraits, Instance, List, Str, \
Tuple
# Local imports.
from task_layout import TaskLayout
class TaskWindowLayout(HasStrictTraits):
""" A picklable object that describes the layout and state of a TaskWindow.
"""
# The ID of the active task. If unspecified, the first task will be active.
active_task = Str
# The IDs of all the tasks attached to the window.
tasks = List(Str)
# The position of the window.
position = Tuple(-1, -1)
# The size of the window.
size = Tuple(800, 600)
# A map from task IDs to their respective layouts. Set by the framework.
layout_state = Dict(Str, Instance(TaskLayout))
def get_active_task(self):
""" Returns the ID of the active task in the layout, or None if there is
no active task.
"""
if self.active_task:
return self.active_task
elif self.tasks:
return self.tasks[0]
return None
def is_equivalent_to(self, layout):
""" Returns whether two layouts are equivalent, i.e. whether they
contain the same tasks.
"""
return isinstance(layout, TaskWindowLayout) and \
self.get_active_task() == layout.get_active_task() and \
self.tasks == layout.tasks
| // ... existing code ...
# A map from task IDs to their respective layouts. Set by the framework.
layout_state = Dict(Str, Instance(TaskLayout))
def get_active_task(self):
""" Returns the ID of the active task in the layout, or None if there is
no active task.
"""
if self.active_task:
return self.active_task
elif self.tasks:
return self.tasks[0]
return None
def is_equivalent_to(self, layout):
""" Returns whether two layouts are equivalent, i.e. whether they
contain the same tasks.
"""
return isinstance(layout, TaskWindowLayout) and \
self.get_active_task() == layout.get_active_task() and \
self.tasks == layout.tasks
// ... rest of the code ... |
c79d040cb952e8e37c231caf90eda92d152978b8 | openfisca_country_template/__init__.py | openfisca_country_template/__init__.py |
import os
from openfisca_core.taxbenefitsystems import TaxBenefitSystem
from . import entities
COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__))
# Our country tax and benefit class inherits from the general TaxBenefitSystem class.
# The name CountryTaxBenefitSystem must not be changed, as all tools of the OpenFisca ecosystem expect a CountryTaxBenefitSystem class to be exposed in the __init__ module of a country package.
class CountryTaxBenefitSystem(TaxBenefitSystem):
def __init__(self):
# We initialize our tax and benefit system with the general constructor
super(CountryTaxBenefitSystem, self).__init__(entities.entities)
# We add to our tax and benefit system all the variables
self.add_variables_from_directory(os.path.join(COUNTRY_DIR, 'variables'))
# We add to our tax and benefit system all the legislation parameters defined in the parameters files
param_files = [
'__root__.xml',
'benefits.xml',
'general.xml',
'taxes.xml',
]
for param_file in param_files:
param_path = os.path.join(COUNTRY_DIR, 'parameters', param_file)
self.add_legislation_params(param_path)
|
import os
from openfisca_core.taxbenefitsystems import TaxBenefitSystem
from . import entities
COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__))
# Our country tax and benefit class inherits from the general TaxBenefitSystem class.
# The name CountryTaxBenefitSystem must not be changed, as all tools of the OpenFisca ecosystem expect a CountryTaxBenefitSystem class to be exposed in the __init__ module of a country package.
class CountryTaxBenefitSystem(TaxBenefitSystem):
def __init__(self):
# We initialize our tax and benefit system with the general constructor
super(CountryTaxBenefitSystem, self).__init__(entities.entities)
# We add to our tax and benefit system all the variables
self.add_variables_from_directory(os.path.join(COUNTRY_DIR, 'variables'))
# We add to our tax and benefit system all the legislation parameters defined in the parameters files
param_path = os.path.join(COUNTRY_DIR, 'parameters')
self.add_legislation_params(param_path)
| Use YAML params instead of XML params | Use YAML params instead of XML params
| Python | agpl-3.0 | openfisca/country-template,openfisca/country-template |
import os
from openfisca_core.taxbenefitsystems import TaxBenefitSystem
from . import entities
COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__))
# Our country tax and benefit class inherits from the general TaxBenefitSystem class.
# The name CountryTaxBenefitSystem must not be changed, as all tools of the OpenFisca ecosystem expect a CountryTaxBenefitSystem class to be exposed in the __init__ module of a country package.
class CountryTaxBenefitSystem(TaxBenefitSystem):
def __init__(self):
# We initialize our tax and benefit system with the general constructor
super(CountryTaxBenefitSystem, self).__init__(entities.entities)
# We add to our tax and benefit system all the variables
self.add_variables_from_directory(os.path.join(COUNTRY_DIR, 'variables'))
# We add to our tax and benefit system all the legislation parameters defined in the parameters files
+ param_path = os.path.join(COUNTRY_DIR, 'parameters')
+ self.add_legislation_params(param_path)
- param_files = [
- '__root__.xml',
- 'benefits.xml',
- 'general.xml',
- 'taxes.xml',
- ]
- for param_file in param_files:
- param_path = os.path.join(COUNTRY_DIR, 'parameters', param_file)
- self.add_legislation_params(param_path)
- | Use YAML params instead of XML params | ## Code Before:
import os
from openfisca_core.taxbenefitsystems import TaxBenefitSystem
from . import entities
COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__))
# Our country tax and benefit class inherits from the general TaxBenefitSystem class.
# The name CountryTaxBenefitSystem must not be changed, as all tools of the OpenFisca ecosystem expect a CountryTaxBenefitSystem class to be exposed in the __init__ module of a country package.
class CountryTaxBenefitSystem(TaxBenefitSystem):
def __init__(self):
# We initialize our tax and benefit system with the general constructor
super(CountryTaxBenefitSystem, self).__init__(entities.entities)
# We add to our tax and benefit system all the variables
self.add_variables_from_directory(os.path.join(COUNTRY_DIR, 'variables'))
# We add to our tax and benefit system all the legislation parameters defined in the parameters files
param_files = [
'__root__.xml',
'benefits.xml',
'general.xml',
'taxes.xml',
]
for param_file in param_files:
param_path = os.path.join(COUNTRY_DIR, 'parameters', param_file)
self.add_legislation_params(param_path)
## Instruction:
Use YAML params instead of XML params
## Code After:
import os
from openfisca_core.taxbenefitsystems import TaxBenefitSystem
from . import entities
COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__))
# Our country tax and benefit class inherits from the general TaxBenefitSystem class.
# The name CountryTaxBenefitSystem must not be changed, as all tools of the OpenFisca ecosystem expect a CountryTaxBenefitSystem class to be exposed in the __init__ module of a country package.
class CountryTaxBenefitSystem(TaxBenefitSystem):
def __init__(self):
# We initialize our tax and benefit system with the general constructor
super(CountryTaxBenefitSystem, self).__init__(entities.entities)
# We add to our tax and benefit system all the variables
self.add_variables_from_directory(os.path.join(COUNTRY_DIR, 'variables'))
# We add to our tax and benefit system all the legislation parameters defined in the parameters files
param_path = os.path.join(COUNTRY_DIR, 'parameters')
self.add_legislation_params(param_path)
| # ... existing code ...
# We add to our tax and benefit system all the legislation parameters defined in the parameters files
param_path = os.path.join(COUNTRY_DIR, 'parameters')
self.add_legislation_params(param_path)
# ... rest of the code ... |
6377a1a50293c2b62eb5e29c936998ad09995c7a | service/inchi.py | service/inchi.py | import requests
import json
from subprocess import Popen, PIPE
import tempfile
import os
import sys
config = {}
with open ('../config/conversion.json') as fp:
config = json.load(fp)
def to_cml(inchi):
request = requests.get('%s/service/chemical/cjson/?q=inchi~eq~%s' % (config['baseUrl'], inchi))
if request.status_code == 200:
cjson = request.json();
else:
print >> sys.stderr, "Unable to access REST API: %s" % request.status_code
return None
# Call convertion routine
p = Popen([config['cjsonToCmlPath']], stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(json.dumps(cjson['results'][0]))
fd, path = tempfile.mkstemp(suffix='.cml')
with open(path, 'w') as fp:
fp.write(str(stdout))
os.close(fd)
return path
| import requests
import json
from subprocess import Popen, PIPE
import tempfile
import os
import sys
config = {}
with open ('../config/conversion.json') as fp:
config = json.load(fp)
def to_cml(inchi):
request_url = '%s/service/chemical/cjson?q=inchi~eq~%s' % (config['baseUrl'], inchi)
request = requests.get(request_url)
if request.status_code == 200:
cjson = request.json();
else:
print >> sys.stderr, "Unable to access REST API at %s: %s" % (request_url, request.status_code)
return None
# Call convertion routine
p = Popen([config['cjsonToCmlPath']], stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(json.dumps(cjson['results'][0]))
fd, path = tempfile.mkstemp(suffix='.cml')
with open(path, 'w') as fp:
fp.write(str(stdout))
os.close(fd)
return path
| Fix URL for fetch CJSON | Fix URL for fetch CJSON
| Python | bsd-3-clause | OpenChemistry/mongochemweb,OpenChemistry/mongochemweb | import requests
import json
from subprocess import Popen, PIPE
import tempfile
import os
import sys
config = {}
with open ('../config/conversion.json') as fp:
config = json.load(fp)
def to_cml(inchi):
- request = requests.get('%s/service/chemical/cjson/?q=inchi~eq~%s' % (config['baseUrl'], inchi))
+ request_url = '%s/service/chemical/cjson?q=inchi~eq~%s' % (config['baseUrl'], inchi)
+ request = requests.get(request_url)
if request.status_code == 200:
cjson = request.json();
else:
- print >> sys.stderr, "Unable to access REST API: %s" % request.status_code
+ print >> sys.stderr, "Unable to access REST API at %s: %s" % (request_url, request.status_code)
return None
# Call convertion routine
p = Popen([config['cjsonToCmlPath']], stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(json.dumps(cjson['results'][0]))
fd, path = tempfile.mkstemp(suffix='.cml')
with open(path, 'w') as fp:
fp.write(str(stdout))
os.close(fd)
return path
| Fix URL for fetch CJSON | ## Code Before:
import requests
import json
from subprocess import Popen, PIPE
import tempfile
import os
import sys
config = {}
with open ('../config/conversion.json') as fp:
config = json.load(fp)
def to_cml(inchi):
request = requests.get('%s/service/chemical/cjson/?q=inchi~eq~%s' % (config['baseUrl'], inchi))
if request.status_code == 200:
cjson = request.json();
else:
print >> sys.stderr, "Unable to access REST API: %s" % request.status_code
return None
# Call convertion routine
p = Popen([config['cjsonToCmlPath']], stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(json.dumps(cjson['results'][0]))
fd, path = tempfile.mkstemp(suffix='.cml')
with open(path, 'w') as fp:
fp.write(str(stdout))
os.close(fd)
return path
## Instruction:
Fix URL for fetch CJSON
## Code After:
import requests
import json
from subprocess import Popen, PIPE
import tempfile
import os
import sys
config = {}
with open ('../config/conversion.json') as fp:
config = json.load(fp)
def to_cml(inchi):
request_url = '%s/service/chemical/cjson?q=inchi~eq~%s' % (config['baseUrl'], inchi)
request = requests.get(request_url)
if request.status_code == 200:
cjson = request.json();
else:
print >> sys.stderr, "Unable to access REST API at %s: %s" % (request_url, request.status_code)
return None
# Call convertion routine
p = Popen([config['cjsonToCmlPath']], stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(json.dumps(cjson['results'][0]))
fd, path = tempfile.mkstemp(suffix='.cml')
with open(path, 'w') as fp:
fp.write(str(stdout))
os.close(fd)
return path
| # ... existing code ...
def to_cml(inchi):
request_url = '%s/service/chemical/cjson?q=inchi~eq~%s' % (config['baseUrl'], inchi)
request = requests.get(request_url)
if request.status_code == 200:
# ... modified code ...
cjson = request.json();
else:
print >> sys.stderr, "Unable to access REST API at %s: %s" % (request_url, request.status_code)
return None
# ... rest of the code ... |
25054586406024e082f9836884d5198ffa669f5b | models/ras_220_genes/build_ras_gene_network.py | models/ras_220_genes/build_ras_gene_network.py | from indra.tools.gene_network import GeneNetwork, grounding_filter
import csv
# STEP 0: Get gene list
gene_list = []
# Get gene list from ras_pathway_proteins.csv
with open('../../data/ras_pathway_proteins.csv') as f:
csvreader = csv.reader(f, delimiter='\t')
for row in csvreader:
gene_list.append(row[0].strip())
gn = GeneNetwork(gene_list, 'ras_genes')
stmts = gn.get_statements(filter=True)
grounded_stmts = grounding_filter(stmts)
results = gn.run_preassembly(grounded_stmts)
| from indra.tools.gene_network import GeneNetwork, grounding_filter
import csv
import pickle
# STEP 0: Get gene list
gene_list = []
# Get gene list from ras_pathway_proteins.csv
with open('../../data/ras_pathway_proteins.csv') as f:
csvreader = csv.reader(f, delimiter='\t')
for row in csvreader:
gene_list.append(row[0].strip())
gn = GeneNetwork(gene_list, 'ras_genes')
stmts = gn.get_statements(filter=True)
grounded_stmts = grounding_filter(stmts)
results = gn.run_preassembly(grounded_stmts)
with open('ras_220_gn_stmts.pkl', 'wb') as f:
pickle.dump(results, f)
| Save the results of ras network | Save the results of ras network
| Python | bsd-2-clause | bgyori/indra,sorgerlab/belpy,johnbachman/indra,johnbachman/belpy,johnbachman/belpy,sorgerlab/indra,johnbachman/belpy,pvtodorov/indra,jmuhlich/indra,bgyori/indra,sorgerlab/indra,pvtodorov/indra,johnbachman/indra,sorgerlab/belpy,sorgerlab/belpy,jmuhlich/indra,bgyori/indra,sorgerlab/indra,pvtodorov/indra,jmuhlich/indra,pvtodorov/indra,johnbachman/indra | from indra.tools.gene_network import GeneNetwork, grounding_filter
import csv
+ import pickle
# STEP 0: Get gene list
gene_list = []
# Get gene list from ras_pathway_proteins.csv
with open('../../data/ras_pathway_proteins.csv') as f:
csvreader = csv.reader(f, delimiter='\t')
for row in csvreader:
gene_list.append(row[0].strip())
gn = GeneNetwork(gene_list, 'ras_genes')
stmts = gn.get_statements(filter=True)
grounded_stmts = grounding_filter(stmts)
results = gn.run_preassembly(grounded_stmts)
+ with open('ras_220_gn_stmts.pkl', 'wb') as f:
+ pickle.dump(results, f)
| Save the results of ras network | ## Code Before:
from indra.tools.gene_network import GeneNetwork, grounding_filter
import csv
# STEP 0: Get gene list
gene_list = []
# Get gene list from ras_pathway_proteins.csv
with open('../../data/ras_pathway_proteins.csv') as f:
csvreader = csv.reader(f, delimiter='\t')
for row in csvreader:
gene_list.append(row[0].strip())
gn = GeneNetwork(gene_list, 'ras_genes')
stmts = gn.get_statements(filter=True)
grounded_stmts = grounding_filter(stmts)
results = gn.run_preassembly(grounded_stmts)
## Instruction:
Save the results of ras network
## Code After:
from indra.tools.gene_network import GeneNetwork, grounding_filter
import csv
import pickle
# STEP 0: Get gene list
gene_list = []
# Get gene list from ras_pathway_proteins.csv
with open('../../data/ras_pathway_proteins.csv') as f:
csvreader = csv.reader(f, delimiter='\t')
for row in csvreader:
gene_list.append(row[0].strip())
gn = GeneNetwork(gene_list, 'ras_genes')
stmts = gn.get_statements(filter=True)
grounded_stmts = grounding_filter(stmts)
results = gn.run_preassembly(grounded_stmts)
with open('ras_220_gn_stmts.pkl', 'wb') as f:
pickle.dump(results, f)
| ...
from indra.tools.gene_network import GeneNetwork, grounding_filter
import csv
import pickle
# STEP 0: Get gene list
...
grounded_stmts = grounding_filter(stmts)
results = gn.run_preassembly(grounded_stmts)
with open('ras_220_gn_stmts.pkl', 'wb') as f:
pickle.dump(results, f)
... |
452924faafcfb4dcb1eb960ea30ab000f1f93962 | migrations/versions/0245_archived_flag_jobs.py | migrations/versions/0245_archived_flag_jobs.py | from alembic import op
import sqlalchemy as sa
revision = '0245_archived_flag_jobs'
down_revision = '0244_another_letter_org'
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('jobs', sa.Column('archived', sa.Boolean(), nullable=False, server_default=sa.false()))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('jobs', 'archived')
# ### end Alembic commands ###
| from alembic import op
import sqlalchemy as sa
revision = '0245_archived_flag_jobs'
down_revision = '0244_another_letter_org'
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('jobs', sa.Column('archived', sa.Boolean(), nullable=True))
op.execute('update jobs set archived = false')
op.alter_column('jobs', 'archived', nullable=False, server_default=sa.false())
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('jobs', 'archived')
# ### end Alembic commands ###
| Update jobs archived flag before setting the default value | Update jobs archived flag before setting the default value
Running an update before setting the column default value reduces
the time the table is locked (since most rows don't have a NULL
value anymore), but the migration takes slightly longer to run
overall.
| Python | mit | alphagov/notifications-api,alphagov/notifications-api | from alembic import op
import sqlalchemy as sa
revision = '0245_archived_flag_jobs'
down_revision = '0244_another_letter_org'
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
+ op.add_column('jobs', sa.Column('archived', sa.Boolean(), nullable=True))
+ op.execute('update jobs set archived = false')
- op.add_column('jobs', sa.Column('archived', sa.Boolean(), nullable=False, server_default=sa.false()))
+ op.alter_column('jobs', 'archived', nullable=False, server_default=sa.false())
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('jobs', 'archived')
# ### end Alembic commands ###
| Update jobs archived flag before setting the default value | ## Code Before:
from alembic import op
import sqlalchemy as sa
revision = '0245_archived_flag_jobs'
down_revision = '0244_another_letter_org'
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('jobs', sa.Column('archived', sa.Boolean(), nullable=False, server_default=sa.false()))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('jobs', 'archived')
# ### end Alembic commands ###
## Instruction:
Update jobs archived flag before setting the default value
## Code After:
from alembic import op
import sqlalchemy as sa
revision = '0245_archived_flag_jobs'
down_revision = '0244_another_letter_org'
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('jobs', sa.Column('archived', sa.Boolean(), nullable=True))
op.execute('update jobs set archived = false')
op.alter_column('jobs', 'archived', nullable=False, server_default=sa.false())
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('jobs', 'archived')
# ### end Alembic commands ###
| # ... existing code ...
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('jobs', sa.Column('archived', sa.Boolean(), nullable=True))
op.execute('update jobs set archived = false')
op.alter_column('jobs', 'archived', nullable=False, server_default=sa.false())
# ### end Alembic commands ###
# ... rest of the code ... |
d0b2b0aa3674fb6b85fd788e88a3a54f4cc22046 | pytablewriter/_excel_workbook.py | pytablewriter/_excel_workbook.py |
from __future__ import absolute_import
import xlsxwriter
class ExcelWorkbookXlsx(object):
@property
def workbook(self):
return self.__workbook
@property
def file_path(self):
return self.__file_path
def __init__(self, file_path):
self.open(file_path)
def __del__(self):
self.close()
def open(self, file_path):
self.__file_path = file_path
self.__workbook = xlsxwriter.Workbook(file_path)
def close(self):
if self.workbook is None:
return
self.__workbook.close()
self.__clear()
def add_worksheet(self, worksheet_name):
worksheet = self.__workbook.add_worksheet(worksheet_name)
return worksheet
def __clear(self):
self.__workbook = None
self.__file_path = None
|
from __future__ import absolute_import
import abc
import six
import xlsxwriter
@six.add_metaclass(abc.ABCMeta)
class ExcelWorkbookInterface(object):
@abc.abstractproperty
def workbook(self):
pass
@abc.abstractproperty
def file_path(self):
pass
@abc.abstractmethod
def open(self, file_path):
pass
@abc.abstractmethod
def close(self):
pass
class ExcelWorkbook(ExcelWorkbookInterface):
@property
def workbook(self):
return self._workbook
@property
def file_path(self):
return self._file_path
def _clear(self):
self._workbook = None
self._file_path = None
class ExcelWorkbookXlsx(ExcelWorkbook):
def __init__(self, file_path):
self.open(file_path)
def __del__(self):
self.close()
def open(self, file_path):
self._file_path = file_path
self._workbook = xlsxwriter.Workbook(file_path)
def close(self):
if self.workbook is None:
return
self._workbook.close()
self._clear()
def add_worksheet(self, worksheet_name):
worksheet = self.workbook.add_worksheet(worksheet_name)
return worksheet
| Add an interface class and a base class of for Excel Workbook | Add an interface class and a base class of for Excel Workbook
| Python | mit | thombashi/pytablewriter |
from __future__ import absolute_import
+ import abc
+ import six
import xlsxwriter
+ @six.add_metaclass(abc.ABCMeta)
- class ExcelWorkbookXlsx(object):
+ class ExcelWorkbookInterface(object):
+
+ @abc.abstractproperty
+ def workbook(self):
+ pass
+
+ @abc.abstractproperty
+ def file_path(self):
+ pass
+
+ @abc.abstractmethod
+ def open(self, file_path):
+ pass
+
+ @abc.abstractmethod
+ def close(self):
+ pass
+
+
+ class ExcelWorkbook(ExcelWorkbookInterface):
@property
def workbook(self):
- return self.__workbook
+ return self._workbook
@property
def file_path(self):
- return self.__file_path
+ return self._file_path
+
+ def _clear(self):
+ self._workbook = None
+ self._file_path = None
+
+
+ class ExcelWorkbookXlsx(ExcelWorkbook):
def __init__(self, file_path):
self.open(file_path)
def __del__(self):
self.close()
def open(self, file_path):
- self.__file_path = file_path
+ self._file_path = file_path
- self.__workbook = xlsxwriter.Workbook(file_path)
+ self._workbook = xlsxwriter.Workbook(file_path)
def close(self):
if self.workbook is None:
return
- self.__workbook.close()
+ self._workbook.close()
- self.__clear()
+ self._clear()
def add_worksheet(self, worksheet_name):
- worksheet = self.__workbook.add_worksheet(worksheet_name)
+ worksheet = self.workbook.add_worksheet(worksheet_name)
return worksheet
- def __clear(self):
- self.__workbook = None
- self.__file_path = None
- | Add an interface class and a base class of for Excel Workbook | ## Code Before:
from __future__ import absolute_import
import xlsxwriter
class ExcelWorkbookXlsx(object):
@property
def workbook(self):
return self.__workbook
@property
def file_path(self):
return self.__file_path
def __init__(self, file_path):
self.open(file_path)
def __del__(self):
self.close()
def open(self, file_path):
self.__file_path = file_path
self.__workbook = xlsxwriter.Workbook(file_path)
def close(self):
if self.workbook is None:
return
self.__workbook.close()
self.__clear()
def add_worksheet(self, worksheet_name):
worksheet = self.__workbook.add_worksheet(worksheet_name)
return worksheet
def __clear(self):
self.__workbook = None
self.__file_path = None
## Instruction:
Add an interface class and a base class of for Excel Workbook
## Code After:
from __future__ import absolute_import
import abc
import six
import xlsxwriter
@six.add_metaclass(abc.ABCMeta)
class ExcelWorkbookInterface(object):
@abc.abstractproperty
def workbook(self):
pass
@abc.abstractproperty
def file_path(self):
pass
@abc.abstractmethod
def open(self, file_path):
pass
@abc.abstractmethod
def close(self):
pass
class ExcelWorkbook(ExcelWorkbookInterface):
@property
def workbook(self):
return self._workbook
@property
def file_path(self):
return self._file_path
def _clear(self):
self._workbook = None
self._file_path = None
class ExcelWorkbookXlsx(ExcelWorkbook):
def __init__(self, file_path):
self.open(file_path)
def __del__(self):
self.close()
def open(self, file_path):
self._file_path = file_path
self._workbook = xlsxwriter.Workbook(file_path)
def close(self):
if self.workbook is None:
return
self._workbook.close()
self._clear()
def add_worksheet(self, worksheet_name):
worksheet = self.workbook.add_worksheet(worksheet_name)
return worksheet
| ...
from __future__ import absolute_import
import abc
import six
import xlsxwriter
@six.add_metaclass(abc.ABCMeta)
class ExcelWorkbookInterface(object):
@abc.abstractproperty
def workbook(self):
pass
@abc.abstractproperty
def file_path(self):
pass
@abc.abstractmethod
def open(self, file_path):
pass
@abc.abstractmethod
def close(self):
pass
class ExcelWorkbook(ExcelWorkbookInterface):
@property
def workbook(self):
return self._workbook
@property
def file_path(self):
return self._file_path
def _clear(self):
self._workbook = None
self._file_path = None
class ExcelWorkbookXlsx(ExcelWorkbook):
def __init__(self, file_path):
...
def open(self, file_path):
self._file_path = file_path
self._workbook = xlsxwriter.Workbook(file_path)
def close(self):
...
return
self._workbook.close()
self._clear()
def add_worksheet(self, worksheet_name):
worksheet = self.workbook.add_worksheet(worksheet_name)
return worksheet
... |
a3b119e14df4aff213231492470587f88457a241 | setuptools/command/upload.py | setuptools/command/upload.py | import getpass
from distutils.command import upload as orig
class upload(orig.upload):
"""
Override default upload behavior to obtain password
in a variety of different ways.
"""
def finalize_options(self):
orig.upload.finalize_options(self)
# Attempt to obtain password. Short circuit evaluation at the first
# sign of success.
self.password = (
self.password or self._load_password_from_keyring() or
self._prompt_for_password()
)
def _load_password_from_keyring(self):
"""
Attempt to load password from keyring. Suppress Exceptions.
"""
try:
keyring = __import__('keyring')
password = keyring.get_password(self.repository, self.username)
except Exception:
password = None
finally:
return password
def _prompt_for_password(self):
"""
Prompt for a password on the tty. Suppress Exceptions.
"""
password = None
try:
while not password:
password = getpass.getpass()
except (Exception, KeyboardInterrupt):
password = None
finally:
return password
| import getpass
from distutils.command import upload as orig
class upload(orig.upload):
"""
Override default upload behavior to obtain password
in a variety of different ways.
"""
def finalize_options(self):
orig.upload.finalize_options(self)
# Attempt to obtain password. Short circuit evaluation at the first
# sign of success.
self.password = (
self.password or
self._load_password_from_keyring() or
self._prompt_for_password()
)
def _load_password_from_keyring(self):
"""
Attempt to load password from keyring. Suppress Exceptions.
"""
try:
keyring = __import__('keyring')
password = keyring.get_password(self.repository, self.username)
except Exception:
password = None
finally:
return password
def _prompt_for_password(self):
"""
Prompt for a password on the tty. Suppress Exceptions.
"""
password = None
try:
while not password:
password = getpass.getpass()
except (Exception, KeyboardInterrupt):
password = None
finally:
return password
| Add carriage return for symmetry | Add carriage return for symmetry
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools | import getpass
from distutils.command import upload as orig
class upload(orig.upload):
"""
Override default upload behavior to obtain password
in a variety of different ways.
"""
def finalize_options(self):
orig.upload.finalize_options(self)
# Attempt to obtain password. Short circuit evaluation at the first
# sign of success.
self.password = (
+ self.password or
- self.password or self._load_password_from_keyring() or
+ self._load_password_from_keyring() or
self._prompt_for_password()
)
def _load_password_from_keyring(self):
"""
Attempt to load password from keyring. Suppress Exceptions.
"""
try:
keyring = __import__('keyring')
password = keyring.get_password(self.repository, self.username)
except Exception:
password = None
finally:
return password
def _prompt_for_password(self):
"""
Prompt for a password on the tty. Suppress Exceptions.
"""
password = None
try:
while not password:
password = getpass.getpass()
except (Exception, KeyboardInterrupt):
password = None
finally:
return password
| Add carriage return for symmetry | ## Code Before:
import getpass
from distutils.command import upload as orig
class upload(orig.upload):
"""
Override default upload behavior to obtain password
in a variety of different ways.
"""
def finalize_options(self):
orig.upload.finalize_options(self)
# Attempt to obtain password. Short circuit evaluation at the first
# sign of success.
self.password = (
self.password or self._load_password_from_keyring() or
self._prompt_for_password()
)
def _load_password_from_keyring(self):
"""
Attempt to load password from keyring. Suppress Exceptions.
"""
try:
keyring = __import__('keyring')
password = keyring.get_password(self.repository, self.username)
except Exception:
password = None
finally:
return password
def _prompt_for_password(self):
"""
Prompt for a password on the tty. Suppress Exceptions.
"""
password = None
try:
while not password:
password = getpass.getpass()
except (Exception, KeyboardInterrupt):
password = None
finally:
return password
## Instruction:
Add carriage return for symmetry
## Code After:
import getpass
from distutils.command import upload as orig
class upload(orig.upload):
"""
Override default upload behavior to obtain password
in a variety of different ways.
"""
def finalize_options(self):
orig.upload.finalize_options(self)
# Attempt to obtain password. Short circuit evaluation at the first
# sign of success.
self.password = (
self.password or
self._load_password_from_keyring() or
self._prompt_for_password()
)
def _load_password_from_keyring(self):
"""
Attempt to load password from keyring. Suppress Exceptions.
"""
try:
keyring = __import__('keyring')
password = keyring.get_password(self.repository, self.username)
except Exception:
password = None
finally:
return password
def _prompt_for_password(self):
"""
Prompt for a password on the tty. Suppress Exceptions.
"""
password = None
try:
while not password:
password = getpass.getpass()
except (Exception, KeyboardInterrupt):
password = None
finally:
return password
| # ... existing code ...
# sign of success.
self.password = (
self.password or
self._load_password_from_keyring() or
self._prompt_for_password()
)
# ... rest of the code ... |
27c2878ab43ff1e38492e17971166e8fe3c8f1e1 | tests/unit/test_test_setup.py | tests/unit/test_test_setup.py | """Tests for correctly generated, working setup."""
from os import system
from sys import version_info
from . import pytest_generate_tests # noqa, pylint: disable=unused-import
# pylint: disable=too-few-public-methods
class TestTestSetup(object):
"""
Tests for verifying generated test setups of this cookiecutter,
executed several times with different values (test scenarios).
"""
scenarios = [
('django', {
'project_slug': 'django-project',
'framework': 'Django',
}),
# ('flask', {
# 'project_slug': 'flask-project',
# 'framework': 'Flask',
# }),
]
# pylint: disable=no-self-use
def test_test_setup(self, cookies, project_slug, framework):
"""
Generate a project and verify the test setup executes successfully.
"""
py_version = 'py%s%s' % version_info[:2]
result = cookies.bake(extra_context={
'project_slug': project_slug,
'framework': framework,
'tests': 'flake8,pylint,%s,behave' % py_version,
})
assert result.exit_code == 0
assert result.exception is None
tox_ini = result.project.join('tox.ini')
assert tox_ini.isfile()
exit_code = system('tox -c %s' % tox_ini)
assert exit_code == 0, 'Running tests in generated project fails.'
| """Tests for correctly generated, working setup."""
from os import system
from sys import version_info
from . import pytest_generate_tests # noqa, pylint: disable=unused-import
# pylint: disable=too-few-public-methods
class TestTestSetup(object):
"""
Tests for verifying generated test setups of this cookiecutter,
executed several times with different values (test scenarios).
"""
scenarios = [
('django', {
'project_slug': 'django-project',
'framework': 'Django',
}),
# ('flask', {
# 'project_slug': 'flask-project',
# 'framework': 'Flask',
# }),
]
# pylint: disable=no-self-use
def test_test_setup(self, cookies, project_slug, framework):
"""
Generate a project and verify the test setup executes successfully.
"""
major, minor = version_info[:2]
py_version = 'py%s%s' % (major, minor)
result = cookies.bake(extra_context={
'project_slug': project_slug,
'framework': framework,
'tests': 'flake8,pylint,%s,behave' % py_version,
})
assert result.exit_code == 0, \
'Cookiecutter exits with %(exit_code)s:' \
' %(exception)s' % result.__dict__
assert result.exception is None
tox_ini = result.project.join('tox.ini')
assert tox_ini.isfile()
exit_code = system('tox -c %s' % tox_ini)
assert exit_code == 0, 'Running tests in generated project fails.'
| Make py_version and assertion more readable | Make py_version and assertion more readable
| Python | apache-2.0 | painless-software/painless-continuous-delivery,painless-software/painless-continuous-delivery,painless-software/painless-continuous-delivery,painless-software/painless-continuous-delivery | """Tests for correctly generated, working setup."""
from os import system
from sys import version_info
from . import pytest_generate_tests # noqa, pylint: disable=unused-import
# pylint: disable=too-few-public-methods
class TestTestSetup(object):
"""
Tests for verifying generated test setups of this cookiecutter,
executed several times with different values (test scenarios).
"""
scenarios = [
('django', {
'project_slug': 'django-project',
'framework': 'Django',
}),
# ('flask', {
# 'project_slug': 'flask-project',
# 'framework': 'Flask',
# }),
]
# pylint: disable=no-self-use
def test_test_setup(self, cookies, project_slug, framework):
"""
Generate a project and verify the test setup executes successfully.
"""
+ major, minor = version_info[:2]
- py_version = 'py%s%s' % version_info[:2]
+ py_version = 'py%s%s' % (major, minor)
result = cookies.bake(extra_context={
'project_slug': project_slug,
'framework': framework,
'tests': 'flake8,pylint,%s,behave' % py_version,
})
- assert result.exit_code == 0
+ assert result.exit_code == 0, \
+ 'Cookiecutter exits with %(exit_code)s:' \
+ ' %(exception)s' % result.__dict__
assert result.exception is None
tox_ini = result.project.join('tox.ini')
assert tox_ini.isfile()
exit_code = system('tox -c %s' % tox_ini)
assert exit_code == 0, 'Running tests in generated project fails.'
| Make py_version and assertion more readable | ## Code Before:
"""Tests for correctly generated, working setup."""
from os import system
from sys import version_info
from . import pytest_generate_tests # noqa, pylint: disable=unused-import
# pylint: disable=too-few-public-methods
class TestTestSetup(object):
"""
Tests for verifying generated test setups of this cookiecutter,
executed several times with different values (test scenarios).
"""
scenarios = [
('django', {
'project_slug': 'django-project',
'framework': 'Django',
}),
# ('flask', {
# 'project_slug': 'flask-project',
# 'framework': 'Flask',
# }),
]
# pylint: disable=no-self-use
def test_test_setup(self, cookies, project_slug, framework):
"""
Generate a project and verify the test setup executes successfully.
"""
py_version = 'py%s%s' % version_info[:2]
result = cookies.bake(extra_context={
'project_slug': project_slug,
'framework': framework,
'tests': 'flake8,pylint,%s,behave' % py_version,
})
assert result.exit_code == 0
assert result.exception is None
tox_ini = result.project.join('tox.ini')
assert tox_ini.isfile()
exit_code = system('tox -c %s' % tox_ini)
assert exit_code == 0, 'Running tests in generated project fails.'
## Instruction:
Make py_version and assertion more readable
## Code After:
"""Tests for correctly generated, working setup."""
from os import system
from sys import version_info
from . import pytest_generate_tests # noqa, pylint: disable=unused-import
# pylint: disable=too-few-public-methods
class TestTestSetup(object):
"""
Tests for verifying generated test setups of this cookiecutter,
executed several times with different values (test scenarios).
"""
scenarios = [
('django', {
'project_slug': 'django-project',
'framework': 'Django',
}),
# ('flask', {
# 'project_slug': 'flask-project',
# 'framework': 'Flask',
# }),
]
# pylint: disable=no-self-use
def test_test_setup(self, cookies, project_slug, framework):
"""
Generate a project and verify the test setup executes successfully.
"""
major, minor = version_info[:2]
py_version = 'py%s%s' % (major, minor)
result = cookies.bake(extra_context={
'project_slug': project_slug,
'framework': framework,
'tests': 'flake8,pylint,%s,behave' % py_version,
})
assert result.exit_code == 0, \
'Cookiecutter exits with %(exit_code)s:' \
' %(exception)s' % result.__dict__
assert result.exception is None
tox_ini = result.project.join('tox.ini')
assert tox_ini.isfile()
exit_code = system('tox -c %s' % tox_ini)
assert exit_code == 0, 'Running tests in generated project fails.'
| ...
Generate a project and verify the test setup executes successfully.
"""
major, minor = version_info[:2]
py_version = 'py%s%s' % (major, minor)
result = cookies.bake(extra_context={
'project_slug': project_slug,
...
})
assert result.exit_code == 0, \
'Cookiecutter exits with %(exit_code)s:' \
' %(exception)s' % result.__dict__
assert result.exception is None
... |
c6e130682712e8534e773036ba3d87c09b91ff1c | knowledge_repo/postprocessors/format_checks.py | knowledge_repo/postprocessors/format_checks.py | from ..constants import FORMAT_CHECKS
from ..post import HEADER_OPTIONAL_FIELD_TYPES, HEADER_REQUIRED_FIELD_TYPES
from ..postprocessor import KnowledgePostProcessor
class FormatChecks(KnowledgePostProcessor):
_registry_keys = [FORMAT_CHECKS]
def process(self, kp):
headers = kp.headers
for field, typ, input in HEADER_REQUIRED_FIELD_TYPES:
assert field in headers, "Required field `{}` missing from headers.".format(
field)
assert isinstance(headers[field], typ), "Value for field `{}` is of type {}, and needs to be of type {}.".format(
field, type(headers[field]), typ)
for field, typ, input in HEADER_OPTIONAL_FIELD_TYPES:
if field in headers:
assert isinstance(headers[field], typ), "Value for field `{}` is of type {}, and needs to be of type {}.".format(
field, type(headers[field]), typ)
| from ..constants import FORMAT_CHECKS
from ..post import HEADER_OPTIONAL_FIELD_TYPES, HEADER_REQUIRED_FIELD_TYPES
from ..postprocessor import KnowledgePostProcessor
class FormatChecks(KnowledgePostProcessor):
_registry_keys = [FORMAT_CHECKS]
def process(self, kp):
headers = kp.headers
for field, typ, input in HEADER_REQUIRED_FIELD_TYPES:
assert field in headers, \
"Required field `{field}` missing from headers."
assert isinstance(headers[field], typ), \
f"Value for field `{field}` is of type " + \
f"{type(headers[field])}, and needs to be of type {typ}."
for field, typ, input in HEADER_OPTIONAL_FIELD_TYPES:
if field in headers:
assert isinstance(headers[field], typ), \
f"Value for field `{field}` is of type " + \
f"{type(headers[field])}, and needs to be of type {typ}."
| Fix lint issues related to long lines | Fix lint issues related to long lines
| Python | apache-2.0 | airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo | from ..constants import FORMAT_CHECKS
from ..post import HEADER_OPTIONAL_FIELD_TYPES, HEADER_REQUIRED_FIELD_TYPES
from ..postprocessor import KnowledgePostProcessor
class FormatChecks(KnowledgePostProcessor):
_registry_keys = [FORMAT_CHECKS]
def process(self, kp):
headers = kp.headers
for field, typ, input in HEADER_REQUIRED_FIELD_TYPES:
- assert field in headers, "Required field `{}` missing from headers.".format(
- field)
- assert isinstance(headers[field], typ), "Value for field `{}` is of type {}, and needs to be of type {}.".format(
- field, type(headers[field]), typ)
+ assert field in headers, \
+ "Required field `{field}` missing from headers."
+ assert isinstance(headers[field], typ), \
+ f"Value for field `{field}` is of type " + \
+ f"{type(headers[field])}, and needs to be of type {typ}."
for field, typ, input in HEADER_OPTIONAL_FIELD_TYPES:
if field in headers:
- assert isinstance(headers[field], typ), "Value for field `{}` is of type {}, and needs to be of type {}.".format(
- field, type(headers[field]), typ)
+ assert isinstance(headers[field], typ), \
+ f"Value for field `{field}` is of type " + \
+ f"{type(headers[field])}, and needs to be of type {typ}."
| Fix lint issues related to long lines | ## Code Before:
from ..constants import FORMAT_CHECKS
from ..post import HEADER_OPTIONAL_FIELD_TYPES, HEADER_REQUIRED_FIELD_TYPES
from ..postprocessor import KnowledgePostProcessor
class FormatChecks(KnowledgePostProcessor):
_registry_keys = [FORMAT_CHECKS]
def process(self, kp):
headers = kp.headers
for field, typ, input in HEADER_REQUIRED_FIELD_TYPES:
assert field in headers, "Required field `{}` missing from headers.".format(
field)
assert isinstance(headers[field], typ), "Value for field `{}` is of type {}, and needs to be of type {}.".format(
field, type(headers[field]), typ)
for field, typ, input in HEADER_OPTIONAL_FIELD_TYPES:
if field in headers:
assert isinstance(headers[field], typ), "Value for field `{}` is of type {}, and needs to be of type {}.".format(
field, type(headers[field]), typ)
## Instruction:
Fix lint issues related to long lines
## Code After:
from ..constants import FORMAT_CHECKS
from ..post import HEADER_OPTIONAL_FIELD_TYPES, HEADER_REQUIRED_FIELD_TYPES
from ..postprocessor import KnowledgePostProcessor
class FormatChecks(KnowledgePostProcessor):
_registry_keys = [FORMAT_CHECKS]
def process(self, kp):
headers = kp.headers
for field, typ, input in HEADER_REQUIRED_FIELD_TYPES:
assert field in headers, \
"Required field `{field}` missing from headers."
assert isinstance(headers[field], typ), \
f"Value for field `{field}` is of type " + \
f"{type(headers[field])}, and needs to be of type {typ}."
for field, typ, input in HEADER_OPTIONAL_FIELD_TYPES:
if field in headers:
assert isinstance(headers[field], typ), \
f"Value for field `{field}` is of type " + \
f"{type(headers[field])}, and needs to be of type {typ}."
| ...
headers = kp.headers
for field, typ, input in HEADER_REQUIRED_FIELD_TYPES:
assert field in headers, \
"Required field `{field}` missing from headers."
assert isinstance(headers[field], typ), \
f"Value for field `{field}` is of type " + \
f"{type(headers[field])}, and needs to be of type {typ}."
for field, typ, input in HEADER_OPTIONAL_FIELD_TYPES:
if field in headers:
assert isinstance(headers[field], typ), \
f"Value for field `{field}` is of type " + \
f"{type(headers[field])}, and needs to be of type {typ}."
... |
7bf4083ef44585116f0eff86753080612a26b374 | src/__init__.py | src/__init__.py | from bayeslite.api import barplot
from bayeslite.api import cardinality
from bayeslite.api import draw_crosscat
from bayeslite.api import estimate_log_likelihood
from bayeslite.api import heatmap
from bayeslite.api import histogram
from bayeslite.api import mi_hist
from bayeslite.api import nullify
from bayeslite.api import pairplot
from bayeslite.api import plot_crosscat_chain_diagnostics
"""Main bdbcontrib API.
The bdbcontrib module servers a sandbox for experimental and semi-stable
features that are not yet ready for integreation to the bayeslite repository.
"""
__all__ = [
'barplot',
'cardinality',
'draw_crosscat',
'estimate_log_likelihood',
'heatmap',
'histogram',
'mi_hist',
'nullify',
'pairplot',
'plot_crosscat_chain_diagnostics'
] | from bdbcontrib.api import barplot
from bdbcontrib.api import cardinality
from bdbcontrib.api import draw_crosscat
from bdbcontrib.api import estimate_log_likelihood
from bdbcontrib.api import heatmap
from bdbcontrib.api import histogram
from bdbcontrib.api import mi_hist
from bdbcontrib.api import nullify
from bdbcontrib.api import pairplot
from bdbcontrib.api import plot_crosscat_chain_diagnostics
"""Main bdbcontrib API.
The bdbcontrib module servers a sandbox for experimental and semi-stable
features that are not yet ready for integreation to the bayeslite repository.
"""
__all__ = [
'barplot',
'cardinality',
'draw_crosscat',
'estimate_log_likelihood',
'heatmap',
'histogram',
'mi_hist',
'nullify',
'pairplot',
'plot_crosscat_chain_diagnostics'
] | Fix big from bayeslite to bdbcontrib. | Fix big from bayeslite to bdbcontrib.
| Python | apache-2.0 | probcomp/bdbcontrib,probcomp/bdbcontrib | - from bayeslite.api import barplot
+ from bdbcontrib.api import barplot
- from bayeslite.api import cardinality
+ from bdbcontrib.api import cardinality
- from bayeslite.api import draw_crosscat
+ from bdbcontrib.api import draw_crosscat
- from bayeslite.api import estimate_log_likelihood
+ from bdbcontrib.api import estimate_log_likelihood
- from bayeslite.api import heatmap
+ from bdbcontrib.api import heatmap
- from bayeslite.api import histogram
+ from bdbcontrib.api import histogram
- from bayeslite.api import mi_hist
+ from bdbcontrib.api import mi_hist
- from bayeslite.api import nullify
+ from bdbcontrib.api import nullify
- from bayeslite.api import pairplot
+ from bdbcontrib.api import pairplot
- from bayeslite.api import plot_crosscat_chain_diagnostics
+ from bdbcontrib.api import plot_crosscat_chain_diagnostics
"""Main bdbcontrib API.
The bdbcontrib module servers a sandbox for experimental and semi-stable
features that are not yet ready for integreation to the bayeslite repository.
"""
__all__ = [
'barplot',
'cardinality',
'draw_crosscat',
'estimate_log_likelihood',
'heatmap',
'histogram',
'mi_hist',
'nullify',
'pairplot',
'plot_crosscat_chain_diagnostics'
] | Fix big from bayeslite to bdbcontrib. | ## Code Before:
from bayeslite.api import barplot
from bayeslite.api import cardinality
from bayeslite.api import draw_crosscat
from bayeslite.api import estimate_log_likelihood
from bayeslite.api import heatmap
from bayeslite.api import histogram
from bayeslite.api import mi_hist
from bayeslite.api import nullify
from bayeslite.api import pairplot
from bayeslite.api import plot_crosscat_chain_diagnostics
"""Main bdbcontrib API.
The bdbcontrib module servers a sandbox for experimental and semi-stable
features that are not yet ready for integreation to the bayeslite repository.
"""
__all__ = [
'barplot',
'cardinality',
'draw_crosscat',
'estimate_log_likelihood',
'heatmap',
'histogram',
'mi_hist',
'nullify',
'pairplot',
'plot_crosscat_chain_diagnostics'
]
## Instruction:
Fix big from bayeslite to bdbcontrib.
## Code After:
from bdbcontrib.api import barplot
from bdbcontrib.api import cardinality
from bdbcontrib.api import draw_crosscat
from bdbcontrib.api import estimate_log_likelihood
from bdbcontrib.api import heatmap
from bdbcontrib.api import histogram
from bdbcontrib.api import mi_hist
from bdbcontrib.api import nullify
from bdbcontrib.api import pairplot
from bdbcontrib.api import plot_crosscat_chain_diagnostics
"""Main bdbcontrib API.
The bdbcontrib module servers a sandbox for experimental and semi-stable
features that are not yet ready for integreation to the bayeslite repository.
"""
__all__ = [
'barplot',
'cardinality',
'draw_crosscat',
'estimate_log_likelihood',
'heatmap',
'histogram',
'mi_hist',
'nullify',
'pairplot',
'plot_crosscat_chain_diagnostics'
] | // ... existing code ...
from bdbcontrib.api import barplot
from bdbcontrib.api import cardinality
from bdbcontrib.api import draw_crosscat
from bdbcontrib.api import estimate_log_likelihood
from bdbcontrib.api import heatmap
from bdbcontrib.api import histogram
from bdbcontrib.api import mi_hist
from bdbcontrib.api import nullify
from bdbcontrib.api import pairplot
from bdbcontrib.api import plot_crosscat_chain_diagnostics
"""Main bdbcontrib API.
// ... rest of the code ... |
05c31095ee828bfe455ad93befc5d189b9d0edc5 | wallace/__init__.py | wallace/__init__.py | from . import models, information, agents, networks, processes
__all__ = ['models', 'information', 'agents',
'sources', 'networks', 'processes']
| from . import models, information, agents, networks, processes
__all__ = ['models', 'information', 'agents', 'sources', 'networks',
'processes', 'transformations']
| Add transformations to Wallace init | Add transformations to Wallace init
| Python | mit | Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,berkeley-cocosci/Wallace,berkeley-cocosci/Wallace,suchow/Wallace,Dallinger/Dallinger,Dallinger/Dallinger,suchow/Wallace,Dallinger/Dallinger,berkeley-cocosci/Wallace,jcpeterson/Dallinger,suchow/Wallace,Dallinger/Dallinger | from . import models, information, agents, networks, processes
- __all__ = ['models', 'information', 'agents',
+ __all__ = ['models', 'information', 'agents', 'sources', 'networks',
- 'sources', 'networks', 'processes']
+ 'processes', 'transformations']
| Add transformations to Wallace init | ## Code Before:
from . import models, information, agents, networks, processes
__all__ = ['models', 'information', 'agents',
'sources', 'networks', 'processes']
## Instruction:
Add transformations to Wallace init
## Code After:
from . import models, information, agents, networks, processes
__all__ = ['models', 'information', 'agents', 'sources', 'networks',
'processes', 'transformations']
| // ... existing code ...
from . import models, information, agents, networks, processes
__all__ = ['models', 'information', 'agents', 'sources', 'networks',
'processes', 'transformations']
// ... rest of the code ... |
0f7816676eceb42f13786408f1d1a09527919a1e | Modules/Biophotonics/python/iMC/msi/io/spectrometerreader.py | Modules/Biophotonics/python/iMC/msi/io/spectrometerreader.py |
import numpy as np
from msi.io.reader import Reader
from msi.msi import Msi
class SpectrometerReader(Reader):
def __init__(self):
pass
def read(self, file_to_read):
# our spectrometer like to follow german standards in files, we need
# to switch to english ones
transformed=""
replacements = {',': '.', '\r\n': ''}
with open(file_to_read) as infile:
for line in infile:
for src, target in replacements.iteritems():
line = line.replace(src, target)
transformed = "\n".join([transformed, line])
for num, line in enumerate(transformed.splitlines(), 1):
if ">>>>>Begin Spectral Data<<<<<" in line:
break
string_only_spectrum = "\n".join(transformed.splitlines()[num:])
data_vector = np.fromstring(string_only_spectrum,
sep="\t").reshape(-1, 2)
msi = Msi(data_vector[:, 1],
{'wavelengths': data_vector[:, 0] * 10 ** -9})
return msi
|
import numpy as np
from msi.io.reader import Reader
from msi.msi import Msi
class SpectrometerReader(Reader):
def __init__(self):
pass
def read(self, file_to_read):
# our spectrometer like to follow german standards in files, we need
# to switch to english ones
transformed=""
replacements = {',': '.', '\r\n': ''}
with open(file_to_read) as infile:
for line in infile:
for src, target in replacements.iteritems():
line = line.replace(src, target)
transformed = "\n".join([transformed, line])
for num, line in enumerate(transformed.splitlines(), 1):
if ">>>>>Begin" in line:
break
for num_end, line in enumerate(transformed.splitlines(), 1):
if ">>>>>End" in line:
num_end -= 1
break
string_only_spectrum = "\n".join(transformed.splitlines()[num:num_end])
data_vector = np.fromstring(string_only_spectrum,
sep="\t").reshape(-1, 2)
msi = Msi(data_vector[:, 1],
{'wavelengths': data_vector[:, 0] * 10 ** -9})
return msi
| Change SpectrometerReader a little so it can handle more data formats. | Change SpectrometerReader a little so it can handle more data formats.
| Python | bsd-3-clause | MITK/MITK,iwegner/MITK,RabadanLab/MITKats,RabadanLab/MITKats,iwegner/MITK,fmilano/mitk,fmilano/mitk,RabadanLab/MITKats,RabadanLab/MITKats,fmilano/mitk,fmilano/mitk,MITK/MITK,RabadanLab/MITKats,RabadanLab/MITKats,fmilano/mitk,fmilano/mitk,iwegner/MITK,fmilano/mitk,MITK/MITK,iwegner/MITK,iwegner/MITK,MITK/MITK,MITK/MITK,iwegner/MITK,MITK/MITK |
import numpy as np
from msi.io.reader import Reader
from msi.msi import Msi
class SpectrometerReader(Reader):
def __init__(self):
pass
def read(self, file_to_read):
# our spectrometer like to follow german standards in files, we need
# to switch to english ones
transformed=""
replacements = {',': '.', '\r\n': ''}
with open(file_to_read) as infile:
for line in infile:
for src, target in replacements.iteritems():
line = line.replace(src, target)
transformed = "\n".join([transformed, line])
for num, line in enumerate(transformed.splitlines(), 1):
- if ">>>>>Begin Spectral Data<<<<<" in line:
+ if ">>>>>Begin" in line:
break
+
+ for num_end, line in enumerate(transformed.splitlines(), 1):
+ if ">>>>>End" in line:
+ num_end -= 1
+ break
- string_only_spectrum = "\n".join(transformed.splitlines()[num:])
+ string_only_spectrum = "\n".join(transformed.splitlines()[num:num_end])
data_vector = np.fromstring(string_only_spectrum,
sep="\t").reshape(-1, 2)
msi = Msi(data_vector[:, 1],
{'wavelengths': data_vector[:, 0] * 10 ** -9})
return msi
| Change SpectrometerReader a little so it can handle more data formats. | ## Code Before:
import numpy as np
from msi.io.reader import Reader
from msi.msi import Msi
class SpectrometerReader(Reader):
def __init__(self):
pass
def read(self, file_to_read):
# our spectrometer like to follow german standards in files, we need
# to switch to english ones
transformed=""
replacements = {',': '.', '\r\n': ''}
with open(file_to_read) as infile:
for line in infile:
for src, target in replacements.iteritems():
line = line.replace(src, target)
transformed = "\n".join([transformed, line])
for num, line in enumerate(transformed.splitlines(), 1):
if ">>>>>Begin Spectral Data<<<<<" in line:
break
string_only_spectrum = "\n".join(transformed.splitlines()[num:])
data_vector = np.fromstring(string_only_spectrum,
sep="\t").reshape(-1, 2)
msi = Msi(data_vector[:, 1],
{'wavelengths': data_vector[:, 0] * 10 ** -9})
return msi
## Instruction:
Change SpectrometerReader a little so it can handle more data formats.
## Code After:
import numpy as np
from msi.io.reader import Reader
from msi.msi import Msi
class SpectrometerReader(Reader):
def __init__(self):
pass
def read(self, file_to_read):
# our spectrometer like to follow german standards in files, we need
# to switch to english ones
transformed=""
replacements = {',': '.', '\r\n': ''}
with open(file_to_read) as infile:
for line in infile:
for src, target in replacements.iteritems():
line = line.replace(src, target)
transformed = "\n".join([transformed, line])
for num, line in enumerate(transformed.splitlines(), 1):
if ">>>>>Begin" in line:
break
for num_end, line in enumerate(transformed.splitlines(), 1):
if ">>>>>End" in line:
num_end -= 1
break
string_only_spectrum = "\n".join(transformed.splitlines()[num:num_end])
data_vector = np.fromstring(string_only_spectrum,
sep="\t").reshape(-1, 2)
msi = Msi(data_vector[:, 1],
{'wavelengths': data_vector[:, 0] * 10 ** -9})
return msi
| // ... existing code ...
for num, line in enumerate(transformed.splitlines(), 1):
if ">>>>>Begin" in line:
break
for num_end, line in enumerate(transformed.splitlines(), 1):
if ">>>>>End" in line:
num_end -= 1
break
string_only_spectrum = "\n".join(transformed.splitlines()[num:num_end])
data_vector = np.fromstring(string_only_spectrum,
sep="\t").reshape(-1, 2)
// ... rest of the code ... |
5841590444d202e6fb1fe8d7d937807ff9805677 | astropy/table/tests/test_row.py | astropy/table/tests/test_row.py | import pytest
import numpy as np
from .. import Column, Row, Table
class TestRow():
def setup_method(self, method):
self.a = Column('a', [1, 2, 3])
self.b = Column('b', [4, 5, 6])
def test_subclass(self):
"""Row is subclass of ndarray and Row"""
table = Table([self.a, self.b])
c = Row(table, 2)
assert isinstance(c, Row)
def test_values(self):
"""Row accurately reflects table values and attributes"""
table = Table([self.a, self.b], meta={'x': 1})
row = table[1]
assert row['a'] == 2
assert row['b'] == 5
assert row[0] == 2
assert row[1] == 5
assert row.meta is table.meta
assert row.colnames == table.colnames
assert row.columns is table.columns
with pytest.raises(IndexError):
row[2]
assert str(row.dtype) == "[('a', '<i8'), ('b', '<i8')]"
def test_ref(self):
"""Row is a reference into original table data"""
table = Table([self.a, self.b])
row = table[1]
row['a'] = 10
assert table['a'][1] == 10
| import pytest
import numpy as np
from .. import Column, Row, Table
class TestRow():
def setup_method(self, method):
self.a = Column('a', [1, 2, 3])
self.b = Column('b', [4, 5, 6])
self.t = Table([self.a, self.b])
def test_subclass(self):
"""Row is subclass of ndarray and Row"""
c = Row(self.t, 2)
assert isinstance(c, Row)
def test_values(self):
"""Row accurately reflects table values and attributes"""
table = self.t
row = table[1]
assert row['a'] == 2
assert row['b'] == 5
assert row[0] == 2
assert row[1] == 5
assert row.meta is table.meta
assert row.colnames == table.colnames
assert row.columns is table.columns
with pytest.raises(IndexError):
row[2]
assert str(row.dtype) == "[('a', '<i8'), ('b', '<i8')]"
def test_ref(self):
"""Row is a reference into original table data"""
table = self.t
row = table[1]
row['a'] = 10
assert table['a'][1] == 10
def SKIP_test_set_slice(self):
"""Set row elements with a slice
This currently fails because the underlying np.void object
row.data = table._data[index] does not support slice assignment.
"""
table = self.t
row = table[0]
row[:] = [-1, -1]
row[:1] = np.array([-2])
assert np.all(table._data == np.array([[-1, -1],
[-2, 5],
[3, 6]]))
| Add a (skipped) test for row slice assignment. | Add a (skipped) test for row slice assignment.
E. Bray requested the ability to assign to a table via a row with
slice assignment, e.g.
row = table[2]
row[2:5] = [2, 3, 4]
row[:] = 3
This does not currently work because np.void (which is what numpy
returns for structured array row access) does not support slice
assignment. Test is left there as a placeholder for now.
| Python | bsd-3-clause | bsipocz/astropy,lpsinger/astropy,MSeifert04/astropy,larrybradley/astropy,bsipocz/astropy,astropy/astropy,kelle/astropy,DougBurke/astropy,stargaser/astropy,dhomeier/astropy,lpsinger/astropy,pllim/astropy,dhomeier/astropy,DougBurke/astropy,lpsinger/astropy,astropy/astropy,tbabej/astropy,joergdietrich/astropy,funbaker/astropy,tbabej/astropy,tbabej/astropy,bsipocz/astropy,saimn/astropy,dhomeier/astropy,pllim/astropy,lpsinger/astropy,tbabej/astropy,larrybradley/astropy,StuartLittlefair/astropy,bsipocz/astropy,pllim/astropy,pllim/astropy,StuartLittlefair/astropy,saimn/astropy,funbaker/astropy,astropy/astropy,astropy/astropy,MSeifert04/astropy,mhvk/astropy,astropy/astropy,stargaser/astropy,AustereCuriosity/astropy,joergdietrich/astropy,DougBurke/astropy,funbaker/astropy,aleksandr-bakanov/astropy,joergdietrich/astropy,joergdietrich/astropy,AustereCuriosity/astropy,MSeifert04/astropy,larrybradley/astropy,StuartLittlefair/astropy,AustereCuriosity/astropy,aleksandr-bakanov/astropy,stargaser/astropy,saimn/astropy,lpsinger/astropy,AustereCuriosity/astropy,mhvk/astropy,kelle/astropy,aleksandr-bakanov/astropy,kelle/astropy,mhvk/astropy,saimn/astropy,larrybradley/astropy,funbaker/astropy,saimn/astropy,StuartLittlefair/astropy,aleksandr-bakanov/astropy,joergdietrich/astropy,mhvk/astropy,StuartLittlefair/astropy,dhomeier/astropy,kelle/astropy,dhomeier/astropy,larrybradley/astropy,AustereCuriosity/astropy,DougBurke/astropy,MSeifert04/astropy,kelle/astropy,pllim/astropy,mhvk/astropy,stargaser/astropy,tbabej/astropy | import pytest
import numpy as np
from .. import Column, Row, Table
class TestRow():
def setup_method(self, method):
self.a = Column('a', [1, 2, 3])
self.b = Column('b', [4, 5, 6])
+ self.t = Table([self.a, self.b])
def test_subclass(self):
"""Row is subclass of ndarray and Row"""
- table = Table([self.a, self.b])
- c = Row(table, 2)
+ c = Row(self.t, 2)
assert isinstance(c, Row)
def test_values(self):
"""Row accurately reflects table values and attributes"""
- table = Table([self.a, self.b], meta={'x': 1})
+ table = self.t
row = table[1]
assert row['a'] == 2
assert row['b'] == 5
assert row[0] == 2
assert row[1] == 5
assert row.meta is table.meta
assert row.colnames == table.colnames
assert row.columns is table.columns
with pytest.raises(IndexError):
row[2]
assert str(row.dtype) == "[('a', '<i8'), ('b', '<i8')]"
def test_ref(self):
"""Row is a reference into original table data"""
- table = Table([self.a, self.b])
+ table = self.t
row = table[1]
row['a'] = 10
assert table['a'][1] == 10
+ def SKIP_test_set_slice(self):
+ """Set row elements with a slice
+
+ This currently fails because the underlying np.void object
+ row.data = table._data[index] does not support slice assignment.
+ """
+ table = self.t
+ row = table[0]
+ row[:] = [-1, -1]
+ row[:1] = np.array([-2])
+ assert np.all(table._data == np.array([[-1, -1],
+ [-2, 5],
+ [3, 6]]))
+ | Add a (skipped) test for row slice assignment. | ## Code Before:
import pytest
import numpy as np
from .. import Column, Row, Table
class TestRow():
def setup_method(self, method):
self.a = Column('a', [1, 2, 3])
self.b = Column('b', [4, 5, 6])
def test_subclass(self):
"""Row is subclass of ndarray and Row"""
table = Table([self.a, self.b])
c = Row(table, 2)
assert isinstance(c, Row)
def test_values(self):
"""Row accurately reflects table values and attributes"""
table = Table([self.a, self.b], meta={'x': 1})
row = table[1]
assert row['a'] == 2
assert row['b'] == 5
assert row[0] == 2
assert row[1] == 5
assert row.meta is table.meta
assert row.colnames == table.colnames
assert row.columns is table.columns
with pytest.raises(IndexError):
row[2]
assert str(row.dtype) == "[('a', '<i8'), ('b', '<i8')]"
def test_ref(self):
"""Row is a reference into original table data"""
table = Table([self.a, self.b])
row = table[1]
row['a'] = 10
assert table['a'][1] == 10
## Instruction:
Add a (skipped) test for row slice assignment.
## Code After:
import pytest
import numpy as np
from .. import Column, Row, Table
class TestRow():
def setup_method(self, method):
self.a = Column('a', [1, 2, 3])
self.b = Column('b', [4, 5, 6])
self.t = Table([self.a, self.b])
def test_subclass(self):
"""Row is subclass of ndarray and Row"""
c = Row(self.t, 2)
assert isinstance(c, Row)
def test_values(self):
"""Row accurately reflects table values and attributes"""
table = self.t
row = table[1]
assert row['a'] == 2
assert row['b'] == 5
assert row[0] == 2
assert row[1] == 5
assert row.meta is table.meta
assert row.colnames == table.colnames
assert row.columns is table.columns
with pytest.raises(IndexError):
row[2]
assert str(row.dtype) == "[('a', '<i8'), ('b', '<i8')]"
def test_ref(self):
"""Row is a reference into original table data"""
table = self.t
row = table[1]
row['a'] = 10
assert table['a'][1] == 10
def SKIP_test_set_slice(self):
"""Set row elements with a slice
This currently fails because the underlying np.void object
row.data = table._data[index] does not support slice assignment.
"""
table = self.t
row = table[0]
row[:] = [-1, -1]
row[:1] = np.array([-2])
assert np.all(table._data == np.array([[-1, -1],
[-2, 5],
[3, 6]]))
| ...
self.a = Column('a', [1, 2, 3])
self.b = Column('b', [4, 5, 6])
self.t = Table([self.a, self.b])
def test_subclass(self):
"""Row is subclass of ndarray and Row"""
c = Row(self.t, 2)
assert isinstance(c, Row)
...
def test_values(self):
"""Row accurately reflects table values and attributes"""
table = self.t
row = table[1]
assert row['a'] == 2
...
def test_ref(self):
"""Row is a reference into original table data"""
table = self.t
row = table[1]
row['a'] = 10
assert table['a'][1] == 10
def SKIP_test_set_slice(self):
"""Set row elements with a slice
This currently fails because the underlying np.void object
row.data = table._data[index] does not support slice assignment.
"""
table = self.t
row = table[0]
row[:] = [-1, -1]
row[:1] = np.array([-2])
assert np.all(table._data == np.array([[-1, -1],
[-2, 5],
[3, 6]]))
... |
8d02522c276b87f45999281c3aa6a57e19df9c09 | src/core/middlewares.py | src/core/middlewares.py | import re
from django.conf import settings
from django.http import HttpResponseRedirect
# Matches things like
# /en
# /en/
# /en/foo/bar (can be anything after the first trailing slash)
# But not
# /en-gb
# because the fallback language code is not followed immediately by a slash.
FALLBACK_PREFIX_PATTERN = re.compile(
r'^/(?P<lang>{langs})(?:/?|/.+)$'.format(
langs='|'.join(settings.FALLBACK_LANGUAGE_PREFIXES.keys()),
),
re.UNICODE,
)
class LocaleFallbackMiddleware:
"""Redirect entries in ``settings.FALLBACK_LANGUAGE_PREFIXES`` to a
valid language prefix.
"""
response_redirect_class = HttpResponseRedirect
def process_request(self, request):
if not settings.USE_I18N:
return
match = FALLBACK_PREFIX_PATTERN.match(request.path_info)
if not match:
return
lang = match.group('lang')
fallback = settings.FALLBACK_LANGUAGE_PREFIXES[lang]
path = request.get_full_path().replace(lang, fallback, 1)
return self.response_redirect_class(path)
| import re
from django.conf import settings
from django.core.urlresolvers import get_script_prefix
from django.http import HttpResponseRedirect
# Matches things like
# /en
# /en/
# /en/foo/bar (can be anything after the first trailing slash)
# But not
# /en-gb
# because the fallback language code is not followed immediately by a slash.
FALLBACK_PREFIX_PATTERN = re.compile(
r'^/(?P<lang>{langs})(?:/?|/.+)$'.format(
langs='|'.join(settings.FALLBACK_LANGUAGE_PREFIXES.keys()),
),
re.UNICODE,
)
class LocaleFallbackMiddleware:
"""Redirect entries in ``settings.FALLBACK_LANGUAGE_PREFIXES`` to a
valid language prefix.
"""
response_redirect_class = HttpResponseRedirect
def process_request(self, request):
if not settings.USE_I18N:
return
match = FALLBACK_PREFIX_PATTERN.match(request.path_info)
if not match:
return
lang = match.group('lang')
fallback = settings.FALLBACK_LANGUAGE_PREFIXES[lang]
script_prefix = get_script_prefix()
path = request.get_full_path().replace(
script_prefix + lang, script_prefix + fallback, 1,
)
return self.response_redirect_class(path)
| Prepend script prefix when replacing lang code | Prepend script prefix when replacing lang code
| Python | mit | pycontw/pycontw2016,uranusjr/pycontw2016,uranusjr/pycontw2016,uranusjr/pycontw2016,uranusjr/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016 | import re
from django.conf import settings
+ from django.core.urlresolvers import get_script_prefix
from django.http import HttpResponseRedirect
# Matches things like
# /en
# /en/
# /en/foo/bar (can be anything after the first trailing slash)
# But not
# /en-gb
# because the fallback language code is not followed immediately by a slash.
FALLBACK_PREFIX_PATTERN = re.compile(
r'^/(?P<lang>{langs})(?:/?|/.+)$'.format(
langs='|'.join(settings.FALLBACK_LANGUAGE_PREFIXES.keys()),
),
re.UNICODE,
)
class LocaleFallbackMiddleware:
"""Redirect entries in ``settings.FALLBACK_LANGUAGE_PREFIXES`` to a
valid language prefix.
"""
response_redirect_class = HttpResponseRedirect
def process_request(self, request):
if not settings.USE_I18N:
return
match = FALLBACK_PREFIX_PATTERN.match(request.path_info)
if not match:
return
lang = match.group('lang')
fallback = settings.FALLBACK_LANGUAGE_PREFIXES[lang]
+ script_prefix = get_script_prefix()
- path = request.get_full_path().replace(lang, fallback, 1)
+ path = request.get_full_path().replace(
+ script_prefix + lang, script_prefix + fallback, 1,
+ )
return self.response_redirect_class(path)
| Prepend script prefix when replacing lang code | ## Code Before:
import re
from django.conf import settings
from django.http import HttpResponseRedirect
# Matches things like
# /en
# /en/
# /en/foo/bar (can be anything after the first trailing slash)
# But not
# /en-gb
# because the fallback language code is not followed immediately by a slash.
FALLBACK_PREFIX_PATTERN = re.compile(
r'^/(?P<lang>{langs})(?:/?|/.+)$'.format(
langs='|'.join(settings.FALLBACK_LANGUAGE_PREFIXES.keys()),
),
re.UNICODE,
)
class LocaleFallbackMiddleware:
"""Redirect entries in ``settings.FALLBACK_LANGUAGE_PREFIXES`` to a
valid language prefix.
"""
response_redirect_class = HttpResponseRedirect
def process_request(self, request):
if not settings.USE_I18N:
return
match = FALLBACK_PREFIX_PATTERN.match(request.path_info)
if not match:
return
lang = match.group('lang')
fallback = settings.FALLBACK_LANGUAGE_PREFIXES[lang]
path = request.get_full_path().replace(lang, fallback, 1)
return self.response_redirect_class(path)
## Instruction:
Prepend script prefix when replacing lang code
## Code After:
import re
from django.conf import settings
from django.core.urlresolvers import get_script_prefix
from django.http import HttpResponseRedirect
# Matches things like
# /en
# /en/
# /en/foo/bar (can be anything after the first trailing slash)
# But not
# /en-gb
# because the fallback language code is not followed immediately by a slash.
FALLBACK_PREFIX_PATTERN = re.compile(
r'^/(?P<lang>{langs})(?:/?|/.+)$'.format(
langs='|'.join(settings.FALLBACK_LANGUAGE_PREFIXES.keys()),
),
re.UNICODE,
)
class LocaleFallbackMiddleware:
"""Redirect entries in ``settings.FALLBACK_LANGUAGE_PREFIXES`` to a
valid language prefix.
"""
response_redirect_class = HttpResponseRedirect
def process_request(self, request):
if not settings.USE_I18N:
return
match = FALLBACK_PREFIX_PATTERN.match(request.path_info)
if not match:
return
lang = match.group('lang')
fallback = settings.FALLBACK_LANGUAGE_PREFIXES[lang]
script_prefix = get_script_prefix()
path = request.get_full_path().replace(
script_prefix + lang, script_prefix + fallback, 1,
)
return self.response_redirect_class(path)
| // ... existing code ...
from django.conf import settings
from django.core.urlresolvers import get_script_prefix
from django.http import HttpResponseRedirect
// ... modified code ...
lang = match.group('lang')
fallback = settings.FALLBACK_LANGUAGE_PREFIXES[lang]
script_prefix = get_script_prefix()
path = request.get_full_path().replace(
script_prefix + lang, script_prefix + fallback, 1,
)
return self.response_redirect_class(path)
// ... rest of the code ... |
1667e4c28d969af615d028a4b828cc2c868957bc | tests/git_code_debt/list_metrics_test.py | tests/git_code_debt/list_metrics_test.py |
import __builtin__
import mock
import pytest
from git_code_debt.list_metrics import color
from git_code_debt.list_metrics import CYAN
from git_code_debt.list_metrics import main
from git_code_debt.list_metrics import NORMAL
@pytest.mark.integration
def test_list_metricssmoke():
# This test is just to make sure that it doesn't fail catastrophically
with mock.patch.object(__builtin__, 'print', autospec=True) as print_mock:
main([])
assert print_mock.called
def test_color_no_color():
ret = color('foo', 'bar', False)
assert ret == 'foo'
def test_colored():
ret = color('foo', CYAN, True)
assert ret == CYAN + 'foo' + NORMAL
|
import __builtin__
import mock
import pytest
from git_code_debt.list_metrics import color
from git_code_debt.list_metrics import CYAN
from git_code_debt.list_metrics import main
from git_code_debt.list_metrics import NORMAL
@pytest.yield_fixture
def print_mock():
with mock.patch.object(__builtin__, 'print', autospec=True) as print_mock:
yield print_mock
@pytest.mark.integration
def test_list_metrics_smoke(print_mock):
# This test is just to make sure that it doesn't fail catastrophically
main([])
assert print_mock.called
@pytest.mark.integration
def test_list_metrics_no_color_smoke(print_mock):
main(['--color', 'never'])
assert all([
'\033' not in call[0][0] for call in print_mock.call_args_list
])
def test_color_no_color():
ret = color('foo', 'bar', False)
assert ret == 'foo'
def test_colored():
ret = color('foo', CYAN, True)
assert ret == CYAN + 'foo' + NORMAL
| Add integration test for --color never. | Add integration test for --color never.
| Python | mit | Yelp/git-code-debt,Yelp/git-code-debt,Yelp/git-code-debt,ucarion/git-code-debt,ucarion/git-code-debt,Yelp/git-code-debt,ucarion/git-code-debt |
import __builtin__
import mock
import pytest
from git_code_debt.list_metrics import color
from git_code_debt.list_metrics import CYAN
from git_code_debt.list_metrics import main
from git_code_debt.list_metrics import NORMAL
+ @pytest.yield_fixture
+ def print_mock():
+ with mock.patch.object(__builtin__, 'print', autospec=True) as print_mock:
+ yield print_mock
+
+
@pytest.mark.integration
- def test_list_metricssmoke():
+ def test_list_metrics_smoke(print_mock):
# This test is just to make sure that it doesn't fail catastrophically
- with mock.patch.object(__builtin__, 'print', autospec=True) as print_mock:
- main([])
+ main([])
- assert print_mock.called
+ assert print_mock.called
+
+
+ @pytest.mark.integration
+ def test_list_metrics_no_color_smoke(print_mock):
+ main(['--color', 'never'])
+ assert all([
+ '\033' not in call[0][0] for call in print_mock.call_args_list
+ ])
def test_color_no_color():
ret = color('foo', 'bar', False)
assert ret == 'foo'
def test_colored():
ret = color('foo', CYAN, True)
assert ret == CYAN + 'foo' + NORMAL
| Add integration test for --color never. | ## Code Before:
import __builtin__
import mock
import pytest
from git_code_debt.list_metrics import color
from git_code_debt.list_metrics import CYAN
from git_code_debt.list_metrics import main
from git_code_debt.list_metrics import NORMAL
@pytest.mark.integration
def test_list_metricssmoke():
# This test is just to make sure that it doesn't fail catastrophically
with mock.patch.object(__builtin__, 'print', autospec=True) as print_mock:
main([])
assert print_mock.called
def test_color_no_color():
ret = color('foo', 'bar', False)
assert ret == 'foo'
def test_colored():
ret = color('foo', CYAN, True)
assert ret == CYAN + 'foo' + NORMAL
## Instruction:
Add integration test for --color never.
## Code After:
import __builtin__
import mock
import pytest
from git_code_debt.list_metrics import color
from git_code_debt.list_metrics import CYAN
from git_code_debt.list_metrics import main
from git_code_debt.list_metrics import NORMAL
@pytest.yield_fixture
def print_mock():
with mock.patch.object(__builtin__, 'print', autospec=True) as print_mock:
yield print_mock
@pytest.mark.integration
def test_list_metrics_smoke(print_mock):
# This test is just to make sure that it doesn't fail catastrophically
main([])
assert print_mock.called
@pytest.mark.integration
def test_list_metrics_no_color_smoke(print_mock):
main(['--color', 'never'])
assert all([
'\033' not in call[0][0] for call in print_mock.call_args_list
])
def test_color_no_color():
ret = color('foo', 'bar', False)
assert ret == 'foo'
def test_colored():
ret = color('foo', CYAN, True)
assert ret == CYAN + 'foo' + NORMAL
| // ... existing code ...
@pytest.yield_fixture
def print_mock():
with mock.patch.object(__builtin__, 'print', autospec=True) as print_mock:
yield print_mock
@pytest.mark.integration
def test_list_metrics_smoke(print_mock):
# This test is just to make sure that it doesn't fail catastrophically
main([])
assert print_mock.called
@pytest.mark.integration
def test_list_metrics_no_color_smoke(print_mock):
main(['--color', 'never'])
assert all([
'\033' not in call[0][0] for call in print_mock.call_args_list
])
// ... rest of the code ... |
Subsets and Splits