commit stringlengths 40 40 | old_file stringlengths 4 118 | new_file stringlengths 4 118 | old_contents stringlengths 0 2.94k | new_contents stringlengths 1 4.43k | subject stringlengths 15 444 | message stringlengths 16 3.45k | lang stringclasses 1 value | license stringclasses 13 values | repos stringlengths 5 43.2k | prompt stringlengths 17 4.58k | response stringlengths 1 4.43k | prompt_tagged stringlengths 58 4.62k | response_tagged stringlengths 1 4.43k | text stringlengths 132 7.29k | text_tagged stringlengths 173 7.33k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4814ef9d78070c14ab4685b802543ba0afa26754 | django/users/views.py | django/users/views.py | from django.shortcuts import redirect
from rest_framework import viewsets
from .models import User
from .permissions import IsUserOrReadOnly
from .serializers import AuthenticatedUserSerializer, UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""API endpoint for viewing and editing users."""
queryset = User.objects.all()
permission_classes = (IsUserOrReadOnly,)
def get_serializer_class(self):
return (AuthenticatedUserSerializer
if self.request.user == self.get_object()
else UserSerializer)
def retrieve(self, request, pk=None):
"""Retrieve given user or current user if ``pk`` is "me"."""
if pk == 'me' and request.user.is_authenticated():
return redirect('user-detail', request.user.pk)
else:
return super(UserViewSet, self).retrieve(request, pk)
| from django.shortcuts import redirect
from rest_framework import viewsets
from .models import User
from .permissions import IsUserOrReadOnly
from .serializers import AuthenticatedUserSerializer, UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""API endpoint for viewing and editing users."""
queryset = User.objects.all()
permission_classes = (IsUserOrReadOnly,)
def get_serializer_class(self):
return (AuthenticatedUserSerializer
if self.request.user == self.get_object()
else UserSerializer)
def retrieve(self, request, pk=None):
"""Retrieve given user or current user if ``pk`` is "me"."""
if pk == 'me' and request.user.is_authenticated():
return redirect('user-detail', request.user.pk)
else:
return super().retrieve(request, pk)
| Use Python 3 style for super | Use Python 3 style for super
| Python | bsd-3-clause | FreeMusicNinja/freemusic.ninja,FreeMusicNinja/freemusic.ninja | from django.shortcuts import redirect
from rest_framework import viewsets
from .models import User
from .permissions import IsUserOrReadOnly
from .serializers import AuthenticatedUserSerializer, UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""API endpoint for viewing and editing users."""
queryset = User.objects.all()
permission_classes = (IsUserOrReadOnly,)
def get_serializer_class(self):
return (AuthenticatedUserSerializer
if self.request.user == self.get_object()
else UserSerializer)
def retrieve(self, request, pk=None):
"""Retrieve given user or current user if ``pk`` is "me"."""
if pk == 'me' and request.user.is_authenticated():
return redirect('user-detail', request.user.pk)
else:
return super(UserViewSet, self).retrieve(request, pk)
Use Python 3 style for super | from django.shortcuts import redirect
from rest_framework import viewsets
from .models import User
from .permissions import IsUserOrReadOnly
from .serializers import AuthenticatedUserSerializer, UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""API endpoint for viewing and editing users."""
queryset = User.objects.all()
permission_classes = (IsUserOrReadOnly,)
def get_serializer_class(self):
return (AuthenticatedUserSerializer
if self.request.user == self.get_object()
else UserSerializer)
def retrieve(self, request, pk=None):
"""Retrieve given user or current user if ``pk`` is "me"."""
if pk == 'me' and request.user.is_authenticated():
return redirect('user-detail', request.user.pk)
else:
return super().retrieve(request, pk)
| <commit_before>from django.shortcuts import redirect
from rest_framework import viewsets
from .models import User
from .permissions import IsUserOrReadOnly
from .serializers import AuthenticatedUserSerializer, UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""API endpoint for viewing and editing users."""
queryset = User.objects.all()
permission_classes = (IsUserOrReadOnly,)
def get_serializer_class(self):
return (AuthenticatedUserSerializer
if self.request.user == self.get_object()
else UserSerializer)
def retrieve(self, request, pk=None):
"""Retrieve given user or current user if ``pk`` is "me"."""
if pk == 'me' and request.user.is_authenticated():
return redirect('user-detail', request.user.pk)
else:
return super(UserViewSet, self).retrieve(request, pk)
<commit_msg>Use Python 3 style for super<commit_after> | from django.shortcuts import redirect
from rest_framework import viewsets
from .models import User
from .permissions import IsUserOrReadOnly
from .serializers import AuthenticatedUserSerializer, UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""API endpoint for viewing and editing users."""
queryset = User.objects.all()
permission_classes = (IsUserOrReadOnly,)
def get_serializer_class(self):
return (AuthenticatedUserSerializer
if self.request.user == self.get_object()
else UserSerializer)
def retrieve(self, request, pk=None):
"""Retrieve given user or current user if ``pk`` is "me"."""
if pk == 'me' and request.user.is_authenticated():
return redirect('user-detail', request.user.pk)
else:
return super().retrieve(request, pk)
| from django.shortcuts import redirect
from rest_framework import viewsets
from .models import User
from .permissions import IsUserOrReadOnly
from .serializers import AuthenticatedUserSerializer, UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""API endpoint for viewing and editing users."""
queryset = User.objects.all()
permission_classes = (IsUserOrReadOnly,)
def get_serializer_class(self):
return (AuthenticatedUserSerializer
if self.request.user == self.get_object()
else UserSerializer)
def retrieve(self, request, pk=None):
"""Retrieve given user or current user if ``pk`` is "me"."""
if pk == 'me' and request.user.is_authenticated():
return redirect('user-detail', request.user.pk)
else:
return super(UserViewSet, self).retrieve(request, pk)
Use Python 3 style for superfrom django.shortcuts import redirect
from rest_framework import viewsets
from .models import User
from .permissions import IsUserOrReadOnly
from .serializers import AuthenticatedUserSerializer, UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""API endpoint for viewing and editing users."""
queryset = User.objects.all()
permission_classes = (IsUserOrReadOnly,)
def get_serializer_class(self):
return (AuthenticatedUserSerializer
if self.request.user == self.get_object()
else UserSerializer)
def retrieve(self, request, pk=None):
"""Retrieve given user or current user if ``pk`` is "me"."""
if pk == 'me' and request.user.is_authenticated():
return redirect('user-detail', request.user.pk)
else:
return super().retrieve(request, pk)
| <commit_before>from django.shortcuts import redirect
from rest_framework import viewsets
from .models import User
from .permissions import IsUserOrReadOnly
from .serializers import AuthenticatedUserSerializer, UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""API endpoint for viewing and editing users."""
queryset = User.objects.all()
permission_classes = (IsUserOrReadOnly,)
def get_serializer_class(self):
return (AuthenticatedUserSerializer
if self.request.user == self.get_object()
else UserSerializer)
def retrieve(self, request, pk=None):
"""Retrieve given user or current user if ``pk`` is "me"."""
if pk == 'me' and request.user.is_authenticated():
return redirect('user-detail', request.user.pk)
else:
return super(UserViewSet, self).retrieve(request, pk)
<commit_msg>Use Python 3 style for super<commit_after>from django.shortcuts import redirect
from rest_framework import viewsets
from .models import User
from .permissions import IsUserOrReadOnly
from .serializers import AuthenticatedUserSerializer, UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""API endpoint for viewing and editing users."""
queryset = User.objects.all()
permission_classes = (IsUserOrReadOnly,)
def get_serializer_class(self):
return (AuthenticatedUserSerializer
if self.request.user == self.get_object()
else UserSerializer)
def retrieve(self, request, pk=None):
"""Retrieve given user or current user if ``pk`` is "me"."""
if pk == 'me' and request.user.is_authenticated():
return redirect('user-detail', request.user.pk)
else:
return super().retrieve(request, pk)
|
760a663ab1c079ea03f022c169f7d2d05346dc02 | scipy/ndimage/io.py | scipy/ndimage/io.py | from __future__ import division, print_function, absolute_import
_have_pil = True
try:
from scipy.misc.pilutil import imread as _imread
except ImportError:
_have_pil = False
__all__ = ['imread']
# Use the implementation of `imread` in `scipy.misc.pilutil.imread`.
# If it weren't for the different names of the first arguments of
# ndimage.io.imread and misc.pilutil.imread, we could simplify this file
# by writing
# from scipy.misc.pilutil import imread
# Unfortunately, because the argument names are different, that
# introduces a backwards incompatibility.
def imread(fname, flatten=False, mode=None):
if _have_pil:
return _imread(fname, flatten, mode)
raise ImportError("Could not import the Python Imaging Library (PIL)"
" required to load image files. Please refer to"
" http://pypi.python.org/pypi/PIL/ for installation"
" instructions.")
if _have_pil and _imread.__doc__ is not None:
imread.__doc__ = _imread.__doc__.replace('name : str', 'fname : str')
| from __future__ import division, print_function, absolute_import
_have_pil = True
try:
from scipy.misc.pilutil import imread as _imread
except ImportError:
_have_pil = False
__all__ = ['imread']
# Use the implementation of `imread` in `scipy.misc.pilutil.imread`.
# If it weren't for the different names of the first arguments of
# ndimage.io.imread and misc.pilutil.imread, we could simplify this file
# by writing
# from scipy.misc.pilutil import imread
# Unfortunately, because the argument names are different, that
# introduces a backwards incompatibility.
def imread(fname, flatten=False, mode=None):
if _have_pil:
return _imread(fname, flatten, mode)
raise ImportError("Could not import the Python Imaging Library (PIL)"
" required to load image files. Please refer to"
" http://pillow.readthedocs.org/en/latest/installation.html"
" for installation instructions.")
if _have_pil and _imread.__doc__ is not None:
imread.__doc__ = _imread.__doc__.replace('name : str', 'fname : str')
| Update PIL error install URL | DOC: Update PIL error install URL
Update URL for PIL import error
to point to Pillow installation
instead of PIL, for the latter
is somewhat out of date and
does not even Python 3 at the
moment unlike Pillow.
Closes gh-5779.
| Python | bsd-3-clause | anielsen001/scipy,dominicelse/scipy,aarchiba/scipy,gdooper/scipy,gfyoung/scipy,gertingold/scipy,woodscn/scipy,aeklant/scipy,Gillu13/scipy,rgommers/scipy,pyramania/scipy,scipy/scipy,mikebenfield/scipy,jakevdp/scipy,perimosocordiae/scipy,sriki18/scipy,anielsen001/scipy,person142/scipy,lhilt/scipy,aeklant/scipy,behzadnouri/scipy,sriki18/scipy,gfyoung/scipy,jamestwebber/scipy,kleskjr/scipy,lhilt/scipy,argriffing/scipy,jakevdp/scipy,Newman101/scipy,WarrenWeckesser/scipy,ilayn/scipy,jor-/scipy,jamestwebber/scipy,kleskjr/scipy,ilayn/scipy,anntzer/scipy,lhilt/scipy,grlee77/scipy,mdhaber/scipy,jakevdp/scipy,andyfaff/scipy,gdooper/scipy,kleskjr/scipy,pyramania/scipy,kalvdans/scipy,vigna/scipy,e-q/scipy,mdhaber/scipy,andyfaff/scipy,befelix/scipy,surhudm/scipy,niknow/scipy,larsmans/scipy,haudren/scipy,Newman101/scipy,ilayn/scipy,larsmans/scipy,anielsen001/scipy,gdooper/scipy,Stefan-Endres/scipy,woodscn/scipy,woodscn/scipy,tylerjereddy/scipy,nonhermitian/scipy,andyfaff/scipy,WarrenWeckesser/scipy,pbrod/scipy,zerothi/scipy,person142/scipy,surhudm/scipy,matthewalbani/scipy,anntzer/scipy,endolith/scipy,sriki18/scipy,apbard/scipy,pschella/scipy,behzadnouri/scipy,pschella/scipy,pbrod/scipy,befelix/scipy,gertingold/scipy,pyramania/scipy,nmayorov/scipy,chatcannon/scipy,mdhaber/scipy,andyfaff/scipy,bkendzior/scipy,apbard/scipy,jor-/scipy,arokem/scipy,maniteja123/scipy,maniteja123/scipy,chatcannon/scipy,larsmans/scipy,Eric89GXL/scipy,kalvdans/scipy,josephcslater/scipy,nonhermitian/scipy,aarchiba/scipy,Stefan-Endres/scipy,haudren/scipy,haudren/scipy,anielsen001/scipy,endolith/scipy,perimosocordiae/scipy,zerothi/scipy,person142/scipy,anntzer/scipy,surhudm/scipy,woodscn/scipy,befelix/scipy,jjhelmus/scipy,dominicelse/scipy,aarchiba/scipy,maniteja123/scipy,WarrenWeckesser/scipy,matthew-brett/scipy,Stefan-Endres/scipy,niknow/scipy,dominicelse/scipy,Stefan-Endres/scipy,argriffing/scipy,mikebenfield/scipy,person142/scipy,anntzer/scipy,chatcannon/scipy,maniteja123/scipy,scipy/scipy,Gillu13/scipy,jor-/scipy,chatcannon/scipy,andyfaff/scipy,arokem/scipy,pizzathief/scipy,arokem/scipy,nmayorov/scipy,Stefan-Endres/scipy,larsmans/scipy,larsmans/scipy,jor-/scipy,vigna/scipy,kleskjr/scipy,jor-/scipy,matthewalbani/scipy,zerothi/scipy,scipy/scipy,aeklant/scipy,tylerjereddy/scipy,Stefan-Endres/scipy,grlee77/scipy,befelix/scipy,aarchiba/scipy,bkendzior/scipy,rgommers/scipy,larsmans/scipy,matthew-brett/scipy,WarrenWeckesser/scipy,Newman101/scipy,gfyoung/scipy,argriffing/scipy,grlee77/scipy,ilayn/scipy,anntzer/scipy,vigna/scipy,woodscn/scipy,pschella/scipy,Eric89GXL/scipy,endolith/scipy,Gillu13/scipy,mikebenfield/scipy,perimosocordiae/scipy,mikebenfield/scipy,behzadnouri/scipy,anntzer/scipy,pschella/scipy,matthew-brett/scipy,jjhelmus/scipy,nonhermitian/scipy,matthew-brett/scipy,zerothi/scipy,matthewalbani/scipy,woodscn/scipy,kalvdans/scipy,ilayn/scipy,gertingold/scipy,haudren/scipy,surhudm/scipy,perimosocordiae/scipy,Newman101/scipy,andyfaff/scipy,aeklant/scipy,gdooper/scipy,scipy/scipy,matthewalbani/scipy,dominicelse/scipy,sriki18/scipy,jamestwebber/scipy,Newman101/scipy,anielsen001/scipy,nmayorov/scipy,person142/scipy,argriffing/scipy,haudren/scipy,josephcslater/scipy,scipy/scipy,behzadnouri/scipy,jakevdp/scipy,rgommers/scipy,gdooper/scipy,grlee77/scipy,befelix/scipy,matthew-brett/scipy,pizzathief/scipy,pyramania/scipy,pizzathief/scipy,perimosocordiae/scipy,chatcannon/scipy,sriki18/scipy,niknow/scipy,argriffing/scipy,gertingold/scipy,kleskjr/scipy,jjhelmus/scipy,vigna/scipy,zerothi/scipy,Gillu13/scipy,pyramania/scipy,maniteja123/scipy,rgommers/scipy,nonhermitian/scipy,surhudm/scipy,josephcslater/scipy,mdhaber/scipy,tylerjereddy/scipy,e-q/scipy,arokem/scipy,mikebenfield/scipy,jjhelmus/scipy,niknow/scipy,ilayn/scipy,Gillu13/scipy,WarrenWeckesser/scipy,sriki18/scipy,arokem/scipy,perimosocordiae/scipy,pschella/scipy,kalvdans/scipy,endolith/scipy,haudren/scipy,niknow/scipy,Newman101/scipy,zerothi/scipy,pbrod/scipy,kleskjr/scipy,pbrod/scipy,aarchiba/scipy,josephcslater/scipy,behzadnouri/scipy,chatcannon/scipy,WarrenWeckesser/scipy,gfyoung/scipy,rgommers/scipy,jamestwebber/scipy,anielsen001/scipy,Eric89GXL/scipy,Eric89GXL/scipy,pbrod/scipy,nmayorov/scipy,Eric89GXL/scipy,Eric89GXL/scipy,e-q/scipy,apbard/scipy,dominicelse/scipy,e-q/scipy,tylerjereddy/scipy,pizzathief/scipy,endolith/scipy,jakevdp/scipy,lhilt/scipy,kalvdans/scipy,aeklant/scipy,nmayorov/scipy,josephcslater/scipy,argriffing/scipy,matthewalbani/scipy,Gillu13/scipy,lhilt/scipy,apbard/scipy,bkendzior/scipy,niknow/scipy,apbard/scipy,mdhaber/scipy,jamestwebber/scipy,jjhelmus/scipy,tylerjereddy/scipy,gfyoung/scipy,e-q/scipy,nonhermitian/scipy,behzadnouri/scipy,gertingold/scipy,endolith/scipy,pizzathief/scipy,surhudm/scipy,bkendzior/scipy,maniteja123/scipy,grlee77/scipy,pbrod/scipy,vigna/scipy,bkendzior/scipy,scipy/scipy,mdhaber/scipy | from __future__ import division, print_function, absolute_import
_have_pil = True
try:
from scipy.misc.pilutil import imread as _imread
except ImportError:
_have_pil = False
__all__ = ['imread']
# Use the implementation of `imread` in `scipy.misc.pilutil.imread`.
# If it weren't for the different names of the first arguments of
# ndimage.io.imread and misc.pilutil.imread, we could simplify this file
# by writing
# from scipy.misc.pilutil import imread
# Unfortunately, because the argument names are different, that
# introduces a backwards incompatibility.
def imread(fname, flatten=False, mode=None):
if _have_pil:
return _imread(fname, flatten, mode)
raise ImportError("Could not import the Python Imaging Library (PIL)"
" required to load image files. Please refer to"
" http://pypi.python.org/pypi/PIL/ for installation"
" instructions.")
if _have_pil and _imread.__doc__ is not None:
imread.__doc__ = _imread.__doc__.replace('name : str', 'fname : str')
DOC: Update PIL error install URL
Update URL for PIL import error
to point to Pillow installation
instead of PIL, for the latter
is somewhat out of date and
does not even Python 3 at the
moment unlike Pillow.
Closes gh-5779. | from __future__ import division, print_function, absolute_import
_have_pil = True
try:
from scipy.misc.pilutil import imread as _imread
except ImportError:
_have_pil = False
__all__ = ['imread']
# Use the implementation of `imread` in `scipy.misc.pilutil.imread`.
# If it weren't for the different names of the first arguments of
# ndimage.io.imread and misc.pilutil.imread, we could simplify this file
# by writing
# from scipy.misc.pilutil import imread
# Unfortunately, because the argument names are different, that
# introduces a backwards incompatibility.
def imread(fname, flatten=False, mode=None):
if _have_pil:
return _imread(fname, flatten, mode)
raise ImportError("Could not import the Python Imaging Library (PIL)"
" required to load image files. Please refer to"
" http://pillow.readthedocs.org/en/latest/installation.html"
" for installation instructions.")
if _have_pil and _imread.__doc__ is not None:
imread.__doc__ = _imread.__doc__.replace('name : str', 'fname : str')
| <commit_before>from __future__ import division, print_function, absolute_import
_have_pil = True
try:
from scipy.misc.pilutil import imread as _imread
except ImportError:
_have_pil = False
__all__ = ['imread']
# Use the implementation of `imread` in `scipy.misc.pilutil.imread`.
# If it weren't for the different names of the first arguments of
# ndimage.io.imread and misc.pilutil.imread, we could simplify this file
# by writing
# from scipy.misc.pilutil import imread
# Unfortunately, because the argument names are different, that
# introduces a backwards incompatibility.
def imread(fname, flatten=False, mode=None):
if _have_pil:
return _imread(fname, flatten, mode)
raise ImportError("Could not import the Python Imaging Library (PIL)"
" required to load image files. Please refer to"
" http://pypi.python.org/pypi/PIL/ for installation"
" instructions.")
if _have_pil and _imread.__doc__ is not None:
imread.__doc__ = _imread.__doc__.replace('name : str', 'fname : str')
<commit_msg>DOC: Update PIL error install URL
Update URL for PIL import error
to point to Pillow installation
instead of PIL, for the latter
is somewhat out of date and
does not even Python 3 at the
moment unlike Pillow.
Closes gh-5779.<commit_after> | from __future__ import division, print_function, absolute_import
_have_pil = True
try:
from scipy.misc.pilutil import imread as _imread
except ImportError:
_have_pil = False
__all__ = ['imread']
# Use the implementation of `imread` in `scipy.misc.pilutil.imread`.
# If it weren't for the different names of the first arguments of
# ndimage.io.imread and misc.pilutil.imread, we could simplify this file
# by writing
# from scipy.misc.pilutil import imread
# Unfortunately, because the argument names are different, that
# introduces a backwards incompatibility.
def imread(fname, flatten=False, mode=None):
if _have_pil:
return _imread(fname, flatten, mode)
raise ImportError("Could not import the Python Imaging Library (PIL)"
" required to load image files. Please refer to"
" http://pillow.readthedocs.org/en/latest/installation.html"
" for installation instructions.")
if _have_pil and _imread.__doc__ is not None:
imread.__doc__ = _imread.__doc__.replace('name : str', 'fname : str')
| from __future__ import division, print_function, absolute_import
_have_pil = True
try:
from scipy.misc.pilutil import imread as _imread
except ImportError:
_have_pil = False
__all__ = ['imread']
# Use the implementation of `imread` in `scipy.misc.pilutil.imread`.
# If it weren't for the different names of the first arguments of
# ndimage.io.imread and misc.pilutil.imread, we could simplify this file
# by writing
# from scipy.misc.pilutil import imread
# Unfortunately, because the argument names are different, that
# introduces a backwards incompatibility.
def imread(fname, flatten=False, mode=None):
if _have_pil:
return _imread(fname, flatten, mode)
raise ImportError("Could not import the Python Imaging Library (PIL)"
" required to load image files. Please refer to"
" http://pypi.python.org/pypi/PIL/ for installation"
" instructions.")
if _have_pil and _imread.__doc__ is not None:
imread.__doc__ = _imread.__doc__.replace('name : str', 'fname : str')
DOC: Update PIL error install URL
Update URL for PIL import error
to point to Pillow installation
instead of PIL, for the latter
is somewhat out of date and
does not even Python 3 at the
moment unlike Pillow.
Closes gh-5779.from __future__ import division, print_function, absolute_import
_have_pil = True
try:
from scipy.misc.pilutil import imread as _imread
except ImportError:
_have_pil = False
__all__ = ['imread']
# Use the implementation of `imread` in `scipy.misc.pilutil.imread`.
# If it weren't for the different names of the first arguments of
# ndimage.io.imread and misc.pilutil.imread, we could simplify this file
# by writing
# from scipy.misc.pilutil import imread
# Unfortunately, because the argument names are different, that
# introduces a backwards incompatibility.
def imread(fname, flatten=False, mode=None):
if _have_pil:
return _imread(fname, flatten, mode)
raise ImportError("Could not import the Python Imaging Library (PIL)"
" required to load image files. Please refer to"
" http://pillow.readthedocs.org/en/latest/installation.html"
" for installation instructions.")
if _have_pil and _imread.__doc__ is not None:
imread.__doc__ = _imread.__doc__.replace('name : str', 'fname : str')
| <commit_before>from __future__ import division, print_function, absolute_import
_have_pil = True
try:
from scipy.misc.pilutil import imread as _imread
except ImportError:
_have_pil = False
__all__ = ['imread']
# Use the implementation of `imread` in `scipy.misc.pilutil.imread`.
# If it weren't for the different names of the first arguments of
# ndimage.io.imread and misc.pilutil.imread, we could simplify this file
# by writing
# from scipy.misc.pilutil import imread
# Unfortunately, because the argument names are different, that
# introduces a backwards incompatibility.
def imread(fname, flatten=False, mode=None):
if _have_pil:
return _imread(fname, flatten, mode)
raise ImportError("Could not import the Python Imaging Library (PIL)"
" required to load image files. Please refer to"
" http://pypi.python.org/pypi/PIL/ for installation"
" instructions.")
if _have_pil and _imread.__doc__ is not None:
imread.__doc__ = _imread.__doc__.replace('name : str', 'fname : str')
<commit_msg>DOC: Update PIL error install URL
Update URL for PIL import error
to point to Pillow installation
instead of PIL, for the latter
is somewhat out of date and
does not even Python 3 at the
moment unlike Pillow.
Closes gh-5779.<commit_after>from __future__ import division, print_function, absolute_import
_have_pil = True
try:
from scipy.misc.pilutil import imread as _imread
except ImportError:
_have_pil = False
__all__ = ['imread']
# Use the implementation of `imread` in `scipy.misc.pilutil.imread`.
# If it weren't for the different names of the first arguments of
# ndimage.io.imread and misc.pilutil.imread, we could simplify this file
# by writing
# from scipy.misc.pilutil import imread
# Unfortunately, because the argument names are different, that
# introduces a backwards incompatibility.
def imread(fname, flatten=False, mode=None):
if _have_pil:
return _imread(fname, flatten, mode)
raise ImportError("Could not import the Python Imaging Library (PIL)"
" required to load image files. Please refer to"
" http://pillow.readthedocs.org/en/latest/installation.html"
" for installation instructions.")
if _have_pil and _imread.__doc__ is not None:
imread.__doc__ = _imread.__doc__.replace('name : str', 'fname : str')
|
115197d42b380ae65de75d74a4d28933eb8defde | testproj/testproj/testapp/models.py | testproj/testproj/testapp/models.py | from django.db import models
from django.utils import timezone
class SecretFile(models.Model):
filename = models.CharField(max_length=255, blank=True, null=True)
order = models.IntegerField(blank=True, null=True)
size = models.PositiveIntegerField(blank=True, null=True)
created_on = models.DateTimeField(default=timezone.now)
is_secret = models.BooleanField()
def __unicode__(self):
return "#%d %s" % (self.pk, self.filename)
| from django.db import models
from django.utils import timezone
class SecretFile(models.Model):
filename = models.CharField(max_length=255, blank=True, null=True)
order = models.IntegerField(blank=True, null=True)
size = models.PositiveIntegerField(blank=True, null=True)
created_on = models.DateTimeField(default=timezone.now)
is_secret = models.BooleanField(default=False)
def __unicode__(self):
return "#%d %s" % (self.pk, self.filename)
| Fix warning about default value for boolean field | Fix warning about default value for boolean field
| Python | bsd-3-clause | artscoop/webstack-django-sorting,artscoop/webstack-django-sorting | from django.db import models
from django.utils import timezone
class SecretFile(models.Model):
filename = models.CharField(max_length=255, blank=True, null=True)
order = models.IntegerField(blank=True, null=True)
size = models.PositiveIntegerField(blank=True, null=True)
created_on = models.DateTimeField(default=timezone.now)
is_secret = models.BooleanField()
def __unicode__(self):
return "#%d %s" % (self.pk, self.filename)
Fix warning about default value for boolean field | from django.db import models
from django.utils import timezone
class SecretFile(models.Model):
filename = models.CharField(max_length=255, blank=True, null=True)
order = models.IntegerField(blank=True, null=True)
size = models.PositiveIntegerField(blank=True, null=True)
created_on = models.DateTimeField(default=timezone.now)
is_secret = models.BooleanField(default=False)
def __unicode__(self):
return "#%d %s" % (self.pk, self.filename)
| <commit_before>from django.db import models
from django.utils import timezone
class SecretFile(models.Model):
filename = models.CharField(max_length=255, blank=True, null=True)
order = models.IntegerField(blank=True, null=True)
size = models.PositiveIntegerField(blank=True, null=True)
created_on = models.DateTimeField(default=timezone.now)
is_secret = models.BooleanField()
def __unicode__(self):
return "#%d %s" % (self.pk, self.filename)
<commit_msg>Fix warning about default value for boolean field<commit_after> | from django.db import models
from django.utils import timezone
class SecretFile(models.Model):
filename = models.CharField(max_length=255, blank=True, null=True)
order = models.IntegerField(blank=True, null=True)
size = models.PositiveIntegerField(blank=True, null=True)
created_on = models.DateTimeField(default=timezone.now)
is_secret = models.BooleanField(default=False)
def __unicode__(self):
return "#%d %s" % (self.pk, self.filename)
| from django.db import models
from django.utils import timezone
class SecretFile(models.Model):
filename = models.CharField(max_length=255, blank=True, null=True)
order = models.IntegerField(blank=True, null=True)
size = models.PositiveIntegerField(blank=True, null=True)
created_on = models.DateTimeField(default=timezone.now)
is_secret = models.BooleanField()
def __unicode__(self):
return "#%d %s" % (self.pk, self.filename)
Fix warning about default value for boolean fieldfrom django.db import models
from django.utils import timezone
class SecretFile(models.Model):
filename = models.CharField(max_length=255, blank=True, null=True)
order = models.IntegerField(blank=True, null=True)
size = models.PositiveIntegerField(blank=True, null=True)
created_on = models.DateTimeField(default=timezone.now)
is_secret = models.BooleanField(default=False)
def __unicode__(self):
return "#%d %s" % (self.pk, self.filename)
| <commit_before>from django.db import models
from django.utils import timezone
class SecretFile(models.Model):
filename = models.CharField(max_length=255, blank=True, null=True)
order = models.IntegerField(blank=True, null=True)
size = models.PositiveIntegerField(blank=True, null=True)
created_on = models.DateTimeField(default=timezone.now)
is_secret = models.BooleanField()
def __unicode__(self):
return "#%d %s" % (self.pk, self.filename)
<commit_msg>Fix warning about default value for boolean field<commit_after>from django.db import models
from django.utils import timezone
class SecretFile(models.Model):
filename = models.CharField(max_length=255, blank=True, null=True)
order = models.IntegerField(blank=True, null=True)
size = models.PositiveIntegerField(blank=True, null=True)
created_on = models.DateTimeField(default=timezone.now)
is_secret = models.BooleanField(default=False)
def __unicode__(self):
return "#%d %s" % (self.pk, self.filename)
|
f0b4b954b8562f621caba98317f03a63d0d01c83 | globus_sdk/version.py | globus_sdk/version.py | # single source of truth for package version,
# see https://packaging.python.org/en/latest/single_source_version/
__version__ = "1.3.0"
| # single source of truth for package version,
# see https://packaging.python.org/en/latest/single_source_version/
__version__ = "1.4.0"
| Update to v1.4.0 for release | Update to v1.4.0 for release
Changelog:
- #261 Add OAuthTokenResponse.by_scopes
- #257, #260 Make `cryptography` a strict requirement,
`globus-sdk[jwt]` is no longer neecessary
- #255 Simplify OAuthTokenResponse.decode_id_token to not require the
client as an argument
- #259 Add (beta) SearchClient class
| Python | apache-2.0 | sirosen/globus-sdk-python,globus/globus-sdk-python,globusonline/globus-sdk-python,globus/globus-sdk-python | # single source of truth for package version,
# see https://packaging.python.org/en/latest/single_source_version/
__version__ = "1.3.0"
Update to v1.4.0 for release
Changelog:
- #261 Add OAuthTokenResponse.by_scopes
- #257, #260 Make `cryptography` a strict requirement,
`globus-sdk[jwt]` is no longer neecessary
- #255 Simplify OAuthTokenResponse.decode_id_token to not require the
client as an argument
- #259 Add (beta) SearchClient class | # single source of truth for package version,
# see https://packaging.python.org/en/latest/single_source_version/
__version__ = "1.4.0"
| <commit_before># single source of truth for package version,
# see https://packaging.python.org/en/latest/single_source_version/
__version__ = "1.3.0"
<commit_msg>Update to v1.4.0 for release
Changelog:
- #261 Add OAuthTokenResponse.by_scopes
- #257, #260 Make `cryptography` a strict requirement,
`globus-sdk[jwt]` is no longer neecessary
- #255 Simplify OAuthTokenResponse.decode_id_token to not require the
client as an argument
- #259 Add (beta) SearchClient class<commit_after> | # single source of truth for package version,
# see https://packaging.python.org/en/latest/single_source_version/
__version__ = "1.4.0"
| # single source of truth for package version,
# see https://packaging.python.org/en/latest/single_source_version/
__version__ = "1.3.0"
Update to v1.4.0 for release
Changelog:
- #261 Add OAuthTokenResponse.by_scopes
- #257, #260 Make `cryptography` a strict requirement,
`globus-sdk[jwt]` is no longer neecessary
- #255 Simplify OAuthTokenResponse.decode_id_token to not require the
client as an argument
- #259 Add (beta) SearchClient class# single source of truth for package version,
# see https://packaging.python.org/en/latest/single_source_version/
__version__ = "1.4.0"
| <commit_before># single source of truth for package version,
# see https://packaging.python.org/en/latest/single_source_version/
__version__ = "1.3.0"
<commit_msg>Update to v1.4.0 for release
Changelog:
- #261 Add OAuthTokenResponse.by_scopes
- #257, #260 Make `cryptography` a strict requirement,
`globus-sdk[jwt]` is no longer neecessary
- #255 Simplify OAuthTokenResponse.decode_id_token to not require the
client as an argument
- #259 Add (beta) SearchClient class<commit_after># single source of truth for package version,
# see https://packaging.python.org/en/latest/single_source_version/
__version__ = "1.4.0"
|
d017a5daeb6849975e57d81246680f9b4e161757 | popit/test_settings.py | popit/test_settings.py | """Settings that need to be set in order to run the tests."""
import os
DEBUG = True
USE_TZ = True
SITE_ID = 1
SECRET_KEY = '...something secure here...'
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "popit-django",
}
}
ROOT_URLCONF = 'popit.tests.urls'
CURRENT_DIR = os.path.dirname(__file__)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(CURRENT_DIR, '../../static/')
STATICFILES_DIRS = (
os.path.join(CURRENT_DIR, 'test_static'),
)
TEMPLATE_DIRS = (
os.path.join(CURRENT_DIR, '../templates'),
)
INSTALLED_APPS = [
'south',
'popit',
]
# Testing related
TEST_POPIT_API_URL = 'http://localhost:3000/api'
| """Settings that need to be set in order to run the tests."""
import os
DEBUG = True
USE_TZ = True
SITE_ID = 1
SECRET_KEY = '...something secure here...'
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "popit-django",
}
}
ROOT_URLCONF = 'popit.tests.urls'
CURRENT_DIR = os.path.dirname(__file__)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(CURRENT_DIR, '../../static/')
STATICFILES_DIRS = (
os.path.join(CURRENT_DIR, 'test_static'),
)
TEMPLATE_DIRS = (
os.path.join(CURRENT_DIR, '../templates'),
)
INSTALLED_APPS = [
'south',
'popit',
]
# Testing related
TEST_POPIT_API_HOST_IP = '127.0.0.1'
TEST_POPIT_API_PORT = '3000'
TEST_POPIT_API_SUBDOMAIN = 'popit-django-test'
# create the url to use for testing the database.
# See http://xip.io/ for details on the domain used.
TEST_POPIT_API_URL = "http://%s.%s.xip.io:%s/api" % ( TEST_POPIT_API_SUBDOMAIN,
TEST_POPIT_API_HOST_IP,
TEST_POPIT_API_PORT )
# If you want to create a test entry this is useful:
# curl \
# -v \
# -H "Content-type: application/json" \
# -X POST \
# -d ' {"name": "Joe Bloggs"}' \
# http://popit-django-test.127.0.0.1.xip.io:3000/api/persons/
| Put more bits into the settings for the PopIt API | Put more bits into the settings for the PopIt API
| Python | agpl-3.0 | mysociety/popit-django,mysociety/popit-django,ciudadanointeligente/popit-django,mysociety/popit-django,ciudadanointeligente/popit-django,ciudadanointeligente/popit-django | """Settings that need to be set in order to run the tests."""
import os
DEBUG = True
USE_TZ = True
SITE_ID = 1
SECRET_KEY = '...something secure here...'
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "popit-django",
}
}
ROOT_URLCONF = 'popit.tests.urls'
CURRENT_DIR = os.path.dirname(__file__)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(CURRENT_DIR, '../../static/')
STATICFILES_DIRS = (
os.path.join(CURRENT_DIR, 'test_static'),
)
TEMPLATE_DIRS = (
os.path.join(CURRENT_DIR, '../templates'),
)
INSTALLED_APPS = [
'south',
'popit',
]
# Testing related
TEST_POPIT_API_URL = 'http://localhost:3000/api'
Put more bits into the settings for the PopIt API | """Settings that need to be set in order to run the tests."""
import os
DEBUG = True
USE_TZ = True
SITE_ID = 1
SECRET_KEY = '...something secure here...'
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "popit-django",
}
}
ROOT_URLCONF = 'popit.tests.urls'
CURRENT_DIR = os.path.dirname(__file__)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(CURRENT_DIR, '../../static/')
STATICFILES_DIRS = (
os.path.join(CURRENT_DIR, 'test_static'),
)
TEMPLATE_DIRS = (
os.path.join(CURRENT_DIR, '../templates'),
)
INSTALLED_APPS = [
'south',
'popit',
]
# Testing related
TEST_POPIT_API_HOST_IP = '127.0.0.1'
TEST_POPIT_API_PORT = '3000'
TEST_POPIT_API_SUBDOMAIN = 'popit-django-test'
# create the url to use for testing the database.
# See http://xip.io/ for details on the domain used.
TEST_POPIT_API_URL = "http://%s.%s.xip.io:%s/api" % ( TEST_POPIT_API_SUBDOMAIN,
TEST_POPIT_API_HOST_IP,
TEST_POPIT_API_PORT )
# If you want to create a test entry this is useful:
# curl \
# -v \
# -H "Content-type: application/json" \
# -X POST \
# -d ' {"name": "Joe Bloggs"}' \
# http://popit-django-test.127.0.0.1.xip.io:3000/api/persons/
| <commit_before>"""Settings that need to be set in order to run the tests."""
import os
DEBUG = True
USE_TZ = True
SITE_ID = 1
SECRET_KEY = '...something secure here...'
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "popit-django",
}
}
ROOT_URLCONF = 'popit.tests.urls'
CURRENT_DIR = os.path.dirname(__file__)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(CURRENT_DIR, '../../static/')
STATICFILES_DIRS = (
os.path.join(CURRENT_DIR, 'test_static'),
)
TEMPLATE_DIRS = (
os.path.join(CURRENT_DIR, '../templates'),
)
INSTALLED_APPS = [
'south',
'popit',
]
# Testing related
TEST_POPIT_API_URL = 'http://localhost:3000/api'
<commit_msg>Put more bits into the settings for the PopIt API<commit_after> | """Settings that need to be set in order to run the tests."""
import os
DEBUG = True
USE_TZ = True
SITE_ID = 1
SECRET_KEY = '...something secure here...'
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "popit-django",
}
}
ROOT_URLCONF = 'popit.tests.urls'
CURRENT_DIR = os.path.dirname(__file__)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(CURRENT_DIR, '../../static/')
STATICFILES_DIRS = (
os.path.join(CURRENT_DIR, 'test_static'),
)
TEMPLATE_DIRS = (
os.path.join(CURRENT_DIR, '../templates'),
)
INSTALLED_APPS = [
'south',
'popit',
]
# Testing related
TEST_POPIT_API_HOST_IP = '127.0.0.1'
TEST_POPIT_API_PORT = '3000'
TEST_POPIT_API_SUBDOMAIN = 'popit-django-test'
# create the url to use for testing the database.
# See http://xip.io/ for details on the domain used.
TEST_POPIT_API_URL = "http://%s.%s.xip.io:%s/api" % ( TEST_POPIT_API_SUBDOMAIN,
TEST_POPIT_API_HOST_IP,
TEST_POPIT_API_PORT )
# If you want to create a test entry this is useful:
# curl \
# -v \
# -H "Content-type: application/json" \
# -X POST \
# -d ' {"name": "Joe Bloggs"}' \
# http://popit-django-test.127.0.0.1.xip.io:3000/api/persons/
| """Settings that need to be set in order to run the tests."""
import os
DEBUG = True
USE_TZ = True
SITE_ID = 1
SECRET_KEY = '...something secure here...'
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "popit-django",
}
}
ROOT_URLCONF = 'popit.tests.urls'
CURRENT_DIR = os.path.dirname(__file__)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(CURRENT_DIR, '../../static/')
STATICFILES_DIRS = (
os.path.join(CURRENT_DIR, 'test_static'),
)
TEMPLATE_DIRS = (
os.path.join(CURRENT_DIR, '../templates'),
)
INSTALLED_APPS = [
'south',
'popit',
]
# Testing related
TEST_POPIT_API_URL = 'http://localhost:3000/api'
Put more bits into the settings for the PopIt API"""Settings that need to be set in order to run the tests."""
import os
DEBUG = True
USE_TZ = True
SITE_ID = 1
SECRET_KEY = '...something secure here...'
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "popit-django",
}
}
ROOT_URLCONF = 'popit.tests.urls'
CURRENT_DIR = os.path.dirname(__file__)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(CURRENT_DIR, '../../static/')
STATICFILES_DIRS = (
os.path.join(CURRENT_DIR, 'test_static'),
)
TEMPLATE_DIRS = (
os.path.join(CURRENT_DIR, '../templates'),
)
INSTALLED_APPS = [
'south',
'popit',
]
# Testing related
TEST_POPIT_API_HOST_IP = '127.0.0.1'
TEST_POPIT_API_PORT = '3000'
TEST_POPIT_API_SUBDOMAIN = 'popit-django-test'
# create the url to use for testing the database.
# See http://xip.io/ for details on the domain used.
TEST_POPIT_API_URL = "http://%s.%s.xip.io:%s/api" % ( TEST_POPIT_API_SUBDOMAIN,
TEST_POPIT_API_HOST_IP,
TEST_POPIT_API_PORT )
# If you want to create a test entry this is useful:
# curl \
# -v \
# -H "Content-type: application/json" \
# -X POST \
# -d ' {"name": "Joe Bloggs"}' \
# http://popit-django-test.127.0.0.1.xip.io:3000/api/persons/
| <commit_before>"""Settings that need to be set in order to run the tests."""
import os
DEBUG = True
USE_TZ = True
SITE_ID = 1
SECRET_KEY = '...something secure here...'
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "popit-django",
}
}
ROOT_URLCONF = 'popit.tests.urls'
CURRENT_DIR = os.path.dirname(__file__)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(CURRENT_DIR, '../../static/')
STATICFILES_DIRS = (
os.path.join(CURRENT_DIR, 'test_static'),
)
TEMPLATE_DIRS = (
os.path.join(CURRENT_DIR, '../templates'),
)
INSTALLED_APPS = [
'south',
'popit',
]
# Testing related
TEST_POPIT_API_URL = 'http://localhost:3000/api'
<commit_msg>Put more bits into the settings for the PopIt API<commit_after>"""Settings that need to be set in order to run the tests."""
import os
DEBUG = True
USE_TZ = True
SITE_ID = 1
SECRET_KEY = '...something secure here...'
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "popit-django",
}
}
ROOT_URLCONF = 'popit.tests.urls'
CURRENT_DIR = os.path.dirname(__file__)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(CURRENT_DIR, '../../static/')
STATICFILES_DIRS = (
os.path.join(CURRENT_DIR, 'test_static'),
)
TEMPLATE_DIRS = (
os.path.join(CURRENT_DIR, '../templates'),
)
INSTALLED_APPS = [
'south',
'popit',
]
# Testing related
TEST_POPIT_API_HOST_IP = '127.0.0.1'
TEST_POPIT_API_PORT = '3000'
TEST_POPIT_API_SUBDOMAIN = 'popit-django-test'
# create the url to use for testing the database.
# See http://xip.io/ for details on the domain used.
TEST_POPIT_API_URL = "http://%s.%s.xip.io:%s/api" % ( TEST_POPIT_API_SUBDOMAIN,
TEST_POPIT_API_HOST_IP,
TEST_POPIT_API_PORT )
# If you want to create a test entry this is useful:
# curl \
# -v \
# -H "Content-type: application/json" \
# -X POST \
# -d ' {"name": "Joe Bloggs"}' \
# http://popit-django-test.127.0.0.1.xip.io:3000/api/persons/
|
e5fd0b527877f5fab1d1a2e76ce32062a4a8d697 | bika/lims/browser/batch/samples.py | bika/lims/browser/batch/samples.py | from bika.lims.browser.sample import SamplesView as _SV
from bika.lims.permissions import *
from Products.CMFCore.utils import getToolByName
from zope.interface import implements
from Products.CMFPlone.utils import safe_unicode
import plone
class SamplesView(_SV):
def __init__(self, context, request):
super(SamplesView, self).__init__(context, request)
self.view_url = self.context.absolute_url() + "/samples"
if 'path' in self.contentFilter:
del(self.contentFilter['path'])
def contentsMethod(self, contentFilter):
tool = getToolByName(self.context, self.catalog)
state = [x for x in self.review_states if x['id'] == self.review_state][0]
for k, v in state['contentFilter'].items():
self.contentFilter[k] = v
tool_samples = tool(contentFilter)
samples = {}
for sample in (p.getObject() for p in tool_samples):
for ar in sample.getAnalysisRequests():
if ar.getBatch().UID() == self.context.UID():
samples[sample.getId()] = sample
return samples.values()
| from bika.lims.browser.sample import SamplesView as _SV
from bika.lims.permissions import *
from Products.CMFCore.utils import getToolByName
from zope.interface import implements
from Products.CMFPlone.utils import safe_unicode
import plone
class SamplesView(_SV):
def __init__(self, context, request):
super(SamplesView, self).__init__(context, request)
self.view_url = self.context.absolute_url() + "/samples"
if 'path' in self.contentFilter:
del(self.contentFilter['path'])
def contentsMethod(self, contentFilter):
tool = getToolByName(self.context, self.catalog)
state = [x for x in self.review_states if x['id'] == self.review_state][0]
for k, v in state['contentFilter'].items():
self.contentFilter[k] = v
tool_samples = tool(contentFilter)
samples = {}
for sample in (p.getObject() for p in tool_samples):
for ar in sample.getAnalysisRequests():
batch = ar.getBatch()
if batch and ar.getBatch().UID() == self.context.UID():
samples[sample.getId()] = sample
return samples.values()
| Fix exception - batch is not required field of AR | Fix exception - batch is not required field of AR
| Python | agpl-3.0 | DeBortoliWines/Bika-LIMS,anneline/Bika-LIMS,labsanmartin/Bika-LIMS,rockfruit/bika.lims,anneline/Bika-LIMS,labsanmartin/Bika-LIMS,veroc/Bika-LIMS,anneline/Bika-LIMS,DeBortoliWines/Bika-LIMS,veroc/Bika-LIMS,veroc/Bika-LIMS,labsanmartin/Bika-LIMS,DeBortoliWines/Bika-LIMS,rockfruit/bika.lims | from bika.lims.browser.sample import SamplesView as _SV
from bika.lims.permissions import *
from Products.CMFCore.utils import getToolByName
from zope.interface import implements
from Products.CMFPlone.utils import safe_unicode
import plone
class SamplesView(_SV):
def __init__(self, context, request):
super(SamplesView, self).__init__(context, request)
self.view_url = self.context.absolute_url() + "/samples"
if 'path' in self.contentFilter:
del(self.contentFilter['path'])
def contentsMethod(self, contentFilter):
tool = getToolByName(self.context, self.catalog)
state = [x for x in self.review_states if x['id'] == self.review_state][0]
for k, v in state['contentFilter'].items():
self.contentFilter[k] = v
tool_samples = tool(contentFilter)
samples = {}
for sample in (p.getObject() for p in tool_samples):
for ar in sample.getAnalysisRequests():
if ar.getBatch().UID() == self.context.UID():
samples[sample.getId()] = sample
return samples.values()
Fix exception - batch is not required field of AR | from bika.lims.browser.sample import SamplesView as _SV
from bika.lims.permissions import *
from Products.CMFCore.utils import getToolByName
from zope.interface import implements
from Products.CMFPlone.utils import safe_unicode
import plone
class SamplesView(_SV):
def __init__(self, context, request):
super(SamplesView, self).__init__(context, request)
self.view_url = self.context.absolute_url() + "/samples"
if 'path' in self.contentFilter:
del(self.contentFilter['path'])
def contentsMethod(self, contentFilter):
tool = getToolByName(self.context, self.catalog)
state = [x for x in self.review_states if x['id'] == self.review_state][0]
for k, v in state['contentFilter'].items():
self.contentFilter[k] = v
tool_samples = tool(contentFilter)
samples = {}
for sample in (p.getObject() for p in tool_samples):
for ar in sample.getAnalysisRequests():
batch = ar.getBatch()
if batch and ar.getBatch().UID() == self.context.UID():
samples[sample.getId()] = sample
return samples.values()
| <commit_before>from bika.lims.browser.sample import SamplesView as _SV
from bika.lims.permissions import *
from Products.CMFCore.utils import getToolByName
from zope.interface import implements
from Products.CMFPlone.utils import safe_unicode
import plone
class SamplesView(_SV):
def __init__(self, context, request):
super(SamplesView, self).__init__(context, request)
self.view_url = self.context.absolute_url() + "/samples"
if 'path' in self.contentFilter:
del(self.contentFilter['path'])
def contentsMethod(self, contentFilter):
tool = getToolByName(self.context, self.catalog)
state = [x for x in self.review_states if x['id'] == self.review_state][0]
for k, v in state['contentFilter'].items():
self.contentFilter[k] = v
tool_samples = tool(contentFilter)
samples = {}
for sample in (p.getObject() for p in tool_samples):
for ar in sample.getAnalysisRequests():
if ar.getBatch().UID() == self.context.UID():
samples[sample.getId()] = sample
return samples.values()
<commit_msg>Fix exception - batch is not required field of AR<commit_after> | from bika.lims.browser.sample import SamplesView as _SV
from bika.lims.permissions import *
from Products.CMFCore.utils import getToolByName
from zope.interface import implements
from Products.CMFPlone.utils import safe_unicode
import plone
class SamplesView(_SV):
def __init__(self, context, request):
super(SamplesView, self).__init__(context, request)
self.view_url = self.context.absolute_url() + "/samples"
if 'path' in self.contentFilter:
del(self.contentFilter['path'])
def contentsMethod(self, contentFilter):
tool = getToolByName(self.context, self.catalog)
state = [x for x in self.review_states if x['id'] == self.review_state][0]
for k, v in state['contentFilter'].items():
self.contentFilter[k] = v
tool_samples = tool(contentFilter)
samples = {}
for sample in (p.getObject() for p in tool_samples):
for ar in sample.getAnalysisRequests():
batch = ar.getBatch()
if batch and ar.getBatch().UID() == self.context.UID():
samples[sample.getId()] = sample
return samples.values()
| from bika.lims.browser.sample import SamplesView as _SV
from bika.lims.permissions import *
from Products.CMFCore.utils import getToolByName
from zope.interface import implements
from Products.CMFPlone.utils import safe_unicode
import plone
class SamplesView(_SV):
def __init__(self, context, request):
super(SamplesView, self).__init__(context, request)
self.view_url = self.context.absolute_url() + "/samples"
if 'path' in self.contentFilter:
del(self.contentFilter['path'])
def contentsMethod(self, contentFilter):
tool = getToolByName(self.context, self.catalog)
state = [x for x in self.review_states if x['id'] == self.review_state][0]
for k, v in state['contentFilter'].items():
self.contentFilter[k] = v
tool_samples = tool(contentFilter)
samples = {}
for sample in (p.getObject() for p in tool_samples):
for ar in sample.getAnalysisRequests():
if ar.getBatch().UID() == self.context.UID():
samples[sample.getId()] = sample
return samples.values()
Fix exception - batch is not required field of ARfrom bika.lims.browser.sample import SamplesView as _SV
from bika.lims.permissions import *
from Products.CMFCore.utils import getToolByName
from zope.interface import implements
from Products.CMFPlone.utils import safe_unicode
import plone
class SamplesView(_SV):
def __init__(self, context, request):
super(SamplesView, self).__init__(context, request)
self.view_url = self.context.absolute_url() + "/samples"
if 'path' in self.contentFilter:
del(self.contentFilter['path'])
def contentsMethod(self, contentFilter):
tool = getToolByName(self.context, self.catalog)
state = [x for x in self.review_states if x['id'] == self.review_state][0]
for k, v in state['contentFilter'].items():
self.contentFilter[k] = v
tool_samples = tool(contentFilter)
samples = {}
for sample in (p.getObject() for p in tool_samples):
for ar in sample.getAnalysisRequests():
batch = ar.getBatch()
if batch and ar.getBatch().UID() == self.context.UID():
samples[sample.getId()] = sample
return samples.values()
| <commit_before>from bika.lims.browser.sample import SamplesView as _SV
from bika.lims.permissions import *
from Products.CMFCore.utils import getToolByName
from zope.interface import implements
from Products.CMFPlone.utils import safe_unicode
import plone
class SamplesView(_SV):
def __init__(self, context, request):
super(SamplesView, self).__init__(context, request)
self.view_url = self.context.absolute_url() + "/samples"
if 'path' in self.contentFilter:
del(self.contentFilter['path'])
def contentsMethod(self, contentFilter):
tool = getToolByName(self.context, self.catalog)
state = [x for x in self.review_states if x['id'] == self.review_state][0]
for k, v in state['contentFilter'].items():
self.contentFilter[k] = v
tool_samples = tool(contentFilter)
samples = {}
for sample in (p.getObject() for p in tool_samples):
for ar in sample.getAnalysisRequests():
if ar.getBatch().UID() == self.context.UID():
samples[sample.getId()] = sample
return samples.values()
<commit_msg>Fix exception - batch is not required field of AR<commit_after>from bika.lims.browser.sample import SamplesView as _SV
from bika.lims.permissions import *
from Products.CMFCore.utils import getToolByName
from zope.interface import implements
from Products.CMFPlone.utils import safe_unicode
import plone
class SamplesView(_SV):
def __init__(self, context, request):
super(SamplesView, self).__init__(context, request)
self.view_url = self.context.absolute_url() + "/samples"
if 'path' in self.contentFilter:
del(self.contentFilter['path'])
def contentsMethod(self, contentFilter):
tool = getToolByName(self.context, self.catalog)
state = [x for x in self.review_states if x['id'] == self.review_state][0]
for k, v in state['contentFilter'].items():
self.contentFilter[k] = v
tool_samples = tool(contentFilter)
samples = {}
for sample in (p.getObject() for p in tool_samples):
for ar in sample.getAnalysisRequests():
batch = ar.getBatch()
if batch and ar.getBatch().UID() == self.context.UID():
samples[sample.getId()] = sample
return samples.values()
|
e2f118ea3d1f9e092567802610915d76d083e9f7 | tests/scoring_engine/test_worker.py | tests/scoring_engine/test_worker.py | import sys
import os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../scoring_engine'))
from worker import Worker
from worker_queue import WorkerQueue
from job import Job
class TestWorker(object):
def test_init(self):
worker = Worker()
assert isinstance(worker.worker_queue, WorkerQueue) is True
def test_execute_simple_cmd(self):
worker = Worker()
job = Job(service_id="12345", command="echo 'HELLO'")
updated_job = worker.execute_cmd(job)
assert updated_job.output == "HELLO\n"
assert updated_job.completed() is True
assert updated_job.passed() is False
def test_execute_cmd_trigger_timeout(self):
worker = Worker()
timeout_time = 1
sleep_time = timeout_time + 1
job = Job(service_id="12345", command="sleep " + str(sleep_time))
updated_job = worker.execute_cmd(job, timeout_time)
assert updated_job.output is None
assert updated_job.reason == "Command Timed Out"
assert updated_job.passed() is False
assert updated_job.completed() is True
| import sys
import os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../scoring_engine'))
from worker import Worker
from worker_queue import WorkerQueue
from job import Job
class TestWorker(object):
def setup(self):
self.worker = Worker()
def test_init(self):
assert isinstance(self.worker.worker_queue, WorkerQueue) is True
def test_execute_simple_cmd(self):
job = Job(service_id="12345", command="echo 'HELLO'")
updated_job = self.worker.execute_cmd(job)
assert updated_job.output == "HELLO\n"
assert updated_job.completed() is True
assert updated_job.passed() is False
def test_execute_cmd_trigger_timeout(self):
timeout_time = 1
sleep_time = timeout_time + 1
job = Job(service_id="12345", command="sleep " + str(sleep_time))
updated_job = self.worker.execute_cmd(job, timeout_time)
assert updated_job.output is None
assert updated_job.reason == "Command Timed Out"
assert updated_job.passed() is False
assert updated_job.completed() is True
| Modify test worker unit test | Modify test worker unit test
Signed-off-by: Brandon Myers <9cda508be11a1ae7ceef912b85c196946f0ec5f3@mozilla.com>
| Python | mit | pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine | import sys
import os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../scoring_engine'))
from worker import Worker
from worker_queue import WorkerQueue
from job import Job
class TestWorker(object):
def test_init(self):
worker = Worker()
assert isinstance(worker.worker_queue, WorkerQueue) is True
def test_execute_simple_cmd(self):
worker = Worker()
job = Job(service_id="12345", command="echo 'HELLO'")
updated_job = worker.execute_cmd(job)
assert updated_job.output == "HELLO\n"
assert updated_job.completed() is True
assert updated_job.passed() is False
def test_execute_cmd_trigger_timeout(self):
worker = Worker()
timeout_time = 1
sleep_time = timeout_time + 1
job = Job(service_id="12345", command="sleep " + str(sleep_time))
updated_job = worker.execute_cmd(job, timeout_time)
assert updated_job.output is None
assert updated_job.reason == "Command Timed Out"
assert updated_job.passed() is False
assert updated_job.completed() is True
Modify test worker unit test
Signed-off-by: Brandon Myers <9cda508be11a1ae7ceef912b85c196946f0ec5f3@mozilla.com> | import sys
import os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../scoring_engine'))
from worker import Worker
from worker_queue import WorkerQueue
from job import Job
class TestWorker(object):
def setup(self):
self.worker = Worker()
def test_init(self):
assert isinstance(self.worker.worker_queue, WorkerQueue) is True
def test_execute_simple_cmd(self):
job = Job(service_id="12345", command="echo 'HELLO'")
updated_job = self.worker.execute_cmd(job)
assert updated_job.output == "HELLO\n"
assert updated_job.completed() is True
assert updated_job.passed() is False
def test_execute_cmd_trigger_timeout(self):
timeout_time = 1
sleep_time = timeout_time + 1
job = Job(service_id="12345", command="sleep " + str(sleep_time))
updated_job = self.worker.execute_cmd(job, timeout_time)
assert updated_job.output is None
assert updated_job.reason == "Command Timed Out"
assert updated_job.passed() is False
assert updated_job.completed() is True
| <commit_before>import sys
import os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../scoring_engine'))
from worker import Worker
from worker_queue import WorkerQueue
from job import Job
class TestWorker(object):
def test_init(self):
worker = Worker()
assert isinstance(worker.worker_queue, WorkerQueue) is True
def test_execute_simple_cmd(self):
worker = Worker()
job = Job(service_id="12345", command="echo 'HELLO'")
updated_job = worker.execute_cmd(job)
assert updated_job.output == "HELLO\n"
assert updated_job.completed() is True
assert updated_job.passed() is False
def test_execute_cmd_trigger_timeout(self):
worker = Worker()
timeout_time = 1
sleep_time = timeout_time + 1
job = Job(service_id="12345", command="sleep " + str(sleep_time))
updated_job = worker.execute_cmd(job, timeout_time)
assert updated_job.output is None
assert updated_job.reason == "Command Timed Out"
assert updated_job.passed() is False
assert updated_job.completed() is True
<commit_msg>Modify test worker unit test
Signed-off-by: Brandon Myers <9cda508be11a1ae7ceef912b85c196946f0ec5f3@mozilla.com><commit_after> | import sys
import os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../scoring_engine'))
from worker import Worker
from worker_queue import WorkerQueue
from job import Job
class TestWorker(object):
def setup(self):
self.worker = Worker()
def test_init(self):
assert isinstance(self.worker.worker_queue, WorkerQueue) is True
def test_execute_simple_cmd(self):
job = Job(service_id="12345", command="echo 'HELLO'")
updated_job = self.worker.execute_cmd(job)
assert updated_job.output == "HELLO\n"
assert updated_job.completed() is True
assert updated_job.passed() is False
def test_execute_cmd_trigger_timeout(self):
timeout_time = 1
sleep_time = timeout_time + 1
job = Job(service_id="12345", command="sleep " + str(sleep_time))
updated_job = self.worker.execute_cmd(job, timeout_time)
assert updated_job.output is None
assert updated_job.reason == "Command Timed Out"
assert updated_job.passed() is False
assert updated_job.completed() is True
| import sys
import os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../scoring_engine'))
from worker import Worker
from worker_queue import WorkerQueue
from job import Job
class TestWorker(object):
def test_init(self):
worker = Worker()
assert isinstance(worker.worker_queue, WorkerQueue) is True
def test_execute_simple_cmd(self):
worker = Worker()
job = Job(service_id="12345", command="echo 'HELLO'")
updated_job = worker.execute_cmd(job)
assert updated_job.output == "HELLO\n"
assert updated_job.completed() is True
assert updated_job.passed() is False
def test_execute_cmd_trigger_timeout(self):
worker = Worker()
timeout_time = 1
sleep_time = timeout_time + 1
job = Job(service_id="12345", command="sleep " + str(sleep_time))
updated_job = worker.execute_cmd(job, timeout_time)
assert updated_job.output is None
assert updated_job.reason == "Command Timed Out"
assert updated_job.passed() is False
assert updated_job.completed() is True
Modify test worker unit test
Signed-off-by: Brandon Myers <9cda508be11a1ae7ceef912b85c196946f0ec5f3@mozilla.com>import sys
import os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../scoring_engine'))
from worker import Worker
from worker_queue import WorkerQueue
from job import Job
class TestWorker(object):
def setup(self):
self.worker = Worker()
def test_init(self):
assert isinstance(self.worker.worker_queue, WorkerQueue) is True
def test_execute_simple_cmd(self):
job = Job(service_id="12345", command="echo 'HELLO'")
updated_job = self.worker.execute_cmd(job)
assert updated_job.output == "HELLO\n"
assert updated_job.completed() is True
assert updated_job.passed() is False
def test_execute_cmd_trigger_timeout(self):
timeout_time = 1
sleep_time = timeout_time + 1
job = Job(service_id="12345", command="sleep " + str(sleep_time))
updated_job = self.worker.execute_cmd(job, timeout_time)
assert updated_job.output is None
assert updated_job.reason == "Command Timed Out"
assert updated_job.passed() is False
assert updated_job.completed() is True
| <commit_before>import sys
import os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../scoring_engine'))
from worker import Worker
from worker_queue import WorkerQueue
from job import Job
class TestWorker(object):
def test_init(self):
worker = Worker()
assert isinstance(worker.worker_queue, WorkerQueue) is True
def test_execute_simple_cmd(self):
worker = Worker()
job = Job(service_id="12345", command="echo 'HELLO'")
updated_job = worker.execute_cmd(job)
assert updated_job.output == "HELLO\n"
assert updated_job.completed() is True
assert updated_job.passed() is False
def test_execute_cmd_trigger_timeout(self):
worker = Worker()
timeout_time = 1
sleep_time = timeout_time + 1
job = Job(service_id="12345", command="sleep " + str(sleep_time))
updated_job = worker.execute_cmd(job, timeout_time)
assert updated_job.output is None
assert updated_job.reason == "Command Timed Out"
assert updated_job.passed() is False
assert updated_job.completed() is True
<commit_msg>Modify test worker unit test
Signed-off-by: Brandon Myers <9cda508be11a1ae7ceef912b85c196946f0ec5f3@mozilla.com><commit_after>import sys
import os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../scoring_engine'))
from worker import Worker
from worker_queue import WorkerQueue
from job import Job
class TestWorker(object):
def setup(self):
self.worker = Worker()
def test_init(self):
assert isinstance(self.worker.worker_queue, WorkerQueue) is True
def test_execute_simple_cmd(self):
job = Job(service_id="12345", command="echo 'HELLO'")
updated_job = self.worker.execute_cmd(job)
assert updated_job.output == "HELLO\n"
assert updated_job.completed() is True
assert updated_job.passed() is False
def test_execute_cmd_trigger_timeout(self):
timeout_time = 1
sleep_time = timeout_time + 1
job = Job(service_id="12345", command="sleep " + str(sleep_time))
updated_job = self.worker.execute_cmd(job, timeout_time)
assert updated_job.output is None
assert updated_job.reason == "Command Timed Out"
assert updated_job.passed() is False
assert updated_job.completed() is True
|
12dc601f18c000630081694cdad461a33db96f64 | django_backend_test/django_backend_test/__init__.py | django_backend_test/django_backend_test/__init__.py | from __future__ import absolute_import
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app # noqa | Update init file to start celery | Update init file to start celery
| Python | mit | semorale/backend-test,semorale/backend-test,semorale/backend-test | Update init file to start celery | from __future__ import absolute_import
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app # noqa | <commit_before><commit_msg>Update init file to start celery<commit_after> | from __future__ import absolute_import
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app # noqa | Update init file to start celeryfrom __future__ import absolute_import
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app # noqa | <commit_before><commit_msg>Update init file to start celery<commit_after>from __future__ import absolute_import
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app # noqa | |
0a8350d98005ef25ea1de4b743d6346bbae9b173 | citrination_client/base/errors.py | citrination_client/base/errors.py | class CitrinationClientError(Exception):
pass
class APIVersionMismatchException(CitrinationClientError):
def __init__(self, message="Version mismatch with Citrination identified. Please check for available PyCC updates"):
super(APIVersionMismatchException, self).__init__(message)
class FeatureUnavailableException(CitrinationClientError):
def __init__(self, message="Access to an unauthorized resource requested"):
super(FeatureUnavailableException, self).__init__(message)
class UnauthorizedAccessException(CitrinationClientError):
def __init__(self, message="Access to an unauthorized resource requested"):
super(UnauthorizedAccessException, self).__init__(message)
class ResourceNotFoundException(CitrinationClientError):
def __init__(self, message="Resource not found"):
super(ResourceNotFoundException, self).__init__(message)
class CitrinationServerErrorException(CitrinationClientError):
def __init__(self, message=None):
super(CitrinationServerErrorException, self).__init__(message)
class RequestTimeoutException(CitrinationClientError):
def __init__(self, message="Request to Citrination host timed out"):
super(RequestTimeoutException, self).__init__(message)
class RateLimitingException(CitrinationClientError):
def __init__(self, message="Rate limit hit, throttle requests"):
super(RateLimitingException, self).__init__(message)
| class CitrinationClientError(Exception):
def __init__(self, message=None, server_response=None):
if message is not None and server_response is not None:
message = "{}\nCitrination returned: {}".format(message, server_response)
super(CitrinationClientError, self).__init__(message)
class APIVersionMismatchException(CitrinationClientError):
def __init__(self, message="Version mismatch with Citrination identified, server_response=None. Please check for available PyCC updates", server_response=None):
super(APIVersionMismatchException, self).__init__(message)
class FeatureUnavailableException(CitrinationClientError):
def __init__(self, message="This feature is unavailable on your Citrination deployment", server_response=None):
super(FeatureUnavailableException, self).__init__(message)
class UnauthorizedAccessException(CitrinationClientError):
def __init__(self, message="Access to an unauthorized resource requested", server_response=None):
super(UnauthorizedAccessException, self).__init__(message)
class ResourceNotFoundException(CitrinationClientError):
def __init__(self, message="Resource not found", server_response=None):
super(ResourceNotFoundException, self).__init__(message)
class CitrinationServerErrorException(CitrinationClientError):
def __init__(self, message=None, server_response=None):
super(CitrinationServerErrorException, self).__init__(message)
class RequestTimeoutException(CitrinationClientError):
def __init__(self, message="Request to Citrination host timed out", server_response=None):
super(RequestTimeoutException, self).__init__(message)
class RateLimitingException(CitrinationClientError):
def __init__(self, message="Rate limit hit, throttle requests", server_response=None):
super(RateLimitingException, self).__init__(message)
| Add Optional Server Response Parameter To Error Classes | Add Optional Server Response Parameter To Error Classes
| Python | apache-2.0 | CitrineInformatics/python-citrination-client | class CitrinationClientError(Exception):
pass
class APIVersionMismatchException(CitrinationClientError):
def __init__(self, message="Version mismatch with Citrination identified. Please check for available PyCC updates"):
super(APIVersionMismatchException, self).__init__(message)
class FeatureUnavailableException(CitrinationClientError):
def __init__(self, message="Access to an unauthorized resource requested"):
super(FeatureUnavailableException, self).__init__(message)
class UnauthorizedAccessException(CitrinationClientError):
def __init__(self, message="Access to an unauthorized resource requested"):
super(UnauthorizedAccessException, self).__init__(message)
class ResourceNotFoundException(CitrinationClientError):
def __init__(self, message="Resource not found"):
super(ResourceNotFoundException, self).__init__(message)
class CitrinationServerErrorException(CitrinationClientError):
def __init__(self, message=None):
super(CitrinationServerErrorException, self).__init__(message)
class RequestTimeoutException(CitrinationClientError):
def __init__(self, message="Request to Citrination host timed out"):
super(RequestTimeoutException, self).__init__(message)
class RateLimitingException(CitrinationClientError):
def __init__(self, message="Rate limit hit, throttle requests"):
super(RateLimitingException, self).__init__(message)
Add Optional Server Response Parameter To Error Classes | class CitrinationClientError(Exception):
def __init__(self, message=None, server_response=None):
if message is not None and server_response is not None:
message = "{}\nCitrination returned: {}".format(message, server_response)
super(CitrinationClientError, self).__init__(message)
class APIVersionMismatchException(CitrinationClientError):
def __init__(self, message="Version mismatch with Citrination identified, server_response=None. Please check for available PyCC updates", server_response=None):
super(APIVersionMismatchException, self).__init__(message)
class FeatureUnavailableException(CitrinationClientError):
def __init__(self, message="This feature is unavailable on your Citrination deployment", server_response=None):
super(FeatureUnavailableException, self).__init__(message)
class UnauthorizedAccessException(CitrinationClientError):
def __init__(self, message="Access to an unauthorized resource requested", server_response=None):
super(UnauthorizedAccessException, self).__init__(message)
class ResourceNotFoundException(CitrinationClientError):
def __init__(self, message="Resource not found", server_response=None):
super(ResourceNotFoundException, self).__init__(message)
class CitrinationServerErrorException(CitrinationClientError):
def __init__(self, message=None, server_response=None):
super(CitrinationServerErrorException, self).__init__(message)
class RequestTimeoutException(CitrinationClientError):
def __init__(self, message="Request to Citrination host timed out", server_response=None):
super(RequestTimeoutException, self).__init__(message)
class RateLimitingException(CitrinationClientError):
def __init__(self, message="Rate limit hit, throttle requests", server_response=None):
super(RateLimitingException, self).__init__(message)
| <commit_before>class CitrinationClientError(Exception):
pass
class APIVersionMismatchException(CitrinationClientError):
def __init__(self, message="Version mismatch with Citrination identified. Please check for available PyCC updates"):
super(APIVersionMismatchException, self).__init__(message)
class FeatureUnavailableException(CitrinationClientError):
def __init__(self, message="Access to an unauthorized resource requested"):
super(FeatureUnavailableException, self).__init__(message)
class UnauthorizedAccessException(CitrinationClientError):
def __init__(self, message="Access to an unauthorized resource requested"):
super(UnauthorizedAccessException, self).__init__(message)
class ResourceNotFoundException(CitrinationClientError):
def __init__(self, message="Resource not found"):
super(ResourceNotFoundException, self).__init__(message)
class CitrinationServerErrorException(CitrinationClientError):
def __init__(self, message=None):
super(CitrinationServerErrorException, self).__init__(message)
class RequestTimeoutException(CitrinationClientError):
def __init__(self, message="Request to Citrination host timed out"):
super(RequestTimeoutException, self).__init__(message)
class RateLimitingException(CitrinationClientError):
def __init__(self, message="Rate limit hit, throttle requests"):
super(RateLimitingException, self).__init__(message)
<commit_msg>Add Optional Server Response Parameter To Error Classes<commit_after> | class CitrinationClientError(Exception):
def __init__(self, message=None, server_response=None):
if message is not None and server_response is not None:
message = "{}\nCitrination returned: {}".format(message, server_response)
super(CitrinationClientError, self).__init__(message)
class APIVersionMismatchException(CitrinationClientError):
def __init__(self, message="Version mismatch with Citrination identified, server_response=None. Please check for available PyCC updates", server_response=None):
super(APIVersionMismatchException, self).__init__(message)
class FeatureUnavailableException(CitrinationClientError):
def __init__(self, message="This feature is unavailable on your Citrination deployment", server_response=None):
super(FeatureUnavailableException, self).__init__(message)
class UnauthorizedAccessException(CitrinationClientError):
def __init__(self, message="Access to an unauthorized resource requested", server_response=None):
super(UnauthorizedAccessException, self).__init__(message)
class ResourceNotFoundException(CitrinationClientError):
def __init__(self, message="Resource not found", server_response=None):
super(ResourceNotFoundException, self).__init__(message)
class CitrinationServerErrorException(CitrinationClientError):
def __init__(self, message=None, server_response=None):
super(CitrinationServerErrorException, self).__init__(message)
class RequestTimeoutException(CitrinationClientError):
def __init__(self, message="Request to Citrination host timed out", server_response=None):
super(RequestTimeoutException, self).__init__(message)
class RateLimitingException(CitrinationClientError):
def __init__(self, message="Rate limit hit, throttle requests", server_response=None):
super(RateLimitingException, self).__init__(message)
| class CitrinationClientError(Exception):
pass
class APIVersionMismatchException(CitrinationClientError):
def __init__(self, message="Version mismatch with Citrination identified. Please check for available PyCC updates"):
super(APIVersionMismatchException, self).__init__(message)
class FeatureUnavailableException(CitrinationClientError):
def __init__(self, message="Access to an unauthorized resource requested"):
super(FeatureUnavailableException, self).__init__(message)
class UnauthorizedAccessException(CitrinationClientError):
def __init__(self, message="Access to an unauthorized resource requested"):
super(UnauthorizedAccessException, self).__init__(message)
class ResourceNotFoundException(CitrinationClientError):
def __init__(self, message="Resource not found"):
super(ResourceNotFoundException, self).__init__(message)
class CitrinationServerErrorException(CitrinationClientError):
def __init__(self, message=None):
super(CitrinationServerErrorException, self).__init__(message)
class RequestTimeoutException(CitrinationClientError):
def __init__(self, message="Request to Citrination host timed out"):
super(RequestTimeoutException, self).__init__(message)
class RateLimitingException(CitrinationClientError):
def __init__(self, message="Rate limit hit, throttle requests"):
super(RateLimitingException, self).__init__(message)
Add Optional Server Response Parameter To Error Classesclass CitrinationClientError(Exception):
def __init__(self, message=None, server_response=None):
if message is not None and server_response is not None:
message = "{}\nCitrination returned: {}".format(message, server_response)
super(CitrinationClientError, self).__init__(message)
class APIVersionMismatchException(CitrinationClientError):
def __init__(self, message="Version mismatch with Citrination identified, server_response=None. Please check for available PyCC updates", server_response=None):
super(APIVersionMismatchException, self).__init__(message)
class FeatureUnavailableException(CitrinationClientError):
def __init__(self, message="This feature is unavailable on your Citrination deployment", server_response=None):
super(FeatureUnavailableException, self).__init__(message)
class UnauthorizedAccessException(CitrinationClientError):
def __init__(self, message="Access to an unauthorized resource requested", server_response=None):
super(UnauthorizedAccessException, self).__init__(message)
class ResourceNotFoundException(CitrinationClientError):
def __init__(self, message="Resource not found", server_response=None):
super(ResourceNotFoundException, self).__init__(message)
class CitrinationServerErrorException(CitrinationClientError):
def __init__(self, message=None, server_response=None):
super(CitrinationServerErrorException, self).__init__(message)
class RequestTimeoutException(CitrinationClientError):
def __init__(self, message="Request to Citrination host timed out", server_response=None):
super(RequestTimeoutException, self).__init__(message)
class RateLimitingException(CitrinationClientError):
def __init__(self, message="Rate limit hit, throttle requests", server_response=None):
super(RateLimitingException, self).__init__(message)
| <commit_before>class CitrinationClientError(Exception):
pass
class APIVersionMismatchException(CitrinationClientError):
def __init__(self, message="Version mismatch with Citrination identified. Please check for available PyCC updates"):
super(APIVersionMismatchException, self).__init__(message)
class FeatureUnavailableException(CitrinationClientError):
def __init__(self, message="Access to an unauthorized resource requested"):
super(FeatureUnavailableException, self).__init__(message)
class UnauthorizedAccessException(CitrinationClientError):
def __init__(self, message="Access to an unauthorized resource requested"):
super(UnauthorizedAccessException, self).__init__(message)
class ResourceNotFoundException(CitrinationClientError):
def __init__(self, message="Resource not found"):
super(ResourceNotFoundException, self).__init__(message)
class CitrinationServerErrorException(CitrinationClientError):
def __init__(self, message=None):
super(CitrinationServerErrorException, self).__init__(message)
class RequestTimeoutException(CitrinationClientError):
def __init__(self, message="Request to Citrination host timed out"):
super(RequestTimeoutException, self).__init__(message)
class RateLimitingException(CitrinationClientError):
def __init__(self, message="Rate limit hit, throttle requests"):
super(RateLimitingException, self).__init__(message)
<commit_msg>Add Optional Server Response Parameter To Error Classes<commit_after>class CitrinationClientError(Exception):
def __init__(self, message=None, server_response=None):
if message is not None and server_response is not None:
message = "{}\nCitrination returned: {}".format(message, server_response)
super(CitrinationClientError, self).__init__(message)
class APIVersionMismatchException(CitrinationClientError):
def __init__(self, message="Version mismatch with Citrination identified, server_response=None. Please check for available PyCC updates", server_response=None):
super(APIVersionMismatchException, self).__init__(message)
class FeatureUnavailableException(CitrinationClientError):
def __init__(self, message="This feature is unavailable on your Citrination deployment", server_response=None):
super(FeatureUnavailableException, self).__init__(message)
class UnauthorizedAccessException(CitrinationClientError):
def __init__(self, message="Access to an unauthorized resource requested", server_response=None):
super(UnauthorizedAccessException, self).__init__(message)
class ResourceNotFoundException(CitrinationClientError):
def __init__(self, message="Resource not found", server_response=None):
super(ResourceNotFoundException, self).__init__(message)
class CitrinationServerErrorException(CitrinationClientError):
def __init__(self, message=None, server_response=None):
super(CitrinationServerErrorException, self).__init__(message)
class RequestTimeoutException(CitrinationClientError):
def __init__(self, message="Request to Citrination host timed out", server_response=None):
super(RequestTimeoutException, self).__init__(message)
class RateLimitingException(CitrinationClientError):
def __init__(self, message="Rate limit hit, throttle requests", server_response=None):
super(RateLimitingException, self).__init__(message)
|
943699de02c3d8f4f8e26370fbbff2dec8a2d5ea | api/identifiers/urls.py | api/identifiers/urls.py | from django.conf.urls import url
from api.identifiers import views
urlpatterns = [
url(r'^(?P<identifier_id>\w+)/$', views.IdentifierDetail.as_view(), name=views.IdentifierDetail.view_name),
]
| from django.conf.urls import url
from api.identifiers import views
urlpatterns = [
url(r'^(?P<identifier_id>\w+)/$', views.IdentifierDetail.as_view(), name=views.IdentifierDetail.view_name),
url(r'^(?P<node_id>\w+)/identifiers/$', views.IdentifierList.as_view(), name=views.IdentifierList.view_name),
]
| Add identifier list to identifier views for use with embeds in registrations | Add identifier list to identifier views for use with embeds in registrations
[#OSF-6628]
| Python | apache-2.0 | saradbowman/osf.io,alexschiller/osf.io,wearpants/osf.io,erinspace/osf.io,alexschiller/osf.io,mluo613/osf.io,rdhyee/osf.io,icereval/osf.io,chrisseto/osf.io,mluo613/osf.io,chennan47/osf.io,emetsger/osf.io,hmoco/osf.io,hmoco/osf.io,hmoco/osf.io,baylee-d/osf.io,baylee-d/osf.io,sloria/osf.io,SSJohns/osf.io,erinspace/osf.io,leb2dg/osf.io,felliott/osf.io,brianjgeiger/osf.io,SSJohns/osf.io,alexschiller/osf.io,HalcyonChimera/osf.io,felliott/osf.io,Nesiehr/osf.io,baylee-d/osf.io,TomBaxter/osf.io,wearpants/osf.io,acshi/osf.io,cslzchen/osf.io,SSJohns/osf.io,leb2dg/osf.io,CenterForOpenScience/osf.io,laurenrevere/osf.io,cslzchen/osf.io,acshi/osf.io,wearpants/osf.io,monikagrabowska/osf.io,brianjgeiger/osf.io,Johnetordoff/osf.io,Nesiehr/osf.io,binoculars/osf.io,adlius/osf.io,chrisseto/osf.io,crcresearch/osf.io,icereval/osf.io,emetsger/osf.io,chennan47/osf.io,SSJohns/osf.io,pattisdr/osf.io,samchrisinger/osf.io,rdhyee/osf.io,mattclark/osf.io,monikagrabowska/osf.io,Johnetordoff/osf.io,HalcyonChimera/osf.io,hmoco/osf.io,caneruguz/osf.io,chrisseto/osf.io,caseyrollins/osf.io,brianjgeiger/osf.io,pattisdr/osf.io,acshi/osf.io,saradbowman/osf.io,felliott/osf.io,icereval/osf.io,cwisecarver/osf.io,laurenrevere/osf.io,monikagrabowska/osf.io,mfraezz/osf.io,mattclark/osf.io,rdhyee/osf.io,caneruguz/osf.io,acshi/osf.io,amyshi188/osf.io,DanielSBrown/osf.io,amyshi188/osf.io,adlius/osf.io,adlius/osf.io,amyshi188/osf.io,DanielSBrown/osf.io,cwisecarver/osf.io,HalcyonChimera/osf.io,erinspace/osf.io,sloria/osf.io,rdhyee/osf.io,amyshi188/osf.io,leb2dg/osf.io,cslzchen/osf.io,mfraezz/osf.io,binoculars/osf.io,mfraezz/osf.io,cwisecarver/osf.io,leb2dg/osf.io,pattisdr/osf.io,cslzchen/osf.io,adlius/osf.io,emetsger/osf.io,aaxelb/osf.io,DanielSBrown/osf.io,cwisecarver/osf.io,emetsger/osf.io,mattclark/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,alexschiller/osf.io,crcresearch/osf.io,brianjgeiger/osf.io,mluo613/osf.io,monikagrabowska/osf.io,caneruguz/osf.io,chennan47/osf.io,CenterForOpenScience/osf.io,Nesiehr/osf.io,CenterForOpenScience/osf.io,binoculars/osf.io,monikagrabowska/osf.io,caseyrollins/osf.io,samchrisinger/osf.io,Nesiehr/osf.io,caseyrollins/osf.io,alexschiller/osf.io,TomBaxter/osf.io,mluo613/osf.io,samchrisinger/osf.io,crcresearch/osf.io,TomBaxter/osf.io,Johnetordoff/osf.io,DanielSBrown/osf.io,mluo613/osf.io,aaxelb/osf.io,felliott/osf.io,laurenrevere/osf.io,CenterForOpenScience/osf.io,HalcyonChimera/osf.io,mfraezz/osf.io,chrisseto/osf.io,acshi/osf.io,caneruguz/osf.io,aaxelb/osf.io,samchrisinger/osf.io,sloria/osf.io,wearpants/osf.io | from django.conf.urls import url
from api.identifiers import views
urlpatterns = [
url(r'^(?P<identifier_id>\w+)/$', views.IdentifierDetail.as_view(), name=views.IdentifierDetail.view_name),
]
Add identifier list to identifier views for use with embeds in registrations
[#OSF-6628] | from django.conf.urls import url
from api.identifiers import views
urlpatterns = [
url(r'^(?P<identifier_id>\w+)/$', views.IdentifierDetail.as_view(), name=views.IdentifierDetail.view_name),
url(r'^(?P<node_id>\w+)/identifiers/$', views.IdentifierList.as_view(), name=views.IdentifierList.view_name),
]
| <commit_before>from django.conf.urls import url
from api.identifiers import views
urlpatterns = [
url(r'^(?P<identifier_id>\w+)/$', views.IdentifierDetail.as_view(), name=views.IdentifierDetail.view_name),
]
<commit_msg>Add identifier list to identifier views for use with embeds in registrations
[#OSF-6628]<commit_after> | from django.conf.urls import url
from api.identifiers import views
urlpatterns = [
url(r'^(?P<identifier_id>\w+)/$', views.IdentifierDetail.as_view(), name=views.IdentifierDetail.view_name),
url(r'^(?P<node_id>\w+)/identifiers/$', views.IdentifierList.as_view(), name=views.IdentifierList.view_name),
]
| from django.conf.urls import url
from api.identifiers import views
urlpatterns = [
url(r'^(?P<identifier_id>\w+)/$', views.IdentifierDetail.as_view(), name=views.IdentifierDetail.view_name),
]
Add identifier list to identifier views for use with embeds in registrations
[#OSF-6628]from django.conf.urls import url
from api.identifiers import views
urlpatterns = [
url(r'^(?P<identifier_id>\w+)/$', views.IdentifierDetail.as_view(), name=views.IdentifierDetail.view_name),
url(r'^(?P<node_id>\w+)/identifiers/$', views.IdentifierList.as_view(), name=views.IdentifierList.view_name),
]
| <commit_before>from django.conf.urls import url
from api.identifiers import views
urlpatterns = [
url(r'^(?P<identifier_id>\w+)/$', views.IdentifierDetail.as_view(), name=views.IdentifierDetail.view_name),
]
<commit_msg>Add identifier list to identifier views for use with embeds in registrations
[#OSF-6628]<commit_after>from django.conf.urls import url
from api.identifiers import views
urlpatterns = [
url(r'^(?P<identifier_id>\w+)/$', views.IdentifierDetail.as_view(), name=views.IdentifierDetail.view_name),
url(r'^(?P<node_id>\w+)/identifiers/$', views.IdentifierList.as_view(), name=views.IdentifierList.view_name),
]
|
99449881029eb29255d0dd9b2b4eb4e4ddd36af8 | recorder.py | recorder.py | #!/usr/bin/env python
from gevent.pywsgi import WSGIServer
from flask import Flask
import views
from handler import PatchedWebSocketHandler
from util import generate_filename, massage_record, make_trace_folder
def setup_routes(app):
app.add_url_rule('/', 'index', views.visualization, methods=['GET'])
app.add_url_rule('/visualization', 'visualization', views.visualization,
methods=['GET'])
app.add_url_rule('/records', 'add_record', views.add_record,
methods=['POST'])
app.add_url_rule('/records', 'show_records', views.show_records,
methods=['GET'])
def create_app(config=None):
app = Flask(__name__)
app.config.from_pyfile("settings.py")
if config:
app.config.update(config)
setup_routes(app)
make_trace_folder(app)
return app
app = create_app()
if __name__ == '__main__':
app = create_app()
server = WSGIServer(('', 5000), app, handler_class=PatchedWebSocketHandler)
server.serve_forever()
| #!/usr/bin/env python
from flask import Flask
import views
from util import generate_filename, massage_record, make_trace_folder
def setup_routes(app):
app.add_url_rule('/', 'index', views.visualization, methods=['GET'])
app.add_url_rule('/visualization', 'visualization', views.visualization,
methods=['GET'])
app.add_url_rule('/records', 'add_record', views.add_record,
methods=['POST'])
app.add_url_rule('/records', 'show_records', views.show_records,
methods=['GET'])
def create_app(config=None):
app = Flask(__name__)
app.config.from_pyfile("settings.py")
if config:
app.config.update(config)
setup_routes(app)
make_trace_folder(app)
return app
app = create_app()
if __name__ == '__main__':
app = create_app()
app.run("0.0.0.0")
| Use built-in Flask server when debugging - websockets won't work. | Use built-in Flask server when debugging - websockets won't work.
| Python | bsd-3-clause | openxc/web-logging-example,openxc/web-logging-example | #!/usr/bin/env python
from gevent.pywsgi import WSGIServer
from flask import Flask
import views
from handler import PatchedWebSocketHandler
from util import generate_filename, massage_record, make_trace_folder
def setup_routes(app):
app.add_url_rule('/', 'index', views.visualization, methods=['GET'])
app.add_url_rule('/visualization', 'visualization', views.visualization,
methods=['GET'])
app.add_url_rule('/records', 'add_record', views.add_record,
methods=['POST'])
app.add_url_rule('/records', 'show_records', views.show_records,
methods=['GET'])
def create_app(config=None):
app = Flask(__name__)
app.config.from_pyfile("settings.py")
if config:
app.config.update(config)
setup_routes(app)
make_trace_folder(app)
return app
app = create_app()
if __name__ == '__main__':
app = create_app()
server = WSGIServer(('', 5000), app, handler_class=PatchedWebSocketHandler)
server.serve_forever()
Use built-in Flask server when debugging - websockets won't work. | #!/usr/bin/env python
from flask import Flask
import views
from util import generate_filename, massage_record, make_trace_folder
def setup_routes(app):
app.add_url_rule('/', 'index', views.visualization, methods=['GET'])
app.add_url_rule('/visualization', 'visualization', views.visualization,
methods=['GET'])
app.add_url_rule('/records', 'add_record', views.add_record,
methods=['POST'])
app.add_url_rule('/records', 'show_records', views.show_records,
methods=['GET'])
def create_app(config=None):
app = Flask(__name__)
app.config.from_pyfile("settings.py")
if config:
app.config.update(config)
setup_routes(app)
make_trace_folder(app)
return app
app = create_app()
if __name__ == '__main__':
app = create_app()
app.run("0.0.0.0")
| <commit_before>#!/usr/bin/env python
from gevent.pywsgi import WSGIServer
from flask import Flask
import views
from handler import PatchedWebSocketHandler
from util import generate_filename, massage_record, make_trace_folder
def setup_routes(app):
app.add_url_rule('/', 'index', views.visualization, methods=['GET'])
app.add_url_rule('/visualization', 'visualization', views.visualization,
methods=['GET'])
app.add_url_rule('/records', 'add_record', views.add_record,
methods=['POST'])
app.add_url_rule('/records', 'show_records', views.show_records,
methods=['GET'])
def create_app(config=None):
app = Flask(__name__)
app.config.from_pyfile("settings.py")
if config:
app.config.update(config)
setup_routes(app)
make_trace_folder(app)
return app
app = create_app()
if __name__ == '__main__':
app = create_app()
server = WSGIServer(('', 5000), app, handler_class=PatchedWebSocketHandler)
server.serve_forever()
<commit_msg>Use built-in Flask server when debugging - websockets won't work.<commit_after> | #!/usr/bin/env python
from flask import Flask
import views
from util import generate_filename, massage_record, make_trace_folder
def setup_routes(app):
app.add_url_rule('/', 'index', views.visualization, methods=['GET'])
app.add_url_rule('/visualization', 'visualization', views.visualization,
methods=['GET'])
app.add_url_rule('/records', 'add_record', views.add_record,
methods=['POST'])
app.add_url_rule('/records', 'show_records', views.show_records,
methods=['GET'])
def create_app(config=None):
app = Flask(__name__)
app.config.from_pyfile("settings.py")
if config:
app.config.update(config)
setup_routes(app)
make_trace_folder(app)
return app
app = create_app()
if __name__ == '__main__':
app = create_app()
app.run("0.0.0.0")
| #!/usr/bin/env python
from gevent.pywsgi import WSGIServer
from flask import Flask
import views
from handler import PatchedWebSocketHandler
from util import generate_filename, massage_record, make_trace_folder
def setup_routes(app):
app.add_url_rule('/', 'index', views.visualization, methods=['GET'])
app.add_url_rule('/visualization', 'visualization', views.visualization,
methods=['GET'])
app.add_url_rule('/records', 'add_record', views.add_record,
methods=['POST'])
app.add_url_rule('/records', 'show_records', views.show_records,
methods=['GET'])
def create_app(config=None):
app = Flask(__name__)
app.config.from_pyfile("settings.py")
if config:
app.config.update(config)
setup_routes(app)
make_trace_folder(app)
return app
app = create_app()
if __name__ == '__main__':
app = create_app()
server = WSGIServer(('', 5000), app, handler_class=PatchedWebSocketHandler)
server.serve_forever()
Use built-in Flask server when debugging - websockets won't work.#!/usr/bin/env python
from flask import Flask
import views
from util import generate_filename, massage_record, make_trace_folder
def setup_routes(app):
app.add_url_rule('/', 'index', views.visualization, methods=['GET'])
app.add_url_rule('/visualization', 'visualization', views.visualization,
methods=['GET'])
app.add_url_rule('/records', 'add_record', views.add_record,
methods=['POST'])
app.add_url_rule('/records', 'show_records', views.show_records,
methods=['GET'])
def create_app(config=None):
app = Flask(__name__)
app.config.from_pyfile("settings.py")
if config:
app.config.update(config)
setup_routes(app)
make_trace_folder(app)
return app
app = create_app()
if __name__ == '__main__':
app = create_app()
app.run("0.0.0.0")
| <commit_before>#!/usr/bin/env python
from gevent.pywsgi import WSGIServer
from flask import Flask
import views
from handler import PatchedWebSocketHandler
from util import generate_filename, massage_record, make_trace_folder
def setup_routes(app):
app.add_url_rule('/', 'index', views.visualization, methods=['GET'])
app.add_url_rule('/visualization', 'visualization', views.visualization,
methods=['GET'])
app.add_url_rule('/records', 'add_record', views.add_record,
methods=['POST'])
app.add_url_rule('/records', 'show_records', views.show_records,
methods=['GET'])
def create_app(config=None):
app = Flask(__name__)
app.config.from_pyfile("settings.py")
if config:
app.config.update(config)
setup_routes(app)
make_trace_folder(app)
return app
app = create_app()
if __name__ == '__main__':
app = create_app()
server = WSGIServer(('', 5000), app, handler_class=PatchedWebSocketHandler)
server.serve_forever()
<commit_msg>Use built-in Flask server when debugging - websockets won't work.<commit_after>#!/usr/bin/env python
from flask import Flask
import views
from util import generate_filename, massage_record, make_trace_folder
def setup_routes(app):
app.add_url_rule('/', 'index', views.visualization, methods=['GET'])
app.add_url_rule('/visualization', 'visualization', views.visualization,
methods=['GET'])
app.add_url_rule('/records', 'add_record', views.add_record,
methods=['POST'])
app.add_url_rule('/records', 'show_records', views.show_records,
methods=['GET'])
def create_app(config=None):
app = Flask(__name__)
app.config.from_pyfile("settings.py")
if config:
app.config.update(config)
setup_routes(app)
make_trace_folder(app)
return app
app = create_app()
if __name__ == '__main__':
app = create_app()
app.run("0.0.0.0")
|
42357c1c7b864668fbf2eb7dd0510b94ad8f295c | FAUSTPy/__init__.py | FAUSTPy/__init__.py | #/usr/bin/env python
"""
A set of classes used to dynamically wrap FAUST DSP programs in Python.
This package defines three types:
- PythonUI is an implementation of the UIGlue C struct.
- FAUSTDsp wraps the DSP struct.
- FAUST integrates the other two, sets up the CFFI environment (defines the
data types and API) and compiles the FAUST program. This is the class you
most likely want to use.
"""
from . wrapper import FAUST
from . python_ui import PythonUI, param
from . python_dsp import FAUSTDsp
__all__ = ["FAUST", "PythonUI", "FAUSTDsp", "param", "wrapper"]
| #/usr/bin/env python
"""
A set of classes used to dynamically wrap FAUST DSP programs in Python.
This package defines three types:
- PythonUI is an implementation of the UIGlue C struct.
- FAUSTDsp wraps the DSP struct.
- FAUST integrates the other two, sets up the CFFI environment (defines the
data types and API) and compiles the FAUST program. This is the class you
most likely want to use.
"""
from . wrapper import FAUST
from . python_ui import PythonUI, param
from . python_dsp import FAUSTDsp
__author__ = "Marc Joliet"
__copyright__ = "Copyright 2013, Marc Joliet"
__credits__ = ["Marc Joliet"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Marc Joliet"
__email__ = "marcec@gmx.de"
__status__ = "Prototype"
__all__ = ["FAUST", "PythonUI", "FAUSTDsp", "param", "wrapper"]
| Add package meta-data (author, email, etc.). | Add package meta-data (author, email, etc.).
| Python | mit | marcecj/faust_python | #/usr/bin/env python
"""
A set of classes used to dynamically wrap FAUST DSP programs in Python.
This package defines three types:
- PythonUI is an implementation of the UIGlue C struct.
- FAUSTDsp wraps the DSP struct.
- FAUST integrates the other two, sets up the CFFI environment (defines the
data types and API) and compiles the FAUST program. This is the class you
most likely want to use.
"""
from . wrapper import FAUST
from . python_ui import PythonUI, param
from . python_dsp import FAUSTDsp
__all__ = ["FAUST", "PythonUI", "FAUSTDsp", "param", "wrapper"]
Add package meta-data (author, email, etc.). | #/usr/bin/env python
"""
A set of classes used to dynamically wrap FAUST DSP programs in Python.
This package defines three types:
- PythonUI is an implementation of the UIGlue C struct.
- FAUSTDsp wraps the DSP struct.
- FAUST integrates the other two, sets up the CFFI environment (defines the
data types and API) and compiles the FAUST program. This is the class you
most likely want to use.
"""
from . wrapper import FAUST
from . python_ui import PythonUI, param
from . python_dsp import FAUSTDsp
__author__ = "Marc Joliet"
__copyright__ = "Copyright 2013, Marc Joliet"
__credits__ = ["Marc Joliet"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Marc Joliet"
__email__ = "marcec@gmx.de"
__status__ = "Prototype"
__all__ = ["FAUST", "PythonUI", "FAUSTDsp", "param", "wrapper"]
| <commit_before>#/usr/bin/env python
"""
A set of classes used to dynamically wrap FAUST DSP programs in Python.
This package defines three types:
- PythonUI is an implementation of the UIGlue C struct.
- FAUSTDsp wraps the DSP struct.
- FAUST integrates the other two, sets up the CFFI environment (defines the
data types and API) and compiles the FAUST program. This is the class you
most likely want to use.
"""
from . wrapper import FAUST
from . python_ui import PythonUI, param
from . python_dsp import FAUSTDsp
__all__ = ["FAUST", "PythonUI", "FAUSTDsp", "param", "wrapper"]
<commit_msg>Add package meta-data (author, email, etc.).<commit_after> | #/usr/bin/env python
"""
A set of classes used to dynamically wrap FAUST DSP programs in Python.
This package defines three types:
- PythonUI is an implementation of the UIGlue C struct.
- FAUSTDsp wraps the DSP struct.
- FAUST integrates the other two, sets up the CFFI environment (defines the
data types and API) and compiles the FAUST program. This is the class you
most likely want to use.
"""
from . wrapper import FAUST
from . python_ui import PythonUI, param
from . python_dsp import FAUSTDsp
__author__ = "Marc Joliet"
__copyright__ = "Copyright 2013, Marc Joliet"
__credits__ = ["Marc Joliet"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Marc Joliet"
__email__ = "marcec@gmx.de"
__status__ = "Prototype"
__all__ = ["FAUST", "PythonUI", "FAUSTDsp", "param", "wrapper"]
| #/usr/bin/env python
"""
A set of classes used to dynamically wrap FAUST DSP programs in Python.
This package defines three types:
- PythonUI is an implementation of the UIGlue C struct.
- FAUSTDsp wraps the DSP struct.
- FAUST integrates the other two, sets up the CFFI environment (defines the
data types and API) and compiles the FAUST program. This is the class you
most likely want to use.
"""
from . wrapper import FAUST
from . python_ui import PythonUI, param
from . python_dsp import FAUSTDsp
__all__ = ["FAUST", "PythonUI", "FAUSTDsp", "param", "wrapper"]
Add package meta-data (author, email, etc.).#/usr/bin/env python
"""
A set of classes used to dynamically wrap FAUST DSP programs in Python.
This package defines three types:
- PythonUI is an implementation of the UIGlue C struct.
- FAUSTDsp wraps the DSP struct.
- FAUST integrates the other two, sets up the CFFI environment (defines the
data types and API) and compiles the FAUST program. This is the class you
most likely want to use.
"""
from . wrapper import FAUST
from . python_ui import PythonUI, param
from . python_dsp import FAUSTDsp
__author__ = "Marc Joliet"
__copyright__ = "Copyright 2013, Marc Joliet"
__credits__ = ["Marc Joliet"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Marc Joliet"
__email__ = "marcec@gmx.de"
__status__ = "Prototype"
__all__ = ["FAUST", "PythonUI", "FAUSTDsp", "param", "wrapper"]
| <commit_before>#/usr/bin/env python
"""
A set of classes used to dynamically wrap FAUST DSP programs in Python.
This package defines three types:
- PythonUI is an implementation of the UIGlue C struct.
- FAUSTDsp wraps the DSP struct.
- FAUST integrates the other two, sets up the CFFI environment (defines the
data types and API) and compiles the FAUST program. This is the class you
most likely want to use.
"""
from . wrapper import FAUST
from . python_ui import PythonUI, param
from . python_dsp import FAUSTDsp
__all__ = ["FAUST", "PythonUI", "FAUSTDsp", "param", "wrapper"]
<commit_msg>Add package meta-data (author, email, etc.).<commit_after>#/usr/bin/env python
"""
A set of classes used to dynamically wrap FAUST DSP programs in Python.
This package defines three types:
- PythonUI is an implementation of the UIGlue C struct.
- FAUSTDsp wraps the DSP struct.
- FAUST integrates the other two, sets up the CFFI environment (defines the
data types and API) and compiles the FAUST program. This is the class you
most likely want to use.
"""
from . wrapper import FAUST
from . python_ui import PythonUI, param
from . python_dsp import FAUSTDsp
__author__ = "Marc Joliet"
__copyright__ = "Copyright 2013, Marc Joliet"
__credits__ = ["Marc Joliet"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Marc Joliet"
__email__ = "marcec@gmx.de"
__status__ = "Prototype"
__all__ = ["FAUST", "PythonUI", "FAUSTDsp", "param", "wrapper"]
|
b21750ad60b84bf87f15c3d25ffa0317091a10dc | pyoracc/test/model/test_corpus.py | pyoracc/test/model/test_corpus.py | import pytest
from ...model.corpus import Corpus
from ..fixtures import tiny_corpus, sample_corpus, whole_corpus
slow = pytest.mark.skipif(
not pytest.config.getoption("--runslow"),
reason="need --runslow option to run"
)
def test_tiny():
corpus = Corpus(source=tiny_corpus())
assert corpus.successes == 1
assert corpus.failures == 1
@slow
def test_sample():
corpus = Corpus(source=sample_corpus())
assert corpus.successes == 36
assert corpus.failures == 3
@pytest.mark.skipif(not whole_corpus(),
reason="Need to set oracc_corpus_path to point "
"to the whole corpus, which is not bundled with "
"pyoracc")
@slow
def test_whole():
corpus = Corpus(source=whole_corpus())
assert corpus.successes == 2477
assert corpus.failures == 391
| import pytest
from ...model.corpus import Corpus
from ..fixtures import tiny_corpus, sample_corpus, whole_corpus
slow = pytest.mark.skipif(
not pytest.config.getoption("--runslow"),
reason="need --runslow option to run"
)
def test_tiny():
corpus = Corpus(source=tiny_corpus())
assert corpus.successes == 1
assert corpus.failures == 1
@slow
def test_sample():
corpus = Corpus(source=sample_corpus())
assert corpus.successes == 36
assert corpus.failures == 3
@pytest.mark.skipif(not whole_corpus(),
reason="Need to set oracc_corpus_path to point "
"to the whole corpus, which is not bundled with "
"pyoracc")
@slow
def test_whole():
corpus = Corpus(source=whole_corpus())
# there is a total of 2868 files in the corpus
assert corpus.successes == 2477
assert corpus.failures == 391
| Comment about number of tests | Comment about number of tests
| Python | mit | UCL/pyoracc | import pytest
from ...model.corpus import Corpus
from ..fixtures import tiny_corpus, sample_corpus, whole_corpus
slow = pytest.mark.skipif(
not pytest.config.getoption("--runslow"),
reason="need --runslow option to run"
)
def test_tiny():
corpus = Corpus(source=tiny_corpus())
assert corpus.successes == 1
assert corpus.failures == 1
@slow
def test_sample():
corpus = Corpus(source=sample_corpus())
assert corpus.successes == 36
assert corpus.failures == 3
@pytest.mark.skipif(not whole_corpus(),
reason="Need to set oracc_corpus_path to point "
"to the whole corpus, which is not bundled with "
"pyoracc")
@slow
def test_whole():
corpus = Corpus(source=whole_corpus())
assert corpus.successes == 2477
assert corpus.failures == 391
Comment about number of tests | import pytest
from ...model.corpus import Corpus
from ..fixtures import tiny_corpus, sample_corpus, whole_corpus
slow = pytest.mark.skipif(
not pytest.config.getoption("--runslow"),
reason="need --runslow option to run"
)
def test_tiny():
corpus = Corpus(source=tiny_corpus())
assert corpus.successes == 1
assert corpus.failures == 1
@slow
def test_sample():
corpus = Corpus(source=sample_corpus())
assert corpus.successes == 36
assert corpus.failures == 3
@pytest.mark.skipif(not whole_corpus(),
reason="Need to set oracc_corpus_path to point "
"to the whole corpus, which is not bundled with "
"pyoracc")
@slow
def test_whole():
corpus = Corpus(source=whole_corpus())
# there is a total of 2868 files in the corpus
assert corpus.successes == 2477
assert corpus.failures == 391
| <commit_before>import pytest
from ...model.corpus import Corpus
from ..fixtures import tiny_corpus, sample_corpus, whole_corpus
slow = pytest.mark.skipif(
not pytest.config.getoption("--runslow"),
reason="need --runslow option to run"
)
def test_tiny():
corpus = Corpus(source=tiny_corpus())
assert corpus.successes == 1
assert corpus.failures == 1
@slow
def test_sample():
corpus = Corpus(source=sample_corpus())
assert corpus.successes == 36
assert corpus.failures == 3
@pytest.mark.skipif(not whole_corpus(),
reason="Need to set oracc_corpus_path to point "
"to the whole corpus, which is not bundled with "
"pyoracc")
@slow
def test_whole():
corpus = Corpus(source=whole_corpus())
assert corpus.successes == 2477
assert corpus.failures == 391
<commit_msg>Comment about number of tests<commit_after> | import pytest
from ...model.corpus import Corpus
from ..fixtures import tiny_corpus, sample_corpus, whole_corpus
slow = pytest.mark.skipif(
not pytest.config.getoption("--runslow"),
reason="need --runslow option to run"
)
def test_tiny():
corpus = Corpus(source=tiny_corpus())
assert corpus.successes == 1
assert corpus.failures == 1
@slow
def test_sample():
corpus = Corpus(source=sample_corpus())
assert corpus.successes == 36
assert corpus.failures == 3
@pytest.mark.skipif(not whole_corpus(),
reason="Need to set oracc_corpus_path to point "
"to the whole corpus, which is not bundled with "
"pyoracc")
@slow
def test_whole():
corpus = Corpus(source=whole_corpus())
# there is a total of 2868 files in the corpus
assert corpus.successes == 2477
assert corpus.failures == 391
| import pytest
from ...model.corpus import Corpus
from ..fixtures import tiny_corpus, sample_corpus, whole_corpus
slow = pytest.mark.skipif(
not pytest.config.getoption("--runslow"),
reason="need --runslow option to run"
)
def test_tiny():
corpus = Corpus(source=tiny_corpus())
assert corpus.successes == 1
assert corpus.failures == 1
@slow
def test_sample():
corpus = Corpus(source=sample_corpus())
assert corpus.successes == 36
assert corpus.failures == 3
@pytest.mark.skipif(not whole_corpus(),
reason="Need to set oracc_corpus_path to point "
"to the whole corpus, which is not bundled with "
"pyoracc")
@slow
def test_whole():
corpus = Corpus(source=whole_corpus())
assert corpus.successes == 2477
assert corpus.failures == 391
Comment about number of testsimport pytest
from ...model.corpus import Corpus
from ..fixtures import tiny_corpus, sample_corpus, whole_corpus
slow = pytest.mark.skipif(
not pytest.config.getoption("--runslow"),
reason="need --runslow option to run"
)
def test_tiny():
corpus = Corpus(source=tiny_corpus())
assert corpus.successes == 1
assert corpus.failures == 1
@slow
def test_sample():
corpus = Corpus(source=sample_corpus())
assert corpus.successes == 36
assert corpus.failures == 3
@pytest.mark.skipif(not whole_corpus(),
reason="Need to set oracc_corpus_path to point "
"to the whole corpus, which is not bundled with "
"pyoracc")
@slow
def test_whole():
corpus = Corpus(source=whole_corpus())
# there is a total of 2868 files in the corpus
assert corpus.successes == 2477
assert corpus.failures == 391
| <commit_before>import pytest
from ...model.corpus import Corpus
from ..fixtures import tiny_corpus, sample_corpus, whole_corpus
slow = pytest.mark.skipif(
not pytest.config.getoption("--runslow"),
reason="need --runslow option to run"
)
def test_tiny():
corpus = Corpus(source=tiny_corpus())
assert corpus.successes == 1
assert corpus.failures == 1
@slow
def test_sample():
corpus = Corpus(source=sample_corpus())
assert corpus.successes == 36
assert corpus.failures == 3
@pytest.mark.skipif(not whole_corpus(),
reason="Need to set oracc_corpus_path to point "
"to the whole corpus, which is not bundled with "
"pyoracc")
@slow
def test_whole():
corpus = Corpus(source=whole_corpus())
assert corpus.successes == 2477
assert corpus.failures == 391
<commit_msg>Comment about number of tests<commit_after>import pytest
from ...model.corpus import Corpus
from ..fixtures import tiny_corpus, sample_corpus, whole_corpus
slow = pytest.mark.skipif(
not pytest.config.getoption("--runslow"),
reason="need --runslow option to run"
)
def test_tiny():
corpus = Corpus(source=tiny_corpus())
assert corpus.successes == 1
assert corpus.failures == 1
@slow
def test_sample():
corpus = Corpus(source=sample_corpus())
assert corpus.successes == 36
assert corpus.failures == 3
@pytest.mark.skipif(not whole_corpus(),
reason="Need to set oracc_corpus_path to point "
"to the whole corpus, which is not bundled with "
"pyoracc")
@slow
def test_whole():
corpus = Corpus(source=whole_corpus())
# there is a total of 2868 files in the corpus
assert corpus.successes == 2477
assert corpus.failures == 391
|
202cfd21d04f9d8ec9fec3b921f6b4d85df5560d | Tools/px4params/xmlout.py | Tools/px4params/xmlout.py | from xml.dom.minidom import getDOMImplementation
import codecs
class XMLOutput():
def __init__(self, groups):
impl = getDOMImplementation()
xml_document = impl.createDocument(None, "parameters", None)
xml_parameters = xml_document.documentElement
xml_version = xml_document.createElement("version")
xml_parameters.appendChild(xml_version)
xml_version_value = xml_document.createTextNode("1")
xml_version.appendChild(xml_version_value)
for group in groups:
xml_group = xml_document.createElement("group")
xml_group.setAttribute("name", group.GetName())
xml_parameters.appendChild(xml_group)
for param in group.GetParams():
xml_param = xml_document.createElement("parameter")
xml_group.appendChild(xml_param)
for code in param.GetFieldCodes():
value = param.GetFieldValue(code)
xml_field = xml_document.createElement(code)
xml_param.appendChild(xml_field)
xml_value = xml_document.createTextNode(value)
xml_field.appendChild(xml_value)
self.xml_document = xml_document
def Save(self, filename):
with codecs.open(filename, 'w', 'utf-8') as f:
self.xml_document.writexml(f, indent=" ", addindent=" ", newl="\n")
| import xml.etree.ElementTree as ET
import codecs
def indent(elem, level=0):
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
class XMLOutput():
def __init__(self, groups):
xml_parameters = ET.Element("parameters")
xml_version = ET.SubElement(xml_parameters, "version")
xml_version.text = "2"
for group in groups:
xml_group = ET.SubElement(xml_parameters, "group")
xml_group.attrib["name"] = group.GetName()
for param in group.GetParams():
xml_param = ET.SubElement(xml_group, "parameter")
for code in param.GetFieldCodes():
value = param.GetFieldValue(code)
if code == "code":
xml_param.attrib["name"] = value
elif code == "default":
xml_param.attrib["default"] = value
elif code == "type":
xml_param.attrib["type"] = value
else:
xml_field = ET.SubElement(xml_param, code)
xml_field.text = value
indent(xml_parameters)
self.xml_document = ET.ElementTree(xml_parameters)
def Save(self, filename):
with codecs.open(filename, 'w', 'utf-8') as f:
self.xml_document.write(f)
| Change to V2 spec of param meta data | Change to V2 spec of param meta data
Had to switch to ElementTree to get attribute support
| Python | mit | darknight-007/Firmware,jlecoeur/Firmware,PX4/Firmware,PX4/Firmware,Aerotenna/Firmware,jlecoeur/Firmware,dagar/Firmware,jlecoeur/Firmware,krbeverx/Firmware,PX4/Firmware,mcgill-robotics/Firmware,PX4/Firmware,dagar/Firmware,mcgill-robotics/Firmware,dagar/Firmware,acfloria/Firmware,Aerotenna/Firmware,Aerotenna/Firmware,mje-nz/PX4-Firmware,krbeverx/Firmware,jlecoeur/Firmware,Aerotenna/Firmware,mje-nz/PX4-Firmware,Aerotenna/Firmware,mcgill-robotics/Firmware,jlecoeur/Firmware,krbeverx/Firmware,PX4/Firmware,krbeverx/Firmware,darknight-007/Firmware,jlecoeur/Firmware,Aerotenna/Firmware,krbeverx/Firmware,mcgill-robotics/Firmware,mcgill-robotics/Firmware,acfloria/Firmware,darknight-007/Firmware,mje-nz/PX4-Firmware,mje-nz/PX4-Firmware,mje-nz/PX4-Firmware,dagar/Firmware,acfloria/Firmware,mje-nz/PX4-Firmware,krbeverx/Firmware,PX4/Firmware,mcgill-robotics/Firmware,mcgill-robotics/Firmware,PX4/Firmware,dagar/Firmware,krbeverx/Firmware,darknight-007/Firmware,acfloria/Firmware,acfloria/Firmware,acfloria/Firmware,dagar/Firmware,darknight-007/Firmware,jlecoeur/Firmware,dagar/Firmware,Aerotenna/Firmware,acfloria/Firmware,jlecoeur/Firmware,mje-nz/PX4-Firmware | from xml.dom.minidom import getDOMImplementation
import codecs
class XMLOutput():
def __init__(self, groups):
impl = getDOMImplementation()
xml_document = impl.createDocument(None, "parameters", None)
xml_parameters = xml_document.documentElement
xml_version = xml_document.createElement("version")
xml_parameters.appendChild(xml_version)
xml_version_value = xml_document.createTextNode("1")
xml_version.appendChild(xml_version_value)
for group in groups:
xml_group = xml_document.createElement("group")
xml_group.setAttribute("name", group.GetName())
xml_parameters.appendChild(xml_group)
for param in group.GetParams():
xml_param = xml_document.createElement("parameter")
xml_group.appendChild(xml_param)
for code in param.GetFieldCodes():
value = param.GetFieldValue(code)
xml_field = xml_document.createElement(code)
xml_param.appendChild(xml_field)
xml_value = xml_document.createTextNode(value)
xml_field.appendChild(xml_value)
self.xml_document = xml_document
def Save(self, filename):
with codecs.open(filename, 'w', 'utf-8') as f:
self.xml_document.writexml(f, indent=" ", addindent=" ", newl="\n")
Change to V2 spec of param meta data
Had to switch to ElementTree to get attribute support | import xml.etree.ElementTree as ET
import codecs
def indent(elem, level=0):
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
class XMLOutput():
def __init__(self, groups):
xml_parameters = ET.Element("parameters")
xml_version = ET.SubElement(xml_parameters, "version")
xml_version.text = "2"
for group in groups:
xml_group = ET.SubElement(xml_parameters, "group")
xml_group.attrib["name"] = group.GetName()
for param in group.GetParams():
xml_param = ET.SubElement(xml_group, "parameter")
for code in param.GetFieldCodes():
value = param.GetFieldValue(code)
if code == "code":
xml_param.attrib["name"] = value
elif code == "default":
xml_param.attrib["default"] = value
elif code == "type":
xml_param.attrib["type"] = value
else:
xml_field = ET.SubElement(xml_param, code)
xml_field.text = value
indent(xml_parameters)
self.xml_document = ET.ElementTree(xml_parameters)
def Save(self, filename):
with codecs.open(filename, 'w', 'utf-8') as f:
self.xml_document.write(f)
| <commit_before>from xml.dom.minidom import getDOMImplementation
import codecs
class XMLOutput():
def __init__(self, groups):
impl = getDOMImplementation()
xml_document = impl.createDocument(None, "parameters", None)
xml_parameters = xml_document.documentElement
xml_version = xml_document.createElement("version")
xml_parameters.appendChild(xml_version)
xml_version_value = xml_document.createTextNode("1")
xml_version.appendChild(xml_version_value)
for group in groups:
xml_group = xml_document.createElement("group")
xml_group.setAttribute("name", group.GetName())
xml_parameters.appendChild(xml_group)
for param in group.GetParams():
xml_param = xml_document.createElement("parameter")
xml_group.appendChild(xml_param)
for code in param.GetFieldCodes():
value = param.GetFieldValue(code)
xml_field = xml_document.createElement(code)
xml_param.appendChild(xml_field)
xml_value = xml_document.createTextNode(value)
xml_field.appendChild(xml_value)
self.xml_document = xml_document
def Save(self, filename):
with codecs.open(filename, 'w', 'utf-8') as f:
self.xml_document.writexml(f, indent=" ", addindent=" ", newl="\n")
<commit_msg>Change to V2 spec of param meta data
Had to switch to ElementTree to get attribute support<commit_after> | import xml.etree.ElementTree as ET
import codecs
def indent(elem, level=0):
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
class XMLOutput():
def __init__(self, groups):
xml_parameters = ET.Element("parameters")
xml_version = ET.SubElement(xml_parameters, "version")
xml_version.text = "2"
for group in groups:
xml_group = ET.SubElement(xml_parameters, "group")
xml_group.attrib["name"] = group.GetName()
for param in group.GetParams():
xml_param = ET.SubElement(xml_group, "parameter")
for code in param.GetFieldCodes():
value = param.GetFieldValue(code)
if code == "code":
xml_param.attrib["name"] = value
elif code == "default":
xml_param.attrib["default"] = value
elif code == "type":
xml_param.attrib["type"] = value
else:
xml_field = ET.SubElement(xml_param, code)
xml_field.text = value
indent(xml_parameters)
self.xml_document = ET.ElementTree(xml_parameters)
def Save(self, filename):
with codecs.open(filename, 'w', 'utf-8') as f:
self.xml_document.write(f)
| from xml.dom.minidom import getDOMImplementation
import codecs
class XMLOutput():
def __init__(self, groups):
impl = getDOMImplementation()
xml_document = impl.createDocument(None, "parameters", None)
xml_parameters = xml_document.documentElement
xml_version = xml_document.createElement("version")
xml_parameters.appendChild(xml_version)
xml_version_value = xml_document.createTextNode("1")
xml_version.appendChild(xml_version_value)
for group in groups:
xml_group = xml_document.createElement("group")
xml_group.setAttribute("name", group.GetName())
xml_parameters.appendChild(xml_group)
for param in group.GetParams():
xml_param = xml_document.createElement("parameter")
xml_group.appendChild(xml_param)
for code in param.GetFieldCodes():
value = param.GetFieldValue(code)
xml_field = xml_document.createElement(code)
xml_param.appendChild(xml_field)
xml_value = xml_document.createTextNode(value)
xml_field.appendChild(xml_value)
self.xml_document = xml_document
def Save(self, filename):
with codecs.open(filename, 'w', 'utf-8') as f:
self.xml_document.writexml(f, indent=" ", addindent=" ", newl="\n")
Change to V2 spec of param meta data
Had to switch to ElementTree to get attribute supportimport xml.etree.ElementTree as ET
import codecs
def indent(elem, level=0):
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
class XMLOutput():
def __init__(self, groups):
xml_parameters = ET.Element("parameters")
xml_version = ET.SubElement(xml_parameters, "version")
xml_version.text = "2"
for group in groups:
xml_group = ET.SubElement(xml_parameters, "group")
xml_group.attrib["name"] = group.GetName()
for param in group.GetParams():
xml_param = ET.SubElement(xml_group, "parameter")
for code in param.GetFieldCodes():
value = param.GetFieldValue(code)
if code == "code":
xml_param.attrib["name"] = value
elif code == "default":
xml_param.attrib["default"] = value
elif code == "type":
xml_param.attrib["type"] = value
else:
xml_field = ET.SubElement(xml_param, code)
xml_field.text = value
indent(xml_parameters)
self.xml_document = ET.ElementTree(xml_parameters)
def Save(self, filename):
with codecs.open(filename, 'w', 'utf-8') as f:
self.xml_document.write(f)
| <commit_before>from xml.dom.minidom import getDOMImplementation
import codecs
class XMLOutput():
def __init__(self, groups):
impl = getDOMImplementation()
xml_document = impl.createDocument(None, "parameters", None)
xml_parameters = xml_document.documentElement
xml_version = xml_document.createElement("version")
xml_parameters.appendChild(xml_version)
xml_version_value = xml_document.createTextNode("1")
xml_version.appendChild(xml_version_value)
for group in groups:
xml_group = xml_document.createElement("group")
xml_group.setAttribute("name", group.GetName())
xml_parameters.appendChild(xml_group)
for param in group.GetParams():
xml_param = xml_document.createElement("parameter")
xml_group.appendChild(xml_param)
for code in param.GetFieldCodes():
value = param.GetFieldValue(code)
xml_field = xml_document.createElement(code)
xml_param.appendChild(xml_field)
xml_value = xml_document.createTextNode(value)
xml_field.appendChild(xml_value)
self.xml_document = xml_document
def Save(self, filename):
with codecs.open(filename, 'w', 'utf-8') as f:
self.xml_document.writexml(f, indent=" ", addindent=" ", newl="\n")
<commit_msg>Change to V2 spec of param meta data
Had to switch to ElementTree to get attribute support<commit_after>import xml.etree.ElementTree as ET
import codecs
def indent(elem, level=0):
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
class XMLOutput():
def __init__(self, groups):
xml_parameters = ET.Element("parameters")
xml_version = ET.SubElement(xml_parameters, "version")
xml_version.text = "2"
for group in groups:
xml_group = ET.SubElement(xml_parameters, "group")
xml_group.attrib["name"] = group.GetName()
for param in group.GetParams():
xml_param = ET.SubElement(xml_group, "parameter")
for code in param.GetFieldCodes():
value = param.GetFieldValue(code)
if code == "code":
xml_param.attrib["name"] = value
elif code == "default":
xml_param.attrib["default"] = value
elif code == "type":
xml_param.attrib["type"] = value
else:
xml_field = ET.SubElement(xml_param, code)
xml_field.text = value
indent(xml_parameters)
self.xml_document = ET.ElementTree(xml_parameters)
def Save(self, filename):
with codecs.open(filename, 'w', 'utf-8') as f:
self.xml_document.write(f)
|
ef6f42a592e79b2693685895d8a654c4f8d9e166 | jupyterlab/labhubapp.py | jupyterlab/labhubapp.py | from .labapp import LabApp
try:
from jupyterhub.singleuser import SingleUserNotebookApp
except ImportError:
SingleUserLabApp = None
raise ImportError('You must have jupyterhub installed for this to work.')
else:
class SingleUserLabApp(SingleUserNotebookApp, LabApp):
def init_webapp(self, *args, **kwargs):
super().init_webapp(*args, **kwargs)
settings = self.web_app.settings
if 'page_config_data' not in settings:
settings['page_config_data'] = {}
settings['page_config_data']['hub_prefix'] = self.hub_prefix
settings['page_config_data']['hub_host'] = self.hub_host
settings['page_config_data']['hub_user'] = self.user
def main(argv=None):
return SingleUserLabApp.launch_instance(argv)
if __name__ == "__main__":
main()
| import os
from .labapp import LabApp
try:
from jupyterhub.singleuser import SingleUserNotebookApp
except ImportError:
SingleUserLabApp = None
raise ImportError('You must have jupyterhub installed for this to work.')
else:
class SingleUserLabApp(SingleUserNotebookApp, LabApp):
def init_webapp(self, *args, **kwargs):
super().init_webapp(*args, **kwargs)
settings = self.web_app.settings
if 'page_config_data' not in settings:
settings['page_config_data'] = {}
settings['page_config_data']['hub_prefix'] = self.hub_prefix
settings['page_config_data']['hub_host'] = self.hub_host
settings['page_config_data']['hub_user'] = self.user
api_token = os.getenv('JUPYTERHUB_API_TOKEN')
if not api_token:
api_token = ''
if not self.token:
try:
self.token = api_token
except AttributeError:
self.log.error("Can't set self.token")
settings['page_config_data']['token'] = api_token
def main(argv=None):
return SingleUserLabApp.launch_instance(argv)
if __name__ == "__main__":
main()
| Add api_token from environment, if it's present. | Add api_token from environment, if it's present.
| Python | bsd-3-clause | jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab | from .labapp import LabApp
try:
from jupyterhub.singleuser import SingleUserNotebookApp
except ImportError:
SingleUserLabApp = None
raise ImportError('You must have jupyterhub installed for this to work.')
else:
class SingleUserLabApp(SingleUserNotebookApp, LabApp):
def init_webapp(self, *args, **kwargs):
super().init_webapp(*args, **kwargs)
settings = self.web_app.settings
if 'page_config_data' not in settings:
settings['page_config_data'] = {}
settings['page_config_data']['hub_prefix'] = self.hub_prefix
settings['page_config_data']['hub_host'] = self.hub_host
settings['page_config_data']['hub_user'] = self.user
def main(argv=None):
return SingleUserLabApp.launch_instance(argv)
if __name__ == "__main__":
main()
Add api_token from environment, if it's present. | import os
from .labapp import LabApp
try:
from jupyterhub.singleuser import SingleUserNotebookApp
except ImportError:
SingleUserLabApp = None
raise ImportError('You must have jupyterhub installed for this to work.')
else:
class SingleUserLabApp(SingleUserNotebookApp, LabApp):
def init_webapp(self, *args, **kwargs):
super().init_webapp(*args, **kwargs)
settings = self.web_app.settings
if 'page_config_data' not in settings:
settings['page_config_data'] = {}
settings['page_config_data']['hub_prefix'] = self.hub_prefix
settings['page_config_data']['hub_host'] = self.hub_host
settings['page_config_data']['hub_user'] = self.user
api_token = os.getenv('JUPYTERHUB_API_TOKEN')
if not api_token:
api_token = ''
if not self.token:
try:
self.token = api_token
except AttributeError:
self.log.error("Can't set self.token")
settings['page_config_data']['token'] = api_token
def main(argv=None):
return SingleUserLabApp.launch_instance(argv)
if __name__ == "__main__":
main()
| <commit_before>from .labapp import LabApp
try:
from jupyterhub.singleuser import SingleUserNotebookApp
except ImportError:
SingleUserLabApp = None
raise ImportError('You must have jupyterhub installed for this to work.')
else:
class SingleUserLabApp(SingleUserNotebookApp, LabApp):
def init_webapp(self, *args, **kwargs):
super().init_webapp(*args, **kwargs)
settings = self.web_app.settings
if 'page_config_data' not in settings:
settings['page_config_data'] = {}
settings['page_config_data']['hub_prefix'] = self.hub_prefix
settings['page_config_data']['hub_host'] = self.hub_host
settings['page_config_data']['hub_user'] = self.user
def main(argv=None):
return SingleUserLabApp.launch_instance(argv)
if __name__ == "__main__":
main()
<commit_msg>Add api_token from environment, if it's present.<commit_after> | import os
from .labapp import LabApp
try:
from jupyterhub.singleuser import SingleUserNotebookApp
except ImportError:
SingleUserLabApp = None
raise ImportError('You must have jupyterhub installed for this to work.')
else:
class SingleUserLabApp(SingleUserNotebookApp, LabApp):
def init_webapp(self, *args, **kwargs):
super().init_webapp(*args, **kwargs)
settings = self.web_app.settings
if 'page_config_data' not in settings:
settings['page_config_data'] = {}
settings['page_config_data']['hub_prefix'] = self.hub_prefix
settings['page_config_data']['hub_host'] = self.hub_host
settings['page_config_data']['hub_user'] = self.user
api_token = os.getenv('JUPYTERHUB_API_TOKEN')
if not api_token:
api_token = ''
if not self.token:
try:
self.token = api_token
except AttributeError:
self.log.error("Can't set self.token")
settings['page_config_data']['token'] = api_token
def main(argv=None):
return SingleUserLabApp.launch_instance(argv)
if __name__ == "__main__":
main()
| from .labapp import LabApp
try:
from jupyterhub.singleuser import SingleUserNotebookApp
except ImportError:
SingleUserLabApp = None
raise ImportError('You must have jupyterhub installed for this to work.')
else:
class SingleUserLabApp(SingleUserNotebookApp, LabApp):
def init_webapp(self, *args, **kwargs):
super().init_webapp(*args, **kwargs)
settings = self.web_app.settings
if 'page_config_data' not in settings:
settings['page_config_data'] = {}
settings['page_config_data']['hub_prefix'] = self.hub_prefix
settings['page_config_data']['hub_host'] = self.hub_host
settings['page_config_data']['hub_user'] = self.user
def main(argv=None):
return SingleUserLabApp.launch_instance(argv)
if __name__ == "__main__":
main()
Add api_token from environment, if it's present.import os
from .labapp import LabApp
try:
from jupyterhub.singleuser import SingleUserNotebookApp
except ImportError:
SingleUserLabApp = None
raise ImportError('You must have jupyterhub installed for this to work.')
else:
class SingleUserLabApp(SingleUserNotebookApp, LabApp):
def init_webapp(self, *args, **kwargs):
super().init_webapp(*args, **kwargs)
settings = self.web_app.settings
if 'page_config_data' not in settings:
settings['page_config_data'] = {}
settings['page_config_data']['hub_prefix'] = self.hub_prefix
settings['page_config_data']['hub_host'] = self.hub_host
settings['page_config_data']['hub_user'] = self.user
api_token = os.getenv('JUPYTERHUB_API_TOKEN')
if not api_token:
api_token = ''
if not self.token:
try:
self.token = api_token
except AttributeError:
self.log.error("Can't set self.token")
settings['page_config_data']['token'] = api_token
def main(argv=None):
return SingleUserLabApp.launch_instance(argv)
if __name__ == "__main__":
main()
| <commit_before>from .labapp import LabApp
try:
from jupyterhub.singleuser import SingleUserNotebookApp
except ImportError:
SingleUserLabApp = None
raise ImportError('You must have jupyterhub installed for this to work.')
else:
class SingleUserLabApp(SingleUserNotebookApp, LabApp):
def init_webapp(self, *args, **kwargs):
super().init_webapp(*args, **kwargs)
settings = self.web_app.settings
if 'page_config_data' not in settings:
settings['page_config_data'] = {}
settings['page_config_data']['hub_prefix'] = self.hub_prefix
settings['page_config_data']['hub_host'] = self.hub_host
settings['page_config_data']['hub_user'] = self.user
def main(argv=None):
return SingleUserLabApp.launch_instance(argv)
if __name__ == "__main__":
main()
<commit_msg>Add api_token from environment, if it's present.<commit_after>import os
from .labapp import LabApp
try:
from jupyterhub.singleuser import SingleUserNotebookApp
except ImportError:
SingleUserLabApp = None
raise ImportError('You must have jupyterhub installed for this to work.')
else:
class SingleUserLabApp(SingleUserNotebookApp, LabApp):
def init_webapp(self, *args, **kwargs):
super().init_webapp(*args, **kwargs)
settings = self.web_app.settings
if 'page_config_data' not in settings:
settings['page_config_data'] = {}
settings['page_config_data']['hub_prefix'] = self.hub_prefix
settings['page_config_data']['hub_host'] = self.hub_host
settings['page_config_data']['hub_user'] = self.user
api_token = os.getenv('JUPYTERHUB_API_TOKEN')
if not api_token:
api_token = ''
if not self.token:
try:
self.token = api_token
except AttributeError:
self.log.error("Can't set self.token")
settings['page_config_data']['token'] = api_token
def main(argv=None):
return SingleUserLabApp.launch_instance(argv)
if __name__ == "__main__":
main()
|
647cb620ffc1ec353a5c9c9d8b5a2965b50647bb | ui/transformations/TransformBox.py | ui/transformations/TransformBox.py | """
TransformBox
:Authors:
Berend Klein Haneveld
"""
from ui.Interactor import Interactor
from PySide.QtCore import QObject
from vtk import vtkBoxWidget
from vtk import vtkTransform
from PySide.QtCore import Signal
class TransformBox(QObject, Interactor):
"""
TransformBox
"""
transformUpdated = Signal(object)
def __init__(self):
super(TransformBox, self).__init__()
def setWidget(self, widget):
self.widget = widget
def cleanUp(self):
# Hide the transformation box
self.transformBox.EnabledOff()
self.cleanUpCallbacks()
def setImageData(self, imageData):
self.transformBox = vtkBoxWidget()
self.transformBox.SetInteractor(self.widget.rwi)
self.transformBox.SetPlaceFactor(1.01)
self.transformBox.SetInputData(imageData)
self.transformBox.SetDefaultRenderer(self.widget.renderer)
self.transformBox.InsideOutOn()
self.transformBox.PlaceWidget()
self.AddObserver(self.transformBox, "InteractionEvent", self.transformCallback)
self.transformBox.GetSelectedFaceProperty().SetOpacity(0.3)
self.transformBox.EnabledOn()
def setTransform(self, transform):
self.transformBox.SetTransform(transform)
def transformCallback(self, arg1, arg2):
transform = vtkTransform()
arg1.GetTransform(transform)
self.transformUpdated.emit(transform)
| """
TransformBox
:Authors:
Berend Klein Haneveld
"""
from ui.Interactor import Interactor
from PySide.QtCore import QObject
from vtk import vtkBoxWidget
from vtk import vtkTransform
from PySide.QtCore import Signal
class TransformBox(QObject, Interactor):
"""
TransformBox
"""
transformUpdated = Signal(object)
def __init__(self):
super(TransformBox, self).__init__()
def setWidget(self, widget):
self.widget = widget
def cleanUp(self):
# Hide the transformation box
self.transformBox.EnabledOff()
self.cleanUpCallbacks()
def setImageData(self, imageData):
self.transformBox = vtkBoxWidget()
self.transformBox.SetInteractor(self.widget.rwi)
self.transformBox.SetPlaceFactor(1.01)
self.transformBox.SetInputData(imageData)
self.transformBox.SetDefaultRenderer(self.widget.rendererOverlay)
self.transformBox.InsideOutOn()
self.transformBox.PlaceWidget()
self.AddObserver(self.transformBox, "InteractionEvent", self.transformCallback)
self.transformBox.GetSelectedFaceProperty().SetOpacity(0.3)
self.transformBox.EnabledOn()
def setTransform(self, transform):
self.transformBox.SetTransform(transform)
def transformCallback(self, arg1, arg2):
transform = vtkTransform()
arg1.GetTransform(transform)
self.transformUpdated.emit(transform)
| Put the transform box in the overlay render for better interaction. | Put the transform box in the overlay render for better interaction.
| Python | mit | berendkleinhaneveld/Registrationshop,berendkleinhaneveld/Registrationshop | """
TransformBox
:Authors:
Berend Klein Haneveld
"""
from ui.Interactor import Interactor
from PySide.QtCore import QObject
from vtk import vtkBoxWidget
from vtk import vtkTransform
from PySide.QtCore import Signal
class TransformBox(QObject, Interactor):
"""
TransformBox
"""
transformUpdated = Signal(object)
def __init__(self):
super(TransformBox, self).__init__()
def setWidget(self, widget):
self.widget = widget
def cleanUp(self):
# Hide the transformation box
self.transformBox.EnabledOff()
self.cleanUpCallbacks()
def setImageData(self, imageData):
self.transformBox = vtkBoxWidget()
self.transformBox.SetInteractor(self.widget.rwi)
self.transformBox.SetPlaceFactor(1.01)
self.transformBox.SetInputData(imageData)
self.transformBox.SetDefaultRenderer(self.widget.renderer)
self.transformBox.InsideOutOn()
self.transformBox.PlaceWidget()
self.AddObserver(self.transformBox, "InteractionEvent", self.transformCallback)
self.transformBox.GetSelectedFaceProperty().SetOpacity(0.3)
self.transformBox.EnabledOn()
def setTransform(self, transform):
self.transformBox.SetTransform(transform)
def transformCallback(self, arg1, arg2):
transform = vtkTransform()
arg1.GetTransform(transform)
self.transformUpdated.emit(transform)
Put the transform box in the overlay render for better interaction. | """
TransformBox
:Authors:
Berend Klein Haneveld
"""
from ui.Interactor import Interactor
from PySide.QtCore import QObject
from vtk import vtkBoxWidget
from vtk import vtkTransform
from PySide.QtCore import Signal
class TransformBox(QObject, Interactor):
"""
TransformBox
"""
transformUpdated = Signal(object)
def __init__(self):
super(TransformBox, self).__init__()
def setWidget(self, widget):
self.widget = widget
def cleanUp(self):
# Hide the transformation box
self.transformBox.EnabledOff()
self.cleanUpCallbacks()
def setImageData(self, imageData):
self.transformBox = vtkBoxWidget()
self.transformBox.SetInteractor(self.widget.rwi)
self.transformBox.SetPlaceFactor(1.01)
self.transformBox.SetInputData(imageData)
self.transformBox.SetDefaultRenderer(self.widget.rendererOverlay)
self.transformBox.InsideOutOn()
self.transformBox.PlaceWidget()
self.AddObserver(self.transformBox, "InteractionEvent", self.transformCallback)
self.transformBox.GetSelectedFaceProperty().SetOpacity(0.3)
self.transformBox.EnabledOn()
def setTransform(self, transform):
self.transformBox.SetTransform(transform)
def transformCallback(self, arg1, arg2):
transform = vtkTransform()
arg1.GetTransform(transform)
self.transformUpdated.emit(transform)
| <commit_before>"""
TransformBox
:Authors:
Berend Klein Haneveld
"""
from ui.Interactor import Interactor
from PySide.QtCore import QObject
from vtk import vtkBoxWidget
from vtk import vtkTransform
from PySide.QtCore import Signal
class TransformBox(QObject, Interactor):
"""
TransformBox
"""
transformUpdated = Signal(object)
def __init__(self):
super(TransformBox, self).__init__()
def setWidget(self, widget):
self.widget = widget
def cleanUp(self):
# Hide the transformation box
self.transformBox.EnabledOff()
self.cleanUpCallbacks()
def setImageData(self, imageData):
self.transformBox = vtkBoxWidget()
self.transformBox.SetInteractor(self.widget.rwi)
self.transformBox.SetPlaceFactor(1.01)
self.transformBox.SetInputData(imageData)
self.transformBox.SetDefaultRenderer(self.widget.renderer)
self.transformBox.InsideOutOn()
self.transformBox.PlaceWidget()
self.AddObserver(self.transformBox, "InteractionEvent", self.transformCallback)
self.transformBox.GetSelectedFaceProperty().SetOpacity(0.3)
self.transformBox.EnabledOn()
def setTransform(self, transform):
self.transformBox.SetTransform(transform)
def transformCallback(self, arg1, arg2):
transform = vtkTransform()
arg1.GetTransform(transform)
self.transformUpdated.emit(transform)
<commit_msg>Put the transform box in the overlay render for better interaction.<commit_after> | """
TransformBox
:Authors:
Berend Klein Haneveld
"""
from ui.Interactor import Interactor
from PySide.QtCore import QObject
from vtk import vtkBoxWidget
from vtk import vtkTransform
from PySide.QtCore import Signal
class TransformBox(QObject, Interactor):
"""
TransformBox
"""
transformUpdated = Signal(object)
def __init__(self):
super(TransformBox, self).__init__()
def setWidget(self, widget):
self.widget = widget
def cleanUp(self):
# Hide the transformation box
self.transformBox.EnabledOff()
self.cleanUpCallbacks()
def setImageData(self, imageData):
self.transformBox = vtkBoxWidget()
self.transformBox.SetInteractor(self.widget.rwi)
self.transformBox.SetPlaceFactor(1.01)
self.transformBox.SetInputData(imageData)
self.transformBox.SetDefaultRenderer(self.widget.rendererOverlay)
self.transformBox.InsideOutOn()
self.transformBox.PlaceWidget()
self.AddObserver(self.transformBox, "InteractionEvent", self.transformCallback)
self.transformBox.GetSelectedFaceProperty().SetOpacity(0.3)
self.transformBox.EnabledOn()
def setTransform(self, transform):
self.transformBox.SetTransform(transform)
def transformCallback(self, arg1, arg2):
transform = vtkTransform()
arg1.GetTransform(transform)
self.transformUpdated.emit(transform)
| """
TransformBox
:Authors:
Berend Klein Haneveld
"""
from ui.Interactor import Interactor
from PySide.QtCore import QObject
from vtk import vtkBoxWidget
from vtk import vtkTransform
from PySide.QtCore import Signal
class TransformBox(QObject, Interactor):
"""
TransformBox
"""
transformUpdated = Signal(object)
def __init__(self):
super(TransformBox, self).__init__()
def setWidget(self, widget):
self.widget = widget
def cleanUp(self):
# Hide the transformation box
self.transformBox.EnabledOff()
self.cleanUpCallbacks()
def setImageData(self, imageData):
self.transformBox = vtkBoxWidget()
self.transformBox.SetInteractor(self.widget.rwi)
self.transformBox.SetPlaceFactor(1.01)
self.transformBox.SetInputData(imageData)
self.transformBox.SetDefaultRenderer(self.widget.renderer)
self.transformBox.InsideOutOn()
self.transformBox.PlaceWidget()
self.AddObserver(self.transformBox, "InteractionEvent", self.transformCallback)
self.transformBox.GetSelectedFaceProperty().SetOpacity(0.3)
self.transformBox.EnabledOn()
def setTransform(self, transform):
self.transformBox.SetTransform(transform)
def transformCallback(self, arg1, arg2):
transform = vtkTransform()
arg1.GetTransform(transform)
self.transformUpdated.emit(transform)
Put the transform box in the overlay render for better interaction."""
TransformBox
:Authors:
Berend Klein Haneveld
"""
from ui.Interactor import Interactor
from PySide.QtCore import QObject
from vtk import vtkBoxWidget
from vtk import vtkTransform
from PySide.QtCore import Signal
class TransformBox(QObject, Interactor):
"""
TransformBox
"""
transformUpdated = Signal(object)
def __init__(self):
super(TransformBox, self).__init__()
def setWidget(self, widget):
self.widget = widget
def cleanUp(self):
# Hide the transformation box
self.transformBox.EnabledOff()
self.cleanUpCallbacks()
def setImageData(self, imageData):
self.transformBox = vtkBoxWidget()
self.transformBox.SetInteractor(self.widget.rwi)
self.transformBox.SetPlaceFactor(1.01)
self.transformBox.SetInputData(imageData)
self.transformBox.SetDefaultRenderer(self.widget.rendererOverlay)
self.transformBox.InsideOutOn()
self.transformBox.PlaceWidget()
self.AddObserver(self.transformBox, "InteractionEvent", self.transformCallback)
self.transformBox.GetSelectedFaceProperty().SetOpacity(0.3)
self.transformBox.EnabledOn()
def setTransform(self, transform):
self.transformBox.SetTransform(transform)
def transformCallback(self, arg1, arg2):
transform = vtkTransform()
arg1.GetTransform(transform)
self.transformUpdated.emit(transform)
| <commit_before>"""
TransformBox
:Authors:
Berend Klein Haneveld
"""
from ui.Interactor import Interactor
from PySide.QtCore import QObject
from vtk import vtkBoxWidget
from vtk import vtkTransform
from PySide.QtCore import Signal
class TransformBox(QObject, Interactor):
"""
TransformBox
"""
transformUpdated = Signal(object)
def __init__(self):
super(TransformBox, self).__init__()
def setWidget(self, widget):
self.widget = widget
def cleanUp(self):
# Hide the transformation box
self.transformBox.EnabledOff()
self.cleanUpCallbacks()
def setImageData(self, imageData):
self.transformBox = vtkBoxWidget()
self.transformBox.SetInteractor(self.widget.rwi)
self.transformBox.SetPlaceFactor(1.01)
self.transformBox.SetInputData(imageData)
self.transformBox.SetDefaultRenderer(self.widget.renderer)
self.transformBox.InsideOutOn()
self.transformBox.PlaceWidget()
self.AddObserver(self.transformBox, "InteractionEvent", self.transformCallback)
self.transformBox.GetSelectedFaceProperty().SetOpacity(0.3)
self.transformBox.EnabledOn()
def setTransform(self, transform):
self.transformBox.SetTransform(transform)
def transformCallback(self, arg1, arg2):
transform = vtkTransform()
arg1.GetTransform(transform)
self.transformUpdated.emit(transform)
<commit_msg>Put the transform box in the overlay render for better interaction.<commit_after>"""
TransformBox
:Authors:
Berend Klein Haneveld
"""
from ui.Interactor import Interactor
from PySide.QtCore import QObject
from vtk import vtkBoxWidget
from vtk import vtkTransform
from PySide.QtCore import Signal
class TransformBox(QObject, Interactor):
"""
TransformBox
"""
transformUpdated = Signal(object)
def __init__(self):
super(TransformBox, self).__init__()
def setWidget(self, widget):
self.widget = widget
def cleanUp(self):
# Hide the transformation box
self.transformBox.EnabledOff()
self.cleanUpCallbacks()
def setImageData(self, imageData):
self.transformBox = vtkBoxWidget()
self.transformBox.SetInteractor(self.widget.rwi)
self.transformBox.SetPlaceFactor(1.01)
self.transformBox.SetInputData(imageData)
self.transformBox.SetDefaultRenderer(self.widget.rendererOverlay)
self.transformBox.InsideOutOn()
self.transformBox.PlaceWidget()
self.AddObserver(self.transformBox, "InteractionEvent", self.transformCallback)
self.transformBox.GetSelectedFaceProperty().SetOpacity(0.3)
self.transformBox.EnabledOn()
def setTransform(self, transform):
self.transformBox.SetTransform(transform)
def transformCallback(self, arg1, arg2):
transform = vtkTransform()
arg1.GetTransform(transform)
self.transformUpdated.emit(transform)
|
db1643b27ce3da3af85f90b941f37a8f356c4acb | lcp/settings/staging.py | lcp/settings/staging.py | import os
from lcp.settings.base import * # noqa
# FIXME: The wildcard is only here while testing on Vagrant.
# Host header checking fails without it.
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ['POSTGRES_DB'],
'USER': os.environ['POSTGRES_USER'],
'PASSWORD': os.environ['POSTGRES_PASSWORD'],
}
}
| import os
from lcp.settings.base import * # noqa
# FIXME: The wildcard is only here while testing on Vagrant.
# Host header checking fails without it.
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ['POSTGRES_DB'],
'USER': os.environ['POSTGRES_USER'],
'PASSWORD': os.environ['POSTGRES_PASSWORD'],
'HOST': '127.0.0.1',
}
}
| Connect to Postgres over TCP. | Connect to Postgres over TCP.
| Python | bsd-2-clause | mblayman/lcp,mblayman/lcp,mblayman/lcp | import os
from lcp.settings.base import * # noqa
# FIXME: The wildcard is only here while testing on Vagrant.
# Host header checking fails without it.
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ['POSTGRES_DB'],
'USER': os.environ['POSTGRES_USER'],
'PASSWORD': os.environ['POSTGRES_PASSWORD'],
}
}
Connect to Postgres over TCP. | import os
from lcp.settings.base import * # noqa
# FIXME: The wildcard is only here while testing on Vagrant.
# Host header checking fails without it.
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ['POSTGRES_DB'],
'USER': os.environ['POSTGRES_USER'],
'PASSWORD': os.environ['POSTGRES_PASSWORD'],
'HOST': '127.0.0.1',
}
}
| <commit_before>import os
from lcp.settings.base import * # noqa
# FIXME: The wildcard is only here while testing on Vagrant.
# Host header checking fails without it.
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ['POSTGRES_DB'],
'USER': os.environ['POSTGRES_USER'],
'PASSWORD': os.environ['POSTGRES_PASSWORD'],
}
}
<commit_msg>Connect to Postgres over TCP.<commit_after> | import os
from lcp.settings.base import * # noqa
# FIXME: The wildcard is only here while testing on Vagrant.
# Host header checking fails without it.
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ['POSTGRES_DB'],
'USER': os.environ['POSTGRES_USER'],
'PASSWORD': os.environ['POSTGRES_PASSWORD'],
'HOST': '127.0.0.1',
}
}
| import os
from lcp.settings.base import * # noqa
# FIXME: The wildcard is only here while testing on Vagrant.
# Host header checking fails without it.
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ['POSTGRES_DB'],
'USER': os.environ['POSTGRES_USER'],
'PASSWORD': os.environ['POSTGRES_PASSWORD'],
}
}
Connect to Postgres over TCP.import os
from lcp.settings.base import * # noqa
# FIXME: The wildcard is only here while testing on Vagrant.
# Host header checking fails without it.
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ['POSTGRES_DB'],
'USER': os.environ['POSTGRES_USER'],
'PASSWORD': os.environ['POSTGRES_PASSWORD'],
'HOST': '127.0.0.1',
}
}
| <commit_before>import os
from lcp.settings.base import * # noqa
# FIXME: The wildcard is only here while testing on Vagrant.
# Host header checking fails without it.
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ['POSTGRES_DB'],
'USER': os.environ['POSTGRES_USER'],
'PASSWORD': os.environ['POSTGRES_PASSWORD'],
}
}
<commit_msg>Connect to Postgres over TCP.<commit_after>import os
from lcp.settings.base import * # noqa
# FIXME: The wildcard is only here while testing on Vagrant.
# Host header checking fails without it.
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.environ['POSTGRES_DB'],
'USER': os.environ['POSTGRES_USER'],
'PASSWORD': os.environ['POSTGRES_PASSWORD'],
'HOST': '127.0.0.1',
}
}
|
eb4032b7467a28ee61496c64f84ddef066b908d5 | random_fact_scraper.py | random_fact_scraper.py | #! python3
"""random_fact_scraper.py - Scrape the http://randomfactgenerator.net website."""
import os
import requests
from flask import Flask
from lxml import html
app = Flask(__name__)
@app.route("/")
def main():
page = requests.get("http://randomfactgenerator.net")
tree = html.fromstring(page.content)
facts = tree.xpath("//div[@id='z']/text()")
return list(filter(lambda x: x!= "\n\n", facts))
#-------------------------------------------------------------------------------
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
| #! python3
"""random_fact_scraper.py - Scrape the http://randomfactgenerator.net website."""
import os
import json
import requests
from flask import Flask, Response
from lxml import html
app = Flask(__name__)
@app.route("/")
def main():
page = requests.get("http://randomfactgenerator.net")
tree = html.fromstring(page.content)
facts = list(filter(lambda x: x!= "\n\n",
tree.xpath("//div[@id='z']/text()")))
resp = Response(response=json.dumps(facts),
status=200, \
mimetype="application/json")
# return list(filter(lambda x: x!= "\n\n", facts))
return resp
#-------------------------------------------------------------------------------
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
| Return facts in JSON format. | [upd] Return facts in JSON format.
| Python | mit | marcelombc/randomfactscraper | #! python3
"""random_fact_scraper.py - Scrape the http://randomfactgenerator.net website."""
import os
import requests
from flask import Flask
from lxml import html
app = Flask(__name__)
@app.route("/")
def main():
page = requests.get("http://randomfactgenerator.net")
tree = html.fromstring(page.content)
facts = tree.xpath("//div[@id='z']/text()")
return list(filter(lambda x: x!= "\n\n", facts))
#-------------------------------------------------------------------------------
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
[upd] Return facts in JSON format. | #! python3
"""random_fact_scraper.py - Scrape the http://randomfactgenerator.net website."""
import os
import json
import requests
from flask import Flask, Response
from lxml import html
app = Flask(__name__)
@app.route("/")
def main():
page = requests.get("http://randomfactgenerator.net")
tree = html.fromstring(page.content)
facts = list(filter(lambda x: x!= "\n\n",
tree.xpath("//div[@id='z']/text()")))
resp = Response(response=json.dumps(facts),
status=200, \
mimetype="application/json")
# return list(filter(lambda x: x!= "\n\n", facts))
return resp
#-------------------------------------------------------------------------------
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
| <commit_before>#! python3
"""random_fact_scraper.py - Scrape the http://randomfactgenerator.net website."""
import os
import requests
from flask import Flask
from lxml import html
app = Flask(__name__)
@app.route("/")
def main():
page = requests.get("http://randomfactgenerator.net")
tree = html.fromstring(page.content)
facts = tree.xpath("//div[@id='z']/text()")
return list(filter(lambda x: x!= "\n\n", facts))
#-------------------------------------------------------------------------------
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
<commit_msg>[upd] Return facts in JSON format.<commit_after> | #! python3
"""random_fact_scraper.py - Scrape the http://randomfactgenerator.net website."""
import os
import json
import requests
from flask import Flask, Response
from lxml import html
app = Flask(__name__)
@app.route("/")
def main():
page = requests.get("http://randomfactgenerator.net")
tree = html.fromstring(page.content)
facts = list(filter(lambda x: x!= "\n\n",
tree.xpath("//div[@id='z']/text()")))
resp = Response(response=json.dumps(facts),
status=200, \
mimetype="application/json")
# return list(filter(lambda x: x!= "\n\n", facts))
return resp
#-------------------------------------------------------------------------------
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
| #! python3
"""random_fact_scraper.py - Scrape the http://randomfactgenerator.net website."""
import os
import requests
from flask import Flask
from lxml import html
app = Flask(__name__)
@app.route("/")
def main():
page = requests.get("http://randomfactgenerator.net")
tree = html.fromstring(page.content)
facts = tree.xpath("//div[@id='z']/text()")
return list(filter(lambda x: x!= "\n\n", facts))
#-------------------------------------------------------------------------------
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
[upd] Return facts in JSON format.#! python3
"""random_fact_scraper.py - Scrape the http://randomfactgenerator.net website."""
import os
import json
import requests
from flask import Flask, Response
from lxml import html
app = Flask(__name__)
@app.route("/")
def main():
page = requests.get("http://randomfactgenerator.net")
tree = html.fromstring(page.content)
facts = list(filter(lambda x: x!= "\n\n",
tree.xpath("//div[@id='z']/text()")))
resp = Response(response=json.dumps(facts),
status=200, \
mimetype="application/json")
# return list(filter(lambda x: x!= "\n\n", facts))
return resp
#-------------------------------------------------------------------------------
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
| <commit_before>#! python3
"""random_fact_scraper.py - Scrape the http://randomfactgenerator.net website."""
import os
import requests
from flask import Flask
from lxml import html
app = Flask(__name__)
@app.route("/")
def main():
page = requests.get("http://randomfactgenerator.net")
tree = html.fromstring(page.content)
facts = tree.xpath("//div[@id='z']/text()")
return list(filter(lambda x: x!= "\n\n", facts))
#-------------------------------------------------------------------------------
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
<commit_msg>[upd] Return facts in JSON format.<commit_after>#! python3
"""random_fact_scraper.py - Scrape the http://randomfactgenerator.net website."""
import os
import json
import requests
from flask import Flask, Response
from lxml import html
app = Flask(__name__)
@app.route("/")
def main():
page = requests.get("http://randomfactgenerator.net")
tree = html.fromstring(page.content)
facts = list(filter(lambda x: x!= "\n\n",
tree.xpath("//div[@id='z']/text()")))
resp = Response(response=json.dumps(facts),
status=200, \
mimetype="application/json")
# return list(filter(lambda x: x!= "\n\n", facts))
return resp
#-------------------------------------------------------------------------------
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port)
|
f966522875e473276170f59933b288ea207b68a1 | backend/django/apps/accounts/urls.py | backend/django/apps/accounts/urls.py | """
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/users/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
3. Add as parameters an object of type dict representing the method type
with it's key e.g. get or post, and the name of the action with
it's value
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from rest_framework import routers
from .views import AccountViewSet
router = routers.SimpleRouter()
router.register(prefix=r'^accounts', viewset=AccountViewSet)
urlpatterns = router.urls
| """
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/users/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
3. Add as parameters an object of type dict representing the method type
with it's key e.g. get or post, and the name of the action with
it's value
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from rest_framework import routers
from .views import AccountViewSet
router = routers.SimpleRouter()
router.register(prefix=r'^accounts', viewset=AccountViewSet)
urlpatterns = router.urls
| Create url config for accounts | Create url config for accounts
| Python | mit | slavpetroff/sweetshop,slavpetroff/sweetshop | """
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/users/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
3. Add as parameters an object of type dict representing the method type
with it's key e.g. get or post, and the name of the action with
it's value
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from rest_framework import routers
from .views import AccountViewSet
router = routers.SimpleRouter()
router.register(prefix=r'^accounts', viewset=AccountViewSet)
urlpatterns = router.urls
Create url config for accounts | """
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/users/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
3. Add as parameters an object of type dict representing the method type
with it's key e.g. get or post, and the name of the action with
it's value
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from rest_framework import routers
from .views import AccountViewSet
router = routers.SimpleRouter()
router.register(prefix=r'^accounts', viewset=AccountViewSet)
urlpatterns = router.urls
| <commit_before>"""
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/users/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
3. Add as parameters an object of type dict representing the method type
with it's key e.g. get or post, and the name of the action with
it's value
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from rest_framework import routers
from .views import AccountViewSet
router = routers.SimpleRouter()
router.register(prefix=r'^accounts', viewset=AccountViewSet)
urlpatterns = router.urls
<commit_msg>Create url config for accounts<commit_after> | """
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/users/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
3. Add as parameters an object of type dict representing the method type
with it's key e.g. get or post, and the name of the action with
it's value
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from rest_framework import routers
from .views import AccountViewSet
router = routers.SimpleRouter()
router.register(prefix=r'^accounts', viewset=AccountViewSet)
urlpatterns = router.urls
| """
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/users/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
3. Add as parameters an object of type dict representing the method type
with it's key e.g. get or post, and the name of the action with
it's value
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from rest_framework import routers
from .views import AccountViewSet
router = routers.SimpleRouter()
router.register(prefix=r'^accounts', viewset=AccountViewSet)
urlpatterns = router.urls
Create url config for accounts"""
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/users/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
3. Add as parameters an object of type dict representing the method type
with it's key e.g. get or post, and the name of the action with
it's value
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from rest_framework import routers
from .views import AccountViewSet
router = routers.SimpleRouter()
router.register(prefix=r'^accounts', viewset=AccountViewSet)
urlpatterns = router.urls
| <commit_before>"""
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/users/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
3. Add as parameters an object of type dict representing the method type
with it's key e.g. get or post, and the name of the action with
it's value
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from rest_framework import routers
from .views import AccountViewSet
router = routers.SimpleRouter()
router.register(prefix=r'^accounts', viewset=AccountViewSet)
urlpatterns = router.urls
<commit_msg>Create url config for accounts<commit_after>"""
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/users/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
3. Add as parameters an object of type dict representing the method type
with it's key e.g. get or post, and the name of the action with
it's value
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from rest_framework import routers
from .views import AccountViewSet
router = routers.SimpleRouter()
router.register(prefix=r'^accounts', viewset=AccountViewSet)
urlpatterns = router.urls
|
4ec5a83837fada00f77c25ff0f4725714a88420a | bokeh/models/tests/test_renderers.py | bokeh/models/tests/test_renderers.py | from __future__ import absolute_import
import unittest
from mock import patch
from bokeh.models.renderers import GlyphRenderer
from bokeh.plotting import ColumnDataSource, figure
from bokeh.validation import check_integrity
class TestGlyphRenderer(unittest.TestCase):
def test_warning_about_colons_in_column_labels(self):
sh = ['0', '1:0']
p = figure()
p.rect('a', 'b', 1, 1, source=ColumnDataSource(data={'a': sh, 'b': sh}))
renderer = p.renderers[-1]
errors = renderer._check_colon_in_category_label()
self.assertEqual(errors, [(
1003,
'COLON_IN_CATEGORY_LABEL',
'Category label contains colons',
'[field:a] [first_value: 1:0] [field:b] [first_value: 1:0] '
'[renderer: '
'GlyphRenderer, ViewModel:GlyphRenderer, ref _id: '
'%s]' % renderer._id
)])
if __name__ == '__main__':
unittest.main()
| from __future__ import absolute_import
import unittest
from mock import patch
from bokeh.models.renderers import GlyphRenderer
from bokeh.plotting import ColumnDataSource, figure
from bokeh.validation import check_integrity
class TestGlyphRenderer(unittest.TestCase):
def test_warning_about_colons_in_column_labels(self):
sh = ['0', '1:0']
plot = figure()
plot.rect('a', 'b', 1, 1, source=ColumnDataSource(data={'a': sh, 'b': sh}))
renderer = plot.select({'type': GlyphRenderer})[0]
errors = renderer._check_colon_in_category_label()
self.assertEqual(errors, [(
1003,
'COLON_IN_CATEGORY_LABEL',
'Category label contains colons',
'[field:a] [first_value: 1:0] [field:b] [first_value: 1:0] '
'[renderer: '
'GlyphRenderer, ViewModel:GlyphRenderer, ref _id: '
'%s]' % renderer._id
)])
if __name__ == '__main__':
unittest.main()
| Fix direct glyph selection with select method | Fix direct glyph selection with select method
| Python | bsd-3-clause | xguse/bokeh,Karel-van-de-Plassche/bokeh,mindriot101/bokeh,aavanian/bokeh,evidation-health/bokeh,matbra/bokeh,KasperPRasmussen/bokeh,philippjfr/bokeh,timsnyder/bokeh,htygithub/bokeh,tacaswell/bokeh,paultcochrane/bokeh,bokeh/bokeh,justacec/bokeh,DuCorey/bokeh,msarahan/bokeh,htygithub/bokeh,jakirkham/bokeh,jplourenco/bokeh,clairetang6/bokeh,rs2/bokeh,ericmjl/bokeh,phobson/bokeh,stonebig/bokeh,tacaswell/bokeh,timsnyder/bokeh,muku42/bokeh,saifrahmed/bokeh,gpfreitas/bokeh,aiguofer/bokeh,deeplook/bokeh,draperjames/bokeh,timsnyder/bokeh,DuCorey/bokeh,maxalbert/bokeh,schoolie/bokeh,khkaminska/bokeh,justacec/bokeh,mindriot101/bokeh,paultcochrane/bokeh,philippjfr/bokeh,daodaoliang/bokeh,muku42/bokeh,rothnic/bokeh,philippjfr/bokeh,phobson/bokeh,maxalbert/bokeh,khkaminska/bokeh,bokeh/bokeh,KasperPRasmussen/bokeh,clairetang6/bokeh,ChinaQuants/bokeh,deeplook/bokeh,phobson/bokeh,gpfreitas/bokeh,bokeh/bokeh,dennisobrien/bokeh,justacec/bokeh,KasperPRasmussen/bokeh,quasiben/bokeh,percyfal/bokeh,msarahan/bokeh,ericdill/bokeh,Karel-van-de-Plassche/bokeh,rothnic/bokeh,ptitjano/bokeh,KasperPRasmussen/bokeh,aiguofer/bokeh,azjps/bokeh,draperjames/bokeh,ptitjano/bokeh,stonebig/bokeh,jplourenco/bokeh,deeplook/bokeh,clairetang6/bokeh,khkaminska/bokeh,jplourenco/bokeh,aavanian/bokeh,clairetang6/bokeh,evidation-health/bokeh,schoolie/bokeh,dennisobrien/bokeh,jakirkham/bokeh,schoolie/bokeh,rothnic/bokeh,muku42/bokeh,tacaswell/bokeh,percyfal/bokeh,schoolie/bokeh,ptitjano/bokeh,ericmjl/bokeh,azjps/bokeh,ericmjl/bokeh,muku42/bokeh,matbra/bokeh,xguse/bokeh,jakirkham/bokeh,gpfreitas/bokeh,aavanian/bokeh,htygithub/bokeh,matbra/bokeh,aiguofer/bokeh,saifrahmed/bokeh,schoolie/bokeh,justacec/bokeh,srinathv/bokeh,paultcochrane/bokeh,jakirkham/bokeh,aiguofer/bokeh,philippjfr/bokeh,draperjames/bokeh,khkaminska/bokeh,Karel-van-de-Plassche/bokeh,daodaoliang/bokeh,xguse/bokeh,evidation-health/bokeh,mindriot101/bokeh,dennisobrien/bokeh,ChinaQuants/bokeh,ericmjl/bokeh,aiguofer/bokeh,DuCorey/bokeh,percyfal/bokeh,bokeh/bokeh,rs2/bokeh,rs2/bokeh,bokeh/bokeh,srinathv/bokeh,saifrahmed/bokeh,draperjames/bokeh,jplourenco/bokeh,evidation-health/bokeh,quasiben/bokeh,percyfal/bokeh,phobson/bokeh,maxalbert/bokeh,DuCorey/bokeh,maxalbert/bokeh,msarahan/bokeh,ChinaQuants/bokeh,philippjfr/bokeh,timsnyder/bokeh,tacaswell/bokeh,paultcochrane/bokeh,timsnyder/bokeh,gpfreitas/bokeh,percyfal/bokeh,draperjames/bokeh,ericdill/bokeh,mindriot101/bokeh,dennisobrien/bokeh,dennisobrien/bokeh,deeplook/bokeh,ptitjano/bokeh,KasperPRasmussen/bokeh,rs2/bokeh,aavanian/bokeh,ptitjano/bokeh,matbra/bokeh,ChinaQuants/bokeh,azjps/bokeh,aavanian/bokeh,ericdill/bokeh,ericdill/bokeh,rs2/bokeh,saifrahmed/bokeh,daodaoliang/bokeh,DuCorey/bokeh,stonebig/bokeh,azjps/bokeh,xguse/bokeh,htygithub/bokeh,phobson/bokeh,daodaoliang/bokeh,stonebig/bokeh,Karel-van-de-Plassche/bokeh,quasiben/bokeh,srinathv/bokeh,azjps/bokeh,ericmjl/bokeh,jakirkham/bokeh,rothnic/bokeh,srinathv/bokeh,msarahan/bokeh,Karel-van-de-Plassche/bokeh | from __future__ import absolute_import
import unittest
from mock import patch
from bokeh.models.renderers import GlyphRenderer
from bokeh.plotting import ColumnDataSource, figure
from bokeh.validation import check_integrity
class TestGlyphRenderer(unittest.TestCase):
def test_warning_about_colons_in_column_labels(self):
sh = ['0', '1:0']
p = figure()
p.rect('a', 'b', 1, 1, source=ColumnDataSource(data={'a': sh, 'b': sh}))
renderer = p.renderers[-1]
errors = renderer._check_colon_in_category_label()
self.assertEqual(errors, [(
1003,
'COLON_IN_CATEGORY_LABEL',
'Category label contains colons',
'[field:a] [first_value: 1:0] [field:b] [first_value: 1:0] '
'[renderer: '
'GlyphRenderer, ViewModel:GlyphRenderer, ref _id: '
'%s]' % renderer._id
)])
if __name__ == '__main__':
unittest.main()
Fix direct glyph selection with select method | from __future__ import absolute_import
import unittest
from mock import patch
from bokeh.models.renderers import GlyphRenderer
from bokeh.plotting import ColumnDataSource, figure
from bokeh.validation import check_integrity
class TestGlyphRenderer(unittest.TestCase):
def test_warning_about_colons_in_column_labels(self):
sh = ['0', '1:0']
plot = figure()
plot.rect('a', 'b', 1, 1, source=ColumnDataSource(data={'a': sh, 'b': sh}))
renderer = plot.select({'type': GlyphRenderer})[0]
errors = renderer._check_colon_in_category_label()
self.assertEqual(errors, [(
1003,
'COLON_IN_CATEGORY_LABEL',
'Category label contains colons',
'[field:a] [first_value: 1:0] [field:b] [first_value: 1:0] '
'[renderer: '
'GlyphRenderer, ViewModel:GlyphRenderer, ref _id: '
'%s]' % renderer._id
)])
if __name__ == '__main__':
unittest.main()
| <commit_before>from __future__ import absolute_import
import unittest
from mock import patch
from bokeh.models.renderers import GlyphRenderer
from bokeh.plotting import ColumnDataSource, figure
from bokeh.validation import check_integrity
class TestGlyphRenderer(unittest.TestCase):
def test_warning_about_colons_in_column_labels(self):
sh = ['0', '1:0']
p = figure()
p.rect('a', 'b', 1, 1, source=ColumnDataSource(data={'a': sh, 'b': sh}))
renderer = p.renderers[-1]
errors = renderer._check_colon_in_category_label()
self.assertEqual(errors, [(
1003,
'COLON_IN_CATEGORY_LABEL',
'Category label contains colons',
'[field:a] [first_value: 1:0] [field:b] [first_value: 1:0] '
'[renderer: '
'GlyphRenderer, ViewModel:GlyphRenderer, ref _id: '
'%s]' % renderer._id
)])
if __name__ == '__main__':
unittest.main()
<commit_msg>Fix direct glyph selection with select method<commit_after> | from __future__ import absolute_import
import unittest
from mock import patch
from bokeh.models.renderers import GlyphRenderer
from bokeh.plotting import ColumnDataSource, figure
from bokeh.validation import check_integrity
class TestGlyphRenderer(unittest.TestCase):
def test_warning_about_colons_in_column_labels(self):
sh = ['0', '1:0']
plot = figure()
plot.rect('a', 'b', 1, 1, source=ColumnDataSource(data={'a': sh, 'b': sh}))
renderer = plot.select({'type': GlyphRenderer})[0]
errors = renderer._check_colon_in_category_label()
self.assertEqual(errors, [(
1003,
'COLON_IN_CATEGORY_LABEL',
'Category label contains colons',
'[field:a] [first_value: 1:0] [field:b] [first_value: 1:0] '
'[renderer: '
'GlyphRenderer, ViewModel:GlyphRenderer, ref _id: '
'%s]' % renderer._id
)])
if __name__ == '__main__':
unittest.main()
| from __future__ import absolute_import
import unittest
from mock import patch
from bokeh.models.renderers import GlyphRenderer
from bokeh.plotting import ColumnDataSource, figure
from bokeh.validation import check_integrity
class TestGlyphRenderer(unittest.TestCase):
def test_warning_about_colons_in_column_labels(self):
sh = ['0', '1:0']
p = figure()
p.rect('a', 'b', 1, 1, source=ColumnDataSource(data={'a': sh, 'b': sh}))
renderer = p.renderers[-1]
errors = renderer._check_colon_in_category_label()
self.assertEqual(errors, [(
1003,
'COLON_IN_CATEGORY_LABEL',
'Category label contains colons',
'[field:a] [first_value: 1:0] [field:b] [first_value: 1:0] '
'[renderer: '
'GlyphRenderer, ViewModel:GlyphRenderer, ref _id: '
'%s]' % renderer._id
)])
if __name__ == '__main__':
unittest.main()
Fix direct glyph selection with select methodfrom __future__ import absolute_import
import unittest
from mock import patch
from bokeh.models.renderers import GlyphRenderer
from bokeh.plotting import ColumnDataSource, figure
from bokeh.validation import check_integrity
class TestGlyphRenderer(unittest.TestCase):
def test_warning_about_colons_in_column_labels(self):
sh = ['0', '1:0']
plot = figure()
plot.rect('a', 'b', 1, 1, source=ColumnDataSource(data={'a': sh, 'b': sh}))
renderer = plot.select({'type': GlyphRenderer})[0]
errors = renderer._check_colon_in_category_label()
self.assertEqual(errors, [(
1003,
'COLON_IN_CATEGORY_LABEL',
'Category label contains colons',
'[field:a] [first_value: 1:0] [field:b] [first_value: 1:0] '
'[renderer: '
'GlyphRenderer, ViewModel:GlyphRenderer, ref _id: '
'%s]' % renderer._id
)])
if __name__ == '__main__':
unittest.main()
| <commit_before>from __future__ import absolute_import
import unittest
from mock import patch
from bokeh.models.renderers import GlyphRenderer
from bokeh.plotting import ColumnDataSource, figure
from bokeh.validation import check_integrity
class TestGlyphRenderer(unittest.TestCase):
def test_warning_about_colons_in_column_labels(self):
sh = ['0', '1:0']
p = figure()
p.rect('a', 'b', 1, 1, source=ColumnDataSource(data={'a': sh, 'b': sh}))
renderer = p.renderers[-1]
errors = renderer._check_colon_in_category_label()
self.assertEqual(errors, [(
1003,
'COLON_IN_CATEGORY_LABEL',
'Category label contains colons',
'[field:a] [first_value: 1:0] [field:b] [first_value: 1:0] '
'[renderer: '
'GlyphRenderer, ViewModel:GlyphRenderer, ref _id: '
'%s]' % renderer._id
)])
if __name__ == '__main__':
unittest.main()
<commit_msg>Fix direct glyph selection with select method<commit_after>from __future__ import absolute_import
import unittest
from mock import patch
from bokeh.models.renderers import GlyphRenderer
from bokeh.plotting import ColumnDataSource, figure
from bokeh.validation import check_integrity
class TestGlyphRenderer(unittest.TestCase):
def test_warning_about_colons_in_column_labels(self):
sh = ['0', '1:0']
plot = figure()
plot.rect('a', 'b', 1, 1, source=ColumnDataSource(data={'a': sh, 'b': sh}))
renderer = plot.select({'type': GlyphRenderer})[0]
errors = renderer._check_colon_in_category_label()
self.assertEqual(errors, [(
1003,
'COLON_IN_CATEGORY_LABEL',
'Category label contains colons',
'[field:a] [first_value: 1:0] [field:b] [first_value: 1:0] '
'[renderer: '
'GlyphRenderer, ViewModel:GlyphRenderer, ref _id: '
'%s]' % renderer._id
)])
if __name__ == '__main__':
unittest.main()
|
633248dd521b6868937d3fb838d39264fc170c61 | greengraph/test/map_integration.py | greengraph/test/map_integration.py | from mock import patch
from mock import Mock
from greengraph import Map
import requests
from matplotlib import image as img
from StringIO import StringIO
with open('image.txt','r') as source:
text = source.read()
lat=51
long=30
satellite=True
zoom=10
size=(400,400)
sensor=False
params=dict(
sensor= str(sensor).lower(),
zoom= zoom,
size= "x".join(map(str, size)),
center= ",".join(map(str, (lat, long) )),
style="feature:all|element:labels|visibility:off"
)
base="http://maps.googleapis.com/maps/api/staticmap?"
text = requests.get(base, params=params).content # Fetch our PNG image data
text = 'hello'
image = Mock()
image.content = text
patch_get = Mock(return_value=image)
with patch.object(requests,'get',patch_get) as mock_get:
with patch.object(img,'imread') as mock_imread:
london_map = Map(52, 0)
print mock_get.mock_calls
print mock_imread.mock_calls
print london_map.count_green()
| from mock import patch
from mock import Mock
from greengraph import Map
import requests
from matplotlib import image as img
from StringIO import StringIO
patch_get = Mock()
patch_get.content = ''
image_array = img.imread('image.png')
patch_imread = Mock(return_value=image_array)
with patch.object(requests,'get',patch_get) as mock_get:
with patch.object(img,'imread',patch_imread) as mock_imread:
my_map = Map(0, 0)
print mock_get.mock_calls
print mock_imread.mock_calls
print my_map.count_green()
| Update Map integration test so that Map is fed a PNG from a local image.png file rather than from the internet. | Update Map integration test so that Map is fed a PNG from a local image.png file rather than from the internet.
| Python | apache-2.0 | paulsbrookes/greengraph | from mock import patch
from mock import Mock
from greengraph import Map
import requests
from matplotlib import image as img
from StringIO import StringIO
with open('image.txt','r') as source:
text = source.read()
lat=51
long=30
satellite=True
zoom=10
size=(400,400)
sensor=False
params=dict(
sensor= str(sensor).lower(),
zoom= zoom,
size= "x".join(map(str, size)),
center= ",".join(map(str, (lat, long) )),
style="feature:all|element:labels|visibility:off"
)
base="http://maps.googleapis.com/maps/api/staticmap?"
text = requests.get(base, params=params).content # Fetch our PNG image data
text = 'hello'
image = Mock()
image.content = text
patch_get = Mock(return_value=image)
with patch.object(requests,'get',patch_get) as mock_get:
with patch.object(img,'imread') as mock_imread:
london_map = Map(52, 0)
print mock_get.mock_calls
print mock_imread.mock_calls
print london_map.count_green()
Update Map integration test so that Map is fed a PNG from a local image.png file rather than from the internet. | from mock import patch
from mock import Mock
from greengraph import Map
import requests
from matplotlib import image as img
from StringIO import StringIO
patch_get = Mock()
patch_get.content = ''
image_array = img.imread('image.png')
patch_imread = Mock(return_value=image_array)
with patch.object(requests,'get',patch_get) as mock_get:
with patch.object(img,'imread',patch_imread) as mock_imread:
my_map = Map(0, 0)
print mock_get.mock_calls
print mock_imread.mock_calls
print my_map.count_green()
| <commit_before>from mock import patch
from mock import Mock
from greengraph import Map
import requests
from matplotlib import image as img
from StringIO import StringIO
with open('image.txt','r') as source:
text = source.read()
lat=51
long=30
satellite=True
zoom=10
size=(400,400)
sensor=False
params=dict(
sensor= str(sensor).lower(),
zoom= zoom,
size= "x".join(map(str, size)),
center= ",".join(map(str, (lat, long) )),
style="feature:all|element:labels|visibility:off"
)
base="http://maps.googleapis.com/maps/api/staticmap?"
text = requests.get(base, params=params).content # Fetch our PNG image data
text = 'hello'
image = Mock()
image.content = text
patch_get = Mock(return_value=image)
with patch.object(requests,'get',patch_get) as mock_get:
with patch.object(img,'imread') as mock_imread:
london_map = Map(52, 0)
print mock_get.mock_calls
print mock_imread.mock_calls
print london_map.count_green()
<commit_msg>Update Map integration test so that Map is fed a PNG from a local image.png file rather than from the internet.<commit_after> | from mock import patch
from mock import Mock
from greengraph import Map
import requests
from matplotlib import image as img
from StringIO import StringIO
patch_get = Mock()
patch_get.content = ''
image_array = img.imread('image.png')
patch_imread = Mock(return_value=image_array)
with patch.object(requests,'get',patch_get) as mock_get:
with patch.object(img,'imread',patch_imread) as mock_imread:
my_map = Map(0, 0)
print mock_get.mock_calls
print mock_imread.mock_calls
print my_map.count_green()
| from mock import patch
from mock import Mock
from greengraph import Map
import requests
from matplotlib import image as img
from StringIO import StringIO
with open('image.txt','r') as source:
text = source.read()
lat=51
long=30
satellite=True
zoom=10
size=(400,400)
sensor=False
params=dict(
sensor= str(sensor).lower(),
zoom= zoom,
size= "x".join(map(str, size)),
center= ",".join(map(str, (lat, long) )),
style="feature:all|element:labels|visibility:off"
)
base="http://maps.googleapis.com/maps/api/staticmap?"
text = requests.get(base, params=params).content # Fetch our PNG image data
text = 'hello'
image = Mock()
image.content = text
patch_get = Mock(return_value=image)
with patch.object(requests,'get',patch_get) as mock_get:
with patch.object(img,'imread') as mock_imread:
london_map = Map(52, 0)
print mock_get.mock_calls
print mock_imread.mock_calls
print london_map.count_green()
Update Map integration test so that Map is fed a PNG from a local image.png file rather than from the internet.from mock import patch
from mock import Mock
from greengraph import Map
import requests
from matplotlib import image as img
from StringIO import StringIO
patch_get = Mock()
patch_get.content = ''
image_array = img.imread('image.png')
patch_imread = Mock(return_value=image_array)
with patch.object(requests,'get',patch_get) as mock_get:
with patch.object(img,'imread',patch_imread) as mock_imread:
my_map = Map(0, 0)
print mock_get.mock_calls
print mock_imread.mock_calls
print my_map.count_green()
| <commit_before>from mock import patch
from mock import Mock
from greengraph import Map
import requests
from matplotlib import image as img
from StringIO import StringIO
with open('image.txt','r') as source:
text = source.read()
lat=51
long=30
satellite=True
zoom=10
size=(400,400)
sensor=False
params=dict(
sensor= str(sensor).lower(),
zoom= zoom,
size= "x".join(map(str, size)),
center= ",".join(map(str, (lat, long) )),
style="feature:all|element:labels|visibility:off"
)
base="http://maps.googleapis.com/maps/api/staticmap?"
text = requests.get(base, params=params).content # Fetch our PNG image data
text = 'hello'
image = Mock()
image.content = text
patch_get = Mock(return_value=image)
with patch.object(requests,'get',patch_get) as mock_get:
with patch.object(img,'imread') as mock_imread:
london_map = Map(52, 0)
print mock_get.mock_calls
print mock_imread.mock_calls
print london_map.count_green()
<commit_msg>Update Map integration test so that Map is fed a PNG from a local image.png file rather than from the internet.<commit_after>from mock import patch
from mock import Mock
from greengraph import Map
import requests
from matplotlib import image as img
from StringIO import StringIO
patch_get = Mock()
patch_get.content = ''
image_array = img.imread('image.png')
patch_imread = Mock(return_value=image_array)
with patch.object(requests,'get',patch_get) as mock_get:
with patch.object(img,'imread',patch_imread) as mock_imread:
my_map = Map(0, 0)
print mock_get.mock_calls
print mock_imread.mock_calls
print my_map.count_green()
|
abd0a6854c90c3647d17dfb3ea980fa49aa5372f | pwndbg/commands/segments.py | pwndbg/commands/segments.py | from __future__ import print_function
import gdb
import pwndbg.regs
class segment(gdb.Function):
"""Get the flat address of memory based off of the named segment register.
"""
def __init__(self, name):
super(segment, self).__init__(name)
self.name = name
def invoke(self, arg=0):
result = getattr(pwndbg.regs, self.name)
return result + arg
segment('fsbase')
segment('gsbase')
| from __future__ import print_function
import gdb
import pwndbg.regs
import pwndbg.commands
class segment(gdb.Function):
"""Get the flat address of memory based off of the named segment register.
"""
def __init__(self, name):
super(segment, self).__init__(name)
self.name = name
def invoke(self, arg=0):
result = getattr(pwndbg.regs, self.name)
return result + arg
segment('fsbase')
segment('gsbase')
@pwndbg.commands.OnlyWhenRunning
@pwndbg.commands.ParsedCommand
def fsbase():
"""
Prints out the FS base address. See also $fsbase.
"""
print(hex(pwndbg.regs.fsbase))
@pwndbg.commands.OnlyWhenRunning
@pwndbg.commands.ParsedCommand
def gsbase():
"""
Prints out the GS base address. See also $gsbase.
"""
print(hex(pwndbg.regs.gsbase))
| Add fsbase and gsbase commands | Add fsbase and gsbase commands
| Python | mit | cebrusfs/217gdb,anthraxx/pwndbg,chubbymaggie/pwndbg,anthraxx/pwndbg,disconnect3d/pwndbg,0xddaa/pwndbg,0xddaa/pwndbg,cebrusfs/217gdb,zachriggle/pwndbg,disconnect3d/pwndbg,pwndbg/pwndbg,disconnect3d/pwndbg,anthraxx/pwndbg,cebrusfs/217gdb,zachriggle/pwndbg,pwndbg/pwndbg,pwndbg/pwndbg,anthraxx/pwndbg,chubbymaggie/pwndbg,cebrusfs/217gdb,pwndbg/pwndbg,0xddaa/pwndbg | from __future__ import print_function
import gdb
import pwndbg.regs
class segment(gdb.Function):
"""Get the flat address of memory based off of the named segment register.
"""
def __init__(self, name):
super(segment, self).__init__(name)
self.name = name
def invoke(self, arg=0):
result = getattr(pwndbg.regs, self.name)
return result + arg
segment('fsbase')
segment('gsbase')
Add fsbase and gsbase commands | from __future__ import print_function
import gdb
import pwndbg.regs
import pwndbg.commands
class segment(gdb.Function):
"""Get the flat address of memory based off of the named segment register.
"""
def __init__(self, name):
super(segment, self).__init__(name)
self.name = name
def invoke(self, arg=0):
result = getattr(pwndbg.regs, self.name)
return result + arg
segment('fsbase')
segment('gsbase')
@pwndbg.commands.OnlyWhenRunning
@pwndbg.commands.ParsedCommand
def fsbase():
"""
Prints out the FS base address. See also $fsbase.
"""
print(hex(pwndbg.regs.fsbase))
@pwndbg.commands.OnlyWhenRunning
@pwndbg.commands.ParsedCommand
def gsbase():
"""
Prints out the GS base address. See also $gsbase.
"""
print(hex(pwndbg.regs.gsbase))
| <commit_before>from __future__ import print_function
import gdb
import pwndbg.regs
class segment(gdb.Function):
"""Get the flat address of memory based off of the named segment register.
"""
def __init__(self, name):
super(segment, self).__init__(name)
self.name = name
def invoke(self, arg=0):
result = getattr(pwndbg.regs, self.name)
return result + arg
segment('fsbase')
segment('gsbase')
<commit_msg>Add fsbase and gsbase commands<commit_after> | from __future__ import print_function
import gdb
import pwndbg.regs
import pwndbg.commands
class segment(gdb.Function):
"""Get the flat address of memory based off of the named segment register.
"""
def __init__(self, name):
super(segment, self).__init__(name)
self.name = name
def invoke(self, arg=0):
result = getattr(pwndbg.regs, self.name)
return result + arg
segment('fsbase')
segment('gsbase')
@pwndbg.commands.OnlyWhenRunning
@pwndbg.commands.ParsedCommand
def fsbase():
"""
Prints out the FS base address. See also $fsbase.
"""
print(hex(pwndbg.regs.fsbase))
@pwndbg.commands.OnlyWhenRunning
@pwndbg.commands.ParsedCommand
def gsbase():
"""
Prints out the GS base address. See also $gsbase.
"""
print(hex(pwndbg.regs.gsbase))
| from __future__ import print_function
import gdb
import pwndbg.regs
class segment(gdb.Function):
"""Get the flat address of memory based off of the named segment register.
"""
def __init__(self, name):
super(segment, self).__init__(name)
self.name = name
def invoke(self, arg=0):
result = getattr(pwndbg.regs, self.name)
return result + arg
segment('fsbase')
segment('gsbase')
Add fsbase and gsbase commandsfrom __future__ import print_function
import gdb
import pwndbg.regs
import pwndbg.commands
class segment(gdb.Function):
"""Get the flat address of memory based off of the named segment register.
"""
def __init__(self, name):
super(segment, self).__init__(name)
self.name = name
def invoke(self, arg=0):
result = getattr(pwndbg.regs, self.name)
return result + arg
segment('fsbase')
segment('gsbase')
@pwndbg.commands.OnlyWhenRunning
@pwndbg.commands.ParsedCommand
def fsbase():
"""
Prints out the FS base address. See also $fsbase.
"""
print(hex(pwndbg.regs.fsbase))
@pwndbg.commands.OnlyWhenRunning
@pwndbg.commands.ParsedCommand
def gsbase():
"""
Prints out the GS base address. See also $gsbase.
"""
print(hex(pwndbg.regs.gsbase))
| <commit_before>from __future__ import print_function
import gdb
import pwndbg.regs
class segment(gdb.Function):
"""Get the flat address of memory based off of the named segment register.
"""
def __init__(self, name):
super(segment, self).__init__(name)
self.name = name
def invoke(self, arg=0):
result = getattr(pwndbg.regs, self.name)
return result + arg
segment('fsbase')
segment('gsbase')
<commit_msg>Add fsbase and gsbase commands<commit_after>from __future__ import print_function
import gdb
import pwndbg.regs
import pwndbg.commands
class segment(gdb.Function):
"""Get the flat address of memory based off of the named segment register.
"""
def __init__(self, name):
super(segment, self).__init__(name)
self.name = name
def invoke(self, arg=0):
result = getattr(pwndbg.regs, self.name)
return result + arg
segment('fsbase')
segment('gsbase')
@pwndbg.commands.OnlyWhenRunning
@pwndbg.commands.ParsedCommand
def fsbase():
"""
Prints out the FS base address. See also $fsbase.
"""
print(hex(pwndbg.regs.fsbase))
@pwndbg.commands.OnlyWhenRunning
@pwndbg.commands.ParsedCommand
def gsbase():
"""
Prints out the GS base address. See also $gsbase.
"""
print(hex(pwndbg.regs.gsbase))
|
85a7b6e39f472ae9465b8fb80e2443da352fee67 | fullcalendar/admin.py | fullcalendar/admin.py | from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(StackedDynamicInlineAdmin):
model = Occurrence
fields = ('start_time', 'end_time', 'description', 'location')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'status')
list_filter = ('event_category',)
search_fields = ('title', 'description', 'content')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
| from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(StackedDynamicInlineAdmin):
model = Occurrence
fields = ('start_time', 'end_time', 'description', 'location')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'status')
search_fields = ('title', 'description', 'content')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
| Remove list filter based on event category | Remove list filter based on event category
| Python | mit | jonge-democraten/mezzanine-fullcalendar | from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(StackedDynamicInlineAdmin):
model = Occurrence
fields = ('start_time', 'end_time', 'description', 'location')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'status')
list_filter = ('event_category',)
search_fields = ('title', 'description', 'content')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
Remove list filter based on event category | from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(StackedDynamicInlineAdmin):
model = Occurrence
fields = ('start_time', 'end_time', 'description', 'location')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'status')
search_fields = ('title', 'description', 'content')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
| <commit_before>from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(StackedDynamicInlineAdmin):
model = Occurrence
fields = ('start_time', 'end_time', 'description', 'location')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'status')
list_filter = ('event_category',)
search_fields = ('title', 'description', 'content')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
<commit_msg>Remove list filter based on event category<commit_after> | from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(StackedDynamicInlineAdmin):
model = Occurrence
fields = ('start_time', 'end_time', 'description', 'location')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'status')
search_fields = ('title', 'description', 'content')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
| from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(StackedDynamicInlineAdmin):
model = Occurrence
fields = ('start_time', 'end_time', 'description', 'location')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'status')
list_filter = ('event_category',)
search_fields = ('title', 'description', 'content')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
Remove list filter based on event categoryfrom django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(StackedDynamicInlineAdmin):
model = Occurrence
fields = ('start_time', 'end_time', 'description', 'location')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'status')
search_fields = ('title', 'description', 'content')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
| <commit_before>from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(StackedDynamicInlineAdmin):
model = Occurrence
fields = ('start_time', 'end_time', 'description', 'location')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'status')
list_filter = ('event_category',)
search_fields = ('title', 'description', 'content')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
<commit_msg>Remove list filter based on event category<commit_after>from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(StackedDynamicInlineAdmin):
model = Occurrence
fields = ('start_time', 'end_time', 'description', 'location')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'status')
search_fields = ('title', 'description', 'content')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
|
c502ead77b9f82205eebdbf9863649160302a681 | scripts/generate_token.py | scripts/generate_token.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
"""
Generate an authentication token for a sensor. This token is used by the sensor
to send the sensor's data to the API.
After generating a token, you have to place it in the sensor's configuration
file if you want it to send data.
"""
import argparse
import sys
from api import db
from api.tokens.models import Token
from sqlalchemy.exc import IntegrityError
def generate_token(name):
token = Token(name)
db.session.add(token)
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
sys.stderr.write('Failed to create token: Name {} already exists.\n'.format(name))
sys.exit(-1)
return token
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-n', '--name', type=str, required=True,
help='Name describing a sensor\'s location')
args = parser.parse_args()
token = generate_token(args.name)
print('''
Successfully created token!
Name: {}
Token: {}
Dont forget to save this token in the sensor's configuration file.
'''.format(token.name, token.token.decode('utf-8')))
if __name__ == '__main__':
main()
| #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
"""
Generate an authentication token for a sensor. This token is used by the sensor
to send the sensor's data to the API.
After generating a token, you have to place it in the sensor's configuration
file if you want it to send data.
"""
import argparse
import sys
from api import db
from api.tokens.models import Token
from sqlalchemy.exc import IntegrityError
def generate_token(name):
token = Token(name)
db.session.add(token)
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
sys.stderr.write('Failed to create token: Name {} already exists.\n'.format(name))
sys.exit(-1)
return token
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('name', type=str,
help='Name describing a sensor\'s location')
args = parser.parse_args()
token = generate_token(args.name)
print('''
Successfully created token!
Name: {}
Token: {}
Dont forget to save this token in the sensor's configuration file.
'''.format(token.name, token.token.decode('utf-8')))
if __name__ == '__main__':
main()
| Change to positional argument for generate-token | Change to positional argument for generate-token
| Python | mit | Proj-P/project-p-api,Proj-P/project-p-api | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
"""
Generate an authentication token for a sensor. This token is used by the sensor
to send the sensor's data to the API.
After generating a token, you have to place it in the sensor's configuration
file if you want it to send data.
"""
import argparse
import sys
from api import db
from api.tokens.models import Token
from sqlalchemy.exc import IntegrityError
def generate_token(name):
token = Token(name)
db.session.add(token)
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
sys.stderr.write('Failed to create token: Name {} already exists.\n'.format(name))
sys.exit(-1)
return token
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-n', '--name', type=str, required=True,
help='Name describing a sensor\'s location')
args = parser.parse_args()
token = generate_token(args.name)
print('''
Successfully created token!
Name: {}
Token: {}
Dont forget to save this token in the sensor's configuration file.
'''.format(token.name, token.token.decode('utf-8')))
if __name__ == '__main__':
main()
Change to positional argument for generate-token | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
"""
Generate an authentication token for a sensor. This token is used by the sensor
to send the sensor's data to the API.
After generating a token, you have to place it in the sensor's configuration
file if you want it to send data.
"""
import argparse
import sys
from api import db
from api.tokens.models import Token
from sqlalchemy.exc import IntegrityError
def generate_token(name):
token = Token(name)
db.session.add(token)
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
sys.stderr.write('Failed to create token: Name {} already exists.\n'.format(name))
sys.exit(-1)
return token
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('name', type=str,
help='Name describing a sensor\'s location')
args = parser.parse_args()
token = generate_token(args.name)
print('''
Successfully created token!
Name: {}
Token: {}
Dont forget to save this token in the sensor's configuration file.
'''.format(token.name, token.token.decode('utf-8')))
if __name__ == '__main__':
main()
| <commit_before>#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
"""
Generate an authentication token for a sensor. This token is used by the sensor
to send the sensor's data to the API.
After generating a token, you have to place it in the sensor's configuration
file if you want it to send data.
"""
import argparse
import sys
from api import db
from api.tokens.models import Token
from sqlalchemy.exc import IntegrityError
def generate_token(name):
token = Token(name)
db.session.add(token)
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
sys.stderr.write('Failed to create token: Name {} already exists.\n'.format(name))
sys.exit(-1)
return token
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-n', '--name', type=str, required=True,
help='Name describing a sensor\'s location')
args = parser.parse_args()
token = generate_token(args.name)
print('''
Successfully created token!
Name: {}
Token: {}
Dont forget to save this token in the sensor's configuration file.
'''.format(token.name, token.token.decode('utf-8')))
if __name__ == '__main__':
main()
<commit_msg>Change to positional argument for generate-token<commit_after> | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
"""
Generate an authentication token for a sensor. This token is used by the sensor
to send the sensor's data to the API.
After generating a token, you have to place it in the sensor's configuration
file if you want it to send data.
"""
import argparse
import sys
from api import db
from api.tokens.models import Token
from sqlalchemy.exc import IntegrityError
def generate_token(name):
token = Token(name)
db.session.add(token)
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
sys.stderr.write('Failed to create token: Name {} already exists.\n'.format(name))
sys.exit(-1)
return token
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('name', type=str,
help='Name describing a sensor\'s location')
args = parser.parse_args()
token = generate_token(args.name)
print('''
Successfully created token!
Name: {}
Token: {}
Dont forget to save this token in the sensor's configuration file.
'''.format(token.name, token.token.decode('utf-8')))
if __name__ == '__main__':
main()
| #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
"""
Generate an authentication token for a sensor. This token is used by the sensor
to send the sensor's data to the API.
After generating a token, you have to place it in the sensor's configuration
file if you want it to send data.
"""
import argparse
import sys
from api import db
from api.tokens.models import Token
from sqlalchemy.exc import IntegrityError
def generate_token(name):
token = Token(name)
db.session.add(token)
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
sys.stderr.write('Failed to create token: Name {} already exists.\n'.format(name))
sys.exit(-1)
return token
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-n', '--name', type=str, required=True,
help='Name describing a sensor\'s location')
args = parser.parse_args()
token = generate_token(args.name)
print('''
Successfully created token!
Name: {}
Token: {}
Dont forget to save this token in the sensor's configuration file.
'''.format(token.name, token.token.decode('utf-8')))
if __name__ == '__main__':
main()
Change to positional argument for generate-token#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
"""
Generate an authentication token for a sensor. This token is used by the sensor
to send the sensor's data to the API.
After generating a token, you have to place it in the sensor's configuration
file if you want it to send data.
"""
import argparse
import sys
from api import db
from api.tokens.models import Token
from sqlalchemy.exc import IntegrityError
def generate_token(name):
token = Token(name)
db.session.add(token)
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
sys.stderr.write('Failed to create token: Name {} already exists.\n'.format(name))
sys.exit(-1)
return token
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('name', type=str,
help='Name describing a sensor\'s location')
args = parser.parse_args()
token = generate_token(args.name)
print('''
Successfully created token!
Name: {}
Token: {}
Dont forget to save this token in the sensor's configuration file.
'''.format(token.name, token.token.decode('utf-8')))
if __name__ == '__main__':
main()
| <commit_before>#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
"""
Generate an authentication token for a sensor. This token is used by the sensor
to send the sensor's data to the API.
After generating a token, you have to place it in the sensor's configuration
file if you want it to send data.
"""
import argparse
import sys
from api import db
from api.tokens.models import Token
from sqlalchemy.exc import IntegrityError
def generate_token(name):
token = Token(name)
db.session.add(token)
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
sys.stderr.write('Failed to create token: Name {} already exists.\n'.format(name))
sys.exit(-1)
return token
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-n', '--name', type=str, required=True,
help='Name describing a sensor\'s location')
args = parser.parse_args()
token = generate_token(args.name)
print('''
Successfully created token!
Name: {}
Token: {}
Dont forget to save this token in the sensor's configuration file.
'''.format(token.name, token.token.decode('utf-8')))
if __name__ == '__main__':
main()
<commit_msg>Change to positional argument for generate-token<commit_after>#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2016 Steven Oud. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found
# in the LICENSE file.
"""
Generate an authentication token for a sensor. This token is used by the sensor
to send the sensor's data to the API.
After generating a token, you have to place it in the sensor's configuration
file if you want it to send data.
"""
import argparse
import sys
from api import db
from api.tokens.models import Token
from sqlalchemy.exc import IntegrityError
def generate_token(name):
token = Token(name)
db.session.add(token)
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
sys.stderr.write('Failed to create token: Name {} already exists.\n'.format(name))
sys.exit(-1)
return token
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('name', type=str,
help='Name describing a sensor\'s location')
args = parser.parse_args()
token = generate_token(args.name)
print('''
Successfully created token!
Name: {}
Token: {}
Dont forget to save this token in the sensor's configuration file.
'''.format(token.name, token.token.decode('utf-8')))
if __name__ == '__main__':
main()
|
a437139ea22cdbf1ea0e47949311a6618b233b74 | csvdiff/error.py | csvdiff/error.py | # -*- coding: utf-8 -*-
#
# error.py
# csvdiff
#
from __future__ import absolute_import, print_function, division
import sys
DEBUG = True
class FatalError(Exception):
pass
def abort(message=None):
if DEBUG:
raise FatalError(message)
print(message, file=sys.stderr)
sys.exit(1)
| # -*- coding: utf-8 -*-
#
# error.py
# csvdiff
#
from __future__ import absolute_import, print_function, division
import sys
DEBUG = False
class FatalError(Exception):
pass
def abort(message=None):
if DEBUG:
raise FatalError(message)
print(message, file=sys.stderr)
sys.exit(1)
| Reset debug flag to False. | Reset debug flag to False.
| Python | bsd-3-clause | larsyencken/csvdiff | # -*- coding: utf-8 -*-
#
# error.py
# csvdiff
#
from __future__ import absolute_import, print_function, division
import sys
DEBUG = True
class FatalError(Exception):
pass
def abort(message=None):
if DEBUG:
raise FatalError(message)
print(message, file=sys.stderr)
sys.exit(1)
Reset debug flag to False. | # -*- coding: utf-8 -*-
#
# error.py
# csvdiff
#
from __future__ import absolute_import, print_function, division
import sys
DEBUG = False
class FatalError(Exception):
pass
def abort(message=None):
if DEBUG:
raise FatalError(message)
print(message, file=sys.stderr)
sys.exit(1)
| <commit_before># -*- coding: utf-8 -*-
#
# error.py
# csvdiff
#
from __future__ import absolute_import, print_function, division
import sys
DEBUG = True
class FatalError(Exception):
pass
def abort(message=None):
if DEBUG:
raise FatalError(message)
print(message, file=sys.stderr)
sys.exit(1)
<commit_msg>Reset debug flag to False.<commit_after> | # -*- coding: utf-8 -*-
#
# error.py
# csvdiff
#
from __future__ import absolute_import, print_function, division
import sys
DEBUG = False
class FatalError(Exception):
pass
def abort(message=None):
if DEBUG:
raise FatalError(message)
print(message, file=sys.stderr)
sys.exit(1)
| # -*- coding: utf-8 -*-
#
# error.py
# csvdiff
#
from __future__ import absolute_import, print_function, division
import sys
DEBUG = True
class FatalError(Exception):
pass
def abort(message=None):
if DEBUG:
raise FatalError(message)
print(message, file=sys.stderr)
sys.exit(1)
Reset debug flag to False.# -*- coding: utf-8 -*-
#
# error.py
# csvdiff
#
from __future__ import absolute_import, print_function, division
import sys
DEBUG = False
class FatalError(Exception):
pass
def abort(message=None):
if DEBUG:
raise FatalError(message)
print(message, file=sys.stderr)
sys.exit(1)
| <commit_before># -*- coding: utf-8 -*-
#
# error.py
# csvdiff
#
from __future__ import absolute_import, print_function, division
import sys
DEBUG = True
class FatalError(Exception):
pass
def abort(message=None):
if DEBUG:
raise FatalError(message)
print(message, file=sys.stderr)
sys.exit(1)
<commit_msg>Reset debug flag to False.<commit_after># -*- coding: utf-8 -*-
#
# error.py
# csvdiff
#
from __future__ import absolute_import, print_function, division
import sys
DEBUG = False
class FatalError(Exception):
pass
def abort(message=None):
if DEBUG:
raise FatalError(message)
print(message, file=sys.stderr)
sys.exit(1)
|
5735c779d44f763e5f993090d92514338d67cc7f | lib/strider/__init__.py | lib/strider/__init__.py | # (C) Michael DeHaan, 2015, michael.dehaan@gmail.copy_from
# LICENSE: APACHE 2
import argparse
class Strider(object):
__SLOTS__ = [ 'provisioner']
def __init__(self, provisioner):
self.provisioner = provisioner
def up(self, instances):
[ x.up() for x in instances ]
return self.provision(instances)
def provision(self, instances):
return [ self.provisioner.converge(x.describe()) for x in instances ]
def destroy(self, instances):
return [ self.destroy(x) for x in instances ]
def cli(self, instances):
parser = argparse.ArgumentParser(description="Dev VM Manager, expects one of the following flags:")
parser.add_argument("--up", action="store_true", help="launch VMs")
parser.add_argument("--provision", action="store_true", help="reconfigure VMs")
parser.add_argument("--destroy", action="store_true", help="destroy VMs")
args = parser.parse_args()
if args.up:
self.up(instances)
elif args.provision:
self.provision(instances)
elif args.destroy:
self.destroy(instances)
else:
parser.print_help()
| # (C) Michael DeHaan, 2015, michael.dehaan@gmail.copy_from
# LICENSE: APACHE 2
import argparse
class Strider(object):
__SLOTS__ = [ 'provisioner']
def __init__(self, provisioner):
self.provisioner = provisioner
def up(self, instances):
[ x.up() for x in instances ]
return self.provision(instances)
def provision(self, instances):
return [ self.provisioner.converge(x.describe()) for x in instances ]
def destroy(self, instances):
return [ x.destroy() for x in instances ]
def cli(self, instances):
parser = argparse.ArgumentParser(description="Dev VM Manager, expects one of the following flags:")
parser.add_argument("--up", action="store_true", help="launch VMs")
parser.add_argument("--provision", action="store_true", help="reconfigure VMs")
parser.add_argument("--destroy", action="store_true", help="destroy VMs")
args = parser.parse_args()
if args.up:
self.up(instances)
elif args.provision:
self.provision(instances)
elif args.destroy:
self.destroy(instances)
else:
parser.print_help()
| Fix buglet in the destroy path. | Fix buglet in the destroy path.
| Python | apache-2.0 | bradparks/strider,mhollick/strider,gcristofol/strider,jsmartin/strider,mpdehaan/strider | # (C) Michael DeHaan, 2015, michael.dehaan@gmail.copy_from
# LICENSE: APACHE 2
import argparse
class Strider(object):
__SLOTS__ = [ 'provisioner']
def __init__(self, provisioner):
self.provisioner = provisioner
def up(self, instances):
[ x.up() for x in instances ]
return self.provision(instances)
def provision(self, instances):
return [ self.provisioner.converge(x.describe()) for x in instances ]
def destroy(self, instances):
return [ self.destroy(x) for x in instances ]
def cli(self, instances):
parser = argparse.ArgumentParser(description="Dev VM Manager, expects one of the following flags:")
parser.add_argument("--up", action="store_true", help="launch VMs")
parser.add_argument("--provision", action="store_true", help="reconfigure VMs")
parser.add_argument("--destroy", action="store_true", help="destroy VMs")
args = parser.parse_args()
if args.up:
self.up(instances)
elif args.provision:
self.provision(instances)
elif args.destroy:
self.destroy(instances)
else:
parser.print_help()
Fix buglet in the destroy path. | # (C) Michael DeHaan, 2015, michael.dehaan@gmail.copy_from
# LICENSE: APACHE 2
import argparse
class Strider(object):
__SLOTS__ = [ 'provisioner']
def __init__(self, provisioner):
self.provisioner = provisioner
def up(self, instances):
[ x.up() for x in instances ]
return self.provision(instances)
def provision(self, instances):
return [ self.provisioner.converge(x.describe()) for x in instances ]
def destroy(self, instances):
return [ x.destroy() for x in instances ]
def cli(self, instances):
parser = argparse.ArgumentParser(description="Dev VM Manager, expects one of the following flags:")
parser.add_argument("--up", action="store_true", help="launch VMs")
parser.add_argument("--provision", action="store_true", help="reconfigure VMs")
parser.add_argument("--destroy", action="store_true", help="destroy VMs")
args = parser.parse_args()
if args.up:
self.up(instances)
elif args.provision:
self.provision(instances)
elif args.destroy:
self.destroy(instances)
else:
parser.print_help()
| <commit_before># (C) Michael DeHaan, 2015, michael.dehaan@gmail.copy_from
# LICENSE: APACHE 2
import argparse
class Strider(object):
__SLOTS__ = [ 'provisioner']
def __init__(self, provisioner):
self.provisioner = provisioner
def up(self, instances):
[ x.up() for x in instances ]
return self.provision(instances)
def provision(self, instances):
return [ self.provisioner.converge(x.describe()) for x in instances ]
def destroy(self, instances):
return [ self.destroy(x) for x in instances ]
def cli(self, instances):
parser = argparse.ArgumentParser(description="Dev VM Manager, expects one of the following flags:")
parser.add_argument("--up", action="store_true", help="launch VMs")
parser.add_argument("--provision", action="store_true", help="reconfigure VMs")
parser.add_argument("--destroy", action="store_true", help="destroy VMs")
args = parser.parse_args()
if args.up:
self.up(instances)
elif args.provision:
self.provision(instances)
elif args.destroy:
self.destroy(instances)
else:
parser.print_help()
<commit_msg>Fix buglet in the destroy path.<commit_after> | # (C) Michael DeHaan, 2015, michael.dehaan@gmail.copy_from
# LICENSE: APACHE 2
import argparse
class Strider(object):
__SLOTS__ = [ 'provisioner']
def __init__(self, provisioner):
self.provisioner = provisioner
def up(self, instances):
[ x.up() for x in instances ]
return self.provision(instances)
def provision(self, instances):
return [ self.provisioner.converge(x.describe()) for x in instances ]
def destroy(self, instances):
return [ x.destroy() for x in instances ]
def cli(self, instances):
parser = argparse.ArgumentParser(description="Dev VM Manager, expects one of the following flags:")
parser.add_argument("--up", action="store_true", help="launch VMs")
parser.add_argument("--provision", action="store_true", help="reconfigure VMs")
parser.add_argument("--destroy", action="store_true", help="destroy VMs")
args = parser.parse_args()
if args.up:
self.up(instances)
elif args.provision:
self.provision(instances)
elif args.destroy:
self.destroy(instances)
else:
parser.print_help()
| # (C) Michael DeHaan, 2015, michael.dehaan@gmail.copy_from
# LICENSE: APACHE 2
import argparse
class Strider(object):
__SLOTS__ = [ 'provisioner']
def __init__(self, provisioner):
self.provisioner = provisioner
def up(self, instances):
[ x.up() for x in instances ]
return self.provision(instances)
def provision(self, instances):
return [ self.provisioner.converge(x.describe()) for x in instances ]
def destroy(self, instances):
return [ self.destroy(x) for x in instances ]
def cli(self, instances):
parser = argparse.ArgumentParser(description="Dev VM Manager, expects one of the following flags:")
parser.add_argument("--up", action="store_true", help="launch VMs")
parser.add_argument("--provision", action="store_true", help="reconfigure VMs")
parser.add_argument("--destroy", action="store_true", help="destroy VMs")
args = parser.parse_args()
if args.up:
self.up(instances)
elif args.provision:
self.provision(instances)
elif args.destroy:
self.destroy(instances)
else:
parser.print_help()
Fix buglet in the destroy path.# (C) Michael DeHaan, 2015, michael.dehaan@gmail.copy_from
# LICENSE: APACHE 2
import argparse
class Strider(object):
__SLOTS__ = [ 'provisioner']
def __init__(self, provisioner):
self.provisioner = provisioner
def up(self, instances):
[ x.up() for x in instances ]
return self.provision(instances)
def provision(self, instances):
return [ self.provisioner.converge(x.describe()) for x in instances ]
def destroy(self, instances):
return [ x.destroy() for x in instances ]
def cli(self, instances):
parser = argparse.ArgumentParser(description="Dev VM Manager, expects one of the following flags:")
parser.add_argument("--up", action="store_true", help="launch VMs")
parser.add_argument("--provision", action="store_true", help="reconfigure VMs")
parser.add_argument("--destroy", action="store_true", help="destroy VMs")
args = parser.parse_args()
if args.up:
self.up(instances)
elif args.provision:
self.provision(instances)
elif args.destroy:
self.destroy(instances)
else:
parser.print_help()
| <commit_before># (C) Michael DeHaan, 2015, michael.dehaan@gmail.copy_from
# LICENSE: APACHE 2
import argparse
class Strider(object):
__SLOTS__ = [ 'provisioner']
def __init__(self, provisioner):
self.provisioner = provisioner
def up(self, instances):
[ x.up() for x in instances ]
return self.provision(instances)
def provision(self, instances):
return [ self.provisioner.converge(x.describe()) for x in instances ]
def destroy(self, instances):
return [ self.destroy(x) for x in instances ]
def cli(self, instances):
parser = argparse.ArgumentParser(description="Dev VM Manager, expects one of the following flags:")
parser.add_argument("--up", action="store_true", help="launch VMs")
parser.add_argument("--provision", action="store_true", help="reconfigure VMs")
parser.add_argument("--destroy", action="store_true", help="destroy VMs")
args = parser.parse_args()
if args.up:
self.up(instances)
elif args.provision:
self.provision(instances)
elif args.destroy:
self.destroy(instances)
else:
parser.print_help()
<commit_msg>Fix buglet in the destroy path.<commit_after># (C) Michael DeHaan, 2015, michael.dehaan@gmail.copy_from
# LICENSE: APACHE 2
import argparse
class Strider(object):
__SLOTS__ = [ 'provisioner']
def __init__(self, provisioner):
self.provisioner = provisioner
def up(self, instances):
[ x.up() for x in instances ]
return self.provision(instances)
def provision(self, instances):
return [ self.provisioner.converge(x.describe()) for x in instances ]
def destroy(self, instances):
return [ x.destroy() for x in instances ]
def cli(self, instances):
parser = argparse.ArgumentParser(description="Dev VM Manager, expects one of the following flags:")
parser.add_argument("--up", action="store_true", help="launch VMs")
parser.add_argument("--provision", action="store_true", help="reconfigure VMs")
parser.add_argument("--destroy", action="store_true", help="destroy VMs")
args = parser.parse_args()
if args.up:
self.up(instances)
elif args.provision:
self.provision(instances)
elif args.destroy:
self.destroy(instances)
else:
parser.print_help()
|
148314dad481385a794e44c115d556117816b2ab | importkit/__init__.py | importkit/__init__.py | ##
# Copyright (c) 2008-2010 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
from .meta import LanguageMeta, DocumentContext
from .import_ import ImportContext
# Import languages to register them
import semantix.utils.lang.yaml
class SemantixLangLoaderError(Exception):
pass
def load(filename, context=None):
(lang, filename) = LanguageMeta.recognize_file(filename)
if lang:
with open(filename) as f:
result = lang.load(f, context)
for d in result:
yield d
return
raise SemantixLangLoaderError('unable to load file: %s' % filename)
| ##
# Copyright (c) 2008-2010 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
from .meta import LanguageMeta, DocumentContext
from .import_ import ImportContext
# Import languages to register them
from semantix.utils.lang import yaml
class SemantixLangLoaderError(Exception):
pass
def load(filename, context=None):
(lang, filename) = LanguageMeta.recognize_file(filename)
if lang:
with open(filename) as f:
result = lang.load(f, context)
for d in result:
yield d
return
raise SemantixLangLoaderError('unable to load file: %s' % filename)
| Add support for data URI scheme | caos: Add support for data URI scheme
It is now possible to use `data:' backend URIs:
meta_backend_uri = 'data:application/x-yaml,<YAML DOCUMENT DATA>'
| Python | mit | sprymix/importkit | ##
# Copyright (c) 2008-2010 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
from .meta import LanguageMeta, DocumentContext
from .import_ import ImportContext
# Import languages to register them
import semantix.utils.lang.yaml
class SemantixLangLoaderError(Exception):
pass
def load(filename, context=None):
(lang, filename) = LanguageMeta.recognize_file(filename)
if lang:
with open(filename) as f:
result = lang.load(f, context)
for d in result:
yield d
return
raise SemantixLangLoaderError('unable to load file: %s' % filename)
caos: Add support for data URI scheme
It is now possible to use `data:' backend URIs:
meta_backend_uri = 'data:application/x-yaml,<YAML DOCUMENT DATA>' | ##
# Copyright (c) 2008-2010 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
from .meta import LanguageMeta, DocumentContext
from .import_ import ImportContext
# Import languages to register them
from semantix.utils.lang import yaml
class SemantixLangLoaderError(Exception):
pass
def load(filename, context=None):
(lang, filename) = LanguageMeta.recognize_file(filename)
if lang:
with open(filename) as f:
result = lang.load(f, context)
for d in result:
yield d
return
raise SemantixLangLoaderError('unable to load file: %s' % filename)
| <commit_before>##
# Copyright (c) 2008-2010 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
from .meta import LanguageMeta, DocumentContext
from .import_ import ImportContext
# Import languages to register them
import semantix.utils.lang.yaml
class SemantixLangLoaderError(Exception):
pass
def load(filename, context=None):
(lang, filename) = LanguageMeta.recognize_file(filename)
if lang:
with open(filename) as f:
result = lang.load(f, context)
for d in result:
yield d
return
raise SemantixLangLoaderError('unable to load file: %s' % filename)
<commit_msg>caos: Add support for data URI scheme
It is now possible to use `data:' backend URIs:
meta_backend_uri = 'data:application/x-yaml,<YAML DOCUMENT DATA>'<commit_after> | ##
# Copyright (c) 2008-2010 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
from .meta import LanguageMeta, DocumentContext
from .import_ import ImportContext
# Import languages to register them
from semantix.utils.lang import yaml
class SemantixLangLoaderError(Exception):
pass
def load(filename, context=None):
(lang, filename) = LanguageMeta.recognize_file(filename)
if lang:
with open(filename) as f:
result = lang.load(f, context)
for d in result:
yield d
return
raise SemantixLangLoaderError('unable to load file: %s' % filename)
| ##
# Copyright (c) 2008-2010 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
from .meta import LanguageMeta, DocumentContext
from .import_ import ImportContext
# Import languages to register them
import semantix.utils.lang.yaml
class SemantixLangLoaderError(Exception):
pass
def load(filename, context=None):
(lang, filename) = LanguageMeta.recognize_file(filename)
if lang:
with open(filename) as f:
result = lang.load(f, context)
for d in result:
yield d
return
raise SemantixLangLoaderError('unable to load file: %s' % filename)
caos: Add support for data URI scheme
It is now possible to use `data:' backend URIs:
meta_backend_uri = 'data:application/x-yaml,<YAML DOCUMENT DATA>'##
# Copyright (c) 2008-2010 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
from .meta import LanguageMeta, DocumentContext
from .import_ import ImportContext
# Import languages to register them
from semantix.utils.lang import yaml
class SemantixLangLoaderError(Exception):
pass
def load(filename, context=None):
(lang, filename) = LanguageMeta.recognize_file(filename)
if lang:
with open(filename) as f:
result = lang.load(f, context)
for d in result:
yield d
return
raise SemantixLangLoaderError('unable to load file: %s' % filename)
| <commit_before>##
# Copyright (c) 2008-2010 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
from .meta import LanguageMeta, DocumentContext
from .import_ import ImportContext
# Import languages to register them
import semantix.utils.lang.yaml
class SemantixLangLoaderError(Exception):
pass
def load(filename, context=None):
(lang, filename) = LanguageMeta.recognize_file(filename)
if lang:
with open(filename) as f:
result = lang.load(f, context)
for d in result:
yield d
return
raise SemantixLangLoaderError('unable to load file: %s' % filename)
<commit_msg>caos: Add support for data URI scheme
It is now possible to use `data:' backend URIs:
meta_backend_uri = 'data:application/x-yaml,<YAML DOCUMENT DATA>'<commit_after>##
# Copyright (c) 2008-2010 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
from .meta import LanguageMeta, DocumentContext
from .import_ import ImportContext
# Import languages to register them
from semantix.utils.lang import yaml
class SemantixLangLoaderError(Exception):
pass
def load(filename, context=None):
(lang, filename) = LanguageMeta.recognize_file(filename)
if lang:
with open(filename) as f:
result = lang.load(f, context)
for d in result:
yield d
return
raise SemantixLangLoaderError('unable to load file: %s' % filename)
|
2ec8d3bf7db7427010ad08644690b1d88a5ffe92 | jenkinsapi/plugins.py | jenkinsapi/plugins.py | import urllib
import logging
from jenkinsapi.jenkinsbase import JenkinsBase
from jenkinsapi.plugin import Plugin
log = logging.getLogger(__name__)
class Plugins(JenkinsBase):
def __init__(self, url, jenkins_obj):
self.jenkins_obj = jenkins_obj
JenkinsBase.__init__(self, url)
# print 'DEBUG: Plugins._data=', self._data
def get_jenkins_obj(self):
return self.jenkins_obj
def _poll(self):
return self.get_data(self.baseurl)
def keys(self):
return self.get_plugins_dict().keys()
def iteritems(self):
return self._get_plugins()
def values(self):
return [a[1] for a in self.iteritems()]
def _get_plugins(self):
if not 'plugins' in self._data:
pass
else:
for p_dict in self._data["plugins"]:
yield p_dict["shortName"], Plugin(p_dict)
def get_plugins_dict(self):
return dict(self._get_plugins())
def __len__(self):
return len(self.get_plugins_dict().keys())
def __getitem__(self, plugin_name):
return self.get_plugins_dict().get(plugin_name, None)
def __contains__(self, plugin_name):
"""
True if plugin_name is the name of a defined plugin
"""
return plugin_name in self.keys()
def __str__(self):
plugins = [plugin["shortName"] for plugin in self._data.get("plugins", [])]
return str(sorted(plugins))
| import urllib
import logging
from jenkinsapi.jenkinsbase import JenkinsBase
from jenkinsapi.plugin import Plugin
log = logging.getLogger(__name__)
class Plugins(JenkinsBase):
def __init__(self, url, jenkins_obj):
self.jenkins_obj = jenkins_obj
JenkinsBase.__init__(self, url)
# print 'DEBUG: Plugins._data=', self._data
def get_jenkins_obj(self):
return self.jenkins_obj
def _poll(self):
return self.get_data(self.baseurl)
def keys(self):
return self.get_plugins_dict().keys()
def iteritems(self):
return self._get_plugins()
def values(self):
return [a[1] for a in self.iteritems()]
def _get_plugins(self):
if not 'plugins' in self._data:
pass
else:
for p_dict in self._data["plugins"]:
yield p_dict["shortName"], Plugin(p_dict)
def get_plugins_dict(self):
return dict(self._get_plugins())
def __len__(self):
return len(self.get_plugins_dict().keys())
def __getitem__(self, plugin_name):
return self.get_plugins_dict().get(plugin_name, None)
def __contains__(self, plugin_name):
"""
True if plugin_name is the name of a defined plugin
"""
return plugin_name in self.keys()
def __str__(self):
plugins = [plugin["shortName"] for plugin in self._data.get("plugins", [])]
return str(sorted(plugins))
| Add trailing newline in file | Add trailing newline in file
| Python | mit | salimfadhley/jenkinsapi,imsardine/jenkinsapi,JohnLZeller/jenkinsapi,aerickson/jenkinsapi,jduan/jenkinsapi,domenkozar/jenkinsapi,imsardine/jenkinsapi,aerickson/jenkinsapi,imsardine/jenkinsapi,salimfadhley/jenkinsapi,JohnLZeller/jenkinsapi,mistermocha/jenkinsapi,zaro0508/jenkinsapi,zaro0508/jenkinsapi,zaro0508/jenkinsapi,jduan/jenkinsapi,domenkozar/jenkinsapi,mistermocha/jenkinsapi,JohnLZeller/jenkinsapi,mistermocha/jenkinsapi | import urllib
import logging
from jenkinsapi.jenkinsbase import JenkinsBase
from jenkinsapi.plugin import Plugin
log = logging.getLogger(__name__)
class Plugins(JenkinsBase):
def __init__(self, url, jenkins_obj):
self.jenkins_obj = jenkins_obj
JenkinsBase.__init__(self, url)
# print 'DEBUG: Plugins._data=', self._data
def get_jenkins_obj(self):
return self.jenkins_obj
def _poll(self):
return self.get_data(self.baseurl)
def keys(self):
return self.get_plugins_dict().keys()
def iteritems(self):
return self._get_plugins()
def values(self):
return [a[1] for a in self.iteritems()]
def _get_plugins(self):
if not 'plugins' in self._data:
pass
else:
for p_dict in self._data["plugins"]:
yield p_dict["shortName"], Plugin(p_dict)
def get_plugins_dict(self):
return dict(self._get_plugins())
def __len__(self):
return len(self.get_plugins_dict().keys())
def __getitem__(self, plugin_name):
return self.get_plugins_dict().get(plugin_name, None)
def __contains__(self, plugin_name):
"""
True if plugin_name is the name of a defined plugin
"""
return plugin_name in self.keys()
def __str__(self):
plugins = [plugin["shortName"] for plugin in self._data.get("plugins", [])]
return str(sorted(plugins))
Add trailing newline in file | import urllib
import logging
from jenkinsapi.jenkinsbase import JenkinsBase
from jenkinsapi.plugin import Plugin
log = logging.getLogger(__name__)
class Plugins(JenkinsBase):
def __init__(self, url, jenkins_obj):
self.jenkins_obj = jenkins_obj
JenkinsBase.__init__(self, url)
# print 'DEBUG: Plugins._data=', self._data
def get_jenkins_obj(self):
return self.jenkins_obj
def _poll(self):
return self.get_data(self.baseurl)
def keys(self):
return self.get_plugins_dict().keys()
def iteritems(self):
return self._get_plugins()
def values(self):
return [a[1] for a in self.iteritems()]
def _get_plugins(self):
if not 'plugins' in self._data:
pass
else:
for p_dict in self._data["plugins"]:
yield p_dict["shortName"], Plugin(p_dict)
def get_plugins_dict(self):
return dict(self._get_plugins())
def __len__(self):
return len(self.get_plugins_dict().keys())
def __getitem__(self, plugin_name):
return self.get_plugins_dict().get(plugin_name, None)
def __contains__(self, plugin_name):
"""
True if plugin_name is the name of a defined plugin
"""
return plugin_name in self.keys()
def __str__(self):
plugins = [plugin["shortName"] for plugin in self._data.get("plugins", [])]
return str(sorted(plugins))
| <commit_before>import urllib
import logging
from jenkinsapi.jenkinsbase import JenkinsBase
from jenkinsapi.plugin import Plugin
log = logging.getLogger(__name__)
class Plugins(JenkinsBase):
def __init__(self, url, jenkins_obj):
self.jenkins_obj = jenkins_obj
JenkinsBase.__init__(self, url)
# print 'DEBUG: Plugins._data=', self._data
def get_jenkins_obj(self):
return self.jenkins_obj
def _poll(self):
return self.get_data(self.baseurl)
def keys(self):
return self.get_plugins_dict().keys()
def iteritems(self):
return self._get_plugins()
def values(self):
return [a[1] for a in self.iteritems()]
def _get_plugins(self):
if not 'plugins' in self._data:
pass
else:
for p_dict in self._data["plugins"]:
yield p_dict["shortName"], Plugin(p_dict)
def get_plugins_dict(self):
return dict(self._get_plugins())
def __len__(self):
return len(self.get_plugins_dict().keys())
def __getitem__(self, plugin_name):
return self.get_plugins_dict().get(plugin_name, None)
def __contains__(self, plugin_name):
"""
True if plugin_name is the name of a defined plugin
"""
return plugin_name in self.keys()
def __str__(self):
plugins = [plugin["shortName"] for plugin in self._data.get("plugins", [])]
return str(sorted(plugins))
<commit_msg>Add trailing newline in file<commit_after> | import urllib
import logging
from jenkinsapi.jenkinsbase import JenkinsBase
from jenkinsapi.plugin import Plugin
log = logging.getLogger(__name__)
class Plugins(JenkinsBase):
def __init__(self, url, jenkins_obj):
self.jenkins_obj = jenkins_obj
JenkinsBase.__init__(self, url)
# print 'DEBUG: Plugins._data=', self._data
def get_jenkins_obj(self):
return self.jenkins_obj
def _poll(self):
return self.get_data(self.baseurl)
def keys(self):
return self.get_plugins_dict().keys()
def iteritems(self):
return self._get_plugins()
def values(self):
return [a[1] for a in self.iteritems()]
def _get_plugins(self):
if not 'plugins' in self._data:
pass
else:
for p_dict in self._data["plugins"]:
yield p_dict["shortName"], Plugin(p_dict)
def get_plugins_dict(self):
return dict(self._get_plugins())
def __len__(self):
return len(self.get_plugins_dict().keys())
def __getitem__(self, plugin_name):
return self.get_plugins_dict().get(plugin_name, None)
def __contains__(self, plugin_name):
"""
True if plugin_name is the name of a defined plugin
"""
return plugin_name in self.keys()
def __str__(self):
plugins = [plugin["shortName"] for plugin in self._data.get("plugins", [])]
return str(sorted(plugins))
| import urllib
import logging
from jenkinsapi.jenkinsbase import JenkinsBase
from jenkinsapi.plugin import Plugin
log = logging.getLogger(__name__)
class Plugins(JenkinsBase):
def __init__(self, url, jenkins_obj):
self.jenkins_obj = jenkins_obj
JenkinsBase.__init__(self, url)
# print 'DEBUG: Plugins._data=', self._data
def get_jenkins_obj(self):
return self.jenkins_obj
def _poll(self):
return self.get_data(self.baseurl)
def keys(self):
return self.get_plugins_dict().keys()
def iteritems(self):
return self._get_plugins()
def values(self):
return [a[1] for a in self.iteritems()]
def _get_plugins(self):
if not 'plugins' in self._data:
pass
else:
for p_dict in self._data["plugins"]:
yield p_dict["shortName"], Plugin(p_dict)
def get_plugins_dict(self):
return dict(self._get_plugins())
def __len__(self):
return len(self.get_plugins_dict().keys())
def __getitem__(self, plugin_name):
return self.get_plugins_dict().get(plugin_name, None)
def __contains__(self, plugin_name):
"""
True if plugin_name is the name of a defined plugin
"""
return plugin_name in self.keys()
def __str__(self):
plugins = [plugin["shortName"] for plugin in self._data.get("plugins", [])]
return str(sorted(plugins))
Add trailing newline in fileimport urllib
import logging
from jenkinsapi.jenkinsbase import JenkinsBase
from jenkinsapi.plugin import Plugin
log = logging.getLogger(__name__)
class Plugins(JenkinsBase):
def __init__(self, url, jenkins_obj):
self.jenkins_obj = jenkins_obj
JenkinsBase.__init__(self, url)
# print 'DEBUG: Plugins._data=', self._data
def get_jenkins_obj(self):
return self.jenkins_obj
def _poll(self):
return self.get_data(self.baseurl)
def keys(self):
return self.get_plugins_dict().keys()
def iteritems(self):
return self._get_plugins()
def values(self):
return [a[1] for a in self.iteritems()]
def _get_plugins(self):
if not 'plugins' in self._data:
pass
else:
for p_dict in self._data["plugins"]:
yield p_dict["shortName"], Plugin(p_dict)
def get_plugins_dict(self):
return dict(self._get_plugins())
def __len__(self):
return len(self.get_plugins_dict().keys())
def __getitem__(self, plugin_name):
return self.get_plugins_dict().get(plugin_name, None)
def __contains__(self, plugin_name):
"""
True if plugin_name is the name of a defined plugin
"""
return plugin_name in self.keys()
def __str__(self):
plugins = [plugin["shortName"] for plugin in self._data.get("plugins", [])]
return str(sorted(plugins))
| <commit_before>import urllib
import logging
from jenkinsapi.jenkinsbase import JenkinsBase
from jenkinsapi.plugin import Plugin
log = logging.getLogger(__name__)
class Plugins(JenkinsBase):
def __init__(self, url, jenkins_obj):
self.jenkins_obj = jenkins_obj
JenkinsBase.__init__(self, url)
# print 'DEBUG: Plugins._data=', self._data
def get_jenkins_obj(self):
return self.jenkins_obj
def _poll(self):
return self.get_data(self.baseurl)
def keys(self):
return self.get_plugins_dict().keys()
def iteritems(self):
return self._get_plugins()
def values(self):
return [a[1] for a in self.iteritems()]
def _get_plugins(self):
if not 'plugins' in self._data:
pass
else:
for p_dict in self._data["plugins"]:
yield p_dict["shortName"], Plugin(p_dict)
def get_plugins_dict(self):
return dict(self._get_plugins())
def __len__(self):
return len(self.get_plugins_dict().keys())
def __getitem__(self, plugin_name):
return self.get_plugins_dict().get(plugin_name, None)
def __contains__(self, plugin_name):
"""
True if plugin_name is the name of a defined plugin
"""
return plugin_name in self.keys()
def __str__(self):
plugins = [plugin["shortName"] for plugin in self._data.get("plugins", [])]
return str(sorted(plugins))
<commit_msg>Add trailing newline in file<commit_after>import urllib
import logging
from jenkinsapi.jenkinsbase import JenkinsBase
from jenkinsapi.plugin import Plugin
log = logging.getLogger(__name__)
class Plugins(JenkinsBase):
def __init__(self, url, jenkins_obj):
self.jenkins_obj = jenkins_obj
JenkinsBase.__init__(self, url)
# print 'DEBUG: Plugins._data=', self._data
def get_jenkins_obj(self):
return self.jenkins_obj
def _poll(self):
return self.get_data(self.baseurl)
def keys(self):
return self.get_plugins_dict().keys()
def iteritems(self):
return self._get_plugins()
def values(self):
return [a[1] for a in self.iteritems()]
def _get_plugins(self):
if not 'plugins' in self._data:
pass
else:
for p_dict in self._data["plugins"]:
yield p_dict["shortName"], Plugin(p_dict)
def get_plugins_dict(self):
return dict(self._get_plugins())
def __len__(self):
return len(self.get_plugins_dict().keys())
def __getitem__(self, plugin_name):
return self.get_plugins_dict().get(plugin_name, None)
def __contains__(self, plugin_name):
"""
True if plugin_name is the name of a defined plugin
"""
return plugin_name in self.keys()
def __str__(self):
plugins = [plugin["shortName"] for plugin in self._data.get("plugins", [])]
return str(sorted(plugins))
|
30f8317838a2e984e54fe22042fd3ffff10f82e6 | waterbutler/core/streams/file.py | waterbutler/core/streams/file.py | import os
import asyncio
from waterbutler.core.streams import BaseStream
class FileStreamReader(BaseStream):
def __init__(self, file_pointer):
super().__init__()
self.file_gen = None
self.file_pointer = file_pointer
self.read_size = None
self.content_type = 'application/octet-stream'
@property
def size(self):
cursor = self.file_pointer.tell()
self.file_pointer.seek(0, os.SEEK_END)
ret = self.file_pointer.tell()
self.file_pointer.seek(cursor)
return ret
def close(self):
self.file_pointer.close()
self.feed_eof()
def read_as_gen(self):
self.file_pointer.seek(0)
while True:
data = self.file_pointer.read(self.read_size)
if not data:
break
yield data
async def _read(self, size):
self.file_gen = self.file_gen or self.read_as_gen()
# add sleep of 0 so read will yield and continue in next io loop iteration
await asyncio.sleep(0)
self.read_size = size
try:
return next(self.file_gen)
except StopIteration:
self.feed_eof()
return b''
| import os
from waterbutler.core.streams import BaseStream
class FileStreamReader(BaseStream):
def __init__(self, file_pointer):
super().__init__()
self.file_gen = None
self.file_pointer = file_pointer
self.read_size = None
self.content_type = 'application/octet-stream'
@property
def size(self):
cursor = self.file_pointer.tell()
self.file_pointer.seek(0, os.SEEK_END)
ret = self.file_pointer.tell()
self.file_pointer.seek(cursor)
return ret
def close(self):
self.file_pointer.close()
self.feed_eof()
def read_as_gen(self):
self.file_pointer.seek(0)
while True:
chunk = self.file_pointer.read(self.read_size)
if not chunk:
self.feed_eof()
chunk = b''
yield chunk
async def _read(self, size):
self.file_gen = self.file_gen or self.read_as_gen()
self.read_size = size
return next(self.file_gen)
| Update FileStreamReader for new python 3.5 async | Update FileStreamReader for new python 3.5 async
| Python | apache-2.0 | RCOSDP/waterbutler,felliott/waterbutler,rdhyee/waterbutler,CenterForOpenScience/waterbutler,TomBaxter/waterbutler,Johnetordoff/waterbutler | import os
import asyncio
from waterbutler.core.streams import BaseStream
class FileStreamReader(BaseStream):
def __init__(self, file_pointer):
super().__init__()
self.file_gen = None
self.file_pointer = file_pointer
self.read_size = None
self.content_type = 'application/octet-stream'
@property
def size(self):
cursor = self.file_pointer.tell()
self.file_pointer.seek(0, os.SEEK_END)
ret = self.file_pointer.tell()
self.file_pointer.seek(cursor)
return ret
def close(self):
self.file_pointer.close()
self.feed_eof()
def read_as_gen(self):
self.file_pointer.seek(0)
while True:
data = self.file_pointer.read(self.read_size)
if not data:
break
yield data
async def _read(self, size):
self.file_gen = self.file_gen or self.read_as_gen()
# add sleep of 0 so read will yield and continue in next io loop iteration
await asyncio.sleep(0)
self.read_size = size
try:
return next(self.file_gen)
except StopIteration:
self.feed_eof()
return b''
Update FileStreamReader for new python 3.5 async | import os
from waterbutler.core.streams import BaseStream
class FileStreamReader(BaseStream):
def __init__(self, file_pointer):
super().__init__()
self.file_gen = None
self.file_pointer = file_pointer
self.read_size = None
self.content_type = 'application/octet-stream'
@property
def size(self):
cursor = self.file_pointer.tell()
self.file_pointer.seek(0, os.SEEK_END)
ret = self.file_pointer.tell()
self.file_pointer.seek(cursor)
return ret
def close(self):
self.file_pointer.close()
self.feed_eof()
def read_as_gen(self):
self.file_pointer.seek(0)
while True:
chunk = self.file_pointer.read(self.read_size)
if not chunk:
self.feed_eof()
chunk = b''
yield chunk
async def _read(self, size):
self.file_gen = self.file_gen or self.read_as_gen()
self.read_size = size
return next(self.file_gen)
| <commit_before>import os
import asyncio
from waterbutler.core.streams import BaseStream
class FileStreamReader(BaseStream):
def __init__(self, file_pointer):
super().__init__()
self.file_gen = None
self.file_pointer = file_pointer
self.read_size = None
self.content_type = 'application/octet-stream'
@property
def size(self):
cursor = self.file_pointer.tell()
self.file_pointer.seek(0, os.SEEK_END)
ret = self.file_pointer.tell()
self.file_pointer.seek(cursor)
return ret
def close(self):
self.file_pointer.close()
self.feed_eof()
def read_as_gen(self):
self.file_pointer.seek(0)
while True:
data = self.file_pointer.read(self.read_size)
if not data:
break
yield data
async def _read(self, size):
self.file_gen = self.file_gen or self.read_as_gen()
# add sleep of 0 so read will yield and continue in next io loop iteration
await asyncio.sleep(0)
self.read_size = size
try:
return next(self.file_gen)
except StopIteration:
self.feed_eof()
return b''
<commit_msg>Update FileStreamReader for new python 3.5 async<commit_after> | import os
from waterbutler.core.streams import BaseStream
class FileStreamReader(BaseStream):
def __init__(self, file_pointer):
super().__init__()
self.file_gen = None
self.file_pointer = file_pointer
self.read_size = None
self.content_type = 'application/octet-stream'
@property
def size(self):
cursor = self.file_pointer.tell()
self.file_pointer.seek(0, os.SEEK_END)
ret = self.file_pointer.tell()
self.file_pointer.seek(cursor)
return ret
def close(self):
self.file_pointer.close()
self.feed_eof()
def read_as_gen(self):
self.file_pointer.seek(0)
while True:
chunk = self.file_pointer.read(self.read_size)
if not chunk:
self.feed_eof()
chunk = b''
yield chunk
async def _read(self, size):
self.file_gen = self.file_gen or self.read_as_gen()
self.read_size = size
return next(self.file_gen)
| import os
import asyncio
from waterbutler.core.streams import BaseStream
class FileStreamReader(BaseStream):
def __init__(self, file_pointer):
super().__init__()
self.file_gen = None
self.file_pointer = file_pointer
self.read_size = None
self.content_type = 'application/octet-stream'
@property
def size(self):
cursor = self.file_pointer.tell()
self.file_pointer.seek(0, os.SEEK_END)
ret = self.file_pointer.tell()
self.file_pointer.seek(cursor)
return ret
def close(self):
self.file_pointer.close()
self.feed_eof()
def read_as_gen(self):
self.file_pointer.seek(0)
while True:
data = self.file_pointer.read(self.read_size)
if not data:
break
yield data
async def _read(self, size):
self.file_gen = self.file_gen or self.read_as_gen()
# add sleep of 0 so read will yield and continue in next io loop iteration
await asyncio.sleep(0)
self.read_size = size
try:
return next(self.file_gen)
except StopIteration:
self.feed_eof()
return b''
Update FileStreamReader for new python 3.5 asyncimport os
from waterbutler.core.streams import BaseStream
class FileStreamReader(BaseStream):
def __init__(self, file_pointer):
super().__init__()
self.file_gen = None
self.file_pointer = file_pointer
self.read_size = None
self.content_type = 'application/octet-stream'
@property
def size(self):
cursor = self.file_pointer.tell()
self.file_pointer.seek(0, os.SEEK_END)
ret = self.file_pointer.tell()
self.file_pointer.seek(cursor)
return ret
def close(self):
self.file_pointer.close()
self.feed_eof()
def read_as_gen(self):
self.file_pointer.seek(0)
while True:
chunk = self.file_pointer.read(self.read_size)
if not chunk:
self.feed_eof()
chunk = b''
yield chunk
async def _read(self, size):
self.file_gen = self.file_gen or self.read_as_gen()
self.read_size = size
return next(self.file_gen)
| <commit_before>import os
import asyncio
from waterbutler.core.streams import BaseStream
class FileStreamReader(BaseStream):
def __init__(self, file_pointer):
super().__init__()
self.file_gen = None
self.file_pointer = file_pointer
self.read_size = None
self.content_type = 'application/octet-stream'
@property
def size(self):
cursor = self.file_pointer.tell()
self.file_pointer.seek(0, os.SEEK_END)
ret = self.file_pointer.tell()
self.file_pointer.seek(cursor)
return ret
def close(self):
self.file_pointer.close()
self.feed_eof()
def read_as_gen(self):
self.file_pointer.seek(0)
while True:
data = self.file_pointer.read(self.read_size)
if not data:
break
yield data
async def _read(self, size):
self.file_gen = self.file_gen or self.read_as_gen()
# add sleep of 0 so read will yield and continue in next io loop iteration
await asyncio.sleep(0)
self.read_size = size
try:
return next(self.file_gen)
except StopIteration:
self.feed_eof()
return b''
<commit_msg>Update FileStreamReader for new python 3.5 async<commit_after>import os
from waterbutler.core.streams import BaseStream
class FileStreamReader(BaseStream):
def __init__(self, file_pointer):
super().__init__()
self.file_gen = None
self.file_pointer = file_pointer
self.read_size = None
self.content_type = 'application/octet-stream'
@property
def size(self):
cursor = self.file_pointer.tell()
self.file_pointer.seek(0, os.SEEK_END)
ret = self.file_pointer.tell()
self.file_pointer.seek(cursor)
return ret
def close(self):
self.file_pointer.close()
self.feed_eof()
def read_as_gen(self):
self.file_pointer.seek(0)
while True:
chunk = self.file_pointer.read(self.read_size)
if not chunk:
self.feed_eof()
chunk = b''
yield chunk
async def _read(self, size):
self.file_gen = self.file_gen or self.read_as_gen()
self.read_size = size
return next(self.file_gen)
|
8ece892f01c4b32f7fa0a34c88bfdf8ea969e5ce | kobo/apps/__init__.py | kobo/apps/__init__.py | # coding: utf-8
import kombu.exceptions
from django.apps import AppConfig
from django.core.checks import register, Tags
from kpi.utils.two_database_configuration_checker import \
TwoDatabaseConfigurationChecker
class KpiConfig(AppConfig):
name = 'kpi'
def ready(self, *args, **kwargs):
# Once it's okay to read from the database, apply the user-desired
# autoscaling configuration for Celery workers
from kobo.celery import update_concurrency_from_constance
try:
update_concurrency_from_constance.delay()
except kombu.exceptions.OperationalError as e:
# It's normal for Django to start without access to a message
# broker, e.g. while running `./manage.py collectstatic`
# during a Docker image build
pass
return super().ready(*args, **kwargs)
register(TwoDatabaseConfigurationChecker().as_check(), Tags.database)
| # coding: utf-8
import kombu.exceptions
from django.apps import AppConfig
from django.core.checks import register, Tags
from kpi.utils.two_database_configuration_checker import \
TwoDatabaseConfigurationChecker
class KpiConfig(AppConfig):
name = 'kpi'
def ready(self, *args, **kwargs):
# Once it's okay to read from the database, apply the user-desired
# autoscaling configuration for Celery workers
from kobo.celery import update_concurrency_from_constance
try:
# Push this onto the task queue with `delay()` instead of calling
# it directly because a direct call in the absence of any Celery
# workers hangs indefinitely
update_concurrency_from_constance.delay()
except kombu.exceptions.OperationalError as e:
# It's normal for Django to start without access to a message
# broker, e.g. while running `./manage.py collectstatic`
# during a Docker image build
pass
return super().ready(*args, **kwargs)
register(TwoDatabaseConfigurationChecker().as_check(), Tags.database)
| Add explanatory comment for odd use of `delay()` | Add explanatory comment for odd use of `delay()`
| Python | agpl-3.0 | kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi | # coding: utf-8
import kombu.exceptions
from django.apps import AppConfig
from django.core.checks import register, Tags
from kpi.utils.two_database_configuration_checker import \
TwoDatabaseConfigurationChecker
class KpiConfig(AppConfig):
name = 'kpi'
def ready(self, *args, **kwargs):
# Once it's okay to read from the database, apply the user-desired
# autoscaling configuration for Celery workers
from kobo.celery import update_concurrency_from_constance
try:
update_concurrency_from_constance.delay()
except kombu.exceptions.OperationalError as e:
# It's normal for Django to start without access to a message
# broker, e.g. while running `./manage.py collectstatic`
# during a Docker image build
pass
return super().ready(*args, **kwargs)
register(TwoDatabaseConfigurationChecker().as_check(), Tags.database)
Add explanatory comment for odd use of `delay()` | # coding: utf-8
import kombu.exceptions
from django.apps import AppConfig
from django.core.checks import register, Tags
from kpi.utils.two_database_configuration_checker import \
TwoDatabaseConfigurationChecker
class KpiConfig(AppConfig):
name = 'kpi'
def ready(self, *args, **kwargs):
# Once it's okay to read from the database, apply the user-desired
# autoscaling configuration for Celery workers
from kobo.celery import update_concurrency_from_constance
try:
# Push this onto the task queue with `delay()` instead of calling
# it directly because a direct call in the absence of any Celery
# workers hangs indefinitely
update_concurrency_from_constance.delay()
except kombu.exceptions.OperationalError as e:
# It's normal for Django to start without access to a message
# broker, e.g. while running `./manage.py collectstatic`
# during a Docker image build
pass
return super().ready(*args, **kwargs)
register(TwoDatabaseConfigurationChecker().as_check(), Tags.database)
| <commit_before># coding: utf-8
import kombu.exceptions
from django.apps import AppConfig
from django.core.checks import register, Tags
from kpi.utils.two_database_configuration_checker import \
TwoDatabaseConfigurationChecker
class KpiConfig(AppConfig):
name = 'kpi'
def ready(self, *args, **kwargs):
# Once it's okay to read from the database, apply the user-desired
# autoscaling configuration for Celery workers
from kobo.celery import update_concurrency_from_constance
try:
update_concurrency_from_constance.delay()
except kombu.exceptions.OperationalError as e:
# It's normal for Django to start without access to a message
# broker, e.g. while running `./manage.py collectstatic`
# during a Docker image build
pass
return super().ready(*args, **kwargs)
register(TwoDatabaseConfigurationChecker().as_check(), Tags.database)
<commit_msg>Add explanatory comment for odd use of `delay()`<commit_after> | # coding: utf-8
import kombu.exceptions
from django.apps import AppConfig
from django.core.checks import register, Tags
from kpi.utils.two_database_configuration_checker import \
TwoDatabaseConfigurationChecker
class KpiConfig(AppConfig):
name = 'kpi'
def ready(self, *args, **kwargs):
# Once it's okay to read from the database, apply the user-desired
# autoscaling configuration for Celery workers
from kobo.celery import update_concurrency_from_constance
try:
# Push this onto the task queue with `delay()` instead of calling
# it directly because a direct call in the absence of any Celery
# workers hangs indefinitely
update_concurrency_from_constance.delay()
except kombu.exceptions.OperationalError as e:
# It's normal for Django to start without access to a message
# broker, e.g. while running `./manage.py collectstatic`
# during a Docker image build
pass
return super().ready(*args, **kwargs)
register(TwoDatabaseConfigurationChecker().as_check(), Tags.database)
| # coding: utf-8
import kombu.exceptions
from django.apps import AppConfig
from django.core.checks import register, Tags
from kpi.utils.two_database_configuration_checker import \
TwoDatabaseConfigurationChecker
class KpiConfig(AppConfig):
name = 'kpi'
def ready(self, *args, **kwargs):
# Once it's okay to read from the database, apply the user-desired
# autoscaling configuration for Celery workers
from kobo.celery import update_concurrency_from_constance
try:
update_concurrency_from_constance.delay()
except kombu.exceptions.OperationalError as e:
# It's normal for Django to start without access to a message
# broker, e.g. while running `./manage.py collectstatic`
# during a Docker image build
pass
return super().ready(*args, **kwargs)
register(TwoDatabaseConfigurationChecker().as_check(), Tags.database)
Add explanatory comment for odd use of `delay()`# coding: utf-8
import kombu.exceptions
from django.apps import AppConfig
from django.core.checks import register, Tags
from kpi.utils.two_database_configuration_checker import \
TwoDatabaseConfigurationChecker
class KpiConfig(AppConfig):
name = 'kpi'
def ready(self, *args, **kwargs):
# Once it's okay to read from the database, apply the user-desired
# autoscaling configuration for Celery workers
from kobo.celery import update_concurrency_from_constance
try:
# Push this onto the task queue with `delay()` instead of calling
# it directly because a direct call in the absence of any Celery
# workers hangs indefinitely
update_concurrency_from_constance.delay()
except kombu.exceptions.OperationalError as e:
# It's normal for Django to start without access to a message
# broker, e.g. while running `./manage.py collectstatic`
# during a Docker image build
pass
return super().ready(*args, **kwargs)
register(TwoDatabaseConfigurationChecker().as_check(), Tags.database)
| <commit_before># coding: utf-8
import kombu.exceptions
from django.apps import AppConfig
from django.core.checks import register, Tags
from kpi.utils.two_database_configuration_checker import \
TwoDatabaseConfigurationChecker
class KpiConfig(AppConfig):
name = 'kpi'
def ready(self, *args, **kwargs):
# Once it's okay to read from the database, apply the user-desired
# autoscaling configuration for Celery workers
from kobo.celery import update_concurrency_from_constance
try:
update_concurrency_from_constance.delay()
except kombu.exceptions.OperationalError as e:
# It's normal for Django to start without access to a message
# broker, e.g. while running `./manage.py collectstatic`
# during a Docker image build
pass
return super().ready(*args, **kwargs)
register(TwoDatabaseConfigurationChecker().as_check(), Tags.database)
<commit_msg>Add explanatory comment for odd use of `delay()`<commit_after># coding: utf-8
import kombu.exceptions
from django.apps import AppConfig
from django.core.checks import register, Tags
from kpi.utils.two_database_configuration_checker import \
TwoDatabaseConfigurationChecker
class KpiConfig(AppConfig):
name = 'kpi'
def ready(self, *args, **kwargs):
# Once it's okay to read from the database, apply the user-desired
# autoscaling configuration for Celery workers
from kobo.celery import update_concurrency_from_constance
try:
# Push this onto the task queue with `delay()` instead of calling
# it directly because a direct call in the absence of any Celery
# workers hangs indefinitely
update_concurrency_from_constance.delay()
except kombu.exceptions.OperationalError as e:
# It's normal for Django to start without access to a message
# broker, e.g. while running `./manage.py collectstatic`
# during a Docker image build
pass
return super().ready(*args, **kwargs)
register(TwoDatabaseConfigurationChecker().as_check(), Tags.database)
|
bf2b6bad53edbf649bdd16830de17fd974ee7443 | lambdawebhook/hook.py | lambdawebhook/hook.py | #!/usr/bin/env python
import os
import sys
import hashlib
# Add the lib directory to the path for Lambda to load our libs
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
import requests # NOQA
import hmac # NOQA
def verify_signature(secret, signature, payload):
computed_hash = hmac.new(str(secret), payload, hashlib.sha1)
computed_signature = '='.join(['sha1', computed_hash.hexdigest()])
return hmac.compare_digest(computed_signature, str(signature))
def lambda_handler(event, context):
print 'Webhook received'
verified = verify_signature(event['secret'],
event['x_hub_signature'],
event['payload'])
print 'Signature verified: ' + str(verified)
if verified:
response = requests.post(event['jenkins_url'],
headers={
'X-GitHub-Delivery': event['x_github_delivery'],
'X-GitHub-Event': event['x_github_event'],
'X-Hub-Signature': event['x_hub_signature']
},
json=event['payload'])
response.raise_for_status()
else:
raise requests.HTTPError('400 Client Error: Bad Request')
if __name__ == "__main__":
pass
| #!/usr/bin/env python
import os
import sys
import hashlib
# Add the lib directory to the path for Lambda to load our libs
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
import requests # NOQA
import hmac # NOQA
def verify_signature(secret, signature, payload):
computed_hash = hmac.new(str(secret), payload, hashlib.sha1)
computed_signature = '='.join(['sha1', computed_hash.hexdigest()])
return hmac.compare_digest(computed_signature, str(signature))
def lambda_handler(event, context):
print 'Webhook received'
verified = verify_signature(event['secret'],
event['x_hub_signature'],
event['payload'])
print 'Signature verified: ' + str(verified)
if verified:
response = requests.post(event['jenkins_url'],
headers={
'Content-Type': 'application/json',
'X-GitHub-Delivery': event['x_github_delivery'],
'X-GitHub-Event': event['x_github_event'],
'X-Hub-Signature': event['x_hub_signature']
},
data=event['payload'])
response.raise_for_status()
else:
raise requests.HTTPError('400 Client Error: Bad Request')
if __name__ == "__main__":
pass
| Send json content-type to Jenkins | Send json content-type to Jenkins
| Python | bsd-3-clause | pristineio/lambda-webhook | #!/usr/bin/env python
import os
import sys
import hashlib
# Add the lib directory to the path for Lambda to load our libs
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
import requests # NOQA
import hmac # NOQA
def verify_signature(secret, signature, payload):
computed_hash = hmac.new(str(secret), payload, hashlib.sha1)
computed_signature = '='.join(['sha1', computed_hash.hexdigest()])
return hmac.compare_digest(computed_signature, str(signature))
def lambda_handler(event, context):
print 'Webhook received'
verified = verify_signature(event['secret'],
event['x_hub_signature'],
event['payload'])
print 'Signature verified: ' + str(verified)
if verified:
response = requests.post(event['jenkins_url'],
headers={
'X-GitHub-Delivery': event['x_github_delivery'],
'X-GitHub-Event': event['x_github_event'],
'X-Hub-Signature': event['x_hub_signature']
},
json=event['payload'])
response.raise_for_status()
else:
raise requests.HTTPError('400 Client Error: Bad Request')
if __name__ == "__main__":
pass
Send json content-type to Jenkins | #!/usr/bin/env python
import os
import sys
import hashlib
# Add the lib directory to the path for Lambda to load our libs
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
import requests # NOQA
import hmac # NOQA
def verify_signature(secret, signature, payload):
computed_hash = hmac.new(str(secret), payload, hashlib.sha1)
computed_signature = '='.join(['sha1', computed_hash.hexdigest()])
return hmac.compare_digest(computed_signature, str(signature))
def lambda_handler(event, context):
print 'Webhook received'
verified = verify_signature(event['secret'],
event['x_hub_signature'],
event['payload'])
print 'Signature verified: ' + str(verified)
if verified:
response = requests.post(event['jenkins_url'],
headers={
'Content-Type': 'application/json',
'X-GitHub-Delivery': event['x_github_delivery'],
'X-GitHub-Event': event['x_github_event'],
'X-Hub-Signature': event['x_hub_signature']
},
data=event['payload'])
response.raise_for_status()
else:
raise requests.HTTPError('400 Client Error: Bad Request')
if __name__ == "__main__":
pass
| <commit_before>#!/usr/bin/env python
import os
import sys
import hashlib
# Add the lib directory to the path for Lambda to load our libs
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
import requests # NOQA
import hmac # NOQA
def verify_signature(secret, signature, payload):
computed_hash = hmac.new(str(secret), payload, hashlib.sha1)
computed_signature = '='.join(['sha1', computed_hash.hexdigest()])
return hmac.compare_digest(computed_signature, str(signature))
def lambda_handler(event, context):
print 'Webhook received'
verified = verify_signature(event['secret'],
event['x_hub_signature'],
event['payload'])
print 'Signature verified: ' + str(verified)
if verified:
response = requests.post(event['jenkins_url'],
headers={
'X-GitHub-Delivery': event['x_github_delivery'],
'X-GitHub-Event': event['x_github_event'],
'X-Hub-Signature': event['x_hub_signature']
},
json=event['payload'])
response.raise_for_status()
else:
raise requests.HTTPError('400 Client Error: Bad Request')
if __name__ == "__main__":
pass
<commit_msg>Send json content-type to Jenkins<commit_after> | #!/usr/bin/env python
import os
import sys
import hashlib
# Add the lib directory to the path for Lambda to load our libs
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
import requests # NOQA
import hmac # NOQA
def verify_signature(secret, signature, payload):
computed_hash = hmac.new(str(secret), payload, hashlib.sha1)
computed_signature = '='.join(['sha1', computed_hash.hexdigest()])
return hmac.compare_digest(computed_signature, str(signature))
def lambda_handler(event, context):
print 'Webhook received'
verified = verify_signature(event['secret'],
event['x_hub_signature'],
event['payload'])
print 'Signature verified: ' + str(verified)
if verified:
response = requests.post(event['jenkins_url'],
headers={
'Content-Type': 'application/json',
'X-GitHub-Delivery': event['x_github_delivery'],
'X-GitHub-Event': event['x_github_event'],
'X-Hub-Signature': event['x_hub_signature']
},
data=event['payload'])
response.raise_for_status()
else:
raise requests.HTTPError('400 Client Error: Bad Request')
if __name__ == "__main__":
pass
| #!/usr/bin/env python
import os
import sys
import hashlib
# Add the lib directory to the path for Lambda to load our libs
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
import requests # NOQA
import hmac # NOQA
def verify_signature(secret, signature, payload):
computed_hash = hmac.new(str(secret), payload, hashlib.sha1)
computed_signature = '='.join(['sha1', computed_hash.hexdigest()])
return hmac.compare_digest(computed_signature, str(signature))
def lambda_handler(event, context):
print 'Webhook received'
verified = verify_signature(event['secret'],
event['x_hub_signature'],
event['payload'])
print 'Signature verified: ' + str(verified)
if verified:
response = requests.post(event['jenkins_url'],
headers={
'X-GitHub-Delivery': event['x_github_delivery'],
'X-GitHub-Event': event['x_github_event'],
'X-Hub-Signature': event['x_hub_signature']
},
json=event['payload'])
response.raise_for_status()
else:
raise requests.HTTPError('400 Client Error: Bad Request')
if __name__ == "__main__":
pass
Send json content-type to Jenkins#!/usr/bin/env python
import os
import sys
import hashlib
# Add the lib directory to the path for Lambda to load our libs
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
import requests # NOQA
import hmac # NOQA
def verify_signature(secret, signature, payload):
computed_hash = hmac.new(str(secret), payload, hashlib.sha1)
computed_signature = '='.join(['sha1', computed_hash.hexdigest()])
return hmac.compare_digest(computed_signature, str(signature))
def lambda_handler(event, context):
print 'Webhook received'
verified = verify_signature(event['secret'],
event['x_hub_signature'],
event['payload'])
print 'Signature verified: ' + str(verified)
if verified:
response = requests.post(event['jenkins_url'],
headers={
'Content-Type': 'application/json',
'X-GitHub-Delivery': event['x_github_delivery'],
'X-GitHub-Event': event['x_github_event'],
'X-Hub-Signature': event['x_hub_signature']
},
data=event['payload'])
response.raise_for_status()
else:
raise requests.HTTPError('400 Client Error: Bad Request')
if __name__ == "__main__":
pass
| <commit_before>#!/usr/bin/env python
import os
import sys
import hashlib
# Add the lib directory to the path for Lambda to load our libs
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
import requests # NOQA
import hmac # NOQA
def verify_signature(secret, signature, payload):
computed_hash = hmac.new(str(secret), payload, hashlib.sha1)
computed_signature = '='.join(['sha1', computed_hash.hexdigest()])
return hmac.compare_digest(computed_signature, str(signature))
def lambda_handler(event, context):
print 'Webhook received'
verified = verify_signature(event['secret'],
event['x_hub_signature'],
event['payload'])
print 'Signature verified: ' + str(verified)
if verified:
response = requests.post(event['jenkins_url'],
headers={
'X-GitHub-Delivery': event['x_github_delivery'],
'X-GitHub-Event': event['x_github_event'],
'X-Hub-Signature': event['x_hub_signature']
},
json=event['payload'])
response.raise_for_status()
else:
raise requests.HTTPError('400 Client Error: Bad Request')
if __name__ == "__main__":
pass
<commit_msg>Send json content-type to Jenkins<commit_after>#!/usr/bin/env python
import os
import sys
import hashlib
# Add the lib directory to the path for Lambda to load our libs
sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))
import requests # NOQA
import hmac # NOQA
def verify_signature(secret, signature, payload):
computed_hash = hmac.new(str(secret), payload, hashlib.sha1)
computed_signature = '='.join(['sha1', computed_hash.hexdigest()])
return hmac.compare_digest(computed_signature, str(signature))
def lambda_handler(event, context):
print 'Webhook received'
verified = verify_signature(event['secret'],
event['x_hub_signature'],
event['payload'])
print 'Signature verified: ' + str(verified)
if verified:
response = requests.post(event['jenkins_url'],
headers={
'Content-Type': 'application/json',
'X-GitHub-Delivery': event['x_github_delivery'],
'X-GitHub-Event': event['x_github_event'],
'X-Hub-Signature': event['x_hub_signature']
},
data=event['payload'])
response.raise_for_status()
else:
raise requests.HTTPError('400 Client Error: Bad Request')
if __name__ == "__main__":
pass
|
43238e5a0f7b3782ebadad43deffc4d768e8f79a | scikits/learn/machine/manifold_learning/regression/neighbors/__init__.py | scikits/learn/machine/manifold_learning/regression/neighbors/__init__.py |
# Matthieu Brucher
# Last Change : 2008-04-15 10:42
"""
Neighbors module
"""
from neighbors import *
from utilities import *
__all__ = ['Neighbors', 'KNeighbors', 'Parzen', 'create_graph']
def test(level=-1, verbosity=1):
from numpy.testing import NumpyTest
return NumpyTest().test(level, verbosity)
|
# Matthieu Brucher
# Last Change : 2008-04-15 10:42
"""
Neighbors module
"""
from neighbors import *
from utilities import *
__all__ = ['Neighbors', 'Kneighbors', 'Parzen', 'create_graph']
def test(level=-1, verbosity=1):
from numpy.testing import NumpyTest
return NumpyTest().test(level, verbosity)
| Fix typo in class name. | Fix typo in class name.
It was preventing import to work properly.
From: Fabian Pedregosa <fabian.pedregosa@inria.fr>
git-svn-id: a2d1b0e147e530765aaf3e1662d4a98e2f63c719@342 22fbfee3-77ab-4535-9bad-27d1bd3bc7d8
| Python | bsd-3-clause | shenzebang/scikit-learn,alexsavio/scikit-learn,PatrickOReilly/scikit-learn,mugizico/scikit-learn,jayflo/scikit-learn,aminert/scikit-learn,glennq/scikit-learn,YinongLong/scikit-learn,fengzhyuan/scikit-learn,arahuja/scikit-learn,adamgreenhall/scikit-learn,mblondel/scikit-learn,pianomania/scikit-learn,ilo10/scikit-learn,ilo10/scikit-learn,henrykironde/scikit-learn,mattilyra/scikit-learn,elkingtonmcb/scikit-learn,manashmndl/scikit-learn,RomainBrault/scikit-learn,costypetrisor/scikit-learn,sgenoud/scikit-learn,mjgrav2001/scikit-learn,OshynSong/scikit-learn,andaag/scikit-learn,shyamalschandra/scikit-learn,zhenv5/scikit-learn,schets/scikit-learn,pkruskal/scikit-learn,carrillo/scikit-learn,0asa/scikit-learn,AlexanderFabisch/scikit-learn,lin-credible/scikit-learn,jakobworldpeace/scikit-learn,Nyker510/scikit-learn,andrewnc/scikit-learn,victorbergelin/scikit-learn,h2educ/scikit-learn,Titan-C/scikit-learn,BiaDarkia/scikit-learn,nvoron23/scikit-learn,ahoyosid/scikit-learn,olologin/scikit-learn,larsmans/scikit-learn,robbymeals/scikit-learn,jmschrei/scikit-learn,ogrisel/scikit-learn,qifeigit/scikit-learn,zorojean/scikit-learn,xyguo/scikit-learn,davidgbe/scikit-learn,hainm/scikit-learn,costypetrisor/scikit-learn,depet/scikit-learn,sanketloke/scikit-learn,ChanderG/scikit-learn,mayblue9/scikit-learn,manhhomienbienthuy/scikit-learn,hdmetor/scikit-learn,arjoly/scikit-learn,nesterione/scikit-learn,henrykironde/scikit-learn,UNR-AERIAL/scikit-learn,JPFrancoia/scikit-learn,rexshihaoren/scikit-learn,mhue/scikit-learn,chrsrds/scikit-learn,pompiduskus/scikit-learn,ltiao/scikit-learn,jaidevd/scikit-learn,rrohan/scikit-learn,meduz/scikit-learn,mrshu/scikit-learn,samuel1208/scikit-learn,appapantula/scikit-learn,shahankhatch/scikit-learn,RayMick/scikit-learn,joshloyal/scikit-learn,wzbozon/scikit-learn,wazeerzulfikar/scikit-learn,xavierwu/scikit-learn,HolgerPeters/scikit-learn,sinhrks/scikit-learn,bhargav/scikit-learn,vybstat/scikit-learn,adamgreenhall/scikit-learn,fredhusser/scikit-learn,glouppe/scikit-learn,B3AU/waveTree,aewhatley/scikit-learn,huzq/scikit-learn,samzhang111/scikit-learn,luo66/scikit-learn,ilo10/scikit-learn,anirudhjayaraman/scikit-learn,treycausey/scikit-learn,ominux/scikit-learn,ClimbsRocks/scikit-learn,shikhardb/scikit-learn,fabianp/scikit-learn,equialgo/scikit-learn,schets/scikit-learn,depet/scikit-learn,harshaneelhg/scikit-learn,lesteve/scikit-learn,qifeigit/scikit-learn,rahuldhote/scikit-learn,Sentient07/scikit-learn,MohammedWasim/scikit-learn,marcocaccin/scikit-learn,RachitKansal/scikit-learn,jblackburne/scikit-learn,mattgiguere/scikit-learn,vshtanko/scikit-learn,sumspr/scikit-learn,h2educ/scikit-learn,simon-pepin/scikit-learn,amueller/scikit-learn,Sentient07/scikit-learn,liangz0707/scikit-learn,sarahgrogan/scikit-learn,ankurankan/scikit-learn,eickenberg/scikit-learn,ldirer/scikit-learn,xavierwu/scikit-learn,vinayak-mehta/scikit-learn,frank-tancf/scikit-learn,bigdataelephants/scikit-learn,thilbern/scikit-learn,manhhomienbienthuy/scikit-learn,AlexRobson/scikit-learn,lbishal/scikit-learn,DSLituiev/scikit-learn,shangwuhencc/scikit-learn,deepesch/scikit-learn,rishikksh20/scikit-learn,nrhine1/scikit-learn,nesterione/scikit-learn,JsNoNo/scikit-learn,pkruskal/scikit-learn,elkingtonmcb/scikit-learn,joernhees/scikit-learn,pkruskal/scikit-learn,glennq/scikit-learn,massmutual/scikit-learn,untom/scikit-learn,evgchz/scikit-learn,Windy-Ground/scikit-learn,imaculate/scikit-learn,trankmichael/scikit-learn,Garrett-R/scikit-learn,Lawrence-Liu/scikit-learn,jmschrei/scikit-learn,plissonf/scikit-learn,clemkoa/scikit-learn,mblondel/scikit-learn,wanggang3333/scikit-learn,mjgrav2001/scikit-learn,RPGOne/scikit-learn,jkarnows/scikit-learn,rahul-c1/scikit-learn,bhargav/scikit-learn,abhishekkrthakur/scikit-learn,phdowling/scikit-learn,shyamalschandra/scikit-learn,dingocuster/scikit-learn,Barmaley-exe/scikit-learn,jzt5132/scikit-learn,glemaitre/scikit-learn,glouppe/scikit-learn,cainiaocome/scikit-learn,equialgo/scikit-learn,icdishb/scikit-learn,nhejazi/scikit-learn,mfjb/scikit-learn,idlead/scikit-learn,ZenDevelopmentSystems/scikit-learn,sarahgrogan/scikit-learn,hrjn/scikit-learn,Adai0808/scikit-learn,rsivapr/scikit-learn,hitszxp/scikit-learn,nrhine1/scikit-learn,hitszxp/scikit-learn,Achuth17/scikit-learn,glennq/scikit-learn,terkkila/scikit-learn,pianomania/scikit-learn,liberatorqjw/scikit-learn,sinhrks/scikit-learn,nmayorov/scikit-learn,andaag/scikit-learn,ssaeger/scikit-learn,hdmetor/scikit-learn,abimannans/scikit-learn,saiwing-yeung/scikit-learn,rahuldhote/scikit-learn,IssamLaradji/scikit-learn,mattgiguere/scikit-learn,ClimbsRocks/scikit-learn,Srisai85/scikit-learn,Obus/scikit-learn,cybernet14/scikit-learn,spallavolu/scikit-learn,ldirer/scikit-learn,betatim/scikit-learn,fabianp/scikit-learn,MartinSavc/scikit-learn,IndraVikas/scikit-learn,YinongLong/scikit-learn,jereze/scikit-learn,bigdataelephants/scikit-learn,cauchycui/scikit-learn,kevin-intel/scikit-learn,jorik041/scikit-learn,robbymeals/scikit-learn,dhruv13J/scikit-learn,zihua/scikit-learn,glemaitre/scikit-learn,wzbozon/scikit-learn,hlin117/scikit-learn,TomDLT/scikit-learn,wzbozon/scikit-learn,kevin-intel/scikit-learn,fengzhyuan/scikit-learn,tosolveit/scikit-learn,abhishekgahlot/scikit-learn,Windy-Ground/scikit-learn,djgagne/scikit-learn,giorgiop/scikit-learn,vortex-ape/scikit-learn,ky822/scikit-learn,ky822/scikit-learn,liyu1990/sklearn,robbymeals/scikit-learn,mattgiguere/scikit-learn,mblondel/scikit-learn,zorojean/scikit-learn,terkkila/scikit-learn,pianomania/scikit-learn,jakobworldpeace/scikit-learn,vermouthmjl/scikit-learn,JPFrancoia/scikit-learn,eickenberg/scikit-learn,khkaminska/scikit-learn,wzbozon/scikit-learn,evgchz/scikit-learn,nrhine1/scikit-learn,tmhm/scikit-learn,mfjb/scikit-learn,Obus/scikit-learn,cauchycui/scikit-learn,kmike/scikit-learn,ldirer/scikit-learn,nikitasingh981/scikit-learn,ominux/scikit-learn,DonBeo/scikit-learn,0asa/scikit-learn,mehdidc/scikit-learn,ycaihua/scikit-learn,vermouthmjl/scikit-learn,AlexanderFabisch/scikit-learn,liberatorqjw/scikit-learn,jereze/scikit-learn,plissonf/scikit-learn,AIML/scikit-learn,fabianp/scikit-learn,mattilyra/scikit-learn,florian-f/sklearn,0asa/scikit-learn,loli/sklearn-ensembletrees,potash/scikit-learn,r-mart/scikit-learn,chrsrds/scikit-learn,JeanKossaifi/scikit-learn,hdmetor/scikit-learn,rahuldhote/scikit-learn,mlyundin/scikit-learn,f3r/scikit-learn,nrhine1/scikit-learn,rrohan/scikit-learn,glennq/scikit-learn,tosolveit/scikit-learn,AlexanderFabisch/scikit-learn,yonglehou/scikit-learn,evgchz/scikit-learn,ycaihua/scikit-learn,sumspr/scikit-learn,mwv/scikit-learn,mxjl620/scikit-learn,harshaneelhg/scikit-learn,nelson-liu/scikit-learn,mjudsp/Tsallis,hsuantien/scikit-learn,Garrett-R/scikit-learn,PatrickOReilly/scikit-learn,ningchi/scikit-learn,huobaowangxi/scikit-learn,zuku1985/scikit-learn,jorge2703/scikit-learn,cainiaocome/scikit-learn,mikebenfield/scikit-learn,rishikksh20/scikit-learn,466152112/scikit-learn,anirudhjayaraman/scikit-learn,aewhatley/scikit-learn,toastedcornflakes/scikit-learn,pypot/scikit-learn,MatthieuBizien/scikit-learn,iismd17/scikit-learn,LohithBlaze/scikit-learn,jkarnows/scikit-learn,aetilley/scikit-learn,rexshihaoren/scikit-learn,LiaoPan/scikit-learn,samuel1208/scikit-learn,lin-credible/scikit-learn,ahoyosid/scikit-learn,Akshay0724/scikit-learn,florian-f/sklearn,xiaoxiamii/scikit-learn,jpautom/scikit-learn,mjudsp/Tsallis,lazywei/scikit-learn,spallavolu/scikit-learn,jmetzen/scikit-learn,xwolf12/scikit-learn,andaag/scikit-learn,RayMick/scikit-learn,ssaeger/scikit-learn,Clyde-fare/scikit-learn,hlin117/scikit-learn,PrashntS/scikit-learn,abimannans/scikit-learn,0asa/scikit-learn,mugizico/scikit-learn,mattilyra/scikit-learn,samuel1208/scikit-learn,treycausey/scikit-learn,rishikksh20/scikit-learn,alexeyum/scikit-learn,vivekmishra1991/scikit-learn,shenzebang/scikit-learn,Titan-C/scikit-learn,B3AU/waveTree,pythonvietnam/scikit-learn,sarahgrogan/scikit-learn,untom/scikit-learn,roxyboy/scikit-learn,jayflo/scikit-learn,kagayakidan/scikit-learn,NelisVerhoef/scikit-learn,ZenDevelopmentSystems/scikit-learn,glemaitre/scikit-learn,rahuldhote/scikit-learn,Barmaley-exe/scikit-learn,JosmanPS/scikit-learn,costypetrisor/scikit-learn,huobaowangxi/scikit-learn,xzh86/scikit-learn,vinayak-mehta/scikit-learn,CVML/scikit-learn,Myasuka/scikit-learn,AIML/scikit-learn,JosmanPS/scikit-learn,wazeerzulfikar/scikit-learn,xzh86/scikit-learn,quheng/scikit-learn,akionakamura/scikit-learn,akionakamura/scikit-learn,yyjiang/scikit-learn,BiaDarkia/scikit-learn,mblondel/scikit-learn,heli522/scikit-learn,belltailjp/scikit-learn,shusenl/scikit-learn,ilo10/scikit-learn,466152112/scikit-learn,B3AU/waveTree,fzalkow/scikit-learn,bigdataelephants/scikit-learn,billy-inn/scikit-learn,ElDeveloper/scikit-learn,lesteve/scikit-learn,anurag313/scikit-learn,deepesch/scikit-learn,liyu1990/sklearn,ZenDevelopmentSystems/scikit-learn,anirudhjayaraman/scikit-learn,voxlol/scikit-learn,waterponey/scikit-learn,NunoEdgarGub1/scikit-learn,RPGOne/scikit-learn,untom/scikit-learn,samzhang111/scikit-learn,MartinDelzant/scikit-learn,RayMick/scikit-learn,bikong2/scikit-learn,xiaoxiamii/scikit-learn,xwolf12/scikit-learn,mrshu/scikit-learn,MartinSavc/scikit-learn,gclenaghan/scikit-learn,vybstat/scikit-learn,UNR-AERIAL/scikit-learn,cauchycui/scikit-learn,TomDLT/scikit-learn,depet/scikit-learn,ephes/scikit-learn,altairpearl/scikit-learn,anntzer/scikit-learn,petosegan/scikit-learn,btabibian/scikit-learn,larsmans/scikit-learn,cybernet14/scikit-learn,tomlof/scikit-learn,vortex-ape/scikit-learn,sanketloke/scikit-learn,eickenberg/scikit-learn,raghavrv/scikit-learn,mhdella/scikit-learn,vigilv/scikit-learn,sgenoud/scikit-learn,madjelan/scikit-learn,adamgreenhall/scikit-learn,Akshay0724/scikit-learn,loli/semisupervisedforests,btabibian/scikit-learn,mugizico/scikit-learn,vshtanko/scikit-learn,yunfeilu/scikit-learn,vermouthmjl/scikit-learn,TomDLT/scikit-learn,fengzhyuan/scikit-learn,ngoix/OCRF,ngoix/OCRF,huzq/scikit-learn,Djabbz/scikit-learn,jakirkham/scikit-learn,CforED/Machine-Learning,Achuth17/scikit-learn,icdishb/scikit-learn,dsquareindia/scikit-learn,nesterione/scikit-learn,qifeigit/scikit-learn,simon-pepin/scikit-learn,dsullivan7/scikit-learn,robin-lai/scikit-learn,mhue/scikit-learn,Fireblend/scikit-learn,aabadie/scikit-learn,xubenben/scikit-learn,aetilley/scikit-learn,hsuantien/scikit-learn,jorge2703/scikit-learn,eg-zhang/scikit-learn,kjung/scikit-learn,jpautom/scikit-learn,jakirkham/scikit-learn,henridwyer/scikit-learn,sgenoud/scikit-learn,shikhardb/scikit-learn,ivannz/scikit-learn,mojoboss/scikit-learn,Adai0808/scikit-learn,thientu/scikit-learn,hainm/scikit-learn,kmike/scikit-learn,poryfly/scikit-learn,walterreade/scikit-learn,xubenben/scikit-learn,RomainBrault/scikit-learn,fengzhyuan/scikit-learn,sanketloke/scikit-learn,anurag313/scikit-learn,kmike/scikit-learn,bnaul/scikit-learn,TomDLT/scikit-learn,ChanderG/scikit-learn,cdegroc/scikit-learn,ominux/scikit-learn,xiaoxiamii/scikit-learn,kaichogami/scikit-learn,simon-pepin/scikit-learn,AlexRobson/scikit-learn,ElDeveloper/scikit-learn,moutai/scikit-learn,Fireblend/scikit-learn,Myasuka/scikit-learn,voxlol/scikit-learn,lin-credible/scikit-learn,toastedcornflakes/scikit-learn,madjelan/scikit-learn,marcocaccin/scikit-learn,chrisburr/scikit-learn,ankurankan/scikit-learn,smartscheduling/scikit-learn-categorical-tree,tosolveit/scikit-learn,yask123/scikit-learn,stylianos-kampakis/scikit-learn,vigilv/scikit-learn,rishikksh20/scikit-learn,Aasmi/scikit-learn,lenovor/scikit-learn,davidgbe/scikit-learn,shikhardb/scikit-learn,ominux/scikit-learn,procoder317/scikit-learn,NunoEdgarGub1/scikit-learn,amueller/scikit-learn,massmutual/scikit-learn,florian-f/sklearn,kagayakidan/scikit-learn,yanlend/scikit-learn,ycaihua/scikit-learn,0x0all/scikit-learn,arahuja/scikit-learn,CforED/Machine-Learning,betatim/scikit-learn,zuku1985/scikit-learn,bikong2/scikit-learn,hsiaoyi0504/scikit-learn,0x0all/scikit-learn,shusenl/scikit-learn,Aasmi/scikit-learn,lucidfrontier45/scikit-learn,ChanderG/scikit-learn,MechCoder/scikit-learn,vortex-ape/scikit-learn,jorik041/scikit-learn,wanggang3333/scikit-learn,jlegendary/scikit-learn,f3r/scikit-learn,imaculate/scikit-learn,rajat1994/scikit-learn,bnaul/scikit-learn,dsquareindia/scikit-learn,plissonf/scikit-learn,tawsifkhan/scikit-learn,shusenl/scikit-learn,rvraghav93/scikit-learn,gclenaghan/scikit-learn,russel1237/scikit-learn,saiwing-yeung/scikit-learn,LiaoPan/scikit-learn,krez13/scikit-learn,mehdidc/scikit-learn,nmayorov/scikit-learn,pnedunuri/scikit-learn,anurag313/scikit-learn,f3r/scikit-learn,HolgerPeters/scikit-learn,nmayorov/scikit-learn,gotomypc/scikit-learn,etkirsch/scikit-learn,ClimbsRocks/scikit-learn,ndingwall/scikit-learn,gclenaghan/scikit-learn,alvarofierroclavero/scikit-learn,cwu2011/scikit-learn,alvarofierroclavero/scikit-learn,PrashntS/scikit-learn,moutai/scikit-learn,Garrett-R/scikit-learn,akionakamura/scikit-learn,aetilley/scikit-learn,jm-begon/scikit-learn,hrjn/scikit-learn,iismd17/scikit-learn,liberatorqjw/scikit-learn,hitszxp/scikit-learn,Lawrence-Liu/scikit-learn,Adai0808/scikit-learn,nikitasingh981/scikit-learn,jorge2703/scikit-learn,PatrickChrist/scikit-learn,fbagirov/scikit-learn,nesterione/scikit-learn,siutanwong/scikit-learn,manashmndl/scikit-learn,lbishal/scikit-learn,hugobowne/scikit-learn,pkruskal/scikit-learn,mhdella/scikit-learn,yonglehou/scikit-learn,loli/semisupervisedforests,loli/sklearn-ensembletrees,treycausey/scikit-learn,fbagirov/scikit-learn,Windy-Ground/scikit-learn,shyamalschandra/scikit-learn,etkirsch/scikit-learn,pratapvardhan/scikit-learn,hugobowne/scikit-learn,murali-munna/scikit-learn,henridwyer/scikit-learn,equialgo/scikit-learn,nhejazi/scikit-learn,ashhher3/scikit-learn,michigraber/scikit-learn,arabenjamin/scikit-learn,jakobworldpeace/scikit-learn,NelisVerhoef/scikit-learn,ndingwall/scikit-learn,jlegendary/scikit-learn,MatthieuBizien/scikit-learn,adamgreenhall/scikit-learn,Akshay0724/scikit-learn,AIML/scikit-learn,sgenoud/scikit-learn,Windy-Ground/scikit-learn,maheshakya/scikit-learn,kjung/scikit-learn,yanlend/scikit-learn,sanketloke/scikit-learn,terkkila/scikit-learn,poryfly/scikit-learn,ashhher3/scikit-learn,imaculate/scikit-learn,theoryno3/scikit-learn,justincassidy/scikit-learn,bthirion/scikit-learn,IshankGulati/scikit-learn,arjoly/scikit-learn,billy-inn/scikit-learn,olologin/scikit-learn,PatrickChrist/scikit-learn,wlamond/scikit-learn,thientu/scikit-learn,mlyundin/scikit-learn,AlexanderFabisch/scikit-learn,devanshdalal/scikit-learn,jm-begon/scikit-learn,r-mart/scikit-learn,jereze/scikit-learn,ankurankan/scikit-learn,466152112/scikit-learn,f3r/scikit-learn,hsiaoyi0504/scikit-learn,vibhorag/scikit-learn,clemkoa/scikit-learn,nmayorov/scikit-learn,herilalaina/scikit-learn,0asa/scikit-learn,JsNoNo/scikit-learn,hlin117/scikit-learn,mwv/scikit-learn,ningchi/scikit-learn,russel1237/scikit-learn,ahoyosid/scikit-learn,LiaoPan/scikit-learn,chrisburr/scikit-learn,ilyes14/scikit-learn,hitszxp/scikit-learn,jseabold/scikit-learn,Titan-C/scikit-learn,carrillo/scikit-learn,kjung/scikit-learn,betatim/scikit-learn,robin-lai/scikit-learn,manhhomienbienthuy/scikit-learn,mfjb/scikit-learn,davidgbe/scikit-learn,Myasuka/scikit-learn,larsmans/scikit-learn,evgchz/scikit-learn,maheshakya/scikit-learn,roxyboy/scikit-learn,wazeerzulfikar/scikit-learn,etkirsch/scikit-learn,hugobowne/scikit-learn,mxjl620/scikit-learn,Myasuka/scikit-learn,phdowling/scikit-learn,poryfly/scikit-learn,wazeerzulfikar/scikit-learn,quheng/scikit-learn,rrohan/scikit-learn,Lawrence-Liu/scikit-learn,vermouthmjl/scikit-learn,schets/scikit-learn,RomainBrault/scikit-learn,jpautom/scikit-learn,jorge2703/scikit-learn,tawsifkhan/scikit-learn,altairpearl/scikit-learn,jjx02230808/project0223,AlexandreAbraham/scikit-learn,PatrickOReilly/scikit-learn,ankurankan/scikit-learn,icdishb/scikit-learn,aabadie/scikit-learn,yyjiang/scikit-learn,ishanic/scikit-learn,q1ang/scikit-learn,zhenv5/scikit-learn,nvoron23/scikit-learn,q1ang/scikit-learn,IshankGulati/scikit-learn,macks22/scikit-learn,arabenjamin/scikit-learn,RPGOne/scikit-learn,justincassidy/scikit-learn,fyffyt/scikit-learn,aflaxman/scikit-learn,pnedunuri/scikit-learn,cl4rke/scikit-learn,pompiduskus/scikit-learn,PrashntS/scikit-learn,shenzebang/scikit-learn,meduz/scikit-learn,dsquareindia/scikit-learn,heli522/scikit-learn,pythonvietnam/scikit-learn,lenovor/scikit-learn,victorbergelin/scikit-learn,procoder317/scikit-learn,cl4rke/scikit-learn,CVML/scikit-learn,eickenberg/scikit-learn,hdmetor/scikit-learn,IndraVikas/scikit-learn,pv/scikit-learn,abhishekgahlot/scikit-learn,pompiduskus/scikit-learn,anntzer/scikit-learn,depet/scikit-learn,jorik041/scikit-learn,ltiao/scikit-learn,AlexRobson/scikit-learn,thientu/scikit-learn,procoder317/scikit-learn,RPGOne/scikit-learn,kashif/scikit-learn,cwu2011/scikit-learn,billy-inn/scikit-learn,jmschrei/scikit-learn,tawsifkhan/scikit-learn,aetilley/scikit-learn,MartinDelzant/scikit-learn,fabioticconi/scikit-learn,aflaxman/scikit-learn,aflaxman/scikit-learn,gotomypc/scikit-learn,carrillo/scikit-learn,moutai/scikit-learn,mehdidc/scikit-learn,altairpearl/scikit-learn,potash/scikit-learn,themrmax/scikit-learn,UNR-AERIAL/scikit-learn,kylerbrown/scikit-learn,ngoix/OCRF,sonnyhu/scikit-learn,kaichogami/scikit-learn,dhruv13J/scikit-learn,xwolf12/scikit-learn,madjelan/scikit-learn,MartinDelzant/scikit-learn,luo66/scikit-learn,appapantula/scikit-learn,potash/scikit-learn,ngoix/OCRF,3manuek/scikit-learn,alvarofierroclavero/scikit-learn,andrewnc/scikit-learn,beepee14/scikit-learn,hugobowne/scikit-learn,vigilv/scikit-learn,rvraghav93/scikit-learn,NelisVerhoef/scikit-learn,Vimos/scikit-learn,cdegroc/scikit-learn,olologin/scikit-learn,trankmichael/scikit-learn,h2educ/scikit-learn,quheng/scikit-learn,ssaeger/scikit-learn,abhishekgahlot/scikit-learn,Nyker510/scikit-learn,PatrickChrist/scikit-learn,ssaeger/scikit-learn,rohanp/scikit-learn,fzalkow/scikit-learn,djgagne/scikit-learn,lucidfrontier45/scikit-learn,nomadcube/scikit-learn,zaxtax/scikit-learn,siutanwong/scikit-learn,HolgerPeters/scikit-learn,xyguo/scikit-learn,yanlend/scikit-learn,arahuja/scikit-learn,alexeyum/scikit-learn,ky822/scikit-learn,espg/scikit-learn,dsullivan7/scikit-learn,MechCoder/scikit-learn,theoryno3/scikit-learn,huobaowangxi/scikit-learn,hlin117/scikit-learn,costypetrisor/scikit-learn,carrillo/scikit-learn,fbagirov/scikit-learn,jblackburne/scikit-learn,untom/scikit-learn,walterreade/scikit-learn,Aasmi/scikit-learn,vivekmishra1991/scikit-learn,Garrett-R/scikit-learn,olologin/scikit-learn,vshtanko/scikit-learn,petosegan/scikit-learn,kylerbrown/scikit-learn,aewhatley/scikit-learn,loli/sklearn-ensembletrees,rohanp/scikit-learn,anurag313/scikit-learn,sinhrks/scikit-learn,jaidevd/scikit-learn,arjoly/scikit-learn,MartinSavc/scikit-learn,qifeigit/scikit-learn,mikebenfield/scikit-learn,mwv/scikit-learn,joshloyal/scikit-learn,sergeyf/scikit-learn,espg/scikit-learn,zorroblue/scikit-learn,bhargav/scikit-learn,vigilv/scikit-learn,BiaDarkia/scikit-learn,betatim/scikit-learn,bigdataelephants/scikit-learn,florian-f/sklearn,jseabold/scikit-learn,glemaitre/scikit-learn,kmike/scikit-learn,quheng/scikit-learn,alvarofierroclavero/scikit-learn,lazywei/scikit-learn,thilbern/scikit-learn,xwolf12/scikit-learn,pratapvardhan/scikit-learn,q1ang/scikit-learn,lesteve/scikit-learn,Srisai85/scikit-learn,theoryno3/scikit-learn,bikong2/scikit-learn,alexeyum/scikit-learn,simon-pepin/scikit-learn,zaxtax/scikit-learn,herilalaina/scikit-learn,lazywei/scikit-learn,xyguo/scikit-learn,MohammedWasim/scikit-learn,RachitKansal/scikit-learn,victorbergelin/scikit-learn,Vimos/scikit-learn,rsivapr/scikit-learn,spallavolu/scikit-learn,waterponey/scikit-learn,nikitasingh981/scikit-learn,andrewnc/scikit-learn,belltailjp/scikit-learn,larsmans/scikit-learn,pratapvardhan/scikit-learn,xavierwu/scikit-learn,giorgiop/scikit-learn,ephes/scikit-learn,DonBeo/scikit-learn,giorgiop/scikit-learn,kashif/scikit-learn,cybernet14/scikit-learn,chrisburr/scikit-learn,shenzebang/scikit-learn,Jimmy-Morzaria/scikit-learn,Barmaley-exe/scikit-learn,Jimmy-Morzaria/scikit-learn,Achuth17/scikit-learn,rohanp/scikit-learn,dhruv13J/scikit-learn,jorik041/scikit-learn,nelson-liu/scikit-learn,mjgrav2001/scikit-learn,MartinSavc/scikit-learn,phdowling/scikit-learn,Barmaley-exe/scikit-learn,pv/scikit-learn,henridwyer/scikit-learn,bthirion/scikit-learn,devanshdalal/scikit-learn,aminert/scikit-learn,LohithBlaze/scikit-learn,andrewnc/scikit-learn,yask123/scikit-learn,ankurankan/scikit-learn,kashif/scikit-learn,lenovor/scikit-learn,russel1237/scikit-learn,joshloyal/scikit-learn,ogrisel/scikit-learn,MechCoder/scikit-learn,kashif/scikit-learn,trungnt13/scikit-learn,zorojean/scikit-learn,eg-zhang/scikit-learn,toastedcornflakes/scikit-learn,manashmndl/scikit-learn,pratapvardhan/scikit-learn,rajat1994/scikit-learn,jakobworldpeace/scikit-learn,rahul-c1/scikit-learn,CVML/scikit-learn,rohanp/scikit-learn,yask123/scikit-learn,pnedunuri/scikit-learn,mfjb/scikit-learn,liangz0707/scikit-learn,nhejazi/scikit-learn,ngoix/OCRF,dhruv13J/scikit-learn,cauchycui/scikit-learn,MartinDelzant/scikit-learn,etkirsch/scikit-learn,CforED/Machine-Learning,billy-inn/scikit-learn,macks22/scikit-learn,mayblue9/scikit-learn,fabioticconi/scikit-learn,Clyde-fare/scikit-learn,jzt5132/scikit-learn,sergeyf/scikit-learn,mattilyra/scikit-learn,jakirkham/scikit-learn,CVML/scikit-learn,ycaihua/scikit-learn,ivannz/scikit-learn,AlexandreAbraham/scikit-learn,0x0all/scikit-learn,kylerbrown/scikit-learn,ChanChiChoi/scikit-learn,xavierwu/scikit-learn,raghavrv/scikit-learn,moutai/scikit-learn,walterreade/scikit-learn,IshankGulati/scikit-learn,pv/scikit-learn,elkingtonmcb/scikit-learn,idlead/scikit-learn,nelson-liu/scikit-learn,YinongLong/scikit-learn,yyjiang/scikit-learn,themrmax/scikit-learn,jakirkham/scikit-learn,deepesch/scikit-learn,loli/semisupervisedforests,espg/scikit-learn,scikit-learn/scikit-learn,vortex-ape/scikit-learn,aabadie/scikit-learn,imaculate/scikit-learn,jm-begon/scikit-learn,zorroblue/scikit-learn,fabioticconi/scikit-learn,yonglehou/scikit-learn,ltiao/scikit-learn,BiaDarkia/scikit-learn,lazywei/scikit-learn,r-mart/scikit-learn,ashhher3/scikit-learn,JosmanPS/scikit-learn,trankmichael/scikit-learn,gotomypc/scikit-learn,vybstat/scikit-learn,RachitKansal/scikit-learn,ahoyosid/scikit-learn,mjudsp/Tsallis,AnasGhrab/scikit-learn,abhishekkrthakur/scikit-learn,mhdella/scikit-learn,marcocaccin/scikit-learn,henrykironde/scikit-learn,Vimos/scikit-learn,nhejazi/scikit-learn,jseabold/scikit-learn,yyjiang/scikit-learn,zaxtax/scikit-learn,cwu2011/scikit-learn,shangwuhencc/scikit-learn,phdowling/scikit-learn,B3AU/waveTree,smartscheduling/scikit-learn-categorical-tree,cainiaocome/scikit-learn,liangz0707/scikit-learn,ZenDevelopmentSystems/scikit-learn,altairpearl/scikit-learn,mjudsp/Tsallis,tdhopper/scikit-learn,mlyundin/scikit-learn,wlamond/scikit-learn,jaidevd/scikit-learn,DSLituiev/scikit-learn,glouppe/scikit-learn,henridwyer/scikit-learn,anntzer/scikit-learn,xuewei4d/scikit-learn,anirudhjayaraman/scikit-learn,q1ang/scikit-learn,rahul-c1/scikit-learn,HolgerPeters/scikit-learn,voxlol/scikit-learn,0x0all/scikit-learn,hrjn/scikit-learn,vybstat/scikit-learn,zuku1985/scikit-learn,cybernet14/scikit-learn,CforED/Machine-Learning,macks22/scikit-learn,AlexandreAbraham/scikit-learn,sergeyf/scikit-learn,xiaoxiamii/scikit-learn,belltailjp/scikit-learn,walterreade/scikit-learn,murali-munna/scikit-learn,macks22/scikit-learn,joernhees/scikit-learn,murali-munna/scikit-learn,jmetzen/scikit-learn,nvoron23/scikit-learn,xuewei4d/scikit-learn,pypot/scikit-learn,pianomania/scikit-learn,luo66/scikit-learn,ephes/scikit-learn,eg-zhang/scikit-learn,alexsavio/scikit-learn,mayblue9/scikit-learn,fabianp/scikit-learn,kevin-intel/scikit-learn,hainm/scikit-learn,yunfeilu/scikit-learn,mojoboss/scikit-learn,JeanKossaifi/scikit-learn,loli/semisupervisedforests,jpautom/scikit-learn,hainm/scikit-learn,PatrickOReilly/scikit-learn,sonnyhu/scikit-learn,ZENGXH/scikit-learn,DonBeo/scikit-learn,DonBeo/scikit-learn,zhenv5/scikit-learn,IndraVikas/scikit-learn,potash/scikit-learn,devanshdalal/scikit-learn,russel1237/scikit-learn,MohammedWasim/scikit-learn,chrsrds/scikit-learn,zorroblue/scikit-learn,ishanic/scikit-learn,lucidfrontier45/scikit-learn,roxyboy/scikit-learn,alexsavio/scikit-learn,shikhardb/scikit-learn,akionakamura/scikit-learn,sergeyf/scikit-learn,xzh86/scikit-learn,Nyker510/scikit-learn,ZENGXH/scikit-learn,appapantula/scikit-learn,arahuja/scikit-learn,shahankhatch/scikit-learn,arabenjamin/scikit-learn,procoder317/scikit-learn,ElDeveloper/scikit-learn,OshynSong/scikit-learn,fyffyt/scikit-learn,dsullivan7/scikit-learn,Akshay0724/scikit-learn,ishanic/scikit-learn,khkaminska/scikit-learn,fbagirov/scikit-learn,samuel1208/scikit-learn,arjoly/scikit-learn,Jimmy-Morzaria/scikit-learn,kaichogami/scikit-learn,IssamLaradji/scikit-learn,dsullivan7/scikit-learn,ClimbsRocks/scikit-learn,abhishekkrthakur/scikit-learn,bnaul/scikit-learn,btabibian/scikit-learn,JsNoNo/scikit-learn,MatthieuBizien/scikit-learn,AlexandreAbraham/scikit-learn,3manuek/scikit-learn,robbymeals/scikit-learn,raghavrv/scikit-learn,petosegan/scikit-learn,thientu/scikit-learn,jayflo/scikit-learn,kevin-intel/scikit-learn,meduz/scikit-learn,loli/sklearn-ensembletrees,MohammedWasim/scikit-learn,Djabbz/scikit-learn,amueller/scikit-learn,ilyes14/scikit-learn,Djabbz/scikit-learn,yonglehou/scikit-learn,mayblue9/scikit-learn,mrshu/scikit-learn,JosmanPS/scikit-learn,trungnt13/scikit-learn,rajat1994/scikit-learn,mjudsp/Tsallis,JPFrancoia/scikit-learn,dingocuster/scikit-learn,tawsifkhan/scikit-learn,terkkila/scikit-learn,frank-tancf/scikit-learn,idlead/scikit-learn,toastedcornflakes/scikit-learn,Garrett-R/scikit-learn,nomadcube/scikit-learn,siutanwong/scikit-learn,mwv/scikit-learn,bhargav/scikit-learn,ivannz/scikit-learn,zuku1985/scikit-learn,stylianos-kampakis/scikit-learn,jlegendary/scikit-learn,Achuth17/scikit-learn,Djabbz/scikit-learn,icdishb/scikit-learn,vibhorag/scikit-learn,heli522/scikit-learn,amueller/scikit-learn,zorroblue/scikit-learn,fzalkow/scikit-learn,Clyde-fare/scikit-learn,ChanderG/scikit-learn,Obus/scikit-learn,ashhher3/scikit-learn,xuewei4d/scikit-learn,giorgiop/scikit-learn,jkarnows/scikit-learn,AlexRobson/scikit-learn,ilyes14/scikit-learn,kmike/scikit-learn,trungnt13/scikit-learn,joshloyal/scikit-learn,Adai0808/scikit-learn,harshaneelhg/scikit-learn,khkaminska/scikit-learn,Srisai85/scikit-learn,mehdidc/scikit-learn,zihua/scikit-learn,mlyundin/scikit-learn,trungnt13/scikit-learn,rexshihaoren/scikit-learn,shangwuhencc/scikit-learn,pythonvietnam/scikit-learn,rsivapr/scikit-learn,liberatorqjw/scikit-learn,thilbern/scikit-learn,wanggang3333/scikit-learn,abimannans/scikit-learn,ningchi/scikit-learn,maheshakya/scikit-learn,manhhomienbienthuy/scikit-learn,JeanKossaifi/scikit-learn,Fireblend/scikit-learn,fabioticconi/scikit-learn,LiaoPan/scikit-learn,thilbern/scikit-learn,chrisburr/scikit-learn,clemkoa/scikit-learn,jmschrei/scikit-learn,jjx02230808/project0223,Vimos/scikit-learn,JeanKossaifi/scikit-learn,jm-begon/scikit-learn,466152112/scikit-learn,Sentient07/scikit-learn,OshynSong/scikit-learn,murali-munna/scikit-learn,pypot/scikit-learn,kaichogami/scikit-learn,hitszxp/scikit-learn,eg-zhang/scikit-learn,mikebenfield/scikit-learn,xzh86/scikit-learn,ogrisel/scikit-learn,schets/scikit-learn,cl4rke/scikit-learn,trankmichael/scikit-learn,ishanic/scikit-learn,treycausey/scikit-learn,cdegroc/scikit-learn,ningchi/scikit-learn,treycausey/scikit-learn,tomlof/scikit-learn,sumspr/scikit-learn,madjelan/scikit-learn,3manuek/scikit-learn,voxlol/scikit-learn,DSLituiev/scikit-learn,wanggang3333/scikit-learn,manashmndl/scikit-learn,ycaihua/scikit-learn,MechCoder/scikit-learn,IshankGulati/scikit-learn,depet/scikit-learn,beepee14/scikit-learn,dingocuster/scikit-learn,spallavolu/scikit-learn,lucidfrontier45/scikit-learn,saiwing-yeung/scikit-learn,vshtanko/scikit-learn,ChanChiChoi/scikit-learn,AnasGhrab/scikit-learn,arabenjamin/scikit-learn,liangz0707/scikit-learn,ndingwall/scikit-learn,krez13/scikit-learn,bthirion/scikit-learn,krez13/scikit-learn,frank-tancf/scikit-learn,mxjl620/scikit-learn,fyffyt/scikit-learn,tdhopper/scikit-learn,fredhusser/scikit-learn,vinayak-mehta/scikit-learn,yask123/scikit-learn,yunfeilu/scikit-learn,khkaminska/scikit-learn,victorbergelin/scikit-learn,bikong2/scikit-learn,JsNoNo/scikit-learn,tmhm/scikit-learn,lucidfrontier45/scikit-learn,AnasGhrab/scikit-learn,sgenoud/scikit-learn,pv/scikit-learn,bthirion/scikit-learn,ogrisel/scikit-learn,mrshu/scikit-learn,tmhm/scikit-learn,Clyde-fare/scikit-learn,bnaul/scikit-learn,xubenben/scikit-learn,yunfeilu/scikit-learn,Lawrence-Liu/scikit-learn,iismd17/scikit-learn,UNR-AERIAL/scikit-learn,saiwing-yeung/scikit-learn,sarahgrogan/scikit-learn,pythonvietnam/scikit-learn,IssamLaradji/scikit-learn,ldirer/scikit-learn,rexshihaoren/scikit-learn,lesteve/scikit-learn,3manuek/scikit-learn,jzt5132/scikit-learn,harshaneelhg/scikit-learn,belltailjp/scikit-learn,iismd17/scikit-learn,LohithBlaze/scikit-learn,Jimmy-Morzaria/scikit-learn,roxyboy/scikit-learn,mikebenfield/scikit-learn,cl4rke/scikit-learn,NunoEdgarGub1/scikit-learn,deepesch/scikit-learn,Fireblend/scikit-learn,plissonf/scikit-learn,espg/scikit-learn,vibhorag/scikit-learn,maheshakya/scikit-learn,devanshdalal/scikit-learn,henrykironde/scikit-learn,LohithBlaze/scikit-learn,petosegan/scikit-learn,mhue/scikit-learn,shahankhatch/scikit-learn,ltiao/scikit-learn,AIML/scikit-learn,smartscheduling/scikit-learn-categorical-tree,kjung/scikit-learn,nelson-liu/scikit-learn,vinayak-mehta/scikit-learn,DSLituiev/scikit-learn,RachitKansal/scikit-learn,MatthieuBizien/scikit-learn,mhue/scikit-learn,xyguo/scikit-learn,stylianos-kampakis/scikit-learn,gclenaghan/scikit-learn,pompiduskus/scikit-learn,florian-f/sklearn,jzt5132/scikit-learn,mhdella/scikit-learn,djgagne/scikit-learn,nikitasingh981/scikit-learn,lbishal/scikit-learn,eickenberg/scikit-learn,btabibian/scikit-learn,huzq/scikit-learn,B3AU/waveTree,lbishal/scikit-learn,waterponey/scikit-learn,larsmans/scikit-learn,ZENGXH/scikit-learn,jmetzen/scikit-learn,nomadcube/scikit-learn,rahul-c1/scikit-learn,rrohan/scikit-learn,yanlend/scikit-learn,NunoEdgarGub1/scikit-learn,abhishekkrthakur/scikit-learn,robin-lai/scikit-learn,mojoboss/scikit-learn,OshynSong/scikit-learn,ndingwall/scikit-learn,rajat1994/scikit-learn,aabadie/scikit-learn,joernhees/scikit-learn,sinhrks/scikit-learn,scikit-learn/scikit-learn,smartscheduling/scikit-learn-categorical-tree,gotomypc/scikit-learn,jjx02230808/project0223,pypot/scikit-learn,fredhusser/scikit-learn,loli/sklearn-ensembletrees,scikit-learn/scikit-learn,jlegendary/scikit-learn,marcocaccin/scikit-learn,rsivapr/scikit-learn,NelisVerhoef/scikit-learn,rsivapr/scikit-learn,ngoix/OCRF,sonnyhu/scikit-learn,mattgiguere/scikit-learn,frank-tancf/scikit-learn,massmutual/scikit-learn,dsquareindia/scikit-learn,aewhatley/scikit-learn,vivekmishra1991/scikit-learn,RayMick/scikit-learn,stylianos-kampakis/scikit-learn,michigraber/scikit-learn,shangwuhencc/scikit-learn,justincassidy/scikit-learn,ChanChiChoi/scikit-learn,tomlof/scikit-learn,jmetzen/scikit-learn,jereze/scikit-learn,jayflo/scikit-learn,AnasGhrab/scikit-learn,tosolveit/scikit-learn,aminert/scikit-learn,ElDeveloper/scikit-learn,themrmax/scikit-learn,Obus/scikit-learn,luo66/scikit-learn,mrshu/scikit-learn,tdhopper/scikit-learn,IssamLaradji/scikit-learn,jjx02230808/project0223,michigraber/scikit-learn,maheshakya/scikit-learn,evgchz/scikit-learn,pnedunuri/scikit-learn,waterponey/scikit-learn,abhishekgahlot/scikit-learn,abimannans/scikit-learn,JPFrancoia/scikit-learn,nomadcube/scikit-learn,tmhm/scikit-learn,r-mart/scikit-learn,sumspr/scikit-learn,michigraber/scikit-learn,Srisai85/scikit-learn,glouppe/scikit-learn,YinongLong/scikit-learn,mugizico/scikit-learn,wlamond/scikit-learn,PrashntS/scikit-learn,tomlof/scikit-learn,sonnyhu/scikit-learn,rvraghav93/scikit-learn,fyffyt/scikit-learn,ephes/scikit-learn,scikit-learn/scikit-learn,xuewei4d/scikit-learn,samzhang111/scikit-learn,themrmax/scikit-learn,zaxtax/scikit-learn,dingocuster/scikit-learn,equialgo/scikit-learn,clemkoa/scikit-learn,xubenben/scikit-learn,jaidevd/scikit-learn,liyu1990/sklearn,cwu2011/scikit-learn,siutanwong/scikit-learn,PatrickChrist/scikit-learn,hsuantien/scikit-learn,aminert/scikit-learn,heli522/scikit-learn,davidgbe/scikit-learn,herilalaina/scikit-learn,aflaxman/scikit-learn,ilyes14/scikit-learn,djgagne/scikit-learn,Titan-C/scikit-learn,ivannz/scikit-learn,jblackburne/scikit-learn,0x0all/scikit-learn,liyu1990/sklearn,andaag/scikit-learn,Nyker510/scikit-learn,fzalkow/scikit-learn,robin-lai/scikit-learn,jseabold/scikit-learn,zihua/scikit-learn,mjgrav2001/scikit-learn,kagayakidan/scikit-learn,mattilyra/scikit-learn,herilalaina/scikit-learn,huzq/scikit-learn,shusenl/scikit-learn,massmutual/scikit-learn,fredhusser/scikit-learn,idlead/scikit-learn,vivekmishra1991/scikit-learn,hsuantien/scikit-learn,mojoboss/scikit-learn,elkingtonmcb/scikit-learn,alexeyum/scikit-learn,kylerbrown/scikit-learn,beepee14/scikit-learn,ZENGXH/scikit-learn,hsiaoyi0504/scikit-learn,zihua/scikit-learn,cainiaocome/scikit-learn,anntzer/scikit-learn,zorojean/scikit-learn,cdegroc/scikit-learn,kagayakidan/scikit-learn,lin-credible/scikit-learn,jblackburne/scikit-learn,hrjn/scikit-learn,beepee14/scikit-learn,justincassidy/scikit-learn,vibhorag/scikit-learn,h2educ/scikit-learn,theoryno3/scikit-learn,raghavrv/scikit-learn,Aasmi/scikit-learn,hsiaoyi0504/scikit-learn,ChanChiChoi/scikit-learn,poryfly/scikit-learn,alexsavio/scikit-learn,wlamond/scikit-learn,chrsrds/scikit-learn,nvoron23/scikit-learn,shyamalschandra/scikit-learn,RomainBrault/scikit-learn,Sentient07/scikit-learn,krez13/scikit-learn,shahankhatch/scikit-learn,mxjl620/scikit-learn,samzhang111/scikit-learn,abhishekgahlot/scikit-learn,ky822/scikit-learn,joernhees/scikit-learn,jkarnows/scikit-learn,appapantula/scikit-learn,tdhopper/scikit-learn,meduz/scikit-learn,lenovor/scikit-learn,zhenv5/scikit-learn,IndraVikas/scikit-learn,huobaowangxi/scikit-learn,rvraghav93/scikit-learn |
# Matthieu Brucher
# Last Change : 2008-04-15 10:42
"""
Neighbors module
"""
from neighbors import *
from utilities import *
__all__ = ['Neighbors', 'KNeighbors', 'Parzen', 'create_graph']
def test(level=-1, verbosity=1):
from numpy.testing import NumpyTest
return NumpyTest().test(level, verbosity)
Fix typo in class name.
It was preventing import to work properly.
From: Fabian Pedregosa <fabian.pedregosa@inria.fr>
git-svn-id: a2d1b0e147e530765aaf3e1662d4a98e2f63c719@342 22fbfee3-77ab-4535-9bad-27d1bd3bc7d8 |
# Matthieu Brucher
# Last Change : 2008-04-15 10:42
"""
Neighbors module
"""
from neighbors import *
from utilities import *
__all__ = ['Neighbors', 'Kneighbors', 'Parzen', 'create_graph']
def test(level=-1, verbosity=1):
from numpy.testing import NumpyTest
return NumpyTest().test(level, verbosity)
| <commit_before>
# Matthieu Brucher
# Last Change : 2008-04-15 10:42
"""
Neighbors module
"""
from neighbors import *
from utilities import *
__all__ = ['Neighbors', 'KNeighbors', 'Parzen', 'create_graph']
def test(level=-1, verbosity=1):
from numpy.testing import NumpyTest
return NumpyTest().test(level, verbosity)
<commit_msg>Fix typo in class name.
It was preventing import to work properly.
From: Fabian Pedregosa <fabian.pedregosa@inria.fr>
git-svn-id: a2d1b0e147e530765aaf3e1662d4a98e2f63c719@342 22fbfee3-77ab-4535-9bad-27d1bd3bc7d8<commit_after> |
# Matthieu Brucher
# Last Change : 2008-04-15 10:42
"""
Neighbors module
"""
from neighbors import *
from utilities import *
__all__ = ['Neighbors', 'Kneighbors', 'Parzen', 'create_graph']
def test(level=-1, verbosity=1):
from numpy.testing import NumpyTest
return NumpyTest().test(level, verbosity)
|
# Matthieu Brucher
# Last Change : 2008-04-15 10:42
"""
Neighbors module
"""
from neighbors import *
from utilities import *
__all__ = ['Neighbors', 'KNeighbors', 'Parzen', 'create_graph']
def test(level=-1, verbosity=1):
from numpy.testing import NumpyTest
return NumpyTest().test(level, verbosity)
Fix typo in class name.
It was preventing import to work properly.
From: Fabian Pedregosa <fabian.pedregosa@inria.fr>
git-svn-id: a2d1b0e147e530765aaf3e1662d4a98e2f63c719@342 22fbfee3-77ab-4535-9bad-27d1bd3bc7d8
# Matthieu Brucher
# Last Change : 2008-04-15 10:42
"""
Neighbors module
"""
from neighbors import *
from utilities import *
__all__ = ['Neighbors', 'Kneighbors', 'Parzen', 'create_graph']
def test(level=-1, verbosity=1):
from numpy.testing import NumpyTest
return NumpyTest().test(level, verbosity)
| <commit_before>
# Matthieu Brucher
# Last Change : 2008-04-15 10:42
"""
Neighbors module
"""
from neighbors import *
from utilities import *
__all__ = ['Neighbors', 'KNeighbors', 'Parzen', 'create_graph']
def test(level=-1, verbosity=1):
from numpy.testing import NumpyTest
return NumpyTest().test(level, verbosity)
<commit_msg>Fix typo in class name.
It was preventing import to work properly.
From: Fabian Pedregosa <fabian.pedregosa@inria.fr>
git-svn-id: a2d1b0e147e530765aaf3e1662d4a98e2f63c719@342 22fbfee3-77ab-4535-9bad-27d1bd3bc7d8<commit_after>
# Matthieu Brucher
# Last Change : 2008-04-15 10:42
"""
Neighbors module
"""
from neighbors import *
from utilities import *
__all__ = ['Neighbors', 'Kneighbors', 'Parzen', 'create_graph']
def test(level=-1, verbosity=1):
from numpy.testing import NumpyTest
return NumpyTest().test(level, verbosity)
|
101e80eb956778e4df74b27eefc07acb926a2974 | alarme/extras/action/rf_transmitter.py | alarme/extras/action/rf_transmitter.py | import asyncio
from alarme import Action
from alarme.extras.common import SingleRFDevice
class RfTransmitterAction(Action):
def __init__(self, app, id_, gpio, code, run_count=1, run_interval=0.02):
super().__init__(app, id_)
self.gpio = gpio
self.code = code
self.run_count = run_count
self.run_interval = run_interval
self.rf_device = SingleRFDevice(self.gpio)
def _continue(self, run_count):
return self.running and (self.run_count is None or run_count < self.run_count)
async def run(self):
self.rf_device.enable_tx()
try:
run_count = 0
while self._continue(run_count):
self.rf_device.tx_code(self.code)
run_count += 1
if self._continue(run_count):
await asyncio.sleep(self.run_interval)
self.rf_device.tx_code(self.code)
finally:
self.rf_device.disable_tx()
async def cleanup(self):
await super().cleanup()
# self.rf_device.cleanup()
| import asyncio
from alarme import Action
from alarme.extras.common import SingleRFDevice
class RfTransmitterAction(Action):
def __init__(self, app, id_, gpio, code, run_count=1, run_interval=0.02):
super().__init__(app, id_)
self.gpio = gpio
self.code = code
self.run_count = run_count
self.run_interval = run_interval
self.rf_device = SingleRFDevice(self.gpio)
def _continue(self, run_count):
return self.running and (self.run_count is None or run_count < self.run_count)
async def run(self):
self.rf_device.enable_tx()
try:
run_count = 0
while self._continue(run_count):
self.rf_device.tx_code(self.code)
run_count += 1
if self._continue(run_count):
await asyncio.sleep(self.run_interval)
finally:
self.rf_device.disable_tx()
async def cleanup(self):
await super().cleanup()
# self.rf_device.cleanup()
| Fix extra code sending after loop in rf transmitter | Fix extra code sending after loop in rf transmitter
| Python | mit | insolite/alarme,insolite/alarme,insolite/alarme | import asyncio
from alarme import Action
from alarme.extras.common import SingleRFDevice
class RfTransmitterAction(Action):
def __init__(self, app, id_, gpio, code, run_count=1, run_interval=0.02):
super().__init__(app, id_)
self.gpio = gpio
self.code = code
self.run_count = run_count
self.run_interval = run_interval
self.rf_device = SingleRFDevice(self.gpio)
def _continue(self, run_count):
return self.running and (self.run_count is None or run_count < self.run_count)
async def run(self):
self.rf_device.enable_tx()
try:
run_count = 0
while self._continue(run_count):
self.rf_device.tx_code(self.code)
run_count += 1
if self._continue(run_count):
await asyncio.sleep(self.run_interval)
self.rf_device.tx_code(self.code)
finally:
self.rf_device.disable_tx()
async def cleanup(self):
await super().cleanup()
# self.rf_device.cleanup()
Fix extra code sending after loop in rf transmitter | import asyncio
from alarme import Action
from alarme.extras.common import SingleRFDevice
class RfTransmitterAction(Action):
def __init__(self, app, id_, gpio, code, run_count=1, run_interval=0.02):
super().__init__(app, id_)
self.gpio = gpio
self.code = code
self.run_count = run_count
self.run_interval = run_interval
self.rf_device = SingleRFDevice(self.gpio)
def _continue(self, run_count):
return self.running and (self.run_count is None or run_count < self.run_count)
async def run(self):
self.rf_device.enable_tx()
try:
run_count = 0
while self._continue(run_count):
self.rf_device.tx_code(self.code)
run_count += 1
if self._continue(run_count):
await asyncio.sleep(self.run_interval)
finally:
self.rf_device.disable_tx()
async def cleanup(self):
await super().cleanup()
# self.rf_device.cleanup()
| <commit_before>import asyncio
from alarme import Action
from alarme.extras.common import SingleRFDevice
class RfTransmitterAction(Action):
def __init__(self, app, id_, gpio, code, run_count=1, run_interval=0.02):
super().__init__(app, id_)
self.gpio = gpio
self.code = code
self.run_count = run_count
self.run_interval = run_interval
self.rf_device = SingleRFDevice(self.gpio)
def _continue(self, run_count):
return self.running and (self.run_count is None or run_count < self.run_count)
async def run(self):
self.rf_device.enable_tx()
try:
run_count = 0
while self._continue(run_count):
self.rf_device.tx_code(self.code)
run_count += 1
if self._continue(run_count):
await asyncio.sleep(self.run_interval)
self.rf_device.tx_code(self.code)
finally:
self.rf_device.disable_tx()
async def cleanup(self):
await super().cleanup()
# self.rf_device.cleanup()
<commit_msg>Fix extra code sending after loop in rf transmitter<commit_after> | import asyncio
from alarme import Action
from alarme.extras.common import SingleRFDevice
class RfTransmitterAction(Action):
def __init__(self, app, id_, gpio, code, run_count=1, run_interval=0.02):
super().__init__(app, id_)
self.gpio = gpio
self.code = code
self.run_count = run_count
self.run_interval = run_interval
self.rf_device = SingleRFDevice(self.gpio)
def _continue(self, run_count):
return self.running and (self.run_count is None or run_count < self.run_count)
async def run(self):
self.rf_device.enable_tx()
try:
run_count = 0
while self._continue(run_count):
self.rf_device.tx_code(self.code)
run_count += 1
if self._continue(run_count):
await asyncio.sleep(self.run_interval)
finally:
self.rf_device.disable_tx()
async def cleanup(self):
await super().cleanup()
# self.rf_device.cleanup()
| import asyncio
from alarme import Action
from alarme.extras.common import SingleRFDevice
class RfTransmitterAction(Action):
def __init__(self, app, id_, gpio, code, run_count=1, run_interval=0.02):
super().__init__(app, id_)
self.gpio = gpio
self.code = code
self.run_count = run_count
self.run_interval = run_interval
self.rf_device = SingleRFDevice(self.gpio)
def _continue(self, run_count):
return self.running and (self.run_count is None or run_count < self.run_count)
async def run(self):
self.rf_device.enable_tx()
try:
run_count = 0
while self._continue(run_count):
self.rf_device.tx_code(self.code)
run_count += 1
if self._continue(run_count):
await asyncio.sleep(self.run_interval)
self.rf_device.tx_code(self.code)
finally:
self.rf_device.disable_tx()
async def cleanup(self):
await super().cleanup()
# self.rf_device.cleanup()
Fix extra code sending after loop in rf transmitterimport asyncio
from alarme import Action
from alarme.extras.common import SingleRFDevice
class RfTransmitterAction(Action):
def __init__(self, app, id_, gpio, code, run_count=1, run_interval=0.02):
super().__init__(app, id_)
self.gpio = gpio
self.code = code
self.run_count = run_count
self.run_interval = run_interval
self.rf_device = SingleRFDevice(self.gpio)
def _continue(self, run_count):
return self.running and (self.run_count is None or run_count < self.run_count)
async def run(self):
self.rf_device.enable_tx()
try:
run_count = 0
while self._continue(run_count):
self.rf_device.tx_code(self.code)
run_count += 1
if self._continue(run_count):
await asyncio.sleep(self.run_interval)
finally:
self.rf_device.disable_tx()
async def cleanup(self):
await super().cleanup()
# self.rf_device.cleanup()
| <commit_before>import asyncio
from alarme import Action
from alarme.extras.common import SingleRFDevice
class RfTransmitterAction(Action):
def __init__(self, app, id_, gpio, code, run_count=1, run_interval=0.02):
super().__init__(app, id_)
self.gpio = gpio
self.code = code
self.run_count = run_count
self.run_interval = run_interval
self.rf_device = SingleRFDevice(self.gpio)
def _continue(self, run_count):
return self.running and (self.run_count is None or run_count < self.run_count)
async def run(self):
self.rf_device.enable_tx()
try:
run_count = 0
while self._continue(run_count):
self.rf_device.tx_code(self.code)
run_count += 1
if self._continue(run_count):
await asyncio.sleep(self.run_interval)
self.rf_device.tx_code(self.code)
finally:
self.rf_device.disable_tx()
async def cleanup(self):
await super().cleanup()
# self.rf_device.cleanup()
<commit_msg>Fix extra code sending after loop in rf transmitter<commit_after>import asyncio
from alarme import Action
from alarme.extras.common import SingleRFDevice
class RfTransmitterAction(Action):
def __init__(self, app, id_, gpio, code, run_count=1, run_interval=0.02):
super().__init__(app, id_)
self.gpio = gpio
self.code = code
self.run_count = run_count
self.run_interval = run_interval
self.rf_device = SingleRFDevice(self.gpio)
def _continue(self, run_count):
return self.running and (self.run_count is None or run_count < self.run_count)
async def run(self):
self.rf_device.enable_tx()
try:
run_count = 0
while self._continue(run_count):
self.rf_device.tx_code(self.code)
run_count += 1
if self._continue(run_count):
await asyncio.sleep(self.run_interval)
finally:
self.rf_device.disable_tx()
async def cleanup(self):
await super().cleanup()
# self.rf_device.cleanup()
|
b1fa16fd4b4cc3b6983290fb38d0be54c2a21742 | test_project/test_app/migrations/0002_initial_data.py | test_project/test_app/migrations/0002_initial_data.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-06-12 09:04
from __future__ import unicode_literals
from django.core.management import call_command
from django.db import migrations
fixture = 'initial_data'
def load_fixture(apps, schema_editor):
call_command('loaddata', fixture, app_label='test_app')
class Migration(migrations.Migration):
dependencies = [
('test_app', '0001_initial'),
]
operations = [
migrations.RunPython(load_fixture),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-06-12 09:04
from __future__ import unicode_literals
from django.core.management import call_command
from django.db import migrations
fixture = 'initial_data'
def load_fixture(apps, schema_editor):
# StackOverflow says it is very wrong to loaddata here, we should get
# "old" models and then load... but, this is only a simple test app
# so whatever. Just don't use loaddata command in your migrations or
# don't be suprised when it stops working... without understanding why.
call_command('loaddata', fixture, app_label='test_app')
class Migration(migrations.Migration):
dependencies = [
('test_app', '0001_initial'),
]
operations = [
migrations.RunPython(load_fixture),
]
| Add comment about how bad this is | Add comment about how bad this is
| Python | mit | mpasternak/django-multiseek,mpasternak/django-multiseek,mpasternak/django-multiseek,mpasternak/django-multiseek | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-06-12 09:04
from __future__ import unicode_literals
from django.core.management import call_command
from django.db import migrations
fixture = 'initial_data'
def load_fixture(apps, schema_editor):
call_command('loaddata', fixture, app_label='test_app')
class Migration(migrations.Migration):
dependencies = [
('test_app', '0001_initial'),
]
operations = [
migrations.RunPython(load_fixture),
]
Add comment about how bad this is | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-06-12 09:04
from __future__ import unicode_literals
from django.core.management import call_command
from django.db import migrations
fixture = 'initial_data'
def load_fixture(apps, schema_editor):
# StackOverflow says it is very wrong to loaddata here, we should get
# "old" models and then load... but, this is only a simple test app
# so whatever. Just don't use loaddata command in your migrations or
# don't be suprised when it stops working... without understanding why.
call_command('loaddata', fixture, app_label='test_app')
class Migration(migrations.Migration):
dependencies = [
('test_app', '0001_initial'),
]
operations = [
migrations.RunPython(load_fixture),
]
| <commit_before># -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-06-12 09:04
from __future__ import unicode_literals
from django.core.management import call_command
from django.db import migrations
fixture = 'initial_data'
def load_fixture(apps, schema_editor):
call_command('loaddata', fixture, app_label='test_app')
class Migration(migrations.Migration):
dependencies = [
('test_app', '0001_initial'),
]
operations = [
migrations.RunPython(load_fixture),
]
<commit_msg>Add comment about how bad this is<commit_after> | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-06-12 09:04
from __future__ import unicode_literals
from django.core.management import call_command
from django.db import migrations
fixture = 'initial_data'
def load_fixture(apps, schema_editor):
# StackOverflow says it is very wrong to loaddata here, we should get
# "old" models and then load... but, this is only a simple test app
# so whatever. Just don't use loaddata command in your migrations or
# don't be suprised when it stops working... without understanding why.
call_command('loaddata', fixture, app_label='test_app')
class Migration(migrations.Migration):
dependencies = [
('test_app', '0001_initial'),
]
operations = [
migrations.RunPython(load_fixture),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-06-12 09:04
from __future__ import unicode_literals
from django.core.management import call_command
from django.db import migrations
fixture = 'initial_data'
def load_fixture(apps, schema_editor):
call_command('loaddata', fixture, app_label='test_app')
class Migration(migrations.Migration):
dependencies = [
('test_app', '0001_initial'),
]
operations = [
migrations.RunPython(load_fixture),
]
Add comment about how bad this is# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-06-12 09:04
from __future__ import unicode_literals
from django.core.management import call_command
from django.db import migrations
fixture = 'initial_data'
def load_fixture(apps, schema_editor):
# StackOverflow says it is very wrong to loaddata here, we should get
# "old" models and then load... but, this is only a simple test app
# so whatever. Just don't use loaddata command in your migrations or
# don't be suprised when it stops working... without understanding why.
call_command('loaddata', fixture, app_label='test_app')
class Migration(migrations.Migration):
dependencies = [
('test_app', '0001_initial'),
]
operations = [
migrations.RunPython(load_fixture),
]
| <commit_before># -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-06-12 09:04
from __future__ import unicode_literals
from django.core.management import call_command
from django.db import migrations
fixture = 'initial_data'
def load_fixture(apps, schema_editor):
call_command('loaddata', fixture, app_label='test_app')
class Migration(migrations.Migration):
dependencies = [
('test_app', '0001_initial'),
]
operations = [
migrations.RunPython(load_fixture),
]
<commit_msg>Add comment about how bad this is<commit_after># -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-06-12 09:04
from __future__ import unicode_literals
from django.core.management import call_command
from django.db import migrations
fixture = 'initial_data'
def load_fixture(apps, schema_editor):
# StackOverflow says it is very wrong to loaddata here, we should get
# "old" models and then load... but, this is only a simple test app
# so whatever. Just don't use loaddata command in your migrations or
# don't be suprised when it stops working... without understanding why.
call_command('loaddata', fixture, app_label='test_app')
class Migration(migrations.Migration):
dependencies = [
('test_app', '0001_initial'),
]
operations = [
migrations.RunPython(load_fixture),
]
|
1ac4e00f3d06955da90bddf03a6e478ddeb4d220 | core/modules/html_has_same_domain.py | core/modules/html_has_same_domain.py | from bs4 import BeautifulSoup as bs
from get_root_domain import get_root_domain
def html_has_same_domain(url, resp):
mod = 'html_has_same_domain'
cnt = 0
root = get_root_domain(url)
current_page = bs(resp.text, 'lxml')
for tag in current_page.find_all('a'):
if tag.get('href'):
in_url = get_root_domain(tag.get('href'))
if in_url == root:
cnt += 1
if ("naver" in tag.text.lower()):
return "P", mod
if cnt >= 1:
return "S", mod
return "U", mod
| from bs4 import BeautifulSoup as bs
from get_root_domain import get_root_domain
def html_has_same_domain(url, resp):
mod = 'html_has_same_domain'
cnt = 0
root = get_root_domain(url)
current_page = bs(resp.text, 'lxml')
for tag in current_page.find_all('a'):
if tag.get('href'):
in_url = get_root_domain(tag.get('href'))
if in_url == root:
cnt += 1
if cnt >= 1:
return "S", mod
return "U", mod
| Undo underperformaing change to code | Undo underperformaing change to code
| Python | bsd-2-clause | mjkim610/phishing-detection,jaeyung1001/phishing_site_detection | from bs4 import BeautifulSoup as bs
from get_root_domain import get_root_domain
def html_has_same_domain(url, resp):
mod = 'html_has_same_domain'
cnt = 0
root = get_root_domain(url)
current_page = bs(resp.text, 'lxml')
for tag in current_page.find_all('a'):
if tag.get('href'):
in_url = get_root_domain(tag.get('href'))
if in_url == root:
cnt += 1
if ("naver" in tag.text.lower()):
return "P", mod
if cnt >= 1:
return "S", mod
return "U", mod
Undo underperformaing change to code | from bs4 import BeautifulSoup as bs
from get_root_domain import get_root_domain
def html_has_same_domain(url, resp):
mod = 'html_has_same_domain'
cnt = 0
root = get_root_domain(url)
current_page = bs(resp.text, 'lxml')
for tag in current_page.find_all('a'):
if tag.get('href'):
in_url = get_root_domain(tag.get('href'))
if in_url == root:
cnt += 1
if cnt >= 1:
return "S", mod
return "U", mod
| <commit_before>from bs4 import BeautifulSoup as bs
from get_root_domain import get_root_domain
def html_has_same_domain(url, resp):
mod = 'html_has_same_domain'
cnt = 0
root = get_root_domain(url)
current_page = bs(resp.text, 'lxml')
for tag in current_page.find_all('a'):
if tag.get('href'):
in_url = get_root_domain(tag.get('href'))
if in_url == root:
cnt += 1
if ("naver" in tag.text.lower()):
return "P", mod
if cnt >= 1:
return "S", mod
return "U", mod
<commit_msg>Undo underperformaing change to code<commit_after> | from bs4 import BeautifulSoup as bs
from get_root_domain import get_root_domain
def html_has_same_domain(url, resp):
mod = 'html_has_same_domain'
cnt = 0
root = get_root_domain(url)
current_page = bs(resp.text, 'lxml')
for tag in current_page.find_all('a'):
if tag.get('href'):
in_url = get_root_domain(tag.get('href'))
if in_url == root:
cnt += 1
if cnt >= 1:
return "S", mod
return "U", mod
| from bs4 import BeautifulSoup as bs
from get_root_domain import get_root_domain
def html_has_same_domain(url, resp):
mod = 'html_has_same_domain'
cnt = 0
root = get_root_domain(url)
current_page = bs(resp.text, 'lxml')
for tag in current_page.find_all('a'):
if tag.get('href'):
in_url = get_root_domain(tag.get('href'))
if in_url == root:
cnt += 1
if ("naver" in tag.text.lower()):
return "P", mod
if cnt >= 1:
return "S", mod
return "U", mod
Undo underperformaing change to codefrom bs4 import BeautifulSoup as bs
from get_root_domain import get_root_domain
def html_has_same_domain(url, resp):
mod = 'html_has_same_domain'
cnt = 0
root = get_root_domain(url)
current_page = bs(resp.text, 'lxml')
for tag in current_page.find_all('a'):
if tag.get('href'):
in_url = get_root_domain(tag.get('href'))
if in_url == root:
cnt += 1
if cnt >= 1:
return "S", mod
return "U", mod
| <commit_before>from bs4 import BeautifulSoup as bs
from get_root_domain import get_root_domain
def html_has_same_domain(url, resp):
mod = 'html_has_same_domain'
cnt = 0
root = get_root_domain(url)
current_page = bs(resp.text, 'lxml')
for tag in current_page.find_all('a'):
if tag.get('href'):
in_url = get_root_domain(tag.get('href'))
if in_url == root:
cnt += 1
if ("naver" in tag.text.lower()):
return "P", mod
if cnt >= 1:
return "S", mod
return "U", mod
<commit_msg>Undo underperformaing change to code<commit_after>from bs4 import BeautifulSoup as bs
from get_root_domain import get_root_domain
def html_has_same_domain(url, resp):
mod = 'html_has_same_domain'
cnt = 0
root = get_root_domain(url)
current_page = bs(resp.text, 'lxml')
for tag in current_page.find_all('a'):
if tag.get('href'):
in_url = get_root_domain(tag.get('href'))
if in_url == root:
cnt += 1
if cnt >= 1:
return "S", mod
return "U", mod
|
de310ce3cdd37a372f92559b7ddcf0397b9fb016 | src/convert_dir_to_CLAHE.py | src/convert_dir_to_CLAHE.py | #!/usr/bin/env jython
from ij import IJ
import os
from mpicbg.ij.clahe import Flat
from ij.process import ImageConverter
# http://fiji.sc/wiki/index.php/Enhance_Local_Contrast_(CLAHE)
# http://fiji.sc/cgi-bin/gitweb.cgi?p=mpicbg.git;a=blob;f=mpicbg/ij/clahe/PlugIn.java;h=663153764493547de560c08ee11f2e6b1e7e1a32;hb=HEAD
dir = "/usr/people/tmacrina/Desktop/test/"
blocksize = 50
histogram_bins = 128
maximum_slope = 3
mask = "*None*"
composite = False
mask = None
files = os.listdir(dir)
files.sort()
for file in files:
if file.endswith(".tif")
fn = os.path.join(dir, file)
imp = IJ.openImage(path)
output_fn = os.path.splitext(fn)[0] + "_CLAHE_8bit.tif"
imp = IJ.openImage(fn)
Flat.getFastInstance().run( imp,
blocksize,
histogram_bins,
maximum_slope,
mask,
composite )
ImageConverter(imp).convertToGray8()
IJ.save(imp, output_fn)
| #!/usr/bin/env jython
from ij import IJ
import os
from mpicbg.ij.clahe import Flat
from ij.process import ImageConverter
# http://fiji.sc/wiki/index.php/Enhance_Local_Contrast_(CLAHE)
# http://fiji.sc/cgi-bin/gitweb.cgi?p=mpicbg.git;a=blob;f=mpicbg/ij/clahe/PlugIn.java;h=663153764493547de560c08ee11f2e6b1e7e1a32;hb=HEAD
dir = "/usr/people/tmacrina/seungmount/research/Julimaps/datasets/AIBS_pilot_v1/0_raw/"
blocksize = 63
histogram_bins = 255
maximum_slope = 3
mask = "*None*"
composite = False
mask = None
# files = os.listdir(dir)
# files.sort()
# for file in files:
# if file.endswith(".tif")
fn = os.path.join(dir, 'original.tif')
imp = IJ.openImage(fn)
output_fn = os.path.splitext(fn)[0] + "_CLAHE_8bit.tif"
imp = IJ.openImage(fn)
Flat.getFastInstance().run( imp,
blocksize,
histogram_bins,
maximum_slope,
mask,
composite )
ImageConverter(imp).convertToGray8()
IJ.save(imp, output_fn)
| Adjust FIJI script for applying CLAHE to a directory | Adjust FIJI script for applying CLAHE to a directory
| Python | mit | seung-lab/Julimaps,seung-lab/Julimaps | #!/usr/bin/env jython
from ij import IJ
import os
from mpicbg.ij.clahe import Flat
from ij.process import ImageConverter
# http://fiji.sc/wiki/index.php/Enhance_Local_Contrast_(CLAHE)
# http://fiji.sc/cgi-bin/gitweb.cgi?p=mpicbg.git;a=blob;f=mpicbg/ij/clahe/PlugIn.java;h=663153764493547de560c08ee11f2e6b1e7e1a32;hb=HEAD
dir = "/usr/people/tmacrina/Desktop/test/"
blocksize = 50
histogram_bins = 128
maximum_slope = 3
mask = "*None*"
composite = False
mask = None
files = os.listdir(dir)
files.sort()
for file in files:
if file.endswith(".tif")
fn = os.path.join(dir, file)
imp = IJ.openImage(path)
output_fn = os.path.splitext(fn)[0] + "_CLAHE_8bit.tif"
imp = IJ.openImage(fn)
Flat.getFastInstance().run( imp,
blocksize,
histogram_bins,
maximum_slope,
mask,
composite )
ImageConverter(imp).convertToGray8()
IJ.save(imp, output_fn)
Adjust FIJI script for applying CLAHE to a directory | #!/usr/bin/env jython
from ij import IJ
import os
from mpicbg.ij.clahe import Flat
from ij.process import ImageConverter
# http://fiji.sc/wiki/index.php/Enhance_Local_Contrast_(CLAHE)
# http://fiji.sc/cgi-bin/gitweb.cgi?p=mpicbg.git;a=blob;f=mpicbg/ij/clahe/PlugIn.java;h=663153764493547de560c08ee11f2e6b1e7e1a32;hb=HEAD
dir = "/usr/people/tmacrina/seungmount/research/Julimaps/datasets/AIBS_pilot_v1/0_raw/"
blocksize = 63
histogram_bins = 255
maximum_slope = 3
mask = "*None*"
composite = False
mask = None
# files = os.listdir(dir)
# files.sort()
# for file in files:
# if file.endswith(".tif")
fn = os.path.join(dir, 'original.tif')
imp = IJ.openImage(fn)
output_fn = os.path.splitext(fn)[0] + "_CLAHE_8bit.tif"
imp = IJ.openImage(fn)
Flat.getFastInstance().run( imp,
blocksize,
histogram_bins,
maximum_slope,
mask,
composite )
ImageConverter(imp).convertToGray8()
IJ.save(imp, output_fn)
| <commit_before>#!/usr/bin/env jython
from ij import IJ
import os
from mpicbg.ij.clahe import Flat
from ij.process import ImageConverter
# http://fiji.sc/wiki/index.php/Enhance_Local_Contrast_(CLAHE)
# http://fiji.sc/cgi-bin/gitweb.cgi?p=mpicbg.git;a=blob;f=mpicbg/ij/clahe/PlugIn.java;h=663153764493547de560c08ee11f2e6b1e7e1a32;hb=HEAD
dir = "/usr/people/tmacrina/Desktop/test/"
blocksize = 50
histogram_bins = 128
maximum_slope = 3
mask = "*None*"
composite = False
mask = None
files = os.listdir(dir)
files.sort()
for file in files:
if file.endswith(".tif")
fn = os.path.join(dir, file)
imp = IJ.openImage(path)
output_fn = os.path.splitext(fn)[0] + "_CLAHE_8bit.tif"
imp = IJ.openImage(fn)
Flat.getFastInstance().run( imp,
blocksize,
histogram_bins,
maximum_slope,
mask,
composite )
ImageConverter(imp).convertToGray8()
IJ.save(imp, output_fn)
<commit_msg>Adjust FIJI script for applying CLAHE to a directory<commit_after> | #!/usr/bin/env jython
from ij import IJ
import os
from mpicbg.ij.clahe import Flat
from ij.process import ImageConverter
# http://fiji.sc/wiki/index.php/Enhance_Local_Contrast_(CLAHE)
# http://fiji.sc/cgi-bin/gitweb.cgi?p=mpicbg.git;a=blob;f=mpicbg/ij/clahe/PlugIn.java;h=663153764493547de560c08ee11f2e6b1e7e1a32;hb=HEAD
dir = "/usr/people/tmacrina/seungmount/research/Julimaps/datasets/AIBS_pilot_v1/0_raw/"
blocksize = 63
histogram_bins = 255
maximum_slope = 3
mask = "*None*"
composite = False
mask = None
# files = os.listdir(dir)
# files.sort()
# for file in files:
# if file.endswith(".tif")
fn = os.path.join(dir, 'original.tif')
imp = IJ.openImage(fn)
output_fn = os.path.splitext(fn)[0] + "_CLAHE_8bit.tif"
imp = IJ.openImage(fn)
Flat.getFastInstance().run( imp,
blocksize,
histogram_bins,
maximum_slope,
mask,
composite )
ImageConverter(imp).convertToGray8()
IJ.save(imp, output_fn)
| #!/usr/bin/env jython
from ij import IJ
import os
from mpicbg.ij.clahe import Flat
from ij.process import ImageConverter
# http://fiji.sc/wiki/index.php/Enhance_Local_Contrast_(CLAHE)
# http://fiji.sc/cgi-bin/gitweb.cgi?p=mpicbg.git;a=blob;f=mpicbg/ij/clahe/PlugIn.java;h=663153764493547de560c08ee11f2e6b1e7e1a32;hb=HEAD
dir = "/usr/people/tmacrina/Desktop/test/"
blocksize = 50
histogram_bins = 128
maximum_slope = 3
mask = "*None*"
composite = False
mask = None
files = os.listdir(dir)
files.sort()
for file in files:
if file.endswith(".tif")
fn = os.path.join(dir, file)
imp = IJ.openImage(path)
output_fn = os.path.splitext(fn)[0] + "_CLAHE_8bit.tif"
imp = IJ.openImage(fn)
Flat.getFastInstance().run( imp,
blocksize,
histogram_bins,
maximum_slope,
mask,
composite )
ImageConverter(imp).convertToGray8()
IJ.save(imp, output_fn)
Adjust FIJI script for applying CLAHE to a directory#!/usr/bin/env jython
from ij import IJ
import os
from mpicbg.ij.clahe import Flat
from ij.process import ImageConverter
# http://fiji.sc/wiki/index.php/Enhance_Local_Contrast_(CLAHE)
# http://fiji.sc/cgi-bin/gitweb.cgi?p=mpicbg.git;a=blob;f=mpicbg/ij/clahe/PlugIn.java;h=663153764493547de560c08ee11f2e6b1e7e1a32;hb=HEAD
dir = "/usr/people/tmacrina/seungmount/research/Julimaps/datasets/AIBS_pilot_v1/0_raw/"
blocksize = 63
histogram_bins = 255
maximum_slope = 3
mask = "*None*"
composite = False
mask = None
# files = os.listdir(dir)
# files.sort()
# for file in files:
# if file.endswith(".tif")
fn = os.path.join(dir, 'original.tif')
imp = IJ.openImage(fn)
output_fn = os.path.splitext(fn)[0] + "_CLAHE_8bit.tif"
imp = IJ.openImage(fn)
Flat.getFastInstance().run( imp,
blocksize,
histogram_bins,
maximum_slope,
mask,
composite )
ImageConverter(imp).convertToGray8()
IJ.save(imp, output_fn)
| <commit_before>#!/usr/bin/env jython
from ij import IJ
import os
from mpicbg.ij.clahe import Flat
from ij.process import ImageConverter
# http://fiji.sc/wiki/index.php/Enhance_Local_Contrast_(CLAHE)
# http://fiji.sc/cgi-bin/gitweb.cgi?p=mpicbg.git;a=blob;f=mpicbg/ij/clahe/PlugIn.java;h=663153764493547de560c08ee11f2e6b1e7e1a32;hb=HEAD
dir = "/usr/people/tmacrina/Desktop/test/"
blocksize = 50
histogram_bins = 128
maximum_slope = 3
mask = "*None*"
composite = False
mask = None
files = os.listdir(dir)
files.sort()
for file in files:
if file.endswith(".tif")
fn = os.path.join(dir, file)
imp = IJ.openImage(path)
output_fn = os.path.splitext(fn)[0] + "_CLAHE_8bit.tif"
imp = IJ.openImage(fn)
Flat.getFastInstance().run( imp,
blocksize,
histogram_bins,
maximum_slope,
mask,
composite )
ImageConverter(imp).convertToGray8()
IJ.save(imp, output_fn)
<commit_msg>Adjust FIJI script for applying CLAHE to a directory<commit_after>#!/usr/bin/env jython
from ij import IJ
import os
from mpicbg.ij.clahe import Flat
from ij.process import ImageConverter
# http://fiji.sc/wiki/index.php/Enhance_Local_Contrast_(CLAHE)
# http://fiji.sc/cgi-bin/gitweb.cgi?p=mpicbg.git;a=blob;f=mpicbg/ij/clahe/PlugIn.java;h=663153764493547de560c08ee11f2e6b1e7e1a32;hb=HEAD
dir = "/usr/people/tmacrina/seungmount/research/Julimaps/datasets/AIBS_pilot_v1/0_raw/"
blocksize = 63
histogram_bins = 255
maximum_slope = 3
mask = "*None*"
composite = False
mask = None
# files = os.listdir(dir)
# files.sort()
# for file in files:
# if file.endswith(".tif")
fn = os.path.join(dir, 'original.tif')
imp = IJ.openImage(fn)
output_fn = os.path.splitext(fn)[0] + "_CLAHE_8bit.tif"
imp = IJ.openImage(fn)
Flat.getFastInstance().run( imp,
blocksize,
histogram_bins,
maximum_slope,
mask,
composite )
ImageConverter(imp).convertToGray8()
IJ.save(imp, output_fn)
|
d731ad50b863d32740bec857d46cc0c80e440185 | tests/melopy_tests.py | tests/melopy_tests.py | #!/usr/bin/env
# -*- coding: utf-8 -*-
from unittest import TestCase
from nose.tools import *
from melopy.melopy import *
class MelopyTests(TestCase):
def test_dummy(self):
assert True
| #!/usr/bin/env
# -*- coding: utf-8 -*-
from unittest import TestCase
from nose.tools import *
from melopy import *
class LibraryFunctionsTests(TestCase):
def test_frequency_from_key(self):
key = 49
assert frequency_from_key(key) == 440
def test_frequency_from_note(self):
note = 'A4'
assert frequency_from_note(note) == 440
def test_key_from_note(self):
note = 'A4'
assert key_from_note(note) == 49
def test_note_from_key(self):
key = 49
assert note_from_key(key) == 'A4'
def test_iterate(self):
start = 'D4'
pattern = [2, 2, 1, 2, 2, 2]
should_be = ['D4', 'E4', 'F#4', 'G4', 'A4', 'B4', 'C#5']
assert iterate(start, pattern) == should_be
def test_generate_major_scale(self):
start = 'D4'
should_be = ['D4', 'E4', 'F#4', 'G4', 'A4', 'B4', 'C#5']
assert generate_major_scale(start) == should_be
def test_generate_minor_scale(self):
start = 'C4'
should_be = ['C4', 'D4', 'Eb4', 'F4', 'G4', 'Ab4', 'Bb4']
assert generate_minor_scale(start) == should_be
def test_generate_major_triad(self):
start = 'A4'
should_be = ['A4', 'C#5', 'E5']
assert generate_major_triad(start) == should_be
def test_generate_minor_triad(self):
start = 'C5'
should_be = ['C5', 'Eb5', 'G5']
assert generate_minor_triad(start) == should_be
class MelopyTests(TestCase):
def test_dummy(self):
assert True
| Add tests for the library methods. All except 2 pass right now. | Add tests for the library methods. All except 2 pass right now.
The two that don't pass, fail because I have changed what their output
should be. In the docs, it is shown that the output of
`generate_minor_scale`, given 'C4', is:
['C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'A#4']
This is incorrect. The actual minor scale is:
['C4', 'D4', 'Eb4', 'F4', 'G4', 'Ab4', 'Bb4']
The same kind of inconsistency is found in the `generate_minor_triad`
output. This is not a proper minor triad:
['C5', 'D#5', 'G5']
because C -> D# is not a minor third interval, it is an augmented second
interval. I know, for all practical purposes it will generate the same
tone, but my musical OCD can't stand to see it this way lol!
| Python | mit | jdan/Melopy,juliowaissman/Melopy | #!/usr/bin/env
# -*- coding: utf-8 -*-
from unittest import TestCase
from nose.tools import *
from melopy.melopy import *
class MelopyTests(TestCase):
def test_dummy(self):
assert True
Add tests for the library methods. All except 2 pass right now.
The two that don't pass, fail because I have changed what their output
should be. In the docs, it is shown that the output of
`generate_minor_scale`, given 'C4', is:
['C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'A#4']
This is incorrect. The actual minor scale is:
['C4', 'D4', 'Eb4', 'F4', 'G4', 'Ab4', 'Bb4']
The same kind of inconsistency is found in the `generate_minor_triad`
output. This is not a proper minor triad:
['C5', 'D#5', 'G5']
because C -> D# is not a minor third interval, it is an augmented second
interval. I know, for all practical purposes it will generate the same
tone, but my musical OCD can't stand to see it this way lol! | #!/usr/bin/env
# -*- coding: utf-8 -*-
from unittest import TestCase
from nose.tools import *
from melopy import *
class LibraryFunctionsTests(TestCase):
def test_frequency_from_key(self):
key = 49
assert frequency_from_key(key) == 440
def test_frequency_from_note(self):
note = 'A4'
assert frequency_from_note(note) == 440
def test_key_from_note(self):
note = 'A4'
assert key_from_note(note) == 49
def test_note_from_key(self):
key = 49
assert note_from_key(key) == 'A4'
def test_iterate(self):
start = 'D4'
pattern = [2, 2, 1, 2, 2, 2]
should_be = ['D4', 'E4', 'F#4', 'G4', 'A4', 'B4', 'C#5']
assert iterate(start, pattern) == should_be
def test_generate_major_scale(self):
start = 'D4'
should_be = ['D4', 'E4', 'F#4', 'G4', 'A4', 'B4', 'C#5']
assert generate_major_scale(start) == should_be
def test_generate_minor_scale(self):
start = 'C4'
should_be = ['C4', 'D4', 'Eb4', 'F4', 'G4', 'Ab4', 'Bb4']
assert generate_minor_scale(start) == should_be
def test_generate_major_triad(self):
start = 'A4'
should_be = ['A4', 'C#5', 'E5']
assert generate_major_triad(start) == should_be
def test_generate_minor_triad(self):
start = 'C5'
should_be = ['C5', 'Eb5', 'G5']
assert generate_minor_triad(start) == should_be
class MelopyTests(TestCase):
def test_dummy(self):
assert True
| <commit_before>#!/usr/bin/env
# -*- coding: utf-8 -*-
from unittest import TestCase
from nose.tools import *
from melopy.melopy import *
class MelopyTests(TestCase):
def test_dummy(self):
assert True
<commit_msg>Add tests for the library methods. All except 2 pass right now.
The two that don't pass, fail because I have changed what their output
should be. In the docs, it is shown that the output of
`generate_minor_scale`, given 'C4', is:
['C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'A#4']
This is incorrect. The actual minor scale is:
['C4', 'D4', 'Eb4', 'F4', 'G4', 'Ab4', 'Bb4']
The same kind of inconsistency is found in the `generate_minor_triad`
output. This is not a proper minor triad:
['C5', 'D#5', 'G5']
because C -> D# is not a minor third interval, it is an augmented second
interval. I know, for all practical purposes it will generate the same
tone, but my musical OCD can't stand to see it this way lol!<commit_after> | #!/usr/bin/env
# -*- coding: utf-8 -*-
from unittest import TestCase
from nose.tools import *
from melopy import *
class LibraryFunctionsTests(TestCase):
def test_frequency_from_key(self):
key = 49
assert frequency_from_key(key) == 440
def test_frequency_from_note(self):
note = 'A4'
assert frequency_from_note(note) == 440
def test_key_from_note(self):
note = 'A4'
assert key_from_note(note) == 49
def test_note_from_key(self):
key = 49
assert note_from_key(key) == 'A4'
def test_iterate(self):
start = 'D4'
pattern = [2, 2, 1, 2, 2, 2]
should_be = ['D4', 'E4', 'F#4', 'G4', 'A4', 'B4', 'C#5']
assert iterate(start, pattern) == should_be
def test_generate_major_scale(self):
start = 'D4'
should_be = ['D4', 'E4', 'F#4', 'G4', 'A4', 'B4', 'C#5']
assert generate_major_scale(start) == should_be
def test_generate_minor_scale(self):
start = 'C4'
should_be = ['C4', 'D4', 'Eb4', 'F4', 'G4', 'Ab4', 'Bb4']
assert generate_minor_scale(start) == should_be
def test_generate_major_triad(self):
start = 'A4'
should_be = ['A4', 'C#5', 'E5']
assert generate_major_triad(start) == should_be
def test_generate_minor_triad(self):
start = 'C5'
should_be = ['C5', 'Eb5', 'G5']
assert generate_minor_triad(start) == should_be
class MelopyTests(TestCase):
def test_dummy(self):
assert True
| #!/usr/bin/env
# -*- coding: utf-8 -*-
from unittest import TestCase
from nose.tools import *
from melopy.melopy import *
class MelopyTests(TestCase):
def test_dummy(self):
assert True
Add tests for the library methods. All except 2 pass right now.
The two that don't pass, fail because I have changed what their output
should be. In the docs, it is shown that the output of
`generate_minor_scale`, given 'C4', is:
['C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'A#4']
This is incorrect. The actual minor scale is:
['C4', 'D4', 'Eb4', 'F4', 'G4', 'Ab4', 'Bb4']
The same kind of inconsistency is found in the `generate_minor_triad`
output. This is not a proper minor triad:
['C5', 'D#5', 'G5']
because C -> D# is not a minor third interval, it is an augmented second
interval. I know, for all practical purposes it will generate the same
tone, but my musical OCD can't stand to see it this way lol!#!/usr/bin/env
# -*- coding: utf-8 -*-
from unittest import TestCase
from nose.tools import *
from melopy import *
class LibraryFunctionsTests(TestCase):
def test_frequency_from_key(self):
key = 49
assert frequency_from_key(key) == 440
def test_frequency_from_note(self):
note = 'A4'
assert frequency_from_note(note) == 440
def test_key_from_note(self):
note = 'A4'
assert key_from_note(note) == 49
def test_note_from_key(self):
key = 49
assert note_from_key(key) == 'A4'
def test_iterate(self):
start = 'D4'
pattern = [2, 2, 1, 2, 2, 2]
should_be = ['D4', 'E4', 'F#4', 'G4', 'A4', 'B4', 'C#5']
assert iterate(start, pattern) == should_be
def test_generate_major_scale(self):
start = 'D4'
should_be = ['D4', 'E4', 'F#4', 'G4', 'A4', 'B4', 'C#5']
assert generate_major_scale(start) == should_be
def test_generate_minor_scale(self):
start = 'C4'
should_be = ['C4', 'D4', 'Eb4', 'F4', 'G4', 'Ab4', 'Bb4']
assert generate_minor_scale(start) == should_be
def test_generate_major_triad(self):
start = 'A4'
should_be = ['A4', 'C#5', 'E5']
assert generate_major_triad(start) == should_be
def test_generate_minor_triad(self):
start = 'C5'
should_be = ['C5', 'Eb5', 'G5']
assert generate_minor_triad(start) == should_be
class MelopyTests(TestCase):
def test_dummy(self):
assert True
| <commit_before>#!/usr/bin/env
# -*- coding: utf-8 -*-
from unittest import TestCase
from nose.tools import *
from melopy.melopy import *
class MelopyTests(TestCase):
def test_dummy(self):
assert True
<commit_msg>Add tests for the library methods. All except 2 pass right now.
The two that don't pass, fail because I have changed what their output
should be. In the docs, it is shown that the output of
`generate_minor_scale`, given 'C4', is:
['C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'A#4']
This is incorrect. The actual minor scale is:
['C4', 'D4', 'Eb4', 'F4', 'G4', 'Ab4', 'Bb4']
The same kind of inconsistency is found in the `generate_minor_triad`
output. This is not a proper minor triad:
['C5', 'D#5', 'G5']
because C -> D# is not a minor third interval, it is an augmented second
interval. I know, for all practical purposes it will generate the same
tone, but my musical OCD can't stand to see it this way lol!<commit_after>#!/usr/bin/env
# -*- coding: utf-8 -*-
from unittest import TestCase
from nose.tools import *
from melopy import *
class LibraryFunctionsTests(TestCase):
def test_frequency_from_key(self):
key = 49
assert frequency_from_key(key) == 440
def test_frequency_from_note(self):
note = 'A4'
assert frequency_from_note(note) == 440
def test_key_from_note(self):
note = 'A4'
assert key_from_note(note) == 49
def test_note_from_key(self):
key = 49
assert note_from_key(key) == 'A4'
def test_iterate(self):
start = 'D4'
pattern = [2, 2, 1, 2, 2, 2]
should_be = ['D4', 'E4', 'F#4', 'G4', 'A4', 'B4', 'C#5']
assert iterate(start, pattern) == should_be
def test_generate_major_scale(self):
start = 'D4'
should_be = ['D4', 'E4', 'F#4', 'G4', 'A4', 'B4', 'C#5']
assert generate_major_scale(start) == should_be
def test_generate_minor_scale(self):
start = 'C4'
should_be = ['C4', 'D4', 'Eb4', 'F4', 'G4', 'Ab4', 'Bb4']
assert generate_minor_scale(start) == should_be
def test_generate_major_triad(self):
start = 'A4'
should_be = ['A4', 'C#5', 'E5']
assert generate_major_triad(start) == should_be
def test_generate_minor_triad(self):
start = 'C5'
should_be = ['C5', 'Eb5', 'G5']
assert generate_minor_triad(start) == should_be
class MelopyTests(TestCase):
def test_dummy(self):
assert True
|
25af2e47b5b107ce4a0be4963b70bbf04b22c142 | tests/test_element.py | tests/test_element.py | import mdtraj as md
import pytest
from mdtraj import element
from mdtraj.testing import eq
def test_immutable():
def f():
element.hydrogen.mass = 1
def g():
element.radium.symbol = 'sdfsdfsdf'
def h():
element.iron.name = 'sdfsdf'
pytest.raises(AttributeError, f)
pytest.raises(AttributeError, g)
pytest.raises(AttributeError, h)
assert element.hydrogen.mass == 1.007947
assert element.radium.symbol == 'Ra'
assert element.iron.name == 'iron'
def test_element_0(get_fn):
t = md.load(get_fn('bpti.pdb'))
a = t.top.atom(15)
H = element.Element.getBySymbol('H')
eq(a.element, element.hydrogen)
| import mdtraj as md
import pytest
import pickle
from mdtraj import element
from mdtraj.testing import eq
def test_immutable():
def f():
element.hydrogen.mass = 1
def g():
element.radium.symbol = 'sdfsdfsdf'
def h():
element.iron.name = 'sdfsdf'
pytest.raises(AttributeError, f)
pytest.raises(AttributeError, g)
pytest.raises(AttributeError, h)
assert element.hydrogen.mass == 1.007947
assert element.radium.symbol == 'Ra'
assert element.iron.name == 'iron'
def test_element_0(get_fn):
t = md.load(get_fn('bpti.pdb'))
a = t.top.atom(15)
H = element.Element.getBySymbol('H')
eq(a.element, element.hydrogen)
def test_element_pickle():
"""Test that every Element object can pickle and de-pickle"""
for el in dir(element):
if isinstance(el, element.Element):
assert el == pickle.loads(pickle.dumps(el))
| Add basic element pickle cycle test | Add basic element pickle cycle test
| Python | lgpl-2.1 | dwhswenson/mdtraj,mattwthompson/mdtraj,jchodera/mdtraj,gph82/mdtraj,dwhswenson/mdtraj,jchodera/mdtraj,rmcgibbo/mdtraj,leeping/mdtraj,gph82/mdtraj,leeping/mdtraj,jchodera/mdtraj,rmcgibbo/mdtraj,mattwthompson/mdtraj,jchodera/mdtraj,dwhswenson/mdtraj,mdtraj/mdtraj,gph82/mdtraj,leeping/mdtraj,leeping/mdtraj,mattwthompson/mdtraj,mdtraj/mdtraj,mdtraj/mdtraj,rmcgibbo/mdtraj,mattwthompson/mdtraj | import mdtraj as md
import pytest
from mdtraj import element
from mdtraj.testing import eq
def test_immutable():
def f():
element.hydrogen.mass = 1
def g():
element.radium.symbol = 'sdfsdfsdf'
def h():
element.iron.name = 'sdfsdf'
pytest.raises(AttributeError, f)
pytest.raises(AttributeError, g)
pytest.raises(AttributeError, h)
assert element.hydrogen.mass == 1.007947
assert element.radium.symbol == 'Ra'
assert element.iron.name == 'iron'
def test_element_0(get_fn):
t = md.load(get_fn('bpti.pdb'))
a = t.top.atom(15)
H = element.Element.getBySymbol('H')
eq(a.element, element.hydrogen)
Add basic element pickle cycle test | import mdtraj as md
import pytest
import pickle
from mdtraj import element
from mdtraj.testing import eq
def test_immutable():
def f():
element.hydrogen.mass = 1
def g():
element.radium.symbol = 'sdfsdfsdf'
def h():
element.iron.name = 'sdfsdf'
pytest.raises(AttributeError, f)
pytest.raises(AttributeError, g)
pytest.raises(AttributeError, h)
assert element.hydrogen.mass == 1.007947
assert element.radium.symbol == 'Ra'
assert element.iron.name == 'iron'
def test_element_0(get_fn):
t = md.load(get_fn('bpti.pdb'))
a = t.top.atom(15)
H = element.Element.getBySymbol('H')
eq(a.element, element.hydrogen)
def test_element_pickle():
"""Test that every Element object can pickle and de-pickle"""
for el in dir(element):
if isinstance(el, element.Element):
assert el == pickle.loads(pickle.dumps(el))
| <commit_before>import mdtraj as md
import pytest
from mdtraj import element
from mdtraj.testing import eq
def test_immutable():
def f():
element.hydrogen.mass = 1
def g():
element.radium.symbol = 'sdfsdfsdf'
def h():
element.iron.name = 'sdfsdf'
pytest.raises(AttributeError, f)
pytest.raises(AttributeError, g)
pytest.raises(AttributeError, h)
assert element.hydrogen.mass == 1.007947
assert element.radium.symbol == 'Ra'
assert element.iron.name == 'iron'
def test_element_0(get_fn):
t = md.load(get_fn('bpti.pdb'))
a = t.top.atom(15)
H = element.Element.getBySymbol('H')
eq(a.element, element.hydrogen)
<commit_msg>Add basic element pickle cycle test<commit_after> | import mdtraj as md
import pytest
import pickle
from mdtraj import element
from mdtraj.testing import eq
def test_immutable():
def f():
element.hydrogen.mass = 1
def g():
element.radium.symbol = 'sdfsdfsdf'
def h():
element.iron.name = 'sdfsdf'
pytest.raises(AttributeError, f)
pytest.raises(AttributeError, g)
pytest.raises(AttributeError, h)
assert element.hydrogen.mass == 1.007947
assert element.radium.symbol == 'Ra'
assert element.iron.name == 'iron'
def test_element_0(get_fn):
t = md.load(get_fn('bpti.pdb'))
a = t.top.atom(15)
H = element.Element.getBySymbol('H')
eq(a.element, element.hydrogen)
def test_element_pickle():
"""Test that every Element object can pickle and de-pickle"""
for el in dir(element):
if isinstance(el, element.Element):
assert el == pickle.loads(pickle.dumps(el))
| import mdtraj as md
import pytest
from mdtraj import element
from mdtraj.testing import eq
def test_immutable():
def f():
element.hydrogen.mass = 1
def g():
element.radium.symbol = 'sdfsdfsdf'
def h():
element.iron.name = 'sdfsdf'
pytest.raises(AttributeError, f)
pytest.raises(AttributeError, g)
pytest.raises(AttributeError, h)
assert element.hydrogen.mass == 1.007947
assert element.radium.symbol == 'Ra'
assert element.iron.name == 'iron'
def test_element_0(get_fn):
t = md.load(get_fn('bpti.pdb'))
a = t.top.atom(15)
H = element.Element.getBySymbol('H')
eq(a.element, element.hydrogen)
Add basic element pickle cycle testimport mdtraj as md
import pytest
import pickle
from mdtraj import element
from mdtraj.testing import eq
def test_immutable():
def f():
element.hydrogen.mass = 1
def g():
element.radium.symbol = 'sdfsdfsdf'
def h():
element.iron.name = 'sdfsdf'
pytest.raises(AttributeError, f)
pytest.raises(AttributeError, g)
pytest.raises(AttributeError, h)
assert element.hydrogen.mass == 1.007947
assert element.radium.symbol == 'Ra'
assert element.iron.name == 'iron'
def test_element_0(get_fn):
t = md.load(get_fn('bpti.pdb'))
a = t.top.atom(15)
H = element.Element.getBySymbol('H')
eq(a.element, element.hydrogen)
def test_element_pickle():
"""Test that every Element object can pickle and de-pickle"""
for el in dir(element):
if isinstance(el, element.Element):
assert el == pickle.loads(pickle.dumps(el))
| <commit_before>import mdtraj as md
import pytest
from mdtraj import element
from mdtraj.testing import eq
def test_immutable():
def f():
element.hydrogen.mass = 1
def g():
element.radium.symbol = 'sdfsdfsdf'
def h():
element.iron.name = 'sdfsdf'
pytest.raises(AttributeError, f)
pytest.raises(AttributeError, g)
pytest.raises(AttributeError, h)
assert element.hydrogen.mass == 1.007947
assert element.radium.symbol == 'Ra'
assert element.iron.name == 'iron'
def test_element_0(get_fn):
t = md.load(get_fn('bpti.pdb'))
a = t.top.atom(15)
H = element.Element.getBySymbol('H')
eq(a.element, element.hydrogen)
<commit_msg>Add basic element pickle cycle test<commit_after>import mdtraj as md
import pytest
import pickle
from mdtraj import element
from mdtraj.testing import eq
def test_immutable():
def f():
element.hydrogen.mass = 1
def g():
element.radium.symbol = 'sdfsdfsdf'
def h():
element.iron.name = 'sdfsdf'
pytest.raises(AttributeError, f)
pytest.raises(AttributeError, g)
pytest.raises(AttributeError, h)
assert element.hydrogen.mass == 1.007947
assert element.radium.symbol == 'Ra'
assert element.iron.name == 'iron'
def test_element_0(get_fn):
t = md.load(get_fn('bpti.pdb'))
a = t.top.atom(15)
H = element.Element.getBySymbol('H')
eq(a.element, element.hydrogen)
def test_element_pickle():
"""Test that every Element object can pickle and de-pickle"""
for el in dir(element):
if isinstance(el, element.Element):
assert el == pickle.loads(pickle.dumps(el))
|
abb34fe5541448dbeb07e5e0e96e51a310de94ab | todolist.py | todolist.py | # -*- coding: utf-8 -*-
from app import create_app
app = create_app('development')
@app.cli.command()
def test():
"""Runs the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
@app.cli.command()
def fill_db():
"""Fills database with random data.
By default 10 users, 40 todolists and 160 todos.
WARNING: will delete existing data. For testing purposes only.
"""
from utils.fake_generator import FakeGenerator
FakeGenerator().start() # side effect: deletes existing data
| # -*- coding: utf-8 -*-
from app import create_app
app = create_app('development')
@app.cli.command()
def test():
"""Runs the unit tests."""
import unittest
import sys
tests = unittest.TestLoader().discover('tests')
result = unittest.TextTestRunner(verbosity=2).run(tests)
if result.errors or result.failures:
sys.exit(1)
@app.cli.command()
def fill_db():
"""Fills database with random data.
By default 10 users, 40 todolists and 160 todos.
WARNING: will delete existing data. For testing purposes only.
"""
from utils.fake_generator import FakeGenerator
FakeGenerator().start() # side effect: deletes existing data
| Fix return code for failing tests | Fix return code for failing tests
Previous the even if tests failed the return code would not indicate
this to the caller of 'flask test' in this case.
| Python | mit | polyfunc/flask-todolist,rtzll/flask-todolist,rtzll/flask-todolist,0xfoo/flask-todolist,rtzll/flask-todolist,polyfunc/flask-todolist,polyfunc/flask-todolist,0xfoo/flask-todolist,0xfoo/flask-todolist,rtzll/flask-todolist | # -*- coding: utf-8 -*-
from app import create_app
app = create_app('development')
@app.cli.command()
def test():
"""Runs the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
@app.cli.command()
def fill_db():
"""Fills database with random data.
By default 10 users, 40 todolists and 160 todos.
WARNING: will delete existing data. For testing purposes only.
"""
from utils.fake_generator import FakeGenerator
FakeGenerator().start() # side effect: deletes existing data
Fix return code for failing tests
Previous the even if tests failed the return code would not indicate
this to the caller of 'flask test' in this case. | # -*- coding: utf-8 -*-
from app import create_app
app = create_app('development')
@app.cli.command()
def test():
"""Runs the unit tests."""
import unittest
import sys
tests = unittest.TestLoader().discover('tests')
result = unittest.TextTestRunner(verbosity=2).run(tests)
if result.errors or result.failures:
sys.exit(1)
@app.cli.command()
def fill_db():
"""Fills database with random data.
By default 10 users, 40 todolists and 160 todos.
WARNING: will delete existing data. For testing purposes only.
"""
from utils.fake_generator import FakeGenerator
FakeGenerator().start() # side effect: deletes existing data
| <commit_before># -*- coding: utf-8 -*-
from app import create_app
app = create_app('development')
@app.cli.command()
def test():
"""Runs the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
@app.cli.command()
def fill_db():
"""Fills database with random data.
By default 10 users, 40 todolists and 160 todos.
WARNING: will delete existing data. For testing purposes only.
"""
from utils.fake_generator import FakeGenerator
FakeGenerator().start() # side effect: deletes existing data
<commit_msg>Fix return code for failing tests
Previous the even if tests failed the return code would not indicate
this to the caller of 'flask test' in this case.<commit_after> | # -*- coding: utf-8 -*-
from app import create_app
app = create_app('development')
@app.cli.command()
def test():
"""Runs the unit tests."""
import unittest
import sys
tests = unittest.TestLoader().discover('tests')
result = unittest.TextTestRunner(verbosity=2).run(tests)
if result.errors or result.failures:
sys.exit(1)
@app.cli.command()
def fill_db():
"""Fills database with random data.
By default 10 users, 40 todolists and 160 todos.
WARNING: will delete existing data. For testing purposes only.
"""
from utils.fake_generator import FakeGenerator
FakeGenerator().start() # side effect: deletes existing data
| # -*- coding: utf-8 -*-
from app import create_app
app = create_app('development')
@app.cli.command()
def test():
"""Runs the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
@app.cli.command()
def fill_db():
"""Fills database with random data.
By default 10 users, 40 todolists and 160 todos.
WARNING: will delete existing data. For testing purposes only.
"""
from utils.fake_generator import FakeGenerator
FakeGenerator().start() # side effect: deletes existing data
Fix return code for failing tests
Previous the even if tests failed the return code would not indicate
this to the caller of 'flask test' in this case.# -*- coding: utf-8 -*-
from app import create_app
app = create_app('development')
@app.cli.command()
def test():
"""Runs the unit tests."""
import unittest
import sys
tests = unittest.TestLoader().discover('tests')
result = unittest.TextTestRunner(verbosity=2).run(tests)
if result.errors or result.failures:
sys.exit(1)
@app.cli.command()
def fill_db():
"""Fills database with random data.
By default 10 users, 40 todolists and 160 todos.
WARNING: will delete existing data. For testing purposes only.
"""
from utils.fake_generator import FakeGenerator
FakeGenerator().start() # side effect: deletes existing data
| <commit_before># -*- coding: utf-8 -*-
from app import create_app
app = create_app('development')
@app.cli.command()
def test():
"""Runs the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
@app.cli.command()
def fill_db():
"""Fills database with random data.
By default 10 users, 40 todolists and 160 todos.
WARNING: will delete existing data. For testing purposes only.
"""
from utils.fake_generator import FakeGenerator
FakeGenerator().start() # side effect: deletes existing data
<commit_msg>Fix return code for failing tests
Previous the even if tests failed the return code would not indicate
this to the caller of 'flask test' in this case.<commit_after># -*- coding: utf-8 -*-
from app import create_app
app = create_app('development')
@app.cli.command()
def test():
"""Runs the unit tests."""
import unittest
import sys
tests = unittest.TestLoader().discover('tests')
result = unittest.TextTestRunner(verbosity=2).run(tests)
if result.errors or result.failures:
sys.exit(1)
@app.cli.command()
def fill_db():
"""Fills database with random data.
By default 10 users, 40 todolists and 160 todos.
WARNING: will delete existing data. For testing purposes only.
"""
from utils.fake_generator import FakeGenerator
FakeGenerator().start() # side effect: deletes existing data
|
949f390a083d8fd166a43a0cd2afa63feb7d86b1 | forum/models.py | forum/models.py | from django.db import models
import django.contrib.auth.models as auth
class User(auth.User):
"""Model for representing users.
It has few fields that aren't in the standard authentication user
table, and are needed for the forum to work, like footers.
"""
display_name = models.CharField(max_length=30, null=True)
footer = models.TextField(null=True)
def __str__(self):
"""Show display name or user name."""
return self.display_name or self.username
class Thread(models.Model):
"""Model for representing threads."""
title = models.CharField(max_length=100)
views = models.PositiveIntegerField(default=0)
sticky = models.BooleanField(default=False)
closed = models.BooleanField(default=False)
def __str__(self):
"""Show thread title."""
return self.title
class Post(models.Model):
"""Model for representing posts.
Actual posts are stored in PostRevision, this only stores the
thread number. The first created revision contains the author
of post and date of its creation. The last revision contains actual
text post.
"""
thread = models.ForeignKey(Thread)
class PostRevision(models.Model):
"""Model for representing post revisions.
The first revision for given post contains its author and date to
show to the user. The last revision shows the date it was created
on.
"""
post = models.ForeignKey(Post)
author = models.ForeignKey(User)
date_created = models.DateTimeField(auto_now=True)
text = models.TextField()
| from django.db import models
import django.contrib.auth.models as auth
class User(auth.User):
"""Model for representing users.
It has few fields that aren't in the standard authentication user
table, and are needed for the forum to work, like footers.
"""
display_name = models.CharField(max_length=30, null=True)
footer = models.TextField(null=True)
def __str__(self):
"""Show display name or user name."""
return self.display_name or self.username
class Thread(models.Model):
"""Model for representing threads."""
title = models.CharField(max_length=100)
views = models.PositiveIntegerField(default=0)
sticky = models.BooleanField(default=False)
closed = models.BooleanField(default=False)
def __str__(self):
"""Show thread title."""
return self.title
class Post(models.Model):
"""Model for representing posts.
Actual posts are stored in PostRevision, this only stores the
thread number. The first created revision contains the author
of post and date of its creation. The last revision contains actual
text post.
"""
thread = models.ForeignKey(Thread)
class PostRevision(models.Model):
"""Model for representing post revisions.
The first revision for given post contains its author and date to
show to the user. The last revision shows the date it was created
on.
"""
post = models.ForeignKey(Post)
author = models.ForeignKey(User)
date_created = models.DateTimeField(auto_now=True)
text = models.TextField()
class Meta:
ordering = ['date_created']
| Order revisions by their creation date. | Order revisions by their creation date.
| Python | mit | xfix/NextBoard | from django.db import models
import django.contrib.auth.models as auth
class User(auth.User):
"""Model for representing users.
It has few fields that aren't in the standard authentication user
table, and are needed for the forum to work, like footers.
"""
display_name = models.CharField(max_length=30, null=True)
footer = models.TextField(null=True)
def __str__(self):
"""Show display name or user name."""
return self.display_name or self.username
class Thread(models.Model):
"""Model for representing threads."""
title = models.CharField(max_length=100)
views = models.PositiveIntegerField(default=0)
sticky = models.BooleanField(default=False)
closed = models.BooleanField(default=False)
def __str__(self):
"""Show thread title."""
return self.title
class Post(models.Model):
"""Model for representing posts.
Actual posts are stored in PostRevision, this only stores the
thread number. The first created revision contains the author
of post and date of its creation. The last revision contains actual
text post.
"""
thread = models.ForeignKey(Thread)
class PostRevision(models.Model):
"""Model for representing post revisions.
The first revision for given post contains its author and date to
show to the user. The last revision shows the date it was created
on.
"""
post = models.ForeignKey(Post)
author = models.ForeignKey(User)
date_created = models.DateTimeField(auto_now=True)
text = models.TextField()
Order revisions by their creation date. | from django.db import models
import django.contrib.auth.models as auth
class User(auth.User):
"""Model for representing users.
It has few fields that aren't in the standard authentication user
table, and are needed for the forum to work, like footers.
"""
display_name = models.CharField(max_length=30, null=True)
footer = models.TextField(null=True)
def __str__(self):
"""Show display name or user name."""
return self.display_name or self.username
class Thread(models.Model):
"""Model for representing threads."""
title = models.CharField(max_length=100)
views = models.PositiveIntegerField(default=0)
sticky = models.BooleanField(default=False)
closed = models.BooleanField(default=False)
def __str__(self):
"""Show thread title."""
return self.title
class Post(models.Model):
"""Model for representing posts.
Actual posts are stored in PostRevision, this only stores the
thread number. The first created revision contains the author
of post and date of its creation. The last revision contains actual
text post.
"""
thread = models.ForeignKey(Thread)
class PostRevision(models.Model):
"""Model for representing post revisions.
The first revision for given post contains its author and date to
show to the user. The last revision shows the date it was created
on.
"""
post = models.ForeignKey(Post)
author = models.ForeignKey(User)
date_created = models.DateTimeField(auto_now=True)
text = models.TextField()
class Meta:
ordering = ['date_created']
| <commit_before>from django.db import models
import django.contrib.auth.models as auth
class User(auth.User):
"""Model for representing users.
It has few fields that aren't in the standard authentication user
table, and are needed for the forum to work, like footers.
"""
display_name = models.CharField(max_length=30, null=True)
footer = models.TextField(null=True)
def __str__(self):
"""Show display name or user name."""
return self.display_name or self.username
class Thread(models.Model):
"""Model for representing threads."""
title = models.CharField(max_length=100)
views = models.PositiveIntegerField(default=0)
sticky = models.BooleanField(default=False)
closed = models.BooleanField(default=False)
def __str__(self):
"""Show thread title."""
return self.title
class Post(models.Model):
"""Model for representing posts.
Actual posts are stored in PostRevision, this only stores the
thread number. The first created revision contains the author
of post and date of its creation. The last revision contains actual
text post.
"""
thread = models.ForeignKey(Thread)
class PostRevision(models.Model):
"""Model for representing post revisions.
The first revision for given post contains its author and date to
show to the user. The last revision shows the date it was created
on.
"""
post = models.ForeignKey(Post)
author = models.ForeignKey(User)
date_created = models.DateTimeField(auto_now=True)
text = models.TextField()
<commit_msg>Order revisions by their creation date.<commit_after> | from django.db import models
import django.contrib.auth.models as auth
class User(auth.User):
"""Model for representing users.
It has few fields that aren't in the standard authentication user
table, and are needed for the forum to work, like footers.
"""
display_name = models.CharField(max_length=30, null=True)
footer = models.TextField(null=True)
def __str__(self):
"""Show display name or user name."""
return self.display_name or self.username
class Thread(models.Model):
"""Model for representing threads."""
title = models.CharField(max_length=100)
views = models.PositiveIntegerField(default=0)
sticky = models.BooleanField(default=False)
closed = models.BooleanField(default=False)
def __str__(self):
"""Show thread title."""
return self.title
class Post(models.Model):
"""Model for representing posts.
Actual posts are stored in PostRevision, this only stores the
thread number. The first created revision contains the author
of post and date of its creation. The last revision contains actual
text post.
"""
thread = models.ForeignKey(Thread)
class PostRevision(models.Model):
"""Model for representing post revisions.
The first revision for given post contains its author and date to
show to the user. The last revision shows the date it was created
on.
"""
post = models.ForeignKey(Post)
author = models.ForeignKey(User)
date_created = models.DateTimeField(auto_now=True)
text = models.TextField()
class Meta:
ordering = ['date_created']
| from django.db import models
import django.contrib.auth.models as auth
class User(auth.User):
"""Model for representing users.
It has few fields that aren't in the standard authentication user
table, and are needed for the forum to work, like footers.
"""
display_name = models.CharField(max_length=30, null=True)
footer = models.TextField(null=True)
def __str__(self):
"""Show display name or user name."""
return self.display_name or self.username
class Thread(models.Model):
"""Model for representing threads."""
title = models.CharField(max_length=100)
views = models.PositiveIntegerField(default=0)
sticky = models.BooleanField(default=False)
closed = models.BooleanField(default=False)
def __str__(self):
"""Show thread title."""
return self.title
class Post(models.Model):
"""Model for representing posts.
Actual posts are stored in PostRevision, this only stores the
thread number. The first created revision contains the author
of post and date of its creation. The last revision contains actual
text post.
"""
thread = models.ForeignKey(Thread)
class PostRevision(models.Model):
"""Model for representing post revisions.
The first revision for given post contains its author and date to
show to the user. The last revision shows the date it was created
on.
"""
post = models.ForeignKey(Post)
author = models.ForeignKey(User)
date_created = models.DateTimeField(auto_now=True)
text = models.TextField()
Order revisions by their creation date.from django.db import models
import django.contrib.auth.models as auth
class User(auth.User):
"""Model for representing users.
It has few fields that aren't in the standard authentication user
table, and are needed for the forum to work, like footers.
"""
display_name = models.CharField(max_length=30, null=True)
footer = models.TextField(null=True)
def __str__(self):
"""Show display name or user name."""
return self.display_name or self.username
class Thread(models.Model):
"""Model for representing threads."""
title = models.CharField(max_length=100)
views = models.PositiveIntegerField(default=0)
sticky = models.BooleanField(default=False)
closed = models.BooleanField(default=False)
def __str__(self):
"""Show thread title."""
return self.title
class Post(models.Model):
"""Model for representing posts.
Actual posts are stored in PostRevision, this only stores the
thread number. The first created revision contains the author
of post and date of its creation. The last revision contains actual
text post.
"""
thread = models.ForeignKey(Thread)
class PostRevision(models.Model):
"""Model for representing post revisions.
The first revision for given post contains its author and date to
show to the user. The last revision shows the date it was created
on.
"""
post = models.ForeignKey(Post)
author = models.ForeignKey(User)
date_created = models.DateTimeField(auto_now=True)
text = models.TextField()
class Meta:
ordering = ['date_created']
| <commit_before>from django.db import models
import django.contrib.auth.models as auth
class User(auth.User):
"""Model for representing users.
It has few fields that aren't in the standard authentication user
table, and are needed for the forum to work, like footers.
"""
display_name = models.CharField(max_length=30, null=True)
footer = models.TextField(null=True)
def __str__(self):
"""Show display name or user name."""
return self.display_name or self.username
class Thread(models.Model):
"""Model for representing threads."""
title = models.CharField(max_length=100)
views = models.PositiveIntegerField(default=0)
sticky = models.BooleanField(default=False)
closed = models.BooleanField(default=False)
def __str__(self):
"""Show thread title."""
return self.title
class Post(models.Model):
"""Model for representing posts.
Actual posts are stored in PostRevision, this only stores the
thread number. The first created revision contains the author
of post and date of its creation. The last revision contains actual
text post.
"""
thread = models.ForeignKey(Thread)
class PostRevision(models.Model):
"""Model for representing post revisions.
The first revision for given post contains its author and date to
show to the user. The last revision shows the date it was created
on.
"""
post = models.ForeignKey(Post)
author = models.ForeignKey(User)
date_created = models.DateTimeField(auto_now=True)
text = models.TextField()
<commit_msg>Order revisions by their creation date.<commit_after>from django.db import models
import django.contrib.auth.models as auth
class User(auth.User):
"""Model for representing users.
It has few fields that aren't in the standard authentication user
table, and are needed for the forum to work, like footers.
"""
display_name = models.CharField(max_length=30, null=True)
footer = models.TextField(null=True)
def __str__(self):
"""Show display name or user name."""
return self.display_name or self.username
class Thread(models.Model):
"""Model for representing threads."""
title = models.CharField(max_length=100)
views = models.PositiveIntegerField(default=0)
sticky = models.BooleanField(default=False)
closed = models.BooleanField(default=False)
def __str__(self):
"""Show thread title."""
return self.title
class Post(models.Model):
"""Model for representing posts.
Actual posts are stored in PostRevision, this only stores the
thread number. The first created revision contains the author
of post and date of its creation. The last revision contains actual
text post.
"""
thread = models.ForeignKey(Thread)
class PostRevision(models.Model):
"""Model for representing post revisions.
The first revision for given post contains its author and date to
show to the user. The last revision shows the date it was created
on.
"""
post = models.ForeignKey(Post)
author = models.ForeignKey(User)
date_created = models.DateTimeField(auto_now=True)
text = models.TextField()
class Meta:
ordering = ['date_created']
|
7a9fc08f3cf32f0bc8ccf49f0301437079c115c9 | logger/__init__.py | logger/__init__.py | #!/usr/bin/env python3
"""Logging package for specific and general needs.
This exposes all the defined loggers, and a generic ready-to-use Logger
for general needs, which can be used right away.
"""
__author__ = "Emanuel 'Vgr' Barry"
__version__ = "0.2.3"
__status__ = "Mass Refactor [Unstable]"
__all__ = []
from . import loggers
from .loggers import *
__all__.extend(loggers.__all__)
| #!/usr/bin/env python3
"""Logging package for specific and general needs.
This exposes all the defined loggers, and a generic ready-to-use Logger
for general needs, which can be used right away.
"""
__author__ = "Emanuel 'Vgr' Barry"
__version__ = "0.2.3"
__status__ = "Mass Refactor [Unstable]"
__all__ = ["loggers"]
from . import loggers
from .loggers import *
__all__.extend(loggers.__all__)
| Add the loggers submodule to __all__ | Add the loggers submodule to __all__
| Python | bsd-2-clause | Vgr255/logging | #!/usr/bin/env python3
"""Logging package for specific and general needs.
This exposes all the defined loggers, and a generic ready-to-use Logger
for general needs, which can be used right away.
"""
__author__ = "Emanuel 'Vgr' Barry"
__version__ = "0.2.3"
__status__ = "Mass Refactor [Unstable]"
__all__ = []
from . import loggers
from .loggers import *
__all__.extend(loggers.__all__)
Add the loggers submodule to __all__ | #!/usr/bin/env python3
"""Logging package for specific and general needs.
This exposes all the defined loggers, and a generic ready-to-use Logger
for general needs, which can be used right away.
"""
__author__ = "Emanuel 'Vgr' Barry"
__version__ = "0.2.3"
__status__ = "Mass Refactor [Unstable]"
__all__ = ["loggers"]
from . import loggers
from .loggers import *
__all__.extend(loggers.__all__)
| <commit_before>#!/usr/bin/env python3
"""Logging package for specific and general needs.
This exposes all the defined loggers, and a generic ready-to-use Logger
for general needs, which can be used right away.
"""
__author__ = "Emanuel 'Vgr' Barry"
__version__ = "0.2.3"
__status__ = "Mass Refactor [Unstable]"
__all__ = []
from . import loggers
from .loggers import *
__all__.extend(loggers.__all__)
<commit_msg>Add the loggers submodule to __all__<commit_after> | #!/usr/bin/env python3
"""Logging package for specific and general needs.
This exposes all the defined loggers, and a generic ready-to-use Logger
for general needs, which can be used right away.
"""
__author__ = "Emanuel 'Vgr' Barry"
__version__ = "0.2.3"
__status__ = "Mass Refactor [Unstable]"
__all__ = ["loggers"]
from . import loggers
from .loggers import *
__all__.extend(loggers.__all__)
| #!/usr/bin/env python3
"""Logging package for specific and general needs.
This exposes all the defined loggers, and a generic ready-to-use Logger
for general needs, which can be used right away.
"""
__author__ = "Emanuel 'Vgr' Barry"
__version__ = "0.2.3"
__status__ = "Mass Refactor [Unstable]"
__all__ = []
from . import loggers
from .loggers import *
__all__.extend(loggers.__all__)
Add the loggers submodule to __all__#!/usr/bin/env python3
"""Logging package for specific and general needs.
This exposes all the defined loggers, and a generic ready-to-use Logger
for general needs, which can be used right away.
"""
__author__ = "Emanuel 'Vgr' Barry"
__version__ = "0.2.3"
__status__ = "Mass Refactor [Unstable]"
__all__ = ["loggers"]
from . import loggers
from .loggers import *
__all__.extend(loggers.__all__)
| <commit_before>#!/usr/bin/env python3
"""Logging package for specific and general needs.
This exposes all the defined loggers, and a generic ready-to-use Logger
for general needs, which can be used right away.
"""
__author__ = "Emanuel 'Vgr' Barry"
__version__ = "0.2.3"
__status__ = "Mass Refactor [Unstable]"
__all__ = []
from . import loggers
from .loggers import *
__all__.extend(loggers.__all__)
<commit_msg>Add the loggers submodule to __all__<commit_after>#!/usr/bin/env python3
"""Logging package for specific and general needs.
This exposes all the defined loggers, and a generic ready-to-use Logger
for general needs, which can be used right away.
"""
__author__ = "Emanuel 'Vgr' Barry"
__version__ = "0.2.3"
__status__ = "Mass Refactor [Unstable]"
__all__ = ["loggers"]
from . import loggers
from .loggers import *
__all__.extend(loggers.__all__)
|
3aee3f32dec40dc42ea857b64eb0f31dae0db07f | wluopensource/osl_comments/urls.py | wluopensource/osl_comments/urls.py | from django.conf.urls.defaults import *
from django.contrib.comments.urls import urlpatterns
urlpatterns += patterns('',
(r'^edit/$', 'osl_comments.views.edit_comment'),
url(r'^cr/(\d+)/(.+)/$', 'django.views.defaults.shortcut', name='comments-url-redirect'),
)
| from django.conf.urls.defaults import *
from django.contrib.comments.urls import urlpatterns
urlpatterns += patterns('',
(r'^edit/$', 'osl_comments.views.edit_comment'),
(r'^edited/$', 'osl_comments.views.comment_edited'),
url(r'^cr/(\d+)/(.+)/$', 'django.views.defaults.shortcut', name='comments-url-redirect'),
)
| Add reference to comment edited in urlconf | Add reference to comment edited in urlconf
| Python | bsd-3-clause | jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website | from django.conf.urls.defaults import *
from django.contrib.comments.urls import urlpatterns
urlpatterns += patterns('',
(r'^edit/$', 'osl_comments.views.edit_comment'),
url(r'^cr/(\d+)/(.+)/$', 'django.views.defaults.shortcut', name='comments-url-redirect'),
)
Add reference to comment edited in urlconf | from django.conf.urls.defaults import *
from django.contrib.comments.urls import urlpatterns
urlpatterns += patterns('',
(r'^edit/$', 'osl_comments.views.edit_comment'),
(r'^edited/$', 'osl_comments.views.comment_edited'),
url(r'^cr/(\d+)/(.+)/$', 'django.views.defaults.shortcut', name='comments-url-redirect'),
)
| <commit_before>from django.conf.urls.defaults import *
from django.contrib.comments.urls import urlpatterns
urlpatterns += patterns('',
(r'^edit/$', 'osl_comments.views.edit_comment'),
url(r'^cr/(\d+)/(.+)/$', 'django.views.defaults.shortcut', name='comments-url-redirect'),
)
<commit_msg>Add reference to comment edited in urlconf<commit_after> | from django.conf.urls.defaults import *
from django.contrib.comments.urls import urlpatterns
urlpatterns += patterns('',
(r'^edit/$', 'osl_comments.views.edit_comment'),
(r'^edited/$', 'osl_comments.views.comment_edited'),
url(r'^cr/(\d+)/(.+)/$', 'django.views.defaults.shortcut', name='comments-url-redirect'),
)
| from django.conf.urls.defaults import *
from django.contrib.comments.urls import urlpatterns
urlpatterns += patterns('',
(r'^edit/$', 'osl_comments.views.edit_comment'),
url(r'^cr/(\d+)/(.+)/$', 'django.views.defaults.shortcut', name='comments-url-redirect'),
)
Add reference to comment edited in urlconffrom django.conf.urls.defaults import *
from django.contrib.comments.urls import urlpatterns
urlpatterns += patterns('',
(r'^edit/$', 'osl_comments.views.edit_comment'),
(r'^edited/$', 'osl_comments.views.comment_edited'),
url(r'^cr/(\d+)/(.+)/$', 'django.views.defaults.shortcut', name='comments-url-redirect'),
)
| <commit_before>from django.conf.urls.defaults import *
from django.contrib.comments.urls import urlpatterns
urlpatterns += patterns('',
(r'^edit/$', 'osl_comments.views.edit_comment'),
url(r'^cr/(\d+)/(.+)/$', 'django.views.defaults.shortcut', name='comments-url-redirect'),
)
<commit_msg>Add reference to comment edited in urlconf<commit_after>from django.conf.urls.defaults import *
from django.contrib.comments.urls import urlpatterns
urlpatterns += patterns('',
(r'^edit/$', 'osl_comments.views.edit_comment'),
(r'^edited/$', 'osl_comments.views.comment_edited'),
url(r'^cr/(\d+)/(.+)/$', 'django.views.defaults.shortcut', name='comments-url-redirect'),
)
|
b6233dff3cec42696f2ea0eea286ded48f02e79b | rllib/optimizers/rollout.py | rllib/optimizers/rollout.py | import logging
import ray
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils.memory import ray_get_and_free
logger = logging.getLogger(__name__)
def collect_samples(agents, sample_batch_size, num_envs_per_worker,
train_batch_size):
"""Collects at least train_batch_size samples, never discarding any."""
num_timesteps_so_far = 0
trajectories = []
agent_dict = {}
for agent in agents:
fut_sample = agent.sample.remote()
agent_dict[fut_sample] = agent
while agent_dict:
[fut_sample], _ = ray.wait(list(agent_dict))
agent = agent_dict.pop(fut_sample)
next_sample = ray_get_and_free(fut_sample)
assert next_sample.count >= sample_batch_size * num_envs_per_worker
num_timesteps_so_far += next_sample.count
trajectories.append(next_sample)
# Only launch more tasks if we don't already have enough pending
pending = len(agent_dict) * sample_batch_size * num_envs_per_worker
if num_timesteps_so_far + pending < train_batch_size:
fut_sample2 = agent.sample.remote()
agent_dict[fut_sample2] = agent
return SampleBatch.concat_samples(trajectories)
| import logging
import ray
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils.memory import ray_get_and_free
logger = logging.getLogger(__name__)
def collect_samples(agents, sample_batch_size, num_envs_per_worker,
train_batch_size):
"""Collects at least train_batch_size samples, never discarding any."""
num_timesteps_so_far = 0
trajectories = []
agent_dict = {}
for agent in agents:
fut_sample = agent.sample.remote()
agent_dict[fut_sample] = agent
while agent_dict:
[fut_sample], _ = ray.wait(list(agent_dict))
agent = agent_dict.pop(fut_sample)
next_sample = ray_get_and_free(fut_sample)
num_timesteps_so_far += next_sample.count
trajectories.append(next_sample)
# Only launch more tasks if we don't already have enough pending
pending = len(agent_dict) * sample_batch_size * num_envs_per_worker
if num_timesteps_so_far + pending < train_batch_size:
fut_sample2 = agent.sample.remote()
agent_dict[fut_sample2] = agent
return SampleBatch.concat_samples(trajectories)
| Fix bad sample count assert | [rllib] Fix bad sample count assert
| Python | apache-2.0 | richardliaw/ray,ray-project/ray,robertnishihara/ray,richardliaw/ray,pcmoritz/ray-1,robertnishihara/ray,ray-project/ray,pcmoritz/ray-1,robertnishihara/ray,pcmoritz/ray-1,pcmoritz/ray-1,robertnishihara/ray,pcmoritz/ray-1,richardliaw/ray,ray-project/ray,richardliaw/ray,pcmoritz/ray-1,richardliaw/ray,ray-project/ray,robertnishihara/ray,robertnishihara/ray,ray-project/ray,pcmoritz/ray-1,robertnishihara/ray,ray-project/ray,ray-project/ray,robertnishihara/ray,pcmoritz/ray-1,richardliaw/ray,robertnishihara/ray,richardliaw/ray,richardliaw/ray,ray-project/ray | import logging
import ray
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils.memory import ray_get_and_free
logger = logging.getLogger(__name__)
def collect_samples(agents, sample_batch_size, num_envs_per_worker,
train_batch_size):
"""Collects at least train_batch_size samples, never discarding any."""
num_timesteps_so_far = 0
trajectories = []
agent_dict = {}
for agent in agents:
fut_sample = agent.sample.remote()
agent_dict[fut_sample] = agent
while agent_dict:
[fut_sample], _ = ray.wait(list(agent_dict))
agent = agent_dict.pop(fut_sample)
next_sample = ray_get_and_free(fut_sample)
assert next_sample.count >= sample_batch_size * num_envs_per_worker
num_timesteps_so_far += next_sample.count
trajectories.append(next_sample)
# Only launch more tasks if we don't already have enough pending
pending = len(agent_dict) * sample_batch_size * num_envs_per_worker
if num_timesteps_so_far + pending < train_batch_size:
fut_sample2 = agent.sample.remote()
agent_dict[fut_sample2] = agent
return SampleBatch.concat_samples(trajectories)
[rllib] Fix bad sample count assert | import logging
import ray
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils.memory import ray_get_and_free
logger = logging.getLogger(__name__)
def collect_samples(agents, sample_batch_size, num_envs_per_worker,
train_batch_size):
"""Collects at least train_batch_size samples, never discarding any."""
num_timesteps_so_far = 0
trajectories = []
agent_dict = {}
for agent in agents:
fut_sample = agent.sample.remote()
agent_dict[fut_sample] = agent
while agent_dict:
[fut_sample], _ = ray.wait(list(agent_dict))
agent = agent_dict.pop(fut_sample)
next_sample = ray_get_and_free(fut_sample)
num_timesteps_so_far += next_sample.count
trajectories.append(next_sample)
# Only launch more tasks if we don't already have enough pending
pending = len(agent_dict) * sample_batch_size * num_envs_per_worker
if num_timesteps_so_far + pending < train_batch_size:
fut_sample2 = agent.sample.remote()
agent_dict[fut_sample2] = agent
return SampleBatch.concat_samples(trajectories)
| <commit_before>import logging
import ray
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils.memory import ray_get_and_free
logger = logging.getLogger(__name__)
def collect_samples(agents, sample_batch_size, num_envs_per_worker,
train_batch_size):
"""Collects at least train_batch_size samples, never discarding any."""
num_timesteps_so_far = 0
trajectories = []
agent_dict = {}
for agent in agents:
fut_sample = agent.sample.remote()
agent_dict[fut_sample] = agent
while agent_dict:
[fut_sample], _ = ray.wait(list(agent_dict))
agent = agent_dict.pop(fut_sample)
next_sample = ray_get_and_free(fut_sample)
assert next_sample.count >= sample_batch_size * num_envs_per_worker
num_timesteps_so_far += next_sample.count
trajectories.append(next_sample)
# Only launch more tasks if we don't already have enough pending
pending = len(agent_dict) * sample_batch_size * num_envs_per_worker
if num_timesteps_so_far + pending < train_batch_size:
fut_sample2 = agent.sample.remote()
agent_dict[fut_sample2] = agent
return SampleBatch.concat_samples(trajectories)
<commit_msg>[rllib] Fix bad sample count assert<commit_after> | import logging
import ray
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils.memory import ray_get_and_free
logger = logging.getLogger(__name__)
def collect_samples(agents, sample_batch_size, num_envs_per_worker,
train_batch_size):
"""Collects at least train_batch_size samples, never discarding any."""
num_timesteps_so_far = 0
trajectories = []
agent_dict = {}
for agent in agents:
fut_sample = agent.sample.remote()
agent_dict[fut_sample] = agent
while agent_dict:
[fut_sample], _ = ray.wait(list(agent_dict))
agent = agent_dict.pop(fut_sample)
next_sample = ray_get_and_free(fut_sample)
num_timesteps_so_far += next_sample.count
trajectories.append(next_sample)
# Only launch more tasks if we don't already have enough pending
pending = len(agent_dict) * sample_batch_size * num_envs_per_worker
if num_timesteps_so_far + pending < train_batch_size:
fut_sample2 = agent.sample.remote()
agent_dict[fut_sample2] = agent
return SampleBatch.concat_samples(trajectories)
| import logging
import ray
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils.memory import ray_get_and_free
logger = logging.getLogger(__name__)
def collect_samples(agents, sample_batch_size, num_envs_per_worker,
train_batch_size):
"""Collects at least train_batch_size samples, never discarding any."""
num_timesteps_so_far = 0
trajectories = []
agent_dict = {}
for agent in agents:
fut_sample = agent.sample.remote()
agent_dict[fut_sample] = agent
while agent_dict:
[fut_sample], _ = ray.wait(list(agent_dict))
agent = agent_dict.pop(fut_sample)
next_sample = ray_get_and_free(fut_sample)
assert next_sample.count >= sample_batch_size * num_envs_per_worker
num_timesteps_so_far += next_sample.count
trajectories.append(next_sample)
# Only launch more tasks if we don't already have enough pending
pending = len(agent_dict) * sample_batch_size * num_envs_per_worker
if num_timesteps_so_far + pending < train_batch_size:
fut_sample2 = agent.sample.remote()
agent_dict[fut_sample2] = agent
return SampleBatch.concat_samples(trajectories)
[rllib] Fix bad sample count assertimport logging
import ray
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils.memory import ray_get_and_free
logger = logging.getLogger(__name__)
def collect_samples(agents, sample_batch_size, num_envs_per_worker,
train_batch_size):
"""Collects at least train_batch_size samples, never discarding any."""
num_timesteps_so_far = 0
trajectories = []
agent_dict = {}
for agent in agents:
fut_sample = agent.sample.remote()
agent_dict[fut_sample] = agent
while agent_dict:
[fut_sample], _ = ray.wait(list(agent_dict))
agent = agent_dict.pop(fut_sample)
next_sample = ray_get_and_free(fut_sample)
num_timesteps_so_far += next_sample.count
trajectories.append(next_sample)
# Only launch more tasks if we don't already have enough pending
pending = len(agent_dict) * sample_batch_size * num_envs_per_worker
if num_timesteps_so_far + pending < train_batch_size:
fut_sample2 = agent.sample.remote()
agent_dict[fut_sample2] = agent
return SampleBatch.concat_samples(trajectories)
| <commit_before>import logging
import ray
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils.memory import ray_get_and_free
logger = logging.getLogger(__name__)
def collect_samples(agents, sample_batch_size, num_envs_per_worker,
train_batch_size):
"""Collects at least train_batch_size samples, never discarding any."""
num_timesteps_so_far = 0
trajectories = []
agent_dict = {}
for agent in agents:
fut_sample = agent.sample.remote()
agent_dict[fut_sample] = agent
while agent_dict:
[fut_sample], _ = ray.wait(list(agent_dict))
agent = agent_dict.pop(fut_sample)
next_sample = ray_get_and_free(fut_sample)
assert next_sample.count >= sample_batch_size * num_envs_per_worker
num_timesteps_so_far += next_sample.count
trajectories.append(next_sample)
# Only launch more tasks if we don't already have enough pending
pending = len(agent_dict) * sample_batch_size * num_envs_per_worker
if num_timesteps_so_far + pending < train_batch_size:
fut_sample2 = agent.sample.remote()
agent_dict[fut_sample2] = agent
return SampleBatch.concat_samples(trajectories)
<commit_msg>[rllib] Fix bad sample count assert<commit_after>import logging
import ray
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils.memory import ray_get_and_free
logger = logging.getLogger(__name__)
def collect_samples(agents, sample_batch_size, num_envs_per_worker,
train_batch_size):
"""Collects at least train_batch_size samples, never discarding any."""
num_timesteps_so_far = 0
trajectories = []
agent_dict = {}
for agent in agents:
fut_sample = agent.sample.remote()
agent_dict[fut_sample] = agent
while agent_dict:
[fut_sample], _ = ray.wait(list(agent_dict))
agent = agent_dict.pop(fut_sample)
next_sample = ray_get_and_free(fut_sample)
num_timesteps_so_far += next_sample.count
trajectories.append(next_sample)
# Only launch more tasks if we don't already have enough pending
pending = len(agent_dict) * sample_batch_size * num_envs_per_worker
if num_timesteps_so_far + pending < train_batch_size:
fut_sample2 = agent.sample.remote()
agent_dict[fut_sample2] = agent
return SampleBatch.concat_samples(trajectories)
|
acdb2445a5ead7d6ae116f839b1710c65ff08137 | nimp/utilities/paths.py | nimp/utilities/paths.py | # -*- coding: utf-8 -*-
import os
import os.path
import shutil
import sys
import fnmatch
import glob
from nimp.utilities.logging import *
#-------------------------------------------------------------------------------
def split_path(path):
splitted_path = []
while True:
(path, folder) = os.path.split(path)
if folder != "":
splitted_path.insert(0, folder)
else:
if path != "":
splitted_path.insert(0, path)
break
return splitted_path
#-------------------------------------------------------------------------------
# This function is necessary because Python’s makedirs cannot create a
# directory such as "d:\data\foo/bar" because it’ll split it as "d:\data"
# and "foo/bar" then try to create a directory named "foo/bar".
def safe_makedirs(path):
if os.sep is '\\':
path = path.replace('/', '\\')
elif os.sep is '/':
path = path.replace('\\', '/')
if not os.path.exists(path):
os.makedirs(path)
| # -*- coding: utf-8 -*-
import os
import os.path
import shutil
import sys
import fnmatch
import glob
from nimp.utilities.logging import *
#-------------------------------------------------------------------------------
def split_path(path):
splitted_path = []
while True:
(path, folder) = os.path.split(path)
if folder != "":
splitted_path.insert(0, folder)
else:
if path != "":
splitted_path.insert(0, path)
break
return splitted_path
#-------------------------------------------------------------------------------
# This function is necessary because Python’s makedirs cannot create a
# directory such as "d:\data\foo/bar" because it’ll split it as "d:\data"
# and "foo/bar" then try to create a directory named "foo/bar".
def safe_makedirs(path):
if os.sep is '\\':
path = path.replace('/', '\\')
elif os.sep is '/':
path = path.replace('\\', '/')
try:
os.makedirs(path)
except FileExistsError:
# Maybe someone else created the directory for us; if so, ignore error
if os.path.exists(path):
return
raise
| Make safe_makedirs resilient to race conditions. | Make safe_makedirs resilient to race conditions.
| Python | mit | dontnod/nimp | # -*- coding: utf-8 -*-
import os
import os.path
import shutil
import sys
import fnmatch
import glob
from nimp.utilities.logging import *
#-------------------------------------------------------------------------------
def split_path(path):
splitted_path = []
while True:
(path, folder) = os.path.split(path)
if folder != "":
splitted_path.insert(0, folder)
else:
if path != "":
splitted_path.insert(0, path)
break
return splitted_path
#-------------------------------------------------------------------------------
# This function is necessary because Python’s makedirs cannot create a
# directory such as "d:\data\foo/bar" because it’ll split it as "d:\data"
# and "foo/bar" then try to create a directory named "foo/bar".
def safe_makedirs(path):
if os.sep is '\\':
path = path.replace('/', '\\')
elif os.sep is '/':
path = path.replace('\\', '/')
if not os.path.exists(path):
os.makedirs(path)
Make safe_makedirs resilient to race conditions. | # -*- coding: utf-8 -*-
import os
import os.path
import shutil
import sys
import fnmatch
import glob
from nimp.utilities.logging import *
#-------------------------------------------------------------------------------
def split_path(path):
splitted_path = []
while True:
(path, folder) = os.path.split(path)
if folder != "":
splitted_path.insert(0, folder)
else:
if path != "":
splitted_path.insert(0, path)
break
return splitted_path
#-------------------------------------------------------------------------------
# This function is necessary because Python’s makedirs cannot create a
# directory such as "d:\data\foo/bar" because it’ll split it as "d:\data"
# and "foo/bar" then try to create a directory named "foo/bar".
def safe_makedirs(path):
if os.sep is '\\':
path = path.replace('/', '\\')
elif os.sep is '/':
path = path.replace('\\', '/')
try:
os.makedirs(path)
except FileExistsError:
# Maybe someone else created the directory for us; if so, ignore error
if os.path.exists(path):
return
raise
| <commit_before># -*- coding: utf-8 -*-
import os
import os.path
import shutil
import sys
import fnmatch
import glob
from nimp.utilities.logging import *
#-------------------------------------------------------------------------------
def split_path(path):
splitted_path = []
while True:
(path, folder) = os.path.split(path)
if folder != "":
splitted_path.insert(0, folder)
else:
if path != "":
splitted_path.insert(0, path)
break
return splitted_path
#-------------------------------------------------------------------------------
# This function is necessary because Python’s makedirs cannot create a
# directory such as "d:\data\foo/bar" because it’ll split it as "d:\data"
# and "foo/bar" then try to create a directory named "foo/bar".
def safe_makedirs(path):
if os.sep is '\\':
path = path.replace('/', '\\')
elif os.sep is '/':
path = path.replace('\\', '/')
if not os.path.exists(path):
os.makedirs(path)
<commit_msg>Make safe_makedirs resilient to race conditions.<commit_after> | # -*- coding: utf-8 -*-
import os
import os.path
import shutil
import sys
import fnmatch
import glob
from nimp.utilities.logging import *
#-------------------------------------------------------------------------------
def split_path(path):
splitted_path = []
while True:
(path, folder) = os.path.split(path)
if folder != "":
splitted_path.insert(0, folder)
else:
if path != "":
splitted_path.insert(0, path)
break
return splitted_path
#-------------------------------------------------------------------------------
# This function is necessary because Python’s makedirs cannot create a
# directory such as "d:\data\foo/bar" because it’ll split it as "d:\data"
# and "foo/bar" then try to create a directory named "foo/bar".
def safe_makedirs(path):
if os.sep is '\\':
path = path.replace('/', '\\')
elif os.sep is '/':
path = path.replace('\\', '/')
try:
os.makedirs(path)
except FileExistsError:
# Maybe someone else created the directory for us; if so, ignore error
if os.path.exists(path):
return
raise
| # -*- coding: utf-8 -*-
import os
import os.path
import shutil
import sys
import fnmatch
import glob
from nimp.utilities.logging import *
#-------------------------------------------------------------------------------
def split_path(path):
splitted_path = []
while True:
(path, folder) = os.path.split(path)
if folder != "":
splitted_path.insert(0, folder)
else:
if path != "":
splitted_path.insert(0, path)
break
return splitted_path
#-------------------------------------------------------------------------------
# This function is necessary because Python’s makedirs cannot create a
# directory such as "d:\data\foo/bar" because it’ll split it as "d:\data"
# and "foo/bar" then try to create a directory named "foo/bar".
def safe_makedirs(path):
if os.sep is '\\':
path = path.replace('/', '\\')
elif os.sep is '/':
path = path.replace('\\', '/')
if not os.path.exists(path):
os.makedirs(path)
Make safe_makedirs resilient to race conditions.# -*- coding: utf-8 -*-
import os
import os.path
import shutil
import sys
import fnmatch
import glob
from nimp.utilities.logging import *
#-------------------------------------------------------------------------------
def split_path(path):
splitted_path = []
while True:
(path, folder) = os.path.split(path)
if folder != "":
splitted_path.insert(0, folder)
else:
if path != "":
splitted_path.insert(0, path)
break
return splitted_path
#-------------------------------------------------------------------------------
# This function is necessary because Python’s makedirs cannot create a
# directory such as "d:\data\foo/bar" because it’ll split it as "d:\data"
# and "foo/bar" then try to create a directory named "foo/bar".
def safe_makedirs(path):
if os.sep is '\\':
path = path.replace('/', '\\')
elif os.sep is '/':
path = path.replace('\\', '/')
try:
os.makedirs(path)
except FileExistsError:
# Maybe someone else created the directory for us; if so, ignore error
if os.path.exists(path):
return
raise
| <commit_before># -*- coding: utf-8 -*-
import os
import os.path
import shutil
import sys
import fnmatch
import glob
from nimp.utilities.logging import *
#-------------------------------------------------------------------------------
def split_path(path):
splitted_path = []
while True:
(path, folder) = os.path.split(path)
if folder != "":
splitted_path.insert(0, folder)
else:
if path != "":
splitted_path.insert(0, path)
break
return splitted_path
#-------------------------------------------------------------------------------
# This function is necessary because Python’s makedirs cannot create a
# directory such as "d:\data\foo/bar" because it’ll split it as "d:\data"
# and "foo/bar" then try to create a directory named "foo/bar".
def safe_makedirs(path):
if os.sep is '\\':
path = path.replace('/', '\\')
elif os.sep is '/':
path = path.replace('\\', '/')
if not os.path.exists(path):
os.makedirs(path)
<commit_msg>Make safe_makedirs resilient to race conditions.<commit_after># -*- coding: utf-8 -*-
import os
import os.path
import shutil
import sys
import fnmatch
import glob
from nimp.utilities.logging import *
#-------------------------------------------------------------------------------
def split_path(path):
splitted_path = []
while True:
(path, folder) = os.path.split(path)
if folder != "":
splitted_path.insert(0, folder)
else:
if path != "":
splitted_path.insert(0, path)
break
return splitted_path
#-------------------------------------------------------------------------------
# This function is necessary because Python’s makedirs cannot create a
# directory such as "d:\data\foo/bar" because it’ll split it as "d:\data"
# and "foo/bar" then try to create a directory named "foo/bar".
def safe_makedirs(path):
if os.sep is '\\':
path = path.replace('/', '\\')
elif os.sep is '/':
path = path.replace('\\', '/')
try:
os.makedirs(path)
except FileExistsError:
# Maybe someone else created the directory for us; if so, ignore error
if os.path.exists(path):
return
raise
|
184d0400f2304b0fe7adf07471526bc66b4eea64 | libs/ConfigHelpers.py | libs/ConfigHelpers.py |
import logging
from tornado.options import options
from datetime import datetime
def save_config():
logging.info("Saving current config to: %s" % options.config)
with open(options.config, 'w') as fp:
fp.write("##########################")
fp.write(" Root the Box Config File ")
fp.write("##########################\n")
fp.write("# Last updated: %s\n" % datetime.now())
for group in options.groups():
# Shitty work around for Tornado 4.1
if 'rootthebox.py' in group.lower() or group == '':
continue
fp.write("\n# [ %s ]\n" % group.title())
try:
# python2
opt = options.group_dict(group).iteritems()
except AttributeError:
# python3
opt = options.group_dict(group).items()
for key, value in opt:
try:
# python2
value_type = basestring
except NameError:
# python 3
value_type = str
if isinstance(value, value_type):
# Str/Unicode needs to have quotes
fp.write(u'%s = "%s"\n' % (key, value))
else:
# Int/Bool/List use __str__
fp.write('%s = %s\n' % (key, value))
|
import logging
from tornado.options import options
from datetime import datetime
def save_config():
logging.info("Saving current config to: %s" % options.config)
with open(options.config, 'w') as fp:
fp.write("##########################")
fp.write(" Root the Box Config File ")
fp.write("##########################\n")
fp.write("# Documentation: %s\n" % "https://github.com/moloch--/RootTheBox/wiki/Configuration-File-Details")
fp.write("# Last updated: %s\n" % datetime.now())
for group in options.groups():
# Shitty work around for Tornado 4.1
if 'rootthebox.py' in group.lower() or group == '':
continue
fp.write("\n# [ %s ]\n" % group.title())
try:
# python2
opt = options.group_dict(group).iteritems()
except AttributeError:
# python3
opt = options.group_dict(group).items()
for key, value in opt:
try:
# python2
value_type = basestring
except NameError:
# python 3
value_type = str
if isinstance(value, value_type):
# Str/Unicode needs to have quotes
fp.write(u'%s = "%s"\n' % (key, value))
else:
# Int/Bool/List use __str__
fp.write('%s = %s\n' % (key, value))
| Add documenation link to config file | Add documenation link to config file
| Python | apache-2.0 | moloch--/RootTheBox,moloch--/RootTheBox,moloch--/RootTheBox,moloch--/RootTheBox |
import logging
from tornado.options import options
from datetime import datetime
def save_config():
logging.info("Saving current config to: %s" % options.config)
with open(options.config, 'w') as fp:
fp.write("##########################")
fp.write(" Root the Box Config File ")
fp.write("##########################\n")
fp.write("# Last updated: %s\n" % datetime.now())
for group in options.groups():
# Shitty work around for Tornado 4.1
if 'rootthebox.py' in group.lower() or group == '':
continue
fp.write("\n# [ %s ]\n" % group.title())
try:
# python2
opt = options.group_dict(group).iteritems()
except AttributeError:
# python3
opt = options.group_dict(group).items()
for key, value in opt:
try:
# python2
value_type = basestring
except NameError:
# python 3
value_type = str
if isinstance(value, value_type):
# Str/Unicode needs to have quotes
fp.write(u'%s = "%s"\n' % (key, value))
else:
# Int/Bool/List use __str__
fp.write('%s = %s\n' % (key, value))
Add documenation link to config file |
import logging
from tornado.options import options
from datetime import datetime
def save_config():
logging.info("Saving current config to: %s" % options.config)
with open(options.config, 'w') as fp:
fp.write("##########################")
fp.write(" Root the Box Config File ")
fp.write("##########################\n")
fp.write("# Documentation: %s\n" % "https://github.com/moloch--/RootTheBox/wiki/Configuration-File-Details")
fp.write("# Last updated: %s\n" % datetime.now())
for group in options.groups():
# Shitty work around for Tornado 4.1
if 'rootthebox.py' in group.lower() or group == '':
continue
fp.write("\n# [ %s ]\n" % group.title())
try:
# python2
opt = options.group_dict(group).iteritems()
except AttributeError:
# python3
opt = options.group_dict(group).items()
for key, value in opt:
try:
# python2
value_type = basestring
except NameError:
# python 3
value_type = str
if isinstance(value, value_type):
# Str/Unicode needs to have quotes
fp.write(u'%s = "%s"\n' % (key, value))
else:
# Int/Bool/List use __str__
fp.write('%s = %s\n' % (key, value))
| <commit_before>
import logging
from tornado.options import options
from datetime import datetime
def save_config():
logging.info("Saving current config to: %s" % options.config)
with open(options.config, 'w') as fp:
fp.write("##########################")
fp.write(" Root the Box Config File ")
fp.write("##########################\n")
fp.write("# Last updated: %s\n" % datetime.now())
for group in options.groups():
# Shitty work around for Tornado 4.1
if 'rootthebox.py' in group.lower() or group == '':
continue
fp.write("\n# [ %s ]\n" % group.title())
try:
# python2
opt = options.group_dict(group).iteritems()
except AttributeError:
# python3
opt = options.group_dict(group).items()
for key, value in opt:
try:
# python2
value_type = basestring
except NameError:
# python 3
value_type = str
if isinstance(value, value_type):
# Str/Unicode needs to have quotes
fp.write(u'%s = "%s"\n' % (key, value))
else:
# Int/Bool/List use __str__
fp.write('%s = %s\n' % (key, value))
<commit_msg>Add documenation link to config file<commit_after> |
import logging
from tornado.options import options
from datetime import datetime
def save_config():
logging.info("Saving current config to: %s" % options.config)
with open(options.config, 'w') as fp:
fp.write("##########################")
fp.write(" Root the Box Config File ")
fp.write("##########################\n")
fp.write("# Documentation: %s\n" % "https://github.com/moloch--/RootTheBox/wiki/Configuration-File-Details")
fp.write("# Last updated: %s\n" % datetime.now())
for group in options.groups():
# Shitty work around for Tornado 4.1
if 'rootthebox.py' in group.lower() or group == '':
continue
fp.write("\n# [ %s ]\n" % group.title())
try:
# python2
opt = options.group_dict(group).iteritems()
except AttributeError:
# python3
opt = options.group_dict(group).items()
for key, value in opt:
try:
# python2
value_type = basestring
except NameError:
# python 3
value_type = str
if isinstance(value, value_type):
# Str/Unicode needs to have quotes
fp.write(u'%s = "%s"\n' % (key, value))
else:
# Int/Bool/List use __str__
fp.write('%s = %s\n' % (key, value))
|
import logging
from tornado.options import options
from datetime import datetime
def save_config():
logging.info("Saving current config to: %s" % options.config)
with open(options.config, 'w') as fp:
fp.write("##########################")
fp.write(" Root the Box Config File ")
fp.write("##########################\n")
fp.write("# Last updated: %s\n" % datetime.now())
for group in options.groups():
# Shitty work around for Tornado 4.1
if 'rootthebox.py' in group.lower() or group == '':
continue
fp.write("\n# [ %s ]\n" % group.title())
try:
# python2
opt = options.group_dict(group).iteritems()
except AttributeError:
# python3
opt = options.group_dict(group).items()
for key, value in opt:
try:
# python2
value_type = basestring
except NameError:
# python 3
value_type = str
if isinstance(value, value_type):
# Str/Unicode needs to have quotes
fp.write(u'%s = "%s"\n' % (key, value))
else:
# Int/Bool/List use __str__
fp.write('%s = %s\n' % (key, value))
Add documenation link to config file
import logging
from tornado.options import options
from datetime import datetime
def save_config():
logging.info("Saving current config to: %s" % options.config)
with open(options.config, 'w') as fp:
fp.write("##########################")
fp.write(" Root the Box Config File ")
fp.write("##########################\n")
fp.write("# Documentation: %s\n" % "https://github.com/moloch--/RootTheBox/wiki/Configuration-File-Details")
fp.write("# Last updated: %s\n" % datetime.now())
for group in options.groups():
# Shitty work around for Tornado 4.1
if 'rootthebox.py' in group.lower() or group == '':
continue
fp.write("\n# [ %s ]\n" % group.title())
try:
# python2
opt = options.group_dict(group).iteritems()
except AttributeError:
# python3
opt = options.group_dict(group).items()
for key, value in opt:
try:
# python2
value_type = basestring
except NameError:
# python 3
value_type = str
if isinstance(value, value_type):
# Str/Unicode needs to have quotes
fp.write(u'%s = "%s"\n' % (key, value))
else:
# Int/Bool/List use __str__
fp.write('%s = %s\n' % (key, value))
| <commit_before>
import logging
from tornado.options import options
from datetime import datetime
def save_config():
logging.info("Saving current config to: %s" % options.config)
with open(options.config, 'w') as fp:
fp.write("##########################")
fp.write(" Root the Box Config File ")
fp.write("##########################\n")
fp.write("# Last updated: %s\n" % datetime.now())
for group in options.groups():
# Shitty work around for Tornado 4.1
if 'rootthebox.py' in group.lower() or group == '':
continue
fp.write("\n# [ %s ]\n" % group.title())
try:
# python2
opt = options.group_dict(group).iteritems()
except AttributeError:
# python3
opt = options.group_dict(group).items()
for key, value in opt:
try:
# python2
value_type = basestring
except NameError:
# python 3
value_type = str
if isinstance(value, value_type):
# Str/Unicode needs to have quotes
fp.write(u'%s = "%s"\n' % (key, value))
else:
# Int/Bool/List use __str__
fp.write('%s = %s\n' % (key, value))
<commit_msg>Add documenation link to config file<commit_after>
import logging
from tornado.options import options
from datetime import datetime
def save_config():
logging.info("Saving current config to: %s" % options.config)
with open(options.config, 'w') as fp:
fp.write("##########################")
fp.write(" Root the Box Config File ")
fp.write("##########################\n")
fp.write("# Documentation: %s\n" % "https://github.com/moloch--/RootTheBox/wiki/Configuration-File-Details")
fp.write("# Last updated: %s\n" % datetime.now())
for group in options.groups():
# Shitty work around for Tornado 4.1
if 'rootthebox.py' in group.lower() or group == '':
continue
fp.write("\n# [ %s ]\n" % group.title())
try:
# python2
opt = options.group_dict(group).iteritems()
except AttributeError:
# python3
opt = options.group_dict(group).items()
for key, value in opt:
try:
# python2
value_type = basestring
except NameError:
# python 3
value_type = str
if isinstance(value, value_type):
# Str/Unicode needs to have quotes
fp.write(u'%s = "%s"\n' % (key, value))
else:
# Int/Bool/List use __str__
fp.write('%s = %s\n' % (key, value))
|
6b183d7541dddc7531b3a37e8550952ec1b12dca | go/apps/urls.py | go/apps/urls.py | from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns('',
url(r'^survey/',
include('go.apps.surveys.urls', namespace='survey')),
url(r'^multi_survey/',
include('go.apps.multi_surveys.urls', namespace='multi_survey')),
url(r'^bulk_message/',
include('go.apps.bulk_message.urls', namespace='bulk_message')),
url(r'^opt_out/',
include('go.apps.opt_out.urls', namespace='opt_out')),
url(r'^sequential_send/',
include('go.apps.sequential_send.urls', namespace='sequential_send')),
url(r'^subscription/',
include('go.apps.subscription.urls', namespace='subscription')),
url(r'^wikipedia_ussd/',
include('go.apps.wikipedia.ussd.urls', namespace='wikipedia_ussd')),
url(r'^wikipedia_sms/',
include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')),
url(r'^jsbox/',
include('go.apps.jsbos.urls', namespace='jsbox')),
)
| from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns('',
url(r'^survey/',
include('go.apps.surveys.urls', namespace='survey')),
url(r'^multi_survey/',
include('go.apps.multi_surveys.urls', namespace='multi_survey')),
url(r'^bulk_message/',
include('go.apps.bulk_message.urls', namespace='bulk_message')),
url(r'^opt_out/',
include('go.apps.opt_out.urls', namespace='opt_out')),
url(r'^sequential_send/',
include('go.apps.sequential_send.urls', namespace='sequential_send')),
url(r'^subscription/',
include('go.apps.subscription.urls', namespace='subscription')),
url(r'^wikipedia_ussd/',
include('go.apps.wikipedia.ussd.urls', namespace='wikipedia_ussd')),
url(r'^wikipedia_sms/',
include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')),
url(r'^jsbox/',
include('go.apps.jsbox.urls', namespace='jsbox')),
)
| Fix typo in jsbox URLs. | Fix typo in jsbox URLs.
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns('',
url(r'^survey/',
include('go.apps.surveys.urls', namespace='survey')),
url(r'^multi_survey/',
include('go.apps.multi_surveys.urls', namespace='multi_survey')),
url(r'^bulk_message/',
include('go.apps.bulk_message.urls', namespace='bulk_message')),
url(r'^opt_out/',
include('go.apps.opt_out.urls', namespace='opt_out')),
url(r'^sequential_send/',
include('go.apps.sequential_send.urls', namespace='sequential_send')),
url(r'^subscription/',
include('go.apps.subscription.urls', namespace='subscription')),
url(r'^wikipedia_ussd/',
include('go.apps.wikipedia.ussd.urls', namespace='wikipedia_ussd')),
url(r'^wikipedia_sms/',
include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')),
url(r'^jsbox/',
include('go.apps.jsbos.urls', namespace='jsbox')),
)
Fix typo in jsbox URLs. | from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns('',
url(r'^survey/',
include('go.apps.surveys.urls', namespace='survey')),
url(r'^multi_survey/',
include('go.apps.multi_surveys.urls', namespace='multi_survey')),
url(r'^bulk_message/',
include('go.apps.bulk_message.urls', namespace='bulk_message')),
url(r'^opt_out/',
include('go.apps.opt_out.urls', namespace='opt_out')),
url(r'^sequential_send/',
include('go.apps.sequential_send.urls', namespace='sequential_send')),
url(r'^subscription/',
include('go.apps.subscription.urls', namespace='subscription')),
url(r'^wikipedia_ussd/',
include('go.apps.wikipedia.ussd.urls', namespace='wikipedia_ussd')),
url(r'^wikipedia_sms/',
include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')),
url(r'^jsbox/',
include('go.apps.jsbox.urls', namespace='jsbox')),
)
| <commit_before>from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns('',
url(r'^survey/',
include('go.apps.surveys.urls', namespace='survey')),
url(r'^multi_survey/',
include('go.apps.multi_surveys.urls', namespace='multi_survey')),
url(r'^bulk_message/',
include('go.apps.bulk_message.urls', namespace='bulk_message')),
url(r'^opt_out/',
include('go.apps.opt_out.urls', namespace='opt_out')),
url(r'^sequential_send/',
include('go.apps.sequential_send.urls', namespace='sequential_send')),
url(r'^subscription/',
include('go.apps.subscription.urls', namespace='subscription')),
url(r'^wikipedia_ussd/',
include('go.apps.wikipedia.ussd.urls', namespace='wikipedia_ussd')),
url(r'^wikipedia_sms/',
include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')),
url(r'^jsbox/',
include('go.apps.jsbos.urls', namespace='jsbox')),
)
<commit_msg>Fix typo in jsbox URLs.<commit_after> | from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns('',
url(r'^survey/',
include('go.apps.surveys.urls', namespace='survey')),
url(r'^multi_survey/',
include('go.apps.multi_surveys.urls', namespace='multi_survey')),
url(r'^bulk_message/',
include('go.apps.bulk_message.urls', namespace='bulk_message')),
url(r'^opt_out/',
include('go.apps.opt_out.urls', namespace='opt_out')),
url(r'^sequential_send/',
include('go.apps.sequential_send.urls', namespace='sequential_send')),
url(r'^subscription/',
include('go.apps.subscription.urls', namespace='subscription')),
url(r'^wikipedia_ussd/',
include('go.apps.wikipedia.ussd.urls', namespace='wikipedia_ussd')),
url(r'^wikipedia_sms/',
include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')),
url(r'^jsbox/',
include('go.apps.jsbox.urls', namespace='jsbox')),
)
| from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns('',
url(r'^survey/',
include('go.apps.surveys.urls', namespace='survey')),
url(r'^multi_survey/',
include('go.apps.multi_surveys.urls', namespace='multi_survey')),
url(r'^bulk_message/',
include('go.apps.bulk_message.urls', namespace='bulk_message')),
url(r'^opt_out/',
include('go.apps.opt_out.urls', namespace='opt_out')),
url(r'^sequential_send/',
include('go.apps.sequential_send.urls', namespace='sequential_send')),
url(r'^subscription/',
include('go.apps.subscription.urls', namespace='subscription')),
url(r'^wikipedia_ussd/',
include('go.apps.wikipedia.ussd.urls', namespace='wikipedia_ussd')),
url(r'^wikipedia_sms/',
include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')),
url(r'^jsbox/',
include('go.apps.jsbos.urls', namespace='jsbox')),
)
Fix typo in jsbox URLs.from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns('',
url(r'^survey/',
include('go.apps.surveys.urls', namespace='survey')),
url(r'^multi_survey/',
include('go.apps.multi_surveys.urls', namespace='multi_survey')),
url(r'^bulk_message/',
include('go.apps.bulk_message.urls', namespace='bulk_message')),
url(r'^opt_out/',
include('go.apps.opt_out.urls', namespace='opt_out')),
url(r'^sequential_send/',
include('go.apps.sequential_send.urls', namespace='sequential_send')),
url(r'^subscription/',
include('go.apps.subscription.urls', namespace='subscription')),
url(r'^wikipedia_ussd/',
include('go.apps.wikipedia.ussd.urls', namespace='wikipedia_ussd')),
url(r'^wikipedia_sms/',
include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')),
url(r'^jsbox/',
include('go.apps.jsbox.urls', namespace='jsbox')),
)
| <commit_before>from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns('',
url(r'^survey/',
include('go.apps.surveys.urls', namespace='survey')),
url(r'^multi_survey/',
include('go.apps.multi_surveys.urls', namespace='multi_survey')),
url(r'^bulk_message/',
include('go.apps.bulk_message.urls', namespace='bulk_message')),
url(r'^opt_out/',
include('go.apps.opt_out.urls', namespace='opt_out')),
url(r'^sequential_send/',
include('go.apps.sequential_send.urls', namespace='sequential_send')),
url(r'^subscription/',
include('go.apps.subscription.urls', namespace='subscription')),
url(r'^wikipedia_ussd/',
include('go.apps.wikipedia.ussd.urls', namespace='wikipedia_ussd')),
url(r'^wikipedia_sms/',
include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')),
url(r'^jsbox/',
include('go.apps.jsbos.urls', namespace='jsbox')),
)
<commit_msg>Fix typo in jsbox URLs.<commit_after>from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns('',
url(r'^survey/',
include('go.apps.surveys.urls', namespace='survey')),
url(r'^multi_survey/',
include('go.apps.multi_surveys.urls', namespace='multi_survey')),
url(r'^bulk_message/',
include('go.apps.bulk_message.urls', namespace='bulk_message')),
url(r'^opt_out/',
include('go.apps.opt_out.urls', namespace='opt_out')),
url(r'^sequential_send/',
include('go.apps.sequential_send.urls', namespace='sequential_send')),
url(r'^subscription/',
include('go.apps.subscription.urls', namespace='subscription')),
url(r'^wikipedia_ussd/',
include('go.apps.wikipedia.ussd.urls', namespace='wikipedia_ussd')),
url(r'^wikipedia_sms/',
include('go.apps.wikipedia.sms.urls', namespace='wikipedia_sms')),
url(r'^jsbox/',
include('go.apps.jsbox.urls', namespace='jsbox')),
)
|
6269ebe131405b444976d5d8108112ec5f8dccd5 | python/animationBase.py | python/animationBase.py | #!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball
rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)
numRows = 16
height = ledMatrix.height
width = ledMatrix.width
ball = Ball(5, 9)
try:
print "Press Ctrl + C to stop executing"
while True:
nextFrame = ledMatrix.CreateFrameCanvas()
ball.updateValues(0.1)
ball.drawOnMatrix(nextFrame)
ledMatrix.SwapOnVSync(nextFrame)
time.sleep(0.1)
except KeyboardInterrupt:
print "Exiting\n"
sys.exit(0) | #!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball
rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)
numRows = 16
height = ledMatrix.height
width = ledMatrix.width
ball = Ball(5, 9, 4)
try:
print "Press Ctrl + C to stop executing"
while True:
nextFrame = ledMatrix.CreateFrameCanvas()
ball.updateValues(1 / 60)
ball.drawOnMatrix(nextFrame)
ledMatrix.SwapOnVSync(nextFrame)
time.sleep(1 / 60)
except KeyboardInterrupt:
print "Exiting\n"
sys.exit(0) | Set framerate to 60 fps | Set framerate to 60 fps
| Python | mit | DarkAce65/rpi-led-matrix,DarkAce65/rpi-led-matrix | #!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball
rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)
numRows = 16
height = ledMatrix.height
width = ledMatrix.width
ball = Ball(5, 9)
try:
print "Press Ctrl + C to stop executing"
while True:
nextFrame = ledMatrix.CreateFrameCanvas()
ball.updateValues(0.1)
ball.drawOnMatrix(nextFrame)
ledMatrix.SwapOnVSync(nextFrame)
time.sleep(0.1)
except KeyboardInterrupt:
print "Exiting\n"
sys.exit(0)Set framerate to 60 fps | #!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball
rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)
numRows = 16
height = ledMatrix.height
width = ledMatrix.width
ball = Ball(5, 9, 4)
try:
print "Press Ctrl + C to stop executing"
while True:
nextFrame = ledMatrix.CreateFrameCanvas()
ball.updateValues(1 / 60)
ball.drawOnMatrix(nextFrame)
ledMatrix.SwapOnVSync(nextFrame)
time.sleep(1 / 60)
except KeyboardInterrupt:
print "Exiting\n"
sys.exit(0) | <commit_before>#!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball
rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)
numRows = 16
height = ledMatrix.height
width = ledMatrix.width
ball = Ball(5, 9)
try:
print "Press Ctrl + C to stop executing"
while True:
nextFrame = ledMatrix.CreateFrameCanvas()
ball.updateValues(0.1)
ball.drawOnMatrix(nextFrame)
ledMatrix.SwapOnVSync(nextFrame)
time.sleep(0.1)
except KeyboardInterrupt:
print "Exiting\n"
sys.exit(0)<commit_msg>Set framerate to 60 fps<commit_after> | #!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball
rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)
numRows = 16
height = ledMatrix.height
width = ledMatrix.width
ball = Ball(5, 9, 4)
try:
print "Press Ctrl + C to stop executing"
while True:
nextFrame = ledMatrix.CreateFrameCanvas()
ball.updateValues(1 / 60)
ball.drawOnMatrix(nextFrame)
ledMatrix.SwapOnVSync(nextFrame)
time.sleep(1 / 60)
except KeyboardInterrupt:
print "Exiting\n"
sys.exit(0) | #!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball
rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)
numRows = 16
height = ledMatrix.height
width = ledMatrix.width
ball = Ball(5, 9)
try:
print "Press Ctrl + C to stop executing"
while True:
nextFrame = ledMatrix.CreateFrameCanvas()
ball.updateValues(0.1)
ball.drawOnMatrix(nextFrame)
ledMatrix.SwapOnVSync(nextFrame)
time.sleep(0.1)
except KeyboardInterrupt:
print "Exiting\n"
sys.exit(0)Set framerate to 60 fps#!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball
rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)
numRows = 16
height = ledMatrix.height
width = ledMatrix.width
ball = Ball(5, 9, 4)
try:
print "Press Ctrl + C to stop executing"
while True:
nextFrame = ledMatrix.CreateFrameCanvas()
ball.updateValues(1 / 60)
ball.drawOnMatrix(nextFrame)
ledMatrix.SwapOnVSync(nextFrame)
time.sleep(1 / 60)
except KeyboardInterrupt:
print "Exiting\n"
sys.exit(0) | <commit_before>#!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball
rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)
numRows = 16
height = ledMatrix.height
width = ledMatrix.width
ball = Ball(5, 9)
try:
print "Press Ctrl + C to stop executing"
while True:
nextFrame = ledMatrix.CreateFrameCanvas()
ball.updateValues(0.1)
ball.drawOnMatrix(nextFrame)
ledMatrix.SwapOnVSync(nextFrame)
time.sleep(0.1)
except KeyboardInterrupt:
print "Exiting\n"
sys.exit(0)<commit_msg>Set framerate to 60 fps<commit_after>#!/usr/bin/env python
from rgbmatrix import RGBMatrix
import sys, time
from ball import Ball
rows = 16
chains = 1
parallel = 1
ledMatrix = RGBMatrix(rows, chains, parallel)
numRows = 16
height = ledMatrix.height
width = ledMatrix.width
ball = Ball(5, 9, 4)
try:
print "Press Ctrl + C to stop executing"
while True:
nextFrame = ledMatrix.CreateFrameCanvas()
ball.updateValues(1 / 60)
ball.drawOnMatrix(nextFrame)
ledMatrix.SwapOnVSync(nextFrame)
time.sleep(1 / 60)
except KeyboardInterrupt:
print "Exiting\n"
sys.exit(0) |
a400c0bee935df7ee19766b04af0e57a655437fd | {{cookiecutter.app_name}}/setup.py | {{cookiecutter.app_name}}/setup.py | import os
from setuptools import setup, find_packages
import uuid
from {{cookiecutter.app_name}} import __version__ as version_string
requirements_path = os.path.join(
os.path.dirname(__file__),
'requirements.txt',
)
try:
from pip.req import parse_requirements
requirements = [
str(req.req) for req in parse_requirements(
requirements_path,
session=uuid.uuid1()
)
]
except (ImportError, AttributeError, ValueError, TypeError):
requirements = []
with open(requirements_path, 'r') as in_:
requirements = [
req for req in in_.readlines()
if not req.startswith('-')
and not req.startswith('#')
]
setup(
name='{{cookiecutter.app_name}}',
version=version_string,
url='https://github.com/{{cookiecutter.github_username}}/{{cookiecutter.repo_name}}',
description="{{cookiecutter.project_short_description}}",
author='{{cookiecutter.full_name}}',
author_email='{{cookiecutter.email}}',
classifiers=[
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
],
install_requires=requirements,
include_package_data=True,
packages=find_packages(),
entry_points={
'{{cookiecutter.app_name}}': [
'{{cookiecutter.plugin_name}} = {{cookiecutter.app_name}}.plugin:Plugin',
]
},
)
| import os
from setuptools import setup, find_packages
import uuid
from {{cookiecutter.app_name}} import __version__ as version_string
requirements_path = os.path.join(
os.path.dirname(__file__),
'requirements.txt',
)
try:
from pip.req import parse_requirements
requirements = [
str(req.req) for req in parse_requirements(
requirements_path,
session=uuid.uuid1()
)
]
except (ImportError, AttributeError, ValueError, TypeError):
requirements = []
with open(requirements_path, 'r') as in_:
requirements = [
req for req in in_.readlines()
if not req.startswith('-')
and not req.startswith('#')
]
setup(
name='{{cookiecutter.app_name}}',
version=version_string,
url='https://github.com/{{cookiecutter.github_username}}/{{cookiecutter.repo_name}}',
description="{{cookiecutter.project_short_description}}",
author='{{cookiecutter.full_name}}',
author_email='{{cookiecutter.email}}',
classifiers=[
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
],
install_requires=requirements,
include_package_data=True,
packages=find_packages(),
entry_points={
'jirafs_plugins': [
'{{cookiecutter.plugin_name}} = {{cookiecutter.app_name}}.plugin:Plugin',
]
},
)
| Use the proper entrypoint name. | Use the proper entrypoint name.
| Python | mit | coddingtonbear/cookiecutter-jirafs-plugin | import os
from setuptools import setup, find_packages
import uuid
from {{cookiecutter.app_name}} import __version__ as version_string
requirements_path = os.path.join(
os.path.dirname(__file__),
'requirements.txt',
)
try:
from pip.req import parse_requirements
requirements = [
str(req.req) for req in parse_requirements(
requirements_path,
session=uuid.uuid1()
)
]
except (ImportError, AttributeError, ValueError, TypeError):
requirements = []
with open(requirements_path, 'r') as in_:
requirements = [
req for req in in_.readlines()
if not req.startswith('-')
and not req.startswith('#')
]
setup(
name='{{cookiecutter.app_name}}',
version=version_string,
url='https://github.com/{{cookiecutter.github_username}}/{{cookiecutter.repo_name}}',
description="{{cookiecutter.project_short_description}}",
author='{{cookiecutter.full_name}}',
author_email='{{cookiecutter.email}}',
classifiers=[
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
],
install_requires=requirements,
include_package_data=True,
packages=find_packages(),
entry_points={
'{{cookiecutter.app_name}}': [
'{{cookiecutter.plugin_name}} = {{cookiecutter.app_name}}.plugin:Plugin',
]
},
)
Use the proper entrypoint name. | import os
from setuptools import setup, find_packages
import uuid
from {{cookiecutter.app_name}} import __version__ as version_string
requirements_path = os.path.join(
os.path.dirname(__file__),
'requirements.txt',
)
try:
from pip.req import parse_requirements
requirements = [
str(req.req) for req in parse_requirements(
requirements_path,
session=uuid.uuid1()
)
]
except (ImportError, AttributeError, ValueError, TypeError):
requirements = []
with open(requirements_path, 'r') as in_:
requirements = [
req for req in in_.readlines()
if not req.startswith('-')
and not req.startswith('#')
]
setup(
name='{{cookiecutter.app_name}}',
version=version_string,
url='https://github.com/{{cookiecutter.github_username}}/{{cookiecutter.repo_name}}',
description="{{cookiecutter.project_short_description}}",
author='{{cookiecutter.full_name}}',
author_email='{{cookiecutter.email}}',
classifiers=[
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
],
install_requires=requirements,
include_package_data=True,
packages=find_packages(),
entry_points={
'jirafs_plugins': [
'{{cookiecutter.plugin_name}} = {{cookiecutter.app_name}}.plugin:Plugin',
]
},
)
| <commit_before>import os
from setuptools import setup, find_packages
import uuid
from {{cookiecutter.app_name}} import __version__ as version_string
requirements_path = os.path.join(
os.path.dirname(__file__),
'requirements.txt',
)
try:
from pip.req import parse_requirements
requirements = [
str(req.req) for req in parse_requirements(
requirements_path,
session=uuid.uuid1()
)
]
except (ImportError, AttributeError, ValueError, TypeError):
requirements = []
with open(requirements_path, 'r') as in_:
requirements = [
req for req in in_.readlines()
if not req.startswith('-')
and not req.startswith('#')
]
setup(
name='{{cookiecutter.app_name}}',
version=version_string,
url='https://github.com/{{cookiecutter.github_username}}/{{cookiecutter.repo_name}}',
description="{{cookiecutter.project_short_description}}",
author='{{cookiecutter.full_name}}',
author_email='{{cookiecutter.email}}',
classifiers=[
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
],
install_requires=requirements,
include_package_data=True,
packages=find_packages(),
entry_points={
'{{cookiecutter.app_name}}': [
'{{cookiecutter.plugin_name}} = {{cookiecutter.app_name}}.plugin:Plugin',
]
},
)
<commit_msg>Use the proper entrypoint name.<commit_after> | import os
from setuptools import setup, find_packages
import uuid
from {{cookiecutter.app_name}} import __version__ as version_string
requirements_path = os.path.join(
os.path.dirname(__file__),
'requirements.txt',
)
try:
from pip.req import parse_requirements
requirements = [
str(req.req) for req in parse_requirements(
requirements_path,
session=uuid.uuid1()
)
]
except (ImportError, AttributeError, ValueError, TypeError):
requirements = []
with open(requirements_path, 'r') as in_:
requirements = [
req for req in in_.readlines()
if not req.startswith('-')
and not req.startswith('#')
]
setup(
name='{{cookiecutter.app_name}}',
version=version_string,
url='https://github.com/{{cookiecutter.github_username}}/{{cookiecutter.repo_name}}',
description="{{cookiecutter.project_short_description}}",
author='{{cookiecutter.full_name}}',
author_email='{{cookiecutter.email}}',
classifiers=[
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
],
install_requires=requirements,
include_package_data=True,
packages=find_packages(),
entry_points={
'jirafs_plugins': [
'{{cookiecutter.plugin_name}} = {{cookiecutter.app_name}}.plugin:Plugin',
]
},
)
| import os
from setuptools import setup, find_packages
import uuid
from {{cookiecutter.app_name}} import __version__ as version_string
requirements_path = os.path.join(
os.path.dirname(__file__),
'requirements.txt',
)
try:
from pip.req import parse_requirements
requirements = [
str(req.req) for req in parse_requirements(
requirements_path,
session=uuid.uuid1()
)
]
except (ImportError, AttributeError, ValueError, TypeError):
requirements = []
with open(requirements_path, 'r') as in_:
requirements = [
req for req in in_.readlines()
if not req.startswith('-')
and not req.startswith('#')
]
setup(
name='{{cookiecutter.app_name}}',
version=version_string,
url='https://github.com/{{cookiecutter.github_username}}/{{cookiecutter.repo_name}}',
description="{{cookiecutter.project_short_description}}",
author='{{cookiecutter.full_name}}',
author_email='{{cookiecutter.email}}',
classifiers=[
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
],
install_requires=requirements,
include_package_data=True,
packages=find_packages(),
entry_points={
'{{cookiecutter.app_name}}': [
'{{cookiecutter.plugin_name}} = {{cookiecutter.app_name}}.plugin:Plugin',
]
},
)
Use the proper entrypoint name.import os
from setuptools import setup, find_packages
import uuid
from {{cookiecutter.app_name}} import __version__ as version_string
requirements_path = os.path.join(
os.path.dirname(__file__),
'requirements.txt',
)
try:
from pip.req import parse_requirements
requirements = [
str(req.req) for req in parse_requirements(
requirements_path,
session=uuid.uuid1()
)
]
except (ImportError, AttributeError, ValueError, TypeError):
requirements = []
with open(requirements_path, 'r') as in_:
requirements = [
req for req in in_.readlines()
if not req.startswith('-')
and not req.startswith('#')
]
setup(
name='{{cookiecutter.app_name}}',
version=version_string,
url='https://github.com/{{cookiecutter.github_username}}/{{cookiecutter.repo_name}}',
description="{{cookiecutter.project_short_description}}",
author='{{cookiecutter.full_name}}',
author_email='{{cookiecutter.email}}',
classifiers=[
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
],
install_requires=requirements,
include_package_data=True,
packages=find_packages(),
entry_points={
'jirafs_plugins': [
'{{cookiecutter.plugin_name}} = {{cookiecutter.app_name}}.plugin:Plugin',
]
},
)
| <commit_before>import os
from setuptools import setup, find_packages
import uuid
from {{cookiecutter.app_name}} import __version__ as version_string
requirements_path = os.path.join(
os.path.dirname(__file__),
'requirements.txt',
)
try:
from pip.req import parse_requirements
requirements = [
str(req.req) for req in parse_requirements(
requirements_path,
session=uuid.uuid1()
)
]
except (ImportError, AttributeError, ValueError, TypeError):
requirements = []
with open(requirements_path, 'r') as in_:
requirements = [
req for req in in_.readlines()
if not req.startswith('-')
and not req.startswith('#')
]
setup(
name='{{cookiecutter.app_name}}',
version=version_string,
url='https://github.com/{{cookiecutter.github_username}}/{{cookiecutter.repo_name}}',
description="{{cookiecutter.project_short_description}}",
author='{{cookiecutter.full_name}}',
author_email='{{cookiecutter.email}}',
classifiers=[
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
],
install_requires=requirements,
include_package_data=True,
packages=find_packages(),
entry_points={
'{{cookiecutter.app_name}}': [
'{{cookiecutter.plugin_name}} = {{cookiecutter.app_name}}.plugin:Plugin',
]
},
)
<commit_msg>Use the proper entrypoint name.<commit_after>import os
from setuptools import setup, find_packages
import uuid
from {{cookiecutter.app_name}} import __version__ as version_string
requirements_path = os.path.join(
os.path.dirname(__file__),
'requirements.txt',
)
try:
from pip.req import parse_requirements
requirements = [
str(req.req) for req in parse_requirements(
requirements_path,
session=uuid.uuid1()
)
]
except (ImportError, AttributeError, ValueError, TypeError):
requirements = []
with open(requirements_path, 'r') as in_:
requirements = [
req for req in in_.readlines()
if not req.startswith('-')
and not req.startswith('#')
]
setup(
name='{{cookiecutter.app_name}}',
version=version_string,
url='https://github.com/{{cookiecutter.github_username}}/{{cookiecutter.repo_name}}',
description="{{cookiecutter.project_short_description}}",
author='{{cookiecutter.full_name}}',
author_email='{{cookiecutter.email}}',
classifiers=[
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
],
install_requires=requirements,
include_package_data=True,
packages=find_packages(),
entry_points={
'jirafs_plugins': [
'{{cookiecutter.plugin_name}} = {{cookiecutter.app_name}}.plugin:Plugin',
]
},
)
|
3ffd3eb8f32fbac7df0f6967b9d6f0437ff3a317 | movieman2/__init__.py | movieman2/__init__.py | import os
import tmdbsimple
tmdbsimple.API_KEY = os.environ['MM2_TMDB_API_KEY']
| import os
import tmdbsimple
from django.conf import settings
tmdbsimple.API_KEY = os.environ['MM2_TMDB_API_KEY'] or settings.MM2_TMDB_API_KEY
| Load API_KEY from django settings.py file as an alternative | Load API_KEY from django settings.py file as an alternative
| Python | mit | simon-andrews/movieman2,simon-andrews/movieman2 | import os
import tmdbsimple
tmdbsimple.API_KEY = os.environ['MM2_TMDB_API_KEY']
Load API_KEY from django settings.py file as an alternative | import os
import tmdbsimple
from django.conf import settings
tmdbsimple.API_KEY = os.environ['MM2_TMDB_API_KEY'] or settings.MM2_TMDB_API_KEY
| <commit_before>import os
import tmdbsimple
tmdbsimple.API_KEY = os.environ['MM2_TMDB_API_KEY']
<commit_msg>Load API_KEY from django settings.py file as an alternative<commit_after> | import os
import tmdbsimple
from django.conf import settings
tmdbsimple.API_KEY = os.environ['MM2_TMDB_API_KEY'] or settings.MM2_TMDB_API_KEY
| import os
import tmdbsimple
tmdbsimple.API_KEY = os.environ['MM2_TMDB_API_KEY']
Load API_KEY from django settings.py file as an alternativeimport os
import tmdbsimple
from django.conf import settings
tmdbsimple.API_KEY = os.environ['MM2_TMDB_API_KEY'] or settings.MM2_TMDB_API_KEY
| <commit_before>import os
import tmdbsimple
tmdbsimple.API_KEY = os.environ['MM2_TMDB_API_KEY']
<commit_msg>Load API_KEY from django settings.py file as an alternative<commit_after>import os
import tmdbsimple
from django.conf import settings
tmdbsimple.API_KEY = os.environ['MM2_TMDB_API_KEY'] or settings.MM2_TMDB_API_KEY
|
8cd29246d496cfbb45df15f0f4cfcca5ffc56630 | alg_bellman_ford_shortest_path.py | alg_bellman_ford_shortest_path.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def bellman_ford(w_graph_d, start_vertex):
"""Bellman-Ford algorithm for weighted / negative graph.
"""
pass
def main():
w_graph_d = {
's': {'a': 2, 'b': 6},
'a': {'b': 3, 'c': 1},
'b': {'a': -5, 'd': 2},
'c': {'b': 1, 'e': 4, 'f': 2},
'd': {'c': 3, 'f': 2},
'e': {},
'f': {'e': 1}
}
start_vertex = 's'
if __name__ == '__main__':
main()
| from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import numpy as np
def update_distance(v, v_neighbor, w_graph_d, previous_d):
if (distance_d[v_neighbor] >
distance_d[v] + w_graph_d[v][v_neighbor]):
distance_d[v_neighbor] = (
distance_d[v] + w_graph_d[v][v_neighbor])
previous_d[v_neighbor] = v
def bellman_ford(w_graph_d, start_vertex):
"""Bellman-Ford algorithm for weighted / negative graph."""
distance_d = {v: np.inf for v in w_graph_d.keys()}
previous_d = {v: None for v in w_graph_d.keys()}
n = len(w_graph_d.keys())
for i in xrange(1, n):
pass
def main():
w_graph_d = {
's': {'a': 2, 'b': 6},
'a': {'b': 3, 'c': 1},
'b': {'a': -5, 'd': 2},
'c': {'b': 1, 'e': 4, 'f': 2},
'd': {'c': 3, 'f': 2},
'e': {},
'f': {'e': 1}
}
start_vertex = 's'
if __name__ == '__main__':
main()
| Implement update_distance(), init setup for Bellman-Ford alg | Implement update_distance(), init setup for Bellman-Ford alg
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def bellman_ford(w_graph_d, start_vertex):
"""Bellman-Ford algorithm for weighted / negative graph.
"""
pass
def main():
w_graph_d = {
's': {'a': 2, 'b': 6},
'a': {'b': 3, 'c': 1},
'b': {'a': -5, 'd': 2},
'c': {'b': 1, 'e': 4, 'f': 2},
'd': {'c': 3, 'f': 2},
'e': {},
'f': {'e': 1}
}
start_vertex = 's'
if __name__ == '__main__':
main()
Implement update_distance(), init setup for Bellman-Ford alg | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import numpy as np
def update_distance(v, v_neighbor, w_graph_d, previous_d):
if (distance_d[v_neighbor] >
distance_d[v] + w_graph_d[v][v_neighbor]):
distance_d[v_neighbor] = (
distance_d[v] + w_graph_d[v][v_neighbor])
previous_d[v_neighbor] = v
def bellman_ford(w_graph_d, start_vertex):
"""Bellman-Ford algorithm for weighted / negative graph."""
distance_d = {v: np.inf for v in w_graph_d.keys()}
previous_d = {v: None for v in w_graph_d.keys()}
n = len(w_graph_d.keys())
for i in xrange(1, n):
pass
def main():
w_graph_d = {
's': {'a': 2, 'b': 6},
'a': {'b': 3, 'c': 1},
'b': {'a': -5, 'd': 2},
'c': {'b': 1, 'e': 4, 'f': 2},
'd': {'c': 3, 'f': 2},
'e': {},
'f': {'e': 1}
}
start_vertex = 's'
if __name__ == '__main__':
main()
| <commit_before>from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def bellman_ford(w_graph_d, start_vertex):
"""Bellman-Ford algorithm for weighted / negative graph.
"""
pass
def main():
w_graph_d = {
's': {'a': 2, 'b': 6},
'a': {'b': 3, 'c': 1},
'b': {'a': -5, 'd': 2},
'c': {'b': 1, 'e': 4, 'f': 2},
'd': {'c': 3, 'f': 2},
'e': {},
'f': {'e': 1}
}
start_vertex = 's'
if __name__ == '__main__':
main()
<commit_msg>Implement update_distance(), init setup for Bellman-Ford alg<commit_after> | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import numpy as np
def update_distance(v, v_neighbor, w_graph_d, previous_d):
if (distance_d[v_neighbor] >
distance_d[v] + w_graph_d[v][v_neighbor]):
distance_d[v_neighbor] = (
distance_d[v] + w_graph_d[v][v_neighbor])
previous_d[v_neighbor] = v
def bellman_ford(w_graph_d, start_vertex):
"""Bellman-Ford algorithm for weighted / negative graph."""
distance_d = {v: np.inf for v in w_graph_d.keys()}
previous_d = {v: None for v in w_graph_d.keys()}
n = len(w_graph_d.keys())
for i in xrange(1, n):
pass
def main():
w_graph_d = {
's': {'a': 2, 'b': 6},
'a': {'b': 3, 'c': 1},
'b': {'a': -5, 'd': 2},
'c': {'b': 1, 'e': 4, 'f': 2},
'd': {'c': 3, 'f': 2},
'e': {},
'f': {'e': 1}
}
start_vertex = 's'
if __name__ == '__main__':
main()
| from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def bellman_ford(w_graph_d, start_vertex):
"""Bellman-Ford algorithm for weighted / negative graph.
"""
pass
def main():
w_graph_d = {
's': {'a': 2, 'b': 6},
'a': {'b': 3, 'c': 1},
'b': {'a': -5, 'd': 2},
'c': {'b': 1, 'e': 4, 'f': 2},
'd': {'c': 3, 'f': 2},
'e': {},
'f': {'e': 1}
}
start_vertex = 's'
if __name__ == '__main__':
main()
Implement update_distance(), init setup for Bellman-Ford algfrom __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import numpy as np
def update_distance(v, v_neighbor, w_graph_d, previous_d):
if (distance_d[v_neighbor] >
distance_d[v] + w_graph_d[v][v_neighbor]):
distance_d[v_neighbor] = (
distance_d[v] + w_graph_d[v][v_neighbor])
previous_d[v_neighbor] = v
def bellman_ford(w_graph_d, start_vertex):
"""Bellman-Ford algorithm for weighted / negative graph."""
distance_d = {v: np.inf for v in w_graph_d.keys()}
previous_d = {v: None for v in w_graph_d.keys()}
n = len(w_graph_d.keys())
for i in xrange(1, n):
pass
def main():
w_graph_d = {
's': {'a': 2, 'b': 6},
'a': {'b': 3, 'c': 1},
'b': {'a': -5, 'd': 2},
'c': {'b': 1, 'e': 4, 'f': 2},
'd': {'c': 3, 'f': 2},
'e': {},
'f': {'e': 1}
}
start_vertex = 's'
if __name__ == '__main__':
main()
| <commit_before>from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def bellman_ford(w_graph_d, start_vertex):
"""Bellman-Ford algorithm for weighted / negative graph.
"""
pass
def main():
w_graph_d = {
's': {'a': 2, 'b': 6},
'a': {'b': 3, 'c': 1},
'b': {'a': -5, 'd': 2},
'c': {'b': 1, 'e': 4, 'f': 2},
'd': {'c': 3, 'f': 2},
'e': {},
'f': {'e': 1}
}
start_vertex = 's'
if __name__ == '__main__':
main()
<commit_msg>Implement update_distance(), init setup for Bellman-Ford alg<commit_after>from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import numpy as np
def update_distance(v, v_neighbor, w_graph_d, previous_d):
if (distance_d[v_neighbor] >
distance_d[v] + w_graph_d[v][v_neighbor]):
distance_d[v_neighbor] = (
distance_d[v] + w_graph_d[v][v_neighbor])
previous_d[v_neighbor] = v
def bellman_ford(w_graph_d, start_vertex):
"""Bellman-Ford algorithm for weighted / negative graph."""
distance_d = {v: np.inf for v in w_graph_d.keys()}
previous_d = {v: None for v in w_graph_d.keys()}
n = len(w_graph_d.keys())
for i in xrange(1, n):
pass
def main():
w_graph_d = {
's': {'a': 2, 'b': 6},
'a': {'b': 3, 'c': 1},
'b': {'a': -5, 'd': 2},
'c': {'b': 1, 'e': 4, 'f': 2},
'd': {'c': 3, 'f': 2},
'e': {},
'f': {'e': 1}
}
start_vertex = 's'
if __name__ == '__main__':
main()
|
d40ecbfdee31f690463e20189b2e7552dd8406dd | ping_publisher/run.py | ping_publisher/run.py | import time
import subprocess
from local_settings import *
import redis
redis_instance = redis.StrictRedis()
def iterate_all_destinations():
times = []
for dest in DESTINATIONS:
# TODO: different parameters for Linux
p = subprocess.Popen(["ping", "-c1", "-t2", dest], stdout=subprocess.PIPE)
p.wait()
(output, _) = p.communicate()
if p.returncode != 0:
continue
output = output.split("\n")
for line in output:
if "bytes from" in line:
line = line.split(" ")
for item in line:
if item.startswith("time="):
item = item.split("=")
times.append(float(item[1]))
message = None
if len(times) == 0:
message = "no_pings"
else:
message = min(times)
redis_instance.publish("home:broadcast:ping", message)
time.sleep(1)
if __name__ == '__main__':
while True:
iterate_all_destinations()
| import time
import subprocess
from local_settings import *
import redis
redis_instance = redis.StrictRedis()
def iterate_all_destinations():
times = []
for dest in DESTINATIONS:
# TODO: different parameters for Linux
p = subprocess.Popen(["ping", "-c1", "-t2", dest], stdout=subprocess.PIPE)
p.wait()
(output, _) = p.communicate()
if p.returncode != 0:
continue
output = output.split("\n")
for line in output:
if "bytes from" in line:
line = line.split(" ")
for item in line:
if item.startswith("time="):
item = item.split("=")
times.append(float(item[1]))
message = None
if len(times) == 0:
message = "no_pings"
else:
message = min(times)
redis_instance.publish("home:broadcast:ping", message)
if __name__ == '__main__':
while True:
iterate_all_destinations()
time.sleep(1)
| Handle sleeping in main loop | Handle sleeping in main loop
| Python | bsd-3-clause | ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display | import time
import subprocess
from local_settings import *
import redis
redis_instance = redis.StrictRedis()
def iterate_all_destinations():
times = []
for dest in DESTINATIONS:
# TODO: different parameters for Linux
p = subprocess.Popen(["ping", "-c1", "-t2", dest], stdout=subprocess.PIPE)
p.wait()
(output, _) = p.communicate()
if p.returncode != 0:
continue
output = output.split("\n")
for line in output:
if "bytes from" in line:
line = line.split(" ")
for item in line:
if item.startswith("time="):
item = item.split("=")
times.append(float(item[1]))
message = None
if len(times) == 0:
message = "no_pings"
else:
message = min(times)
redis_instance.publish("home:broadcast:ping", message)
time.sleep(1)
if __name__ == '__main__':
while True:
iterate_all_destinations()
Handle sleeping in main loop | import time
import subprocess
from local_settings import *
import redis
redis_instance = redis.StrictRedis()
def iterate_all_destinations():
times = []
for dest in DESTINATIONS:
# TODO: different parameters for Linux
p = subprocess.Popen(["ping", "-c1", "-t2", dest], stdout=subprocess.PIPE)
p.wait()
(output, _) = p.communicate()
if p.returncode != 0:
continue
output = output.split("\n")
for line in output:
if "bytes from" in line:
line = line.split(" ")
for item in line:
if item.startswith("time="):
item = item.split("=")
times.append(float(item[1]))
message = None
if len(times) == 0:
message = "no_pings"
else:
message = min(times)
redis_instance.publish("home:broadcast:ping", message)
if __name__ == '__main__':
while True:
iterate_all_destinations()
time.sleep(1)
| <commit_before>import time
import subprocess
from local_settings import *
import redis
redis_instance = redis.StrictRedis()
def iterate_all_destinations():
times = []
for dest in DESTINATIONS:
# TODO: different parameters for Linux
p = subprocess.Popen(["ping", "-c1", "-t2", dest], stdout=subprocess.PIPE)
p.wait()
(output, _) = p.communicate()
if p.returncode != 0:
continue
output = output.split("\n")
for line in output:
if "bytes from" in line:
line = line.split(" ")
for item in line:
if item.startswith("time="):
item = item.split("=")
times.append(float(item[1]))
message = None
if len(times) == 0:
message = "no_pings"
else:
message = min(times)
redis_instance.publish("home:broadcast:ping", message)
time.sleep(1)
if __name__ == '__main__':
while True:
iterate_all_destinations()
<commit_msg>Handle sleeping in main loop<commit_after> | import time
import subprocess
from local_settings import *
import redis
redis_instance = redis.StrictRedis()
def iterate_all_destinations():
times = []
for dest in DESTINATIONS:
# TODO: different parameters for Linux
p = subprocess.Popen(["ping", "-c1", "-t2", dest], stdout=subprocess.PIPE)
p.wait()
(output, _) = p.communicate()
if p.returncode != 0:
continue
output = output.split("\n")
for line in output:
if "bytes from" in line:
line = line.split(" ")
for item in line:
if item.startswith("time="):
item = item.split("=")
times.append(float(item[1]))
message = None
if len(times) == 0:
message = "no_pings"
else:
message = min(times)
redis_instance.publish("home:broadcast:ping", message)
if __name__ == '__main__':
while True:
iterate_all_destinations()
time.sleep(1)
| import time
import subprocess
from local_settings import *
import redis
redis_instance = redis.StrictRedis()
def iterate_all_destinations():
times = []
for dest in DESTINATIONS:
# TODO: different parameters for Linux
p = subprocess.Popen(["ping", "-c1", "-t2", dest], stdout=subprocess.PIPE)
p.wait()
(output, _) = p.communicate()
if p.returncode != 0:
continue
output = output.split("\n")
for line in output:
if "bytes from" in line:
line = line.split(" ")
for item in line:
if item.startswith("time="):
item = item.split("=")
times.append(float(item[1]))
message = None
if len(times) == 0:
message = "no_pings"
else:
message = min(times)
redis_instance.publish("home:broadcast:ping", message)
time.sleep(1)
if __name__ == '__main__':
while True:
iterate_all_destinations()
Handle sleeping in main loopimport time
import subprocess
from local_settings import *
import redis
redis_instance = redis.StrictRedis()
def iterate_all_destinations():
times = []
for dest in DESTINATIONS:
# TODO: different parameters for Linux
p = subprocess.Popen(["ping", "-c1", "-t2", dest], stdout=subprocess.PIPE)
p.wait()
(output, _) = p.communicate()
if p.returncode != 0:
continue
output = output.split("\n")
for line in output:
if "bytes from" in line:
line = line.split(" ")
for item in line:
if item.startswith("time="):
item = item.split("=")
times.append(float(item[1]))
message = None
if len(times) == 0:
message = "no_pings"
else:
message = min(times)
redis_instance.publish("home:broadcast:ping", message)
if __name__ == '__main__':
while True:
iterate_all_destinations()
time.sleep(1)
| <commit_before>import time
import subprocess
from local_settings import *
import redis
redis_instance = redis.StrictRedis()
def iterate_all_destinations():
times = []
for dest in DESTINATIONS:
# TODO: different parameters for Linux
p = subprocess.Popen(["ping", "-c1", "-t2", dest], stdout=subprocess.PIPE)
p.wait()
(output, _) = p.communicate()
if p.returncode != 0:
continue
output = output.split("\n")
for line in output:
if "bytes from" in line:
line = line.split(" ")
for item in line:
if item.startswith("time="):
item = item.split("=")
times.append(float(item[1]))
message = None
if len(times) == 0:
message = "no_pings"
else:
message = min(times)
redis_instance.publish("home:broadcast:ping", message)
time.sleep(1)
if __name__ == '__main__':
while True:
iterate_all_destinations()
<commit_msg>Handle sleeping in main loop<commit_after>import time
import subprocess
from local_settings import *
import redis
redis_instance = redis.StrictRedis()
def iterate_all_destinations():
times = []
for dest in DESTINATIONS:
# TODO: different parameters for Linux
p = subprocess.Popen(["ping", "-c1", "-t2", dest], stdout=subprocess.PIPE)
p.wait()
(output, _) = p.communicate()
if p.returncode != 0:
continue
output = output.split("\n")
for line in output:
if "bytes from" in line:
line = line.split(" ")
for item in line:
if item.startswith("time="):
item = item.split("=")
times.append(float(item[1]))
message = None
if len(times) == 0:
message = "no_pings"
else:
message = min(times)
redis_instance.publish("home:broadcast:ping", message)
if __name__ == '__main__':
while True:
iterate_all_destinations()
time.sleep(1)
|
5dc2ee040b5de973233ea04a310f7b6b3b0b9de9 | mangacork/__init__.py | mangacork/__init__.py | import logging
from flask import Flask
log = logging.getLogger(__name__)
app = Flask(__name__)
import mangacork.views
| import os
import logging
from flask import Flask
log = logging.getLogger(__name__)
app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])
import mangacork.views
| Add config for different env | Add config for different env
| Python | mit | ma3lstrom/manga-cork,ma3lstrom/manga-cork,ma3lstrom/manga-cork | import logging
from flask import Flask
log = logging.getLogger(__name__)
app = Flask(__name__)
import mangacork.views
Add config for different env | import os
import logging
from flask import Flask
log = logging.getLogger(__name__)
app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])
import mangacork.views
| <commit_before>import logging
from flask import Flask
log = logging.getLogger(__name__)
app = Flask(__name__)
import mangacork.views
<commit_msg>Add config for different env<commit_after> | import os
import logging
from flask import Flask
log = logging.getLogger(__name__)
app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])
import mangacork.views
| import logging
from flask import Flask
log = logging.getLogger(__name__)
app = Flask(__name__)
import mangacork.views
Add config for different envimport os
import logging
from flask import Flask
log = logging.getLogger(__name__)
app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])
import mangacork.views
| <commit_before>import logging
from flask import Flask
log = logging.getLogger(__name__)
app = Flask(__name__)
import mangacork.views
<commit_msg>Add config for different env<commit_after>import os
import logging
from flask import Flask
log = logging.getLogger(__name__)
app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])
import mangacork.views
|
97d4603032803aa52230726d35e1a84b3250245d | dummy.py | dummy.py | import sys
import time
import logging
log = logging.getLogger(__name__)
# test cases
def test_test():
for i in range(200):
print "Mu! {0}".format(i)
assert False
def test_test2():
assert really_long_name_for_a_variable_oh_boy_this_is_long_wheeeeeeeeeeeeeeee == YOUR_MOTHER_IS_A_NICE_LADY
def test():
assert True
def test_test_test_test_test_test_test_test_test_test_test_test_test_test_test():
assert False
def test_test3():
assert False
def test_test4():
time.sleep(1)
assert False
def test_test5():
assert False
def test_test6():
assert False
def test_test7():
assert False
def test_test8():
assert False
def test_test9():
assert False
def test_test10():
assert False
def mu_test():
print "BANG BANG"
sys.stderr.write("MU\n")
log.debug('DANG')
assert aoeu
| import sys
import time
import logging
log = logging.getLogger(__name__)
# test cases
def test_test():
for i in range(200):
print "Mu! {0}".format(i)
print 'WHEE' * 100
assert False
def test_test2():
assert really_long_name_for_a_variable_oh_boy_this_is_long_wheeeeeeeeeeeeeeee == YOUR_MOTHER_IS_A_NICE_LADY
def test():
assert True
def test_test_test_test_test_test_test_test_test_test_test_test_test_test_test():
assert False
def test_test3():
assert False
def test_test4():
time.sleep(1)
assert False
def test_test5():
assert False
def test_test6():
assert False
def test_test7():
assert False
def test_test8():
assert False
def test_test9():
assert False
def test_test10():
assert False
def mu_test():
print "BANG BANG"
sys.stderr.write("MU\n")
log.debug('DANG')
assert aoeu
| Add stress test for wrapping stdout | Add stress test for wrapping stdout
| Python | mit | thenoviceoof/booger,thenoviceoof/booger | import sys
import time
import logging
log = logging.getLogger(__name__)
# test cases
def test_test():
for i in range(200):
print "Mu! {0}".format(i)
assert False
def test_test2():
assert really_long_name_for_a_variable_oh_boy_this_is_long_wheeeeeeeeeeeeeeee == YOUR_MOTHER_IS_A_NICE_LADY
def test():
assert True
def test_test_test_test_test_test_test_test_test_test_test_test_test_test_test():
assert False
def test_test3():
assert False
def test_test4():
time.sleep(1)
assert False
def test_test5():
assert False
def test_test6():
assert False
def test_test7():
assert False
def test_test8():
assert False
def test_test9():
assert False
def test_test10():
assert False
def mu_test():
print "BANG BANG"
sys.stderr.write("MU\n")
log.debug('DANG')
assert aoeu
Add stress test for wrapping stdout | import sys
import time
import logging
log = logging.getLogger(__name__)
# test cases
def test_test():
for i in range(200):
print "Mu! {0}".format(i)
print 'WHEE' * 100
assert False
def test_test2():
assert really_long_name_for_a_variable_oh_boy_this_is_long_wheeeeeeeeeeeeeeee == YOUR_MOTHER_IS_A_NICE_LADY
def test():
assert True
def test_test_test_test_test_test_test_test_test_test_test_test_test_test_test():
assert False
def test_test3():
assert False
def test_test4():
time.sleep(1)
assert False
def test_test5():
assert False
def test_test6():
assert False
def test_test7():
assert False
def test_test8():
assert False
def test_test9():
assert False
def test_test10():
assert False
def mu_test():
print "BANG BANG"
sys.stderr.write("MU\n")
log.debug('DANG')
assert aoeu
| <commit_before>import sys
import time
import logging
log = logging.getLogger(__name__)
# test cases
def test_test():
for i in range(200):
print "Mu! {0}".format(i)
assert False
def test_test2():
assert really_long_name_for_a_variable_oh_boy_this_is_long_wheeeeeeeeeeeeeeee == YOUR_MOTHER_IS_A_NICE_LADY
def test():
assert True
def test_test_test_test_test_test_test_test_test_test_test_test_test_test_test():
assert False
def test_test3():
assert False
def test_test4():
time.sleep(1)
assert False
def test_test5():
assert False
def test_test6():
assert False
def test_test7():
assert False
def test_test8():
assert False
def test_test9():
assert False
def test_test10():
assert False
def mu_test():
print "BANG BANG"
sys.stderr.write("MU\n")
log.debug('DANG')
assert aoeu
<commit_msg>Add stress test for wrapping stdout<commit_after> | import sys
import time
import logging
log = logging.getLogger(__name__)
# test cases
def test_test():
for i in range(200):
print "Mu! {0}".format(i)
print 'WHEE' * 100
assert False
def test_test2():
assert really_long_name_for_a_variable_oh_boy_this_is_long_wheeeeeeeeeeeeeeee == YOUR_MOTHER_IS_A_NICE_LADY
def test():
assert True
def test_test_test_test_test_test_test_test_test_test_test_test_test_test_test():
assert False
def test_test3():
assert False
def test_test4():
time.sleep(1)
assert False
def test_test5():
assert False
def test_test6():
assert False
def test_test7():
assert False
def test_test8():
assert False
def test_test9():
assert False
def test_test10():
assert False
def mu_test():
print "BANG BANG"
sys.stderr.write("MU\n")
log.debug('DANG')
assert aoeu
| import sys
import time
import logging
log = logging.getLogger(__name__)
# test cases
def test_test():
for i in range(200):
print "Mu! {0}".format(i)
assert False
def test_test2():
assert really_long_name_for_a_variable_oh_boy_this_is_long_wheeeeeeeeeeeeeeee == YOUR_MOTHER_IS_A_NICE_LADY
def test():
assert True
def test_test_test_test_test_test_test_test_test_test_test_test_test_test_test():
assert False
def test_test3():
assert False
def test_test4():
time.sleep(1)
assert False
def test_test5():
assert False
def test_test6():
assert False
def test_test7():
assert False
def test_test8():
assert False
def test_test9():
assert False
def test_test10():
assert False
def mu_test():
print "BANG BANG"
sys.stderr.write("MU\n")
log.debug('DANG')
assert aoeu
Add stress test for wrapping stdoutimport sys
import time
import logging
log = logging.getLogger(__name__)
# test cases
def test_test():
for i in range(200):
print "Mu! {0}".format(i)
print 'WHEE' * 100
assert False
def test_test2():
assert really_long_name_for_a_variable_oh_boy_this_is_long_wheeeeeeeeeeeeeeee == YOUR_MOTHER_IS_A_NICE_LADY
def test():
assert True
def test_test_test_test_test_test_test_test_test_test_test_test_test_test_test():
assert False
def test_test3():
assert False
def test_test4():
time.sleep(1)
assert False
def test_test5():
assert False
def test_test6():
assert False
def test_test7():
assert False
def test_test8():
assert False
def test_test9():
assert False
def test_test10():
assert False
def mu_test():
print "BANG BANG"
sys.stderr.write("MU\n")
log.debug('DANG')
assert aoeu
| <commit_before>import sys
import time
import logging
log = logging.getLogger(__name__)
# test cases
def test_test():
for i in range(200):
print "Mu! {0}".format(i)
assert False
def test_test2():
assert really_long_name_for_a_variable_oh_boy_this_is_long_wheeeeeeeeeeeeeeee == YOUR_MOTHER_IS_A_NICE_LADY
def test():
assert True
def test_test_test_test_test_test_test_test_test_test_test_test_test_test_test():
assert False
def test_test3():
assert False
def test_test4():
time.sleep(1)
assert False
def test_test5():
assert False
def test_test6():
assert False
def test_test7():
assert False
def test_test8():
assert False
def test_test9():
assert False
def test_test10():
assert False
def mu_test():
print "BANG BANG"
sys.stderr.write("MU\n")
log.debug('DANG')
assert aoeu
<commit_msg>Add stress test for wrapping stdout<commit_after>import sys
import time
import logging
log = logging.getLogger(__name__)
# test cases
def test_test():
for i in range(200):
print "Mu! {0}".format(i)
print 'WHEE' * 100
assert False
def test_test2():
assert really_long_name_for_a_variable_oh_boy_this_is_long_wheeeeeeeeeeeeeeee == YOUR_MOTHER_IS_A_NICE_LADY
def test():
assert True
def test_test_test_test_test_test_test_test_test_test_test_test_test_test_test():
assert False
def test_test3():
assert False
def test_test4():
time.sleep(1)
assert False
def test_test5():
assert False
def test_test6():
assert False
def test_test7():
assert False
def test_test8():
assert False
def test_test9():
assert False
def test_test10():
assert False
def mu_test():
print "BANG BANG"
sys.stderr.write("MU\n")
log.debug('DANG')
assert aoeu
|
8d778a0eea84f06fdf832de0f458bceaabd1b644 | jacquard/cli.py | jacquard/cli.py | import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='store_true',
)
parser.add_argument(
'-c',
'--config',
help="config file",
type=pathlib.Path,
default=pathlib.Path('config.cfg'),
)
parser.set_defaults(func=None)
subparsers = parser.add_subparsers(metavar='subcommand')
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
command_help = getattr(entry_point, 'help', entry_point.name)
subparser = subparsers.add_parser(
entry_point.name,
help=command_help,
description=command_help,
)
subparser.set_defaults(func=command.handle)
command.add_arguments(subparser)
return parser
def main(args=sys.argv[1:]):
parser = argument_parser()
options = parser.parse_args(args)
if options.func is None:
parser.print_usage()
return
# Parse options
config = load_config(options.config)
# Run subcommand
options.func(config, options)
if '__name__' == '__main__':
main()
| import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='store_true',
)
parser.add_argument(
'-c',
'--config',
help="config file",
type=pathlib.Path,
default=pathlib.Path('config.cfg'),
)
parser.set_defaults(func=None)
subparsers = parser.add_subparsers(metavar='subcommand')
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
command_help = getattr(command, 'help', entry_point.name)
subparser = subparsers.add_parser(
entry_point.name,
help=command_help,
description=command_help,
)
subparser.set_defaults(func=command.handle)
command.add_arguments(subparser)
return parser
def main(args=sys.argv[1:]):
parser = argument_parser()
options = parser.parse_args(args)
if options.func is None:
parser.print_usage()
return
# Parse options
config = load_config(options.config)
# Run subcommand
options.func(config, options)
if '__name__' == '__main__':
main()
| Fix help messages for commands | Fix help messages for commands
| Python | mit | prophile/jacquard,prophile/jacquard | import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='store_true',
)
parser.add_argument(
'-c',
'--config',
help="config file",
type=pathlib.Path,
default=pathlib.Path('config.cfg'),
)
parser.set_defaults(func=None)
subparsers = parser.add_subparsers(metavar='subcommand')
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
command_help = getattr(entry_point, 'help', entry_point.name)
subparser = subparsers.add_parser(
entry_point.name,
help=command_help,
description=command_help,
)
subparser.set_defaults(func=command.handle)
command.add_arguments(subparser)
return parser
def main(args=sys.argv[1:]):
parser = argument_parser()
options = parser.parse_args(args)
if options.func is None:
parser.print_usage()
return
# Parse options
config = load_config(options.config)
# Run subcommand
options.func(config, options)
if '__name__' == '__main__':
main()
Fix help messages for commands | import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='store_true',
)
parser.add_argument(
'-c',
'--config',
help="config file",
type=pathlib.Path,
default=pathlib.Path('config.cfg'),
)
parser.set_defaults(func=None)
subparsers = parser.add_subparsers(metavar='subcommand')
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
command_help = getattr(command, 'help', entry_point.name)
subparser = subparsers.add_parser(
entry_point.name,
help=command_help,
description=command_help,
)
subparser.set_defaults(func=command.handle)
command.add_arguments(subparser)
return parser
def main(args=sys.argv[1:]):
parser = argument_parser()
options = parser.parse_args(args)
if options.func is None:
parser.print_usage()
return
# Parse options
config = load_config(options.config)
# Run subcommand
options.func(config, options)
if '__name__' == '__main__':
main()
| <commit_before>import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='store_true',
)
parser.add_argument(
'-c',
'--config',
help="config file",
type=pathlib.Path,
default=pathlib.Path('config.cfg'),
)
parser.set_defaults(func=None)
subparsers = parser.add_subparsers(metavar='subcommand')
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
command_help = getattr(entry_point, 'help', entry_point.name)
subparser = subparsers.add_parser(
entry_point.name,
help=command_help,
description=command_help,
)
subparser.set_defaults(func=command.handle)
command.add_arguments(subparser)
return parser
def main(args=sys.argv[1:]):
parser = argument_parser()
options = parser.parse_args(args)
if options.func is None:
parser.print_usage()
return
# Parse options
config = load_config(options.config)
# Run subcommand
options.func(config, options)
if '__name__' == '__main__':
main()
<commit_msg>Fix help messages for commands<commit_after> | import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='store_true',
)
parser.add_argument(
'-c',
'--config',
help="config file",
type=pathlib.Path,
default=pathlib.Path('config.cfg'),
)
parser.set_defaults(func=None)
subparsers = parser.add_subparsers(metavar='subcommand')
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
command_help = getattr(command, 'help', entry_point.name)
subparser = subparsers.add_parser(
entry_point.name,
help=command_help,
description=command_help,
)
subparser.set_defaults(func=command.handle)
command.add_arguments(subparser)
return parser
def main(args=sys.argv[1:]):
parser = argument_parser()
options = parser.parse_args(args)
if options.func is None:
parser.print_usage()
return
# Parse options
config = load_config(options.config)
# Run subcommand
options.func(config, options)
if '__name__' == '__main__':
main()
| import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='store_true',
)
parser.add_argument(
'-c',
'--config',
help="config file",
type=pathlib.Path,
default=pathlib.Path('config.cfg'),
)
parser.set_defaults(func=None)
subparsers = parser.add_subparsers(metavar='subcommand')
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
command_help = getattr(entry_point, 'help', entry_point.name)
subparser = subparsers.add_parser(
entry_point.name,
help=command_help,
description=command_help,
)
subparser.set_defaults(func=command.handle)
command.add_arguments(subparser)
return parser
def main(args=sys.argv[1:]):
parser = argument_parser()
options = parser.parse_args(args)
if options.func is None:
parser.print_usage()
return
# Parse options
config = load_config(options.config)
# Run subcommand
options.func(config, options)
if '__name__' == '__main__':
main()
Fix help messages for commandsimport sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='store_true',
)
parser.add_argument(
'-c',
'--config',
help="config file",
type=pathlib.Path,
default=pathlib.Path('config.cfg'),
)
parser.set_defaults(func=None)
subparsers = parser.add_subparsers(metavar='subcommand')
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
command_help = getattr(command, 'help', entry_point.name)
subparser = subparsers.add_parser(
entry_point.name,
help=command_help,
description=command_help,
)
subparser.set_defaults(func=command.handle)
command.add_arguments(subparser)
return parser
def main(args=sys.argv[1:]):
parser = argument_parser()
options = parser.parse_args(args)
if options.func is None:
parser.print_usage()
return
# Parse options
config = load_config(options.config)
# Run subcommand
options.func(config, options)
if '__name__' == '__main__':
main()
| <commit_before>import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='store_true',
)
parser.add_argument(
'-c',
'--config',
help="config file",
type=pathlib.Path,
default=pathlib.Path('config.cfg'),
)
parser.set_defaults(func=None)
subparsers = parser.add_subparsers(metavar='subcommand')
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
command_help = getattr(entry_point, 'help', entry_point.name)
subparser = subparsers.add_parser(
entry_point.name,
help=command_help,
description=command_help,
)
subparser.set_defaults(func=command.handle)
command.add_arguments(subparser)
return parser
def main(args=sys.argv[1:]):
parser = argument_parser()
options = parser.parse_args(args)
if options.func is None:
parser.print_usage()
return
# Parse options
config = load_config(options.config)
# Run subcommand
options.func(config, options)
if '__name__' == '__main__':
main()
<commit_msg>Fix help messages for commands<commit_after>import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='store_true',
)
parser.add_argument(
'-c',
'--config',
help="config file",
type=pathlib.Path,
default=pathlib.Path('config.cfg'),
)
parser.set_defaults(func=None)
subparsers = parser.add_subparsers(metavar='subcommand')
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
command_help = getattr(command, 'help', entry_point.name)
subparser = subparsers.add_parser(
entry_point.name,
help=command_help,
description=command_help,
)
subparser.set_defaults(func=command.handle)
command.add_arguments(subparser)
return parser
def main(args=sys.argv[1:]):
parser = argument_parser()
options = parser.parse_args(args)
if options.func is None:
parser.print_usage()
return
# Parse options
config = load_config(options.config)
# Run subcommand
options.func(config, options)
if '__name__' == '__main__':
main()
|
06ef7333ea7c584166b1a7361e1d41143a0c85c8 | moveon/managers.py | moveon/managers.py | from django.db import models
class CompanyManager(models.Manager):
def get_by_code(self, company_code):
return self.get(code=company_code)
class TransportManager(models.Manager):
def get_by_name(self, transport_name):
return self.get(name=transport_name)
class StationManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
class NodeManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
| from django.db import models
from django.db.models import Q
class CompanyManager(models.Manager):
def get_by_code(self, company_code):
return self.get(code=company_code)
class TransportManager(models.Manager):
def get_by_name(self, transport_name):
return self.get(name=transport_name)
class StationManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
def get_near_stations(self, left, bottom, right, top):
stations = self.filter(Q(latitude__gte=left) & Q(longitude__gte=bottom) &
Q(latitude__lte=right) & Q(longitude__lte=top))
return stations
class NodeManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
| Add the query to get the near stations | Add the query to get the near stations
This query takes four parameters that define a coordinates bounding
box. This allows to get the stations that fir into the area defined
by the box. | Python | agpl-3.0 | SeGarVi/moveon-web,SeGarVi/moveon-web,SeGarVi/moveon-web | from django.db import models
class CompanyManager(models.Manager):
def get_by_code(self, company_code):
return self.get(code=company_code)
class TransportManager(models.Manager):
def get_by_name(self, transport_name):
return self.get(name=transport_name)
class StationManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
class NodeManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
Add the query to get the near stations
This query takes four parameters that define a coordinates bounding
box. This allows to get the stations that fir into the area defined
by the box. | from django.db import models
from django.db.models import Q
class CompanyManager(models.Manager):
def get_by_code(self, company_code):
return self.get(code=company_code)
class TransportManager(models.Manager):
def get_by_name(self, transport_name):
return self.get(name=transport_name)
class StationManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
def get_near_stations(self, left, bottom, right, top):
stations = self.filter(Q(latitude__gte=left) & Q(longitude__gte=bottom) &
Q(latitude__lte=right) & Q(longitude__lte=top))
return stations
class NodeManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
| <commit_before>from django.db import models
class CompanyManager(models.Manager):
def get_by_code(self, company_code):
return self.get(code=company_code)
class TransportManager(models.Manager):
def get_by_name(self, transport_name):
return self.get(name=transport_name)
class StationManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
class NodeManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
<commit_msg>Add the query to get the near stations
This query takes four parameters that define a coordinates bounding
box. This allows to get the stations that fir into the area defined
by the box.<commit_after> | from django.db import models
from django.db.models import Q
class CompanyManager(models.Manager):
def get_by_code(self, company_code):
return self.get(code=company_code)
class TransportManager(models.Manager):
def get_by_name(self, transport_name):
return self.get(name=transport_name)
class StationManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
def get_near_stations(self, left, bottom, right, top):
stations = self.filter(Q(latitude__gte=left) & Q(longitude__gte=bottom) &
Q(latitude__lte=right) & Q(longitude__lte=top))
return stations
class NodeManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
| from django.db import models
class CompanyManager(models.Manager):
def get_by_code(self, company_code):
return self.get(code=company_code)
class TransportManager(models.Manager):
def get_by_name(self, transport_name):
return self.get(name=transport_name)
class StationManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
class NodeManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
Add the query to get the near stations
This query takes four parameters that define a coordinates bounding
box. This allows to get the stations that fir into the area defined
by the box.from django.db import models
from django.db.models import Q
class CompanyManager(models.Manager):
def get_by_code(self, company_code):
return self.get(code=company_code)
class TransportManager(models.Manager):
def get_by_name(self, transport_name):
return self.get(name=transport_name)
class StationManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
def get_near_stations(self, left, bottom, right, top):
stations = self.filter(Q(latitude__gte=left) & Q(longitude__gte=bottom) &
Q(latitude__lte=right) & Q(longitude__lte=top))
return stations
class NodeManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
| <commit_before>from django.db import models
class CompanyManager(models.Manager):
def get_by_code(self, company_code):
return self.get(code=company_code)
class TransportManager(models.Manager):
def get_by_name(self, transport_name):
return self.get(name=transport_name)
class StationManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
class NodeManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
<commit_msg>Add the query to get the near stations
This query takes four parameters that define a coordinates bounding
box. This allows to get the stations that fir into the area defined
by the box.<commit_after>from django.db import models
from django.db.models import Q
class CompanyManager(models.Manager):
def get_by_code(self, company_code):
return self.get(code=company_code)
class TransportManager(models.Manager):
def get_by_name(self, transport_name):
return self.get(name=transport_name)
class StationManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
def get_near_stations(self, left, bottom, right, top):
stations = self.filter(Q(latitude__gte=left) & Q(longitude__gte=bottom) &
Q(latitude__lte=right) & Q(longitude__lte=top))
return stations
class NodeManager(models.Manager):
def get_by_id(self, station_id):
return self.get(osmid=station_id)
|
59066fc1def071aa51a87a6393c8bdf34f081188 | opps/core/__init__.py | opps/core/__init__.py | # -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
trans_app_label = _('Core')
settings.INSTALLED_APPS += (
'opps.article',
'opps.image',
'opps.channel',
'opps.source',
'django.contrib.redirects',
'django_thumbor',
'googl',
'redactor',
'static_sitemaps',
'tagging',)
settings.MIDDLEWARE_CLASSES += (
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',)
# Opps
getattr(settings, 'OPPS_SHORT', 'googl')
getattr(settings, 'OPPS_SHORT_URL', 'googl.short.GooglUrlShort')
# Sitemap
if not hasattr(settings, 'STATICSITEMAPS_ROOT_SITEMAP'):
settings.STATICSITEMAPS_ROOT_SITEMAP = 'opps.sitemaps.feed.sitemaps'
# redactor
getattr(settings, 'REDACTOR_OPTIONS', {'lang': 'en'})
getattr(settings, 'REDACTOR_UPLOAD', 'uploads/')
# thumbor
getattr(settings, 'THUMBOR_SERVER', 'http://localhost:8888')
getattr(settings, 'THUMBOR_MEDIA_URL', 'http://localhost:8000/media')
getattr(settings, 'THUMBOR_SECURITY_KEY', '')
| # -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
trans_app_label = _('Core')
settings.INSTALLED_APPS += (
'opps.article',
'opps.image',
'opps.channel',
'opps.source',
'django.contrib.redirects',
'django_thumbor',
'googl',
'redactor',
'static_sitemaps',
'tagging',)
settings.MIDDLEWARE_CLASSES += (
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',)
# Opps
getattr(settings, 'OPPS_SHORT', 'googl')
getattr(settings, 'OPPS_SHORT_URL', 'googl.short.GooglUrlShort')
# Sitemap
if not hasattr(settings, 'STATICSITEMAPS_ROOT_SITEMAP'):
settings.STATICSITEMAPS_ROOT_SITEMAP = 'opps.sitemaps.feed.sitemaps'
# Haystack
getattr(settings, 'HAYSTACK_CONNECTIONS', {
'default': {'ENGINE': 'haystack.backends.simple_backend.SimpleEngine'}})
# redactor
getattr(settings, 'REDACTOR_OPTIONS', {'lang': 'en'})
getattr(settings, 'REDACTOR_UPLOAD', 'uploads/')
# thumbor
getattr(settings, 'THUMBOR_SERVER', 'http://localhost:8888')
getattr(settings, 'THUMBOR_MEDIA_URL', 'http://localhost:8000/media')
getattr(settings, 'THUMBOR_SECURITY_KEY', '')
| Add haystack connections simples engine om opps | Add haystack connections simples engine om opps
| Python | mit | YACOWS/opps,jeanmask/opps,opps/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,opps/opps,opps/opps,YACOWS/opps,YACOWS/opps,opps/opps,williamroot/opps,YACOWS/opps,williamroot/opps,jeanmask/opps | # -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
trans_app_label = _('Core')
settings.INSTALLED_APPS += (
'opps.article',
'opps.image',
'opps.channel',
'opps.source',
'django.contrib.redirects',
'django_thumbor',
'googl',
'redactor',
'static_sitemaps',
'tagging',)
settings.MIDDLEWARE_CLASSES += (
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',)
# Opps
getattr(settings, 'OPPS_SHORT', 'googl')
getattr(settings, 'OPPS_SHORT_URL', 'googl.short.GooglUrlShort')
# Sitemap
if not hasattr(settings, 'STATICSITEMAPS_ROOT_SITEMAP'):
settings.STATICSITEMAPS_ROOT_SITEMAP = 'opps.sitemaps.feed.sitemaps'
# redactor
getattr(settings, 'REDACTOR_OPTIONS', {'lang': 'en'})
getattr(settings, 'REDACTOR_UPLOAD', 'uploads/')
# thumbor
getattr(settings, 'THUMBOR_SERVER', 'http://localhost:8888')
getattr(settings, 'THUMBOR_MEDIA_URL', 'http://localhost:8000/media')
getattr(settings, 'THUMBOR_SECURITY_KEY', '')
Add haystack connections simples engine om opps | # -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
trans_app_label = _('Core')
settings.INSTALLED_APPS += (
'opps.article',
'opps.image',
'opps.channel',
'opps.source',
'django.contrib.redirects',
'django_thumbor',
'googl',
'redactor',
'static_sitemaps',
'tagging',)
settings.MIDDLEWARE_CLASSES += (
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',)
# Opps
getattr(settings, 'OPPS_SHORT', 'googl')
getattr(settings, 'OPPS_SHORT_URL', 'googl.short.GooglUrlShort')
# Sitemap
if not hasattr(settings, 'STATICSITEMAPS_ROOT_SITEMAP'):
settings.STATICSITEMAPS_ROOT_SITEMAP = 'opps.sitemaps.feed.sitemaps'
# Haystack
getattr(settings, 'HAYSTACK_CONNECTIONS', {
'default': {'ENGINE': 'haystack.backends.simple_backend.SimpleEngine'}})
# redactor
getattr(settings, 'REDACTOR_OPTIONS', {'lang': 'en'})
getattr(settings, 'REDACTOR_UPLOAD', 'uploads/')
# thumbor
getattr(settings, 'THUMBOR_SERVER', 'http://localhost:8888')
getattr(settings, 'THUMBOR_MEDIA_URL', 'http://localhost:8000/media')
getattr(settings, 'THUMBOR_SECURITY_KEY', '')
| <commit_before># -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
trans_app_label = _('Core')
settings.INSTALLED_APPS += (
'opps.article',
'opps.image',
'opps.channel',
'opps.source',
'django.contrib.redirects',
'django_thumbor',
'googl',
'redactor',
'static_sitemaps',
'tagging',)
settings.MIDDLEWARE_CLASSES += (
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',)
# Opps
getattr(settings, 'OPPS_SHORT', 'googl')
getattr(settings, 'OPPS_SHORT_URL', 'googl.short.GooglUrlShort')
# Sitemap
if not hasattr(settings, 'STATICSITEMAPS_ROOT_SITEMAP'):
settings.STATICSITEMAPS_ROOT_SITEMAP = 'opps.sitemaps.feed.sitemaps'
# redactor
getattr(settings, 'REDACTOR_OPTIONS', {'lang': 'en'})
getattr(settings, 'REDACTOR_UPLOAD', 'uploads/')
# thumbor
getattr(settings, 'THUMBOR_SERVER', 'http://localhost:8888')
getattr(settings, 'THUMBOR_MEDIA_URL', 'http://localhost:8000/media')
getattr(settings, 'THUMBOR_SECURITY_KEY', '')
<commit_msg>Add haystack connections simples engine om opps<commit_after> | # -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
trans_app_label = _('Core')
settings.INSTALLED_APPS += (
'opps.article',
'opps.image',
'opps.channel',
'opps.source',
'django.contrib.redirects',
'django_thumbor',
'googl',
'redactor',
'static_sitemaps',
'tagging',)
settings.MIDDLEWARE_CLASSES += (
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',)
# Opps
getattr(settings, 'OPPS_SHORT', 'googl')
getattr(settings, 'OPPS_SHORT_URL', 'googl.short.GooglUrlShort')
# Sitemap
if not hasattr(settings, 'STATICSITEMAPS_ROOT_SITEMAP'):
settings.STATICSITEMAPS_ROOT_SITEMAP = 'opps.sitemaps.feed.sitemaps'
# Haystack
getattr(settings, 'HAYSTACK_CONNECTIONS', {
'default': {'ENGINE': 'haystack.backends.simple_backend.SimpleEngine'}})
# redactor
getattr(settings, 'REDACTOR_OPTIONS', {'lang': 'en'})
getattr(settings, 'REDACTOR_UPLOAD', 'uploads/')
# thumbor
getattr(settings, 'THUMBOR_SERVER', 'http://localhost:8888')
getattr(settings, 'THUMBOR_MEDIA_URL', 'http://localhost:8000/media')
getattr(settings, 'THUMBOR_SECURITY_KEY', '')
| # -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
trans_app_label = _('Core')
settings.INSTALLED_APPS += (
'opps.article',
'opps.image',
'opps.channel',
'opps.source',
'django.contrib.redirects',
'django_thumbor',
'googl',
'redactor',
'static_sitemaps',
'tagging',)
settings.MIDDLEWARE_CLASSES += (
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',)
# Opps
getattr(settings, 'OPPS_SHORT', 'googl')
getattr(settings, 'OPPS_SHORT_URL', 'googl.short.GooglUrlShort')
# Sitemap
if not hasattr(settings, 'STATICSITEMAPS_ROOT_SITEMAP'):
settings.STATICSITEMAPS_ROOT_SITEMAP = 'opps.sitemaps.feed.sitemaps'
# redactor
getattr(settings, 'REDACTOR_OPTIONS', {'lang': 'en'})
getattr(settings, 'REDACTOR_UPLOAD', 'uploads/')
# thumbor
getattr(settings, 'THUMBOR_SERVER', 'http://localhost:8888')
getattr(settings, 'THUMBOR_MEDIA_URL', 'http://localhost:8000/media')
getattr(settings, 'THUMBOR_SECURITY_KEY', '')
Add haystack connections simples engine om opps# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
trans_app_label = _('Core')
settings.INSTALLED_APPS += (
'opps.article',
'opps.image',
'opps.channel',
'opps.source',
'django.contrib.redirects',
'django_thumbor',
'googl',
'redactor',
'static_sitemaps',
'tagging',)
settings.MIDDLEWARE_CLASSES += (
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',)
# Opps
getattr(settings, 'OPPS_SHORT', 'googl')
getattr(settings, 'OPPS_SHORT_URL', 'googl.short.GooglUrlShort')
# Sitemap
if not hasattr(settings, 'STATICSITEMAPS_ROOT_SITEMAP'):
settings.STATICSITEMAPS_ROOT_SITEMAP = 'opps.sitemaps.feed.sitemaps'
# Haystack
getattr(settings, 'HAYSTACK_CONNECTIONS', {
'default': {'ENGINE': 'haystack.backends.simple_backend.SimpleEngine'}})
# redactor
getattr(settings, 'REDACTOR_OPTIONS', {'lang': 'en'})
getattr(settings, 'REDACTOR_UPLOAD', 'uploads/')
# thumbor
getattr(settings, 'THUMBOR_SERVER', 'http://localhost:8888')
getattr(settings, 'THUMBOR_MEDIA_URL', 'http://localhost:8000/media')
getattr(settings, 'THUMBOR_SECURITY_KEY', '')
| <commit_before># -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
trans_app_label = _('Core')
settings.INSTALLED_APPS += (
'opps.article',
'opps.image',
'opps.channel',
'opps.source',
'django.contrib.redirects',
'django_thumbor',
'googl',
'redactor',
'static_sitemaps',
'tagging',)
settings.MIDDLEWARE_CLASSES += (
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',)
# Opps
getattr(settings, 'OPPS_SHORT', 'googl')
getattr(settings, 'OPPS_SHORT_URL', 'googl.short.GooglUrlShort')
# Sitemap
if not hasattr(settings, 'STATICSITEMAPS_ROOT_SITEMAP'):
settings.STATICSITEMAPS_ROOT_SITEMAP = 'opps.sitemaps.feed.sitemaps'
# redactor
getattr(settings, 'REDACTOR_OPTIONS', {'lang': 'en'})
getattr(settings, 'REDACTOR_UPLOAD', 'uploads/')
# thumbor
getattr(settings, 'THUMBOR_SERVER', 'http://localhost:8888')
getattr(settings, 'THUMBOR_MEDIA_URL', 'http://localhost:8000/media')
getattr(settings, 'THUMBOR_SECURITY_KEY', '')
<commit_msg>Add haystack connections simples engine om opps<commit_after># -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
trans_app_label = _('Core')
settings.INSTALLED_APPS += (
'opps.article',
'opps.image',
'opps.channel',
'opps.source',
'django.contrib.redirects',
'django_thumbor',
'googl',
'redactor',
'static_sitemaps',
'tagging',)
settings.MIDDLEWARE_CLASSES += (
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',)
# Opps
getattr(settings, 'OPPS_SHORT', 'googl')
getattr(settings, 'OPPS_SHORT_URL', 'googl.short.GooglUrlShort')
# Sitemap
if not hasattr(settings, 'STATICSITEMAPS_ROOT_SITEMAP'):
settings.STATICSITEMAPS_ROOT_SITEMAP = 'opps.sitemaps.feed.sitemaps'
# Haystack
getattr(settings, 'HAYSTACK_CONNECTIONS', {
'default': {'ENGINE': 'haystack.backends.simple_backend.SimpleEngine'}})
# redactor
getattr(settings, 'REDACTOR_OPTIONS', {'lang': 'en'})
getattr(settings, 'REDACTOR_UPLOAD', 'uploads/')
# thumbor
getattr(settings, 'THUMBOR_SERVER', 'http://localhost:8888')
getattr(settings, 'THUMBOR_MEDIA_URL', 'http://localhost:8000/media')
getattr(settings, 'THUMBOR_SECURITY_KEY', '')
|
aaad7fe2f7d90a7f20ec794b374855f72c2dc155 | pgroonga/migrations/0001_enable.py | pgroonga/migrations/0001_enable.py | # -*- coding: utf-8 -*-
from django.db import models, migrations
from django.contrib.postgres import operations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('zerver', '0001_initial'),
]
database_setting = settings.DATABASES["default"]
if "postgres" in database_setting["ENGINE"]:
operations = [
migrations.RunSQL("""
ALTER ROLE %(USER)s SET search_path TO %(SCHEMA)s,public,pgroonga,pg_catalog;
SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog;
ALTER TABLE zerver_message ADD COLUMN search_pgroonga text;
UPDATE zerver_message SET search_pgroonga = subject || ' ' || rendered_content;
-- TODO: We want to use CREATE INDEX CONCURRENTLY but it can't be used in
-- transaction. Django uses transaction implicitly.
-- Django 1.10 may solve the problem.
CREATE INDEX zerver_message_search_pgroonga ON zerver_message
USING pgroonga(search_pgroonga pgroonga.text_full_text_search_ops);
""" % database_setting,
"""
SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog;
DROP INDEX zerver_message_search_pgroonga;
ALTER TABLE zerver_message DROP COLUMN search_pgroonga;
SET search_path = %(SCHEMA)s,public;
ALTER ROLE %(USER)s SET search_path TO %(SCHEMA)s,public;
""" % database_setting),
]
else:
operations = []
| # -*- coding: utf-8 -*-
from django.db import models, migrations
from django.contrib.postgres import operations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('zerver', '0001_initial'),
]
database_setting = settings.DATABASES["default"]
if "postgres" in database_setting["ENGINE"]:
operations = [
migrations.RunSQL("""
ALTER ROLE %(USER)s SET search_path TO %(SCHEMA)s,public,pgroonga,pg_catalog;
SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog;
ALTER TABLE zerver_message ADD COLUMN search_pgroonga text;
-- TODO: We want to use CREATE INDEX CONCURRENTLY but it can't be used in
-- transaction. Django uses transaction implicitly.
-- Django 1.10 may solve the problem.
CREATE INDEX zerver_message_search_pgroonga ON zerver_message
USING pgroonga(search_pgroonga pgroonga.text_full_text_search_ops);
""" % database_setting,
"""
SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog;
DROP INDEX zerver_message_search_pgroonga;
ALTER TABLE zerver_message DROP COLUMN search_pgroonga;
SET search_path = %(SCHEMA)s,public;
ALTER ROLE %(USER)s SET search_path TO %(SCHEMA)s,public;
""" % database_setting),
]
else:
operations = []
| Remove long-running update query in initial migration. | pgroonga: Remove long-running update query in initial migration.
This query doesn't add any value, because it'll be overwritten in
migration 0002 anyway. And because it isn't batched, it can take
several minutes to run on servers with hundreds of thousands to
millions of messages of history. During that time, it's in a
transaction, and thus one can't send messages, so it forces downtime.
| Python | apache-2.0 | zulip/zulip,kou/zulip,timabbott/zulip,shubhamdhama/zulip,andersk/zulip,showell/zulip,kou/zulip,rht/zulip,shubhamdhama/zulip,tommyip/zulip,timabbott/zulip,tommyip/zulip,dhcrzf/zulip,rht/zulip,punchagan/zulip,jackrzhang/zulip,timabbott/zulip,rishig/zulip,punchagan/zulip,eeshangarg/zulip,showell/zulip,hackerkid/zulip,timabbott/zulip,kou/zulip,punchagan/zulip,punchagan/zulip,synicalsyntax/zulip,brainwane/zulip,andersk/zulip,kou/zulip,rht/zulip,synicalsyntax/zulip,timabbott/zulip,eeshangarg/zulip,zulip/zulip,rishig/zulip,rht/zulip,andersk/zulip,timabbott/zulip,jackrzhang/zulip,hackerkid/zulip,tommyip/zulip,dhcrzf/zulip,punchagan/zulip,andersk/zulip,showell/zulip,shubhamdhama/zulip,hackerkid/zulip,brainwane/zulip,tommyip/zulip,synicalsyntax/zulip,andersk/zulip,kou/zulip,dhcrzf/zulip,timabbott/zulip,tommyip/zulip,hackerkid/zulip,zulip/zulip,showell/zulip,shubhamdhama/zulip,hackerkid/zulip,zulip/zulip,tommyip/zulip,dhcrzf/zulip,rishig/zulip,rishig/zulip,eeshangarg/zulip,jackrzhang/zulip,punchagan/zulip,rishig/zulip,jackrzhang/zulip,synicalsyntax/zulip,hackerkid/zulip,andersk/zulip,rht/zulip,tommyip/zulip,jackrzhang/zulip,kou/zulip,dhcrzf/zulip,brainwane/zulip,eeshangarg/zulip,eeshangarg/zulip,rht/zulip,hackerkid/zulip,kou/zulip,dhcrzf/zulip,rishig/zulip,zulip/zulip,rht/zulip,showell/zulip,showell/zulip,brainwane/zulip,synicalsyntax/zulip,shubhamdhama/zulip,zulip/zulip,zulip/zulip,punchagan/zulip,andersk/zulip,eeshangarg/zulip,showell/zulip,shubhamdhama/zulip,brainwane/zulip,jackrzhang/zulip,synicalsyntax/zulip,brainwane/zulip,brainwane/zulip,shubhamdhama/zulip,rishig/zulip,dhcrzf/zulip,synicalsyntax/zulip,eeshangarg/zulip,jackrzhang/zulip | # -*- coding: utf-8 -*-
from django.db import models, migrations
from django.contrib.postgres import operations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('zerver', '0001_initial'),
]
database_setting = settings.DATABASES["default"]
if "postgres" in database_setting["ENGINE"]:
operations = [
migrations.RunSQL("""
ALTER ROLE %(USER)s SET search_path TO %(SCHEMA)s,public,pgroonga,pg_catalog;
SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog;
ALTER TABLE zerver_message ADD COLUMN search_pgroonga text;
UPDATE zerver_message SET search_pgroonga = subject || ' ' || rendered_content;
-- TODO: We want to use CREATE INDEX CONCURRENTLY but it can't be used in
-- transaction. Django uses transaction implicitly.
-- Django 1.10 may solve the problem.
CREATE INDEX zerver_message_search_pgroonga ON zerver_message
USING pgroonga(search_pgroonga pgroonga.text_full_text_search_ops);
""" % database_setting,
"""
SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog;
DROP INDEX zerver_message_search_pgroonga;
ALTER TABLE zerver_message DROP COLUMN search_pgroonga;
SET search_path = %(SCHEMA)s,public;
ALTER ROLE %(USER)s SET search_path TO %(SCHEMA)s,public;
""" % database_setting),
]
else:
operations = []
pgroonga: Remove long-running update query in initial migration.
This query doesn't add any value, because it'll be overwritten in
migration 0002 anyway. And because it isn't batched, it can take
several minutes to run on servers with hundreds of thousands to
millions of messages of history. During that time, it's in a
transaction, and thus one can't send messages, so it forces downtime. | # -*- coding: utf-8 -*-
from django.db import models, migrations
from django.contrib.postgres import operations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('zerver', '0001_initial'),
]
database_setting = settings.DATABASES["default"]
if "postgres" in database_setting["ENGINE"]:
operations = [
migrations.RunSQL("""
ALTER ROLE %(USER)s SET search_path TO %(SCHEMA)s,public,pgroonga,pg_catalog;
SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog;
ALTER TABLE zerver_message ADD COLUMN search_pgroonga text;
-- TODO: We want to use CREATE INDEX CONCURRENTLY but it can't be used in
-- transaction. Django uses transaction implicitly.
-- Django 1.10 may solve the problem.
CREATE INDEX zerver_message_search_pgroonga ON zerver_message
USING pgroonga(search_pgroonga pgroonga.text_full_text_search_ops);
""" % database_setting,
"""
SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog;
DROP INDEX zerver_message_search_pgroonga;
ALTER TABLE zerver_message DROP COLUMN search_pgroonga;
SET search_path = %(SCHEMA)s,public;
ALTER ROLE %(USER)s SET search_path TO %(SCHEMA)s,public;
""" % database_setting),
]
else:
operations = []
| <commit_before># -*- coding: utf-8 -*-
from django.db import models, migrations
from django.contrib.postgres import operations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('zerver', '0001_initial'),
]
database_setting = settings.DATABASES["default"]
if "postgres" in database_setting["ENGINE"]:
operations = [
migrations.RunSQL("""
ALTER ROLE %(USER)s SET search_path TO %(SCHEMA)s,public,pgroonga,pg_catalog;
SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog;
ALTER TABLE zerver_message ADD COLUMN search_pgroonga text;
UPDATE zerver_message SET search_pgroonga = subject || ' ' || rendered_content;
-- TODO: We want to use CREATE INDEX CONCURRENTLY but it can't be used in
-- transaction. Django uses transaction implicitly.
-- Django 1.10 may solve the problem.
CREATE INDEX zerver_message_search_pgroonga ON zerver_message
USING pgroonga(search_pgroonga pgroonga.text_full_text_search_ops);
""" % database_setting,
"""
SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog;
DROP INDEX zerver_message_search_pgroonga;
ALTER TABLE zerver_message DROP COLUMN search_pgroonga;
SET search_path = %(SCHEMA)s,public;
ALTER ROLE %(USER)s SET search_path TO %(SCHEMA)s,public;
""" % database_setting),
]
else:
operations = []
<commit_msg>pgroonga: Remove long-running update query in initial migration.
This query doesn't add any value, because it'll be overwritten in
migration 0002 anyway. And because it isn't batched, it can take
several minutes to run on servers with hundreds of thousands to
millions of messages of history. During that time, it's in a
transaction, and thus one can't send messages, so it forces downtime.<commit_after> | # -*- coding: utf-8 -*-
from django.db import models, migrations
from django.contrib.postgres import operations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('zerver', '0001_initial'),
]
database_setting = settings.DATABASES["default"]
if "postgres" in database_setting["ENGINE"]:
operations = [
migrations.RunSQL("""
ALTER ROLE %(USER)s SET search_path TO %(SCHEMA)s,public,pgroonga,pg_catalog;
SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog;
ALTER TABLE zerver_message ADD COLUMN search_pgroonga text;
-- TODO: We want to use CREATE INDEX CONCURRENTLY but it can't be used in
-- transaction. Django uses transaction implicitly.
-- Django 1.10 may solve the problem.
CREATE INDEX zerver_message_search_pgroonga ON zerver_message
USING pgroonga(search_pgroonga pgroonga.text_full_text_search_ops);
""" % database_setting,
"""
SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog;
DROP INDEX zerver_message_search_pgroonga;
ALTER TABLE zerver_message DROP COLUMN search_pgroonga;
SET search_path = %(SCHEMA)s,public;
ALTER ROLE %(USER)s SET search_path TO %(SCHEMA)s,public;
""" % database_setting),
]
else:
operations = []
| # -*- coding: utf-8 -*-
from django.db import models, migrations
from django.contrib.postgres import operations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('zerver', '0001_initial'),
]
database_setting = settings.DATABASES["default"]
if "postgres" in database_setting["ENGINE"]:
operations = [
migrations.RunSQL("""
ALTER ROLE %(USER)s SET search_path TO %(SCHEMA)s,public,pgroonga,pg_catalog;
SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog;
ALTER TABLE zerver_message ADD COLUMN search_pgroonga text;
UPDATE zerver_message SET search_pgroonga = subject || ' ' || rendered_content;
-- TODO: We want to use CREATE INDEX CONCURRENTLY but it can't be used in
-- transaction. Django uses transaction implicitly.
-- Django 1.10 may solve the problem.
CREATE INDEX zerver_message_search_pgroonga ON zerver_message
USING pgroonga(search_pgroonga pgroonga.text_full_text_search_ops);
""" % database_setting,
"""
SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog;
DROP INDEX zerver_message_search_pgroonga;
ALTER TABLE zerver_message DROP COLUMN search_pgroonga;
SET search_path = %(SCHEMA)s,public;
ALTER ROLE %(USER)s SET search_path TO %(SCHEMA)s,public;
""" % database_setting),
]
else:
operations = []
pgroonga: Remove long-running update query in initial migration.
This query doesn't add any value, because it'll be overwritten in
migration 0002 anyway. And because it isn't batched, it can take
several minutes to run on servers with hundreds of thousands to
millions of messages of history. During that time, it's in a
transaction, and thus one can't send messages, so it forces downtime.# -*- coding: utf-8 -*-
from django.db import models, migrations
from django.contrib.postgres import operations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('zerver', '0001_initial'),
]
database_setting = settings.DATABASES["default"]
if "postgres" in database_setting["ENGINE"]:
operations = [
migrations.RunSQL("""
ALTER ROLE %(USER)s SET search_path TO %(SCHEMA)s,public,pgroonga,pg_catalog;
SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog;
ALTER TABLE zerver_message ADD COLUMN search_pgroonga text;
-- TODO: We want to use CREATE INDEX CONCURRENTLY but it can't be used in
-- transaction. Django uses transaction implicitly.
-- Django 1.10 may solve the problem.
CREATE INDEX zerver_message_search_pgroonga ON zerver_message
USING pgroonga(search_pgroonga pgroonga.text_full_text_search_ops);
""" % database_setting,
"""
SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog;
DROP INDEX zerver_message_search_pgroonga;
ALTER TABLE zerver_message DROP COLUMN search_pgroonga;
SET search_path = %(SCHEMA)s,public;
ALTER ROLE %(USER)s SET search_path TO %(SCHEMA)s,public;
""" % database_setting),
]
else:
operations = []
| <commit_before># -*- coding: utf-8 -*-
from django.db import models, migrations
from django.contrib.postgres import operations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('zerver', '0001_initial'),
]
database_setting = settings.DATABASES["default"]
if "postgres" in database_setting["ENGINE"]:
operations = [
migrations.RunSQL("""
ALTER ROLE %(USER)s SET search_path TO %(SCHEMA)s,public,pgroonga,pg_catalog;
SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog;
ALTER TABLE zerver_message ADD COLUMN search_pgroonga text;
UPDATE zerver_message SET search_pgroonga = subject || ' ' || rendered_content;
-- TODO: We want to use CREATE INDEX CONCURRENTLY but it can't be used in
-- transaction. Django uses transaction implicitly.
-- Django 1.10 may solve the problem.
CREATE INDEX zerver_message_search_pgroonga ON zerver_message
USING pgroonga(search_pgroonga pgroonga.text_full_text_search_ops);
""" % database_setting,
"""
SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog;
DROP INDEX zerver_message_search_pgroonga;
ALTER TABLE zerver_message DROP COLUMN search_pgroonga;
SET search_path = %(SCHEMA)s,public;
ALTER ROLE %(USER)s SET search_path TO %(SCHEMA)s,public;
""" % database_setting),
]
else:
operations = []
<commit_msg>pgroonga: Remove long-running update query in initial migration.
This query doesn't add any value, because it'll be overwritten in
migration 0002 anyway. And because it isn't batched, it can take
several minutes to run on servers with hundreds of thousands to
millions of messages of history. During that time, it's in a
transaction, and thus one can't send messages, so it forces downtime.<commit_after># -*- coding: utf-8 -*-
from django.db import models, migrations
from django.contrib.postgres import operations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('zerver', '0001_initial'),
]
database_setting = settings.DATABASES["default"]
if "postgres" in database_setting["ENGINE"]:
operations = [
migrations.RunSQL("""
ALTER ROLE %(USER)s SET search_path TO %(SCHEMA)s,public,pgroonga,pg_catalog;
SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog;
ALTER TABLE zerver_message ADD COLUMN search_pgroonga text;
-- TODO: We want to use CREATE INDEX CONCURRENTLY but it can't be used in
-- transaction. Django uses transaction implicitly.
-- Django 1.10 may solve the problem.
CREATE INDEX zerver_message_search_pgroonga ON zerver_message
USING pgroonga(search_pgroonga pgroonga.text_full_text_search_ops);
""" % database_setting,
"""
SET search_path = %(SCHEMA)s,public,pgroonga,pg_catalog;
DROP INDEX zerver_message_search_pgroonga;
ALTER TABLE zerver_message DROP COLUMN search_pgroonga;
SET search_path = %(SCHEMA)s,public;
ALTER ROLE %(USER)s SET search_path TO %(SCHEMA)s,public;
""" % database_setting),
]
else:
operations = []
|
3ecc57fa3f62943061fbeb26c7ecce02c17daf4e | tests/test_config.py | tests/test_config.py | import xdg
from click.testing import CliRunner
from todoman.cli import cli
def test_explicit_nonexistant(runner):
result = CliRunner().invoke(
cli,
env={
'TODOMAN_CONFIG': '/nonexistant',
},
catch_exceptions=True,
)
assert result.exception
assert "Configuration file /nonexistant does not exist" in result.output
def test_xdg_nonexistant(runner):
original_dirs = xdg.BaseDirectory.xdg_config_dirs
xdg.BaseDirectory.xdg_config_dirs = []
try:
result = CliRunner().invoke(
cli,
catch_exceptions=True,
)
assert result.exception
assert "No configuration file found" in result.output
except:
raise
finally:
# Make sure we ALWAYS set this back to the origianl value, even if the
# test failed.
xdg.BaseDirectory.xdg_config_dirs = original_dirs
| import xdg
from click.testing import CliRunner
from todoman.cli import cli
def test_explicit_nonexistant(runner):
result = CliRunner().invoke(
cli,
env={
'TODOMAN_CONFIG': '/nonexistant',
},
catch_exceptions=True,
)
assert result.exception
assert "Configuration file /nonexistant does not exist" in result.output
def test_xdg_nonexistant(runner):
original_dirs = xdg.BaseDirectory.xdg_config_dirs
xdg.BaseDirectory.xdg_config_dirs = []
try:
result = CliRunner().invoke(
cli,
catch_exceptions=True,
)
assert result.exception
assert "No configuration file found" in result.output
except:
raise
finally:
# Make sure we ALWAYS set this back to the origianl value, even if the
# test failed.
xdg.BaseDirectory.xdg_config_dirs = original_dirs
def test_xdg_existant(runner, tmpdir, config):
conf_path = tmpdir.mkdir('todoman')
with conf_path.join('todoman.conf').open('w') as f:
f.write(config.open().read())
original_dirs = xdg.BaseDirectory.xdg_config_dirs
xdg.BaseDirectory.xdg_config_dirs = [str(tmpdir)]
try:
result = CliRunner().invoke(
cli,
catch_exceptions=True,
)
assert not result.exception
assert result.output == ''
except:
raise
finally:
# Make sure we ALWAYS set this back to the origianl value, even if the
# test failed.
xdg.BaseDirectory.xdg_config_dirs = original_dirs
| Add a test case for settings discovery | Add a test case for settings discovery
| Python | isc | hobarrera/todoman,Sakshisaraswat/todoman,pimutils/todoman,rimshaakhan/todoman,AnubhaAgrawal/todoman,asalminen/todoman | import xdg
from click.testing import CliRunner
from todoman.cli import cli
def test_explicit_nonexistant(runner):
result = CliRunner().invoke(
cli,
env={
'TODOMAN_CONFIG': '/nonexistant',
},
catch_exceptions=True,
)
assert result.exception
assert "Configuration file /nonexistant does not exist" in result.output
def test_xdg_nonexistant(runner):
original_dirs = xdg.BaseDirectory.xdg_config_dirs
xdg.BaseDirectory.xdg_config_dirs = []
try:
result = CliRunner().invoke(
cli,
catch_exceptions=True,
)
assert result.exception
assert "No configuration file found" in result.output
except:
raise
finally:
# Make sure we ALWAYS set this back to the origianl value, even if the
# test failed.
xdg.BaseDirectory.xdg_config_dirs = original_dirs
Add a test case for settings discovery | import xdg
from click.testing import CliRunner
from todoman.cli import cli
def test_explicit_nonexistant(runner):
result = CliRunner().invoke(
cli,
env={
'TODOMAN_CONFIG': '/nonexistant',
},
catch_exceptions=True,
)
assert result.exception
assert "Configuration file /nonexistant does not exist" in result.output
def test_xdg_nonexistant(runner):
original_dirs = xdg.BaseDirectory.xdg_config_dirs
xdg.BaseDirectory.xdg_config_dirs = []
try:
result = CliRunner().invoke(
cli,
catch_exceptions=True,
)
assert result.exception
assert "No configuration file found" in result.output
except:
raise
finally:
# Make sure we ALWAYS set this back to the origianl value, even if the
# test failed.
xdg.BaseDirectory.xdg_config_dirs = original_dirs
def test_xdg_existant(runner, tmpdir, config):
conf_path = tmpdir.mkdir('todoman')
with conf_path.join('todoman.conf').open('w') as f:
f.write(config.open().read())
original_dirs = xdg.BaseDirectory.xdg_config_dirs
xdg.BaseDirectory.xdg_config_dirs = [str(tmpdir)]
try:
result = CliRunner().invoke(
cli,
catch_exceptions=True,
)
assert not result.exception
assert result.output == ''
except:
raise
finally:
# Make sure we ALWAYS set this back to the origianl value, even if the
# test failed.
xdg.BaseDirectory.xdg_config_dirs = original_dirs
| <commit_before>import xdg
from click.testing import CliRunner
from todoman.cli import cli
def test_explicit_nonexistant(runner):
result = CliRunner().invoke(
cli,
env={
'TODOMAN_CONFIG': '/nonexistant',
},
catch_exceptions=True,
)
assert result.exception
assert "Configuration file /nonexistant does not exist" in result.output
def test_xdg_nonexistant(runner):
original_dirs = xdg.BaseDirectory.xdg_config_dirs
xdg.BaseDirectory.xdg_config_dirs = []
try:
result = CliRunner().invoke(
cli,
catch_exceptions=True,
)
assert result.exception
assert "No configuration file found" in result.output
except:
raise
finally:
# Make sure we ALWAYS set this back to the origianl value, even if the
# test failed.
xdg.BaseDirectory.xdg_config_dirs = original_dirs
<commit_msg>Add a test case for settings discovery<commit_after> | import xdg
from click.testing import CliRunner
from todoman.cli import cli
def test_explicit_nonexistant(runner):
result = CliRunner().invoke(
cli,
env={
'TODOMAN_CONFIG': '/nonexistant',
},
catch_exceptions=True,
)
assert result.exception
assert "Configuration file /nonexistant does not exist" in result.output
def test_xdg_nonexistant(runner):
original_dirs = xdg.BaseDirectory.xdg_config_dirs
xdg.BaseDirectory.xdg_config_dirs = []
try:
result = CliRunner().invoke(
cli,
catch_exceptions=True,
)
assert result.exception
assert "No configuration file found" in result.output
except:
raise
finally:
# Make sure we ALWAYS set this back to the origianl value, even if the
# test failed.
xdg.BaseDirectory.xdg_config_dirs = original_dirs
def test_xdg_existant(runner, tmpdir, config):
conf_path = tmpdir.mkdir('todoman')
with conf_path.join('todoman.conf').open('w') as f:
f.write(config.open().read())
original_dirs = xdg.BaseDirectory.xdg_config_dirs
xdg.BaseDirectory.xdg_config_dirs = [str(tmpdir)]
try:
result = CliRunner().invoke(
cli,
catch_exceptions=True,
)
assert not result.exception
assert result.output == ''
except:
raise
finally:
# Make sure we ALWAYS set this back to the origianl value, even if the
# test failed.
xdg.BaseDirectory.xdg_config_dirs = original_dirs
| import xdg
from click.testing import CliRunner
from todoman.cli import cli
def test_explicit_nonexistant(runner):
result = CliRunner().invoke(
cli,
env={
'TODOMAN_CONFIG': '/nonexistant',
},
catch_exceptions=True,
)
assert result.exception
assert "Configuration file /nonexistant does not exist" in result.output
def test_xdg_nonexistant(runner):
original_dirs = xdg.BaseDirectory.xdg_config_dirs
xdg.BaseDirectory.xdg_config_dirs = []
try:
result = CliRunner().invoke(
cli,
catch_exceptions=True,
)
assert result.exception
assert "No configuration file found" in result.output
except:
raise
finally:
# Make sure we ALWAYS set this back to the origianl value, even if the
# test failed.
xdg.BaseDirectory.xdg_config_dirs = original_dirs
Add a test case for settings discoveryimport xdg
from click.testing import CliRunner
from todoman.cli import cli
def test_explicit_nonexistant(runner):
result = CliRunner().invoke(
cli,
env={
'TODOMAN_CONFIG': '/nonexistant',
},
catch_exceptions=True,
)
assert result.exception
assert "Configuration file /nonexistant does not exist" in result.output
def test_xdg_nonexistant(runner):
original_dirs = xdg.BaseDirectory.xdg_config_dirs
xdg.BaseDirectory.xdg_config_dirs = []
try:
result = CliRunner().invoke(
cli,
catch_exceptions=True,
)
assert result.exception
assert "No configuration file found" in result.output
except:
raise
finally:
# Make sure we ALWAYS set this back to the origianl value, even if the
# test failed.
xdg.BaseDirectory.xdg_config_dirs = original_dirs
def test_xdg_existant(runner, tmpdir, config):
conf_path = tmpdir.mkdir('todoman')
with conf_path.join('todoman.conf').open('w') as f:
f.write(config.open().read())
original_dirs = xdg.BaseDirectory.xdg_config_dirs
xdg.BaseDirectory.xdg_config_dirs = [str(tmpdir)]
try:
result = CliRunner().invoke(
cli,
catch_exceptions=True,
)
assert not result.exception
assert result.output == ''
except:
raise
finally:
# Make sure we ALWAYS set this back to the origianl value, even if the
# test failed.
xdg.BaseDirectory.xdg_config_dirs = original_dirs
| <commit_before>import xdg
from click.testing import CliRunner
from todoman.cli import cli
def test_explicit_nonexistant(runner):
result = CliRunner().invoke(
cli,
env={
'TODOMAN_CONFIG': '/nonexistant',
},
catch_exceptions=True,
)
assert result.exception
assert "Configuration file /nonexistant does not exist" in result.output
def test_xdg_nonexistant(runner):
original_dirs = xdg.BaseDirectory.xdg_config_dirs
xdg.BaseDirectory.xdg_config_dirs = []
try:
result = CliRunner().invoke(
cli,
catch_exceptions=True,
)
assert result.exception
assert "No configuration file found" in result.output
except:
raise
finally:
# Make sure we ALWAYS set this back to the origianl value, even if the
# test failed.
xdg.BaseDirectory.xdg_config_dirs = original_dirs
<commit_msg>Add a test case for settings discovery<commit_after>import xdg
from click.testing import CliRunner
from todoman.cli import cli
def test_explicit_nonexistant(runner):
result = CliRunner().invoke(
cli,
env={
'TODOMAN_CONFIG': '/nonexistant',
},
catch_exceptions=True,
)
assert result.exception
assert "Configuration file /nonexistant does not exist" in result.output
def test_xdg_nonexistant(runner):
original_dirs = xdg.BaseDirectory.xdg_config_dirs
xdg.BaseDirectory.xdg_config_dirs = []
try:
result = CliRunner().invoke(
cli,
catch_exceptions=True,
)
assert result.exception
assert "No configuration file found" in result.output
except:
raise
finally:
# Make sure we ALWAYS set this back to the origianl value, even if the
# test failed.
xdg.BaseDirectory.xdg_config_dirs = original_dirs
def test_xdg_existant(runner, tmpdir, config):
conf_path = tmpdir.mkdir('todoman')
with conf_path.join('todoman.conf').open('w') as f:
f.write(config.open().read())
original_dirs = xdg.BaseDirectory.xdg_config_dirs
xdg.BaseDirectory.xdg_config_dirs = [str(tmpdir)]
try:
result = CliRunner().invoke(
cli,
catch_exceptions=True,
)
assert not result.exception
assert result.output == ''
except:
raise
finally:
# Make sure we ALWAYS set this back to the origianl value, even if the
# test failed.
xdg.BaseDirectory.xdg_config_dirs = original_dirs
|
4c19fea0ff628666e24b2a4d133fa25903a155ff | tests/test_people.py | tests/test_people.py | from models.people import Person, Fellow, Staff
from unittest import TestCase
class PersonTestCases(TestCase):
"""Tests the functionality of the person parent class
"""
def setUp(self):
"""Passes an instance of class Person to all the methods in this class
"""
self.person = Person('Oluwafemi', 'Sule', 'Fellow')
def test_full_name_is_correct(self):
self.assertEqual(self.person.first_name + ' ' + self.person.last_name, 'Oluwafemi Sule')
class FellowTestCases(TestCase):
def setUp(self):
self.fellow = Fellow('Nadia', 'Alexis', 'Fellow')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Fellow, Person))
def test_person_name_is_correct(self):
self.assertEqual(self.fellow.first_name + ' ' + self.fellow.last_name, 'Nadia Alexis')
def test_fellow_id_generation(self):
self.assertEqual(self.fellow.id, 'fel57')
class StaffTestCases(TestCase):
def setUp(self):
self.staff = Staff('Nadia', 'Alexis', 'Staff')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Staff, Person))
def test_full_name_is_correct(self):
self.assertEqual(self.staff.first_name + ' ' + self.staff.last_name, 'Nadia Alexis')
def test_staff_id_generation(self):
self.assertEqual(self.staff.id, 'stf62')
| from models.people import Person, Fellow, Staff
from unittest import TestCase
class FellowTestCases(TestCase):
def setUp(self):
self.fellow = Fellow('Nadia', 'Alexis', 'Fellow')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Fellow, Person))
def test_person_name_is_correct(self):
self.assertEqual(self.fellow.first_name + ' ' + self.fellow.last_name, 'Nadia Alexis')
def test_fellow_id_generation(self):
self.assertEqual(self.fellow.id, 'fel57')
class StaffTestCases(TestCase):
def setUp(self):
self.staff = Staff('Nadia', 'Alexis', 'Staff')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Staff, Person))
def test_full_name_is_correct(self):
self.assertEqual(self.staff.first_name + ' ' + self.staff.last_name, 'Nadia Alexis')
def test_staff_id_generation(self):
self.assertEqual(self.staff.id, 'stf62')
| Remove test for parent class | Remove test for parent class
| Python | mit | Alweezy/alvin-mutisya-dojo-project | from models.people import Person, Fellow, Staff
from unittest import TestCase
class PersonTestCases(TestCase):
"""Tests the functionality of the person parent class
"""
def setUp(self):
"""Passes an instance of class Person to all the methods in this class
"""
self.person = Person('Oluwafemi', 'Sule', 'Fellow')
def test_full_name_is_correct(self):
self.assertEqual(self.person.first_name + ' ' + self.person.last_name, 'Oluwafemi Sule')
class FellowTestCases(TestCase):
def setUp(self):
self.fellow = Fellow('Nadia', 'Alexis', 'Fellow')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Fellow, Person))
def test_person_name_is_correct(self):
self.assertEqual(self.fellow.first_name + ' ' + self.fellow.last_name, 'Nadia Alexis')
def test_fellow_id_generation(self):
self.assertEqual(self.fellow.id, 'fel57')
class StaffTestCases(TestCase):
def setUp(self):
self.staff = Staff('Nadia', 'Alexis', 'Staff')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Staff, Person))
def test_full_name_is_correct(self):
self.assertEqual(self.staff.first_name + ' ' + self.staff.last_name, 'Nadia Alexis')
def test_staff_id_generation(self):
self.assertEqual(self.staff.id, 'stf62')
Remove test for parent class | from models.people import Person, Fellow, Staff
from unittest import TestCase
class FellowTestCases(TestCase):
def setUp(self):
self.fellow = Fellow('Nadia', 'Alexis', 'Fellow')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Fellow, Person))
def test_person_name_is_correct(self):
self.assertEqual(self.fellow.first_name + ' ' + self.fellow.last_name, 'Nadia Alexis')
def test_fellow_id_generation(self):
self.assertEqual(self.fellow.id, 'fel57')
class StaffTestCases(TestCase):
def setUp(self):
self.staff = Staff('Nadia', 'Alexis', 'Staff')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Staff, Person))
def test_full_name_is_correct(self):
self.assertEqual(self.staff.first_name + ' ' + self.staff.last_name, 'Nadia Alexis')
def test_staff_id_generation(self):
self.assertEqual(self.staff.id, 'stf62')
| <commit_before>from models.people import Person, Fellow, Staff
from unittest import TestCase
class PersonTestCases(TestCase):
"""Tests the functionality of the person parent class
"""
def setUp(self):
"""Passes an instance of class Person to all the methods in this class
"""
self.person = Person('Oluwafemi', 'Sule', 'Fellow')
def test_full_name_is_correct(self):
self.assertEqual(self.person.first_name + ' ' + self.person.last_name, 'Oluwafemi Sule')
class FellowTestCases(TestCase):
def setUp(self):
self.fellow = Fellow('Nadia', 'Alexis', 'Fellow')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Fellow, Person))
def test_person_name_is_correct(self):
self.assertEqual(self.fellow.first_name + ' ' + self.fellow.last_name, 'Nadia Alexis')
def test_fellow_id_generation(self):
self.assertEqual(self.fellow.id, 'fel57')
class StaffTestCases(TestCase):
def setUp(self):
self.staff = Staff('Nadia', 'Alexis', 'Staff')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Staff, Person))
def test_full_name_is_correct(self):
self.assertEqual(self.staff.first_name + ' ' + self.staff.last_name, 'Nadia Alexis')
def test_staff_id_generation(self):
self.assertEqual(self.staff.id, 'stf62')
<commit_msg>Remove test for parent class<commit_after> | from models.people import Person, Fellow, Staff
from unittest import TestCase
class FellowTestCases(TestCase):
def setUp(self):
self.fellow = Fellow('Nadia', 'Alexis', 'Fellow')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Fellow, Person))
def test_person_name_is_correct(self):
self.assertEqual(self.fellow.first_name + ' ' + self.fellow.last_name, 'Nadia Alexis')
def test_fellow_id_generation(self):
self.assertEqual(self.fellow.id, 'fel57')
class StaffTestCases(TestCase):
def setUp(self):
self.staff = Staff('Nadia', 'Alexis', 'Staff')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Staff, Person))
def test_full_name_is_correct(self):
self.assertEqual(self.staff.first_name + ' ' + self.staff.last_name, 'Nadia Alexis')
def test_staff_id_generation(self):
self.assertEqual(self.staff.id, 'stf62')
| from models.people import Person, Fellow, Staff
from unittest import TestCase
class PersonTestCases(TestCase):
"""Tests the functionality of the person parent class
"""
def setUp(self):
"""Passes an instance of class Person to all the methods in this class
"""
self.person = Person('Oluwafemi', 'Sule', 'Fellow')
def test_full_name_is_correct(self):
self.assertEqual(self.person.first_name + ' ' + self.person.last_name, 'Oluwafemi Sule')
class FellowTestCases(TestCase):
def setUp(self):
self.fellow = Fellow('Nadia', 'Alexis', 'Fellow')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Fellow, Person))
def test_person_name_is_correct(self):
self.assertEqual(self.fellow.first_name + ' ' + self.fellow.last_name, 'Nadia Alexis')
def test_fellow_id_generation(self):
self.assertEqual(self.fellow.id, 'fel57')
class StaffTestCases(TestCase):
def setUp(self):
self.staff = Staff('Nadia', 'Alexis', 'Staff')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Staff, Person))
def test_full_name_is_correct(self):
self.assertEqual(self.staff.first_name + ' ' + self.staff.last_name, 'Nadia Alexis')
def test_staff_id_generation(self):
self.assertEqual(self.staff.id, 'stf62')
Remove test for parent classfrom models.people import Person, Fellow, Staff
from unittest import TestCase
class FellowTestCases(TestCase):
def setUp(self):
self.fellow = Fellow('Nadia', 'Alexis', 'Fellow')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Fellow, Person))
def test_person_name_is_correct(self):
self.assertEqual(self.fellow.first_name + ' ' + self.fellow.last_name, 'Nadia Alexis')
def test_fellow_id_generation(self):
self.assertEqual(self.fellow.id, 'fel57')
class StaffTestCases(TestCase):
def setUp(self):
self.staff = Staff('Nadia', 'Alexis', 'Staff')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Staff, Person))
def test_full_name_is_correct(self):
self.assertEqual(self.staff.first_name + ' ' + self.staff.last_name, 'Nadia Alexis')
def test_staff_id_generation(self):
self.assertEqual(self.staff.id, 'stf62')
| <commit_before>from models.people import Person, Fellow, Staff
from unittest import TestCase
class PersonTestCases(TestCase):
"""Tests the functionality of the person parent class
"""
def setUp(self):
"""Passes an instance of class Person to all the methods in this class
"""
self.person = Person('Oluwafemi', 'Sule', 'Fellow')
def test_full_name_is_correct(self):
self.assertEqual(self.person.first_name + ' ' + self.person.last_name, 'Oluwafemi Sule')
class FellowTestCases(TestCase):
def setUp(self):
self.fellow = Fellow('Nadia', 'Alexis', 'Fellow')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Fellow, Person))
def test_person_name_is_correct(self):
self.assertEqual(self.fellow.first_name + ' ' + self.fellow.last_name, 'Nadia Alexis')
def test_fellow_id_generation(self):
self.assertEqual(self.fellow.id, 'fel57')
class StaffTestCases(TestCase):
def setUp(self):
self.staff = Staff('Nadia', 'Alexis', 'Staff')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Staff, Person))
def test_full_name_is_correct(self):
self.assertEqual(self.staff.first_name + ' ' + self.staff.last_name, 'Nadia Alexis')
def test_staff_id_generation(self):
self.assertEqual(self.staff.id, 'stf62')
<commit_msg>Remove test for parent class<commit_after>from models.people import Person, Fellow, Staff
from unittest import TestCase
class FellowTestCases(TestCase):
def setUp(self):
self.fellow = Fellow('Nadia', 'Alexis', 'Fellow')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Fellow, Person))
def test_person_name_is_correct(self):
self.assertEqual(self.fellow.first_name + ' ' + self.fellow.last_name, 'Nadia Alexis')
def test_fellow_id_generation(self):
self.assertEqual(self.fellow.id, 'fel57')
class StaffTestCases(TestCase):
def setUp(self):
self.staff = Staff('Nadia', 'Alexis', 'Staff')
def test_if_inherits_from_Person(self):
self.assertTrue(issubclass(Staff, Person))
def test_full_name_is_correct(self):
self.assertEqual(self.staff.first_name + ' ' + self.staff.last_name, 'Nadia Alexis')
def test_staff_id_generation(self):
self.assertEqual(self.staff.id, 'stf62')
|
7ccacd1390e3f3ee86a1d21534db2c775003e432 | writeboards/models.py | writeboards/models.py | from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from tagging.models import Tag
from tagging.fields import TagField
class Writeboard(models.model):
writeboard_name = models.CharField(_('writeboard name'), max_length=100)
slug = models.SlugField(_('slug'), unique=True)
creator = models.ForeignKey(_('creator'), User, related_name=_("creator"))
create_date = models.DateTimeField(_("created"), default=datetime.now)
writeboard_id = models.IntegerField(_('writeboard id'),)
tags = TagField()
active = models.BooleanField(default=True)
def __unicode__(self):
return self.writeboard_name
class Meta(object):
verbose_name = _('writeboard')
verbose_name_plural = _('writeboards')
ordering=['modified']
@models.permalink
def get_absolute_url(self):
return ('writeboard_detail', None, {'slug': self.slug})
| from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from tagging.models import Tag
from tagging.fields import TagField
class Writeboard(models.model):
"""
Plaintext password field could simply be filled in with a reminder of.
"""
writeboard_name = models.CharField(_('writeboard name'), max_length=100)
slug = models.SlugField(_('slug'), unique=True)
creator = models.ForeignKey(_('creator'), User, related_name=_("creator"))
create_date = models.DateTimeField(_("created"), default=datetime.now)
writeboard_id = models.IntegerField(_('writeboard id'),)
tags = TagField()
public = models.BooleanField(default=True)
plaintext_password = models.CharField(_('plaintext password'),
max_length=100, blank =True, null =True, help_text="no encryption")
active = models.BooleanField(default=True)
def __unicode__(self):
return self.writeboard_name
class Meta(object):
verbose_name = _('writeboard')
verbose_name_plural = _('writeboards')
ordering=['modified']
def create_a_writeboard():
return ('http://writeboard.com/')
@models.permalink
def get_absolute_url(self):
return ('writeboard_detail', None, {'slug': self.slug})
| Add writeboard specific fields to model | Add writeboard specific fields to model | Python | mit | rizumu/django-paste-organizer | from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from tagging.models import Tag
from tagging.fields import TagField
class Writeboard(models.model):
writeboard_name = models.CharField(_('writeboard name'), max_length=100)
slug = models.SlugField(_('slug'), unique=True)
creator = models.ForeignKey(_('creator'), User, related_name=_("creator"))
create_date = models.DateTimeField(_("created"), default=datetime.now)
writeboard_id = models.IntegerField(_('writeboard id'),)
tags = TagField()
active = models.BooleanField(default=True)
def __unicode__(self):
return self.writeboard_name
class Meta(object):
verbose_name = _('writeboard')
verbose_name_plural = _('writeboards')
ordering=['modified']
@models.permalink
def get_absolute_url(self):
return ('writeboard_detail', None, {'slug': self.slug})
Add writeboard specific fields to model | from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from tagging.models import Tag
from tagging.fields import TagField
class Writeboard(models.model):
"""
Plaintext password field could simply be filled in with a reminder of.
"""
writeboard_name = models.CharField(_('writeboard name'), max_length=100)
slug = models.SlugField(_('slug'), unique=True)
creator = models.ForeignKey(_('creator'), User, related_name=_("creator"))
create_date = models.DateTimeField(_("created"), default=datetime.now)
writeboard_id = models.IntegerField(_('writeboard id'),)
tags = TagField()
public = models.BooleanField(default=True)
plaintext_password = models.CharField(_('plaintext password'),
max_length=100, blank =True, null =True, help_text="no encryption")
active = models.BooleanField(default=True)
def __unicode__(self):
return self.writeboard_name
class Meta(object):
verbose_name = _('writeboard')
verbose_name_plural = _('writeboards')
ordering=['modified']
def create_a_writeboard():
return ('http://writeboard.com/')
@models.permalink
def get_absolute_url(self):
return ('writeboard_detail', None, {'slug': self.slug})
| <commit_before>from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from tagging.models import Tag
from tagging.fields import TagField
class Writeboard(models.model):
writeboard_name = models.CharField(_('writeboard name'), max_length=100)
slug = models.SlugField(_('slug'), unique=True)
creator = models.ForeignKey(_('creator'), User, related_name=_("creator"))
create_date = models.DateTimeField(_("created"), default=datetime.now)
writeboard_id = models.IntegerField(_('writeboard id'),)
tags = TagField()
active = models.BooleanField(default=True)
def __unicode__(self):
return self.writeboard_name
class Meta(object):
verbose_name = _('writeboard')
verbose_name_plural = _('writeboards')
ordering=['modified']
@models.permalink
def get_absolute_url(self):
return ('writeboard_detail', None, {'slug': self.slug})
<commit_msg>Add writeboard specific fields to model <commit_after> | from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from tagging.models import Tag
from tagging.fields import TagField
class Writeboard(models.model):
"""
Plaintext password field could simply be filled in with a reminder of.
"""
writeboard_name = models.CharField(_('writeboard name'), max_length=100)
slug = models.SlugField(_('slug'), unique=True)
creator = models.ForeignKey(_('creator'), User, related_name=_("creator"))
create_date = models.DateTimeField(_("created"), default=datetime.now)
writeboard_id = models.IntegerField(_('writeboard id'),)
tags = TagField()
public = models.BooleanField(default=True)
plaintext_password = models.CharField(_('plaintext password'),
max_length=100, blank =True, null =True, help_text="no encryption")
active = models.BooleanField(default=True)
def __unicode__(self):
return self.writeboard_name
class Meta(object):
verbose_name = _('writeboard')
verbose_name_plural = _('writeboards')
ordering=['modified']
def create_a_writeboard():
return ('http://writeboard.com/')
@models.permalink
def get_absolute_url(self):
return ('writeboard_detail', None, {'slug': self.slug})
| from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from tagging.models import Tag
from tagging.fields import TagField
class Writeboard(models.model):
writeboard_name = models.CharField(_('writeboard name'), max_length=100)
slug = models.SlugField(_('slug'), unique=True)
creator = models.ForeignKey(_('creator'), User, related_name=_("creator"))
create_date = models.DateTimeField(_("created"), default=datetime.now)
writeboard_id = models.IntegerField(_('writeboard id'),)
tags = TagField()
active = models.BooleanField(default=True)
def __unicode__(self):
return self.writeboard_name
class Meta(object):
verbose_name = _('writeboard')
verbose_name_plural = _('writeboards')
ordering=['modified']
@models.permalink
def get_absolute_url(self):
return ('writeboard_detail', None, {'slug': self.slug})
Add writeboard specific fields to model from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from tagging.models import Tag
from tagging.fields import TagField
class Writeboard(models.model):
"""
Plaintext password field could simply be filled in with a reminder of.
"""
writeboard_name = models.CharField(_('writeboard name'), max_length=100)
slug = models.SlugField(_('slug'), unique=True)
creator = models.ForeignKey(_('creator'), User, related_name=_("creator"))
create_date = models.DateTimeField(_("created"), default=datetime.now)
writeboard_id = models.IntegerField(_('writeboard id'),)
tags = TagField()
public = models.BooleanField(default=True)
plaintext_password = models.CharField(_('plaintext password'),
max_length=100, blank =True, null =True, help_text="no encryption")
active = models.BooleanField(default=True)
def __unicode__(self):
return self.writeboard_name
class Meta(object):
verbose_name = _('writeboard')
verbose_name_plural = _('writeboards')
ordering=['modified']
def create_a_writeboard():
return ('http://writeboard.com/')
@models.permalink
def get_absolute_url(self):
return ('writeboard_detail', None, {'slug': self.slug})
| <commit_before>from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from tagging.models import Tag
from tagging.fields import TagField
class Writeboard(models.model):
writeboard_name = models.CharField(_('writeboard name'), max_length=100)
slug = models.SlugField(_('slug'), unique=True)
creator = models.ForeignKey(_('creator'), User, related_name=_("creator"))
create_date = models.DateTimeField(_("created"), default=datetime.now)
writeboard_id = models.IntegerField(_('writeboard id'),)
tags = TagField()
active = models.BooleanField(default=True)
def __unicode__(self):
return self.writeboard_name
class Meta(object):
verbose_name = _('writeboard')
verbose_name_plural = _('writeboards')
ordering=['modified']
@models.permalink
def get_absolute_url(self):
return ('writeboard_detail', None, {'slug': self.slug})
<commit_msg>Add writeboard specific fields to model <commit_after>from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from tagging.models import Tag
from tagging.fields import TagField
class Writeboard(models.model):
"""
Plaintext password field could simply be filled in with a reminder of.
"""
writeboard_name = models.CharField(_('writeboard name'), max_length=100)
slug = models.SlugField(_('slug'), unique=True)
creator = models.ForeignKey(_('creator'), User, related_name=_("creator"))
create_date = models.DateTimeField(_("created"), default=datetime.now)
writeboard_id = models.IntegerField(_('writeboard id'),)
tags = TagField()
public = models.BooleanField(default=True)
plaintext_password = models.CharField(_('plaintext password'),
max_length=100, blank =True, null =True, help_text="no encryption")
active = models.BooleanField(default=True)
def __unicode__(self):
return self.writeboard_name
class Meta(object):
verbose_name = _('writeboard')
verbose_name_plural = _('writeboards')
ordering=['modified']
def create_a_writeboard():
return ('http://writeboard.com/')
@models.permalink
def get_absolute_url(self):
return ('writeboard_detail', None, {'slug': self.slug})
|
df4d4f2972d8d1a91ce4353343c6279580985e3c | index.py | index.py | from __future__ import division
import urllib.request as request, json, os.path
import json, time
if os.path.exists('config/config.json'):
config_file = open('config/config.json')
config = json.load(config_file)
else:
print('Please copy the config.json file to config-local.json and fill in the file.')
exit()
print(time.strftime("%x") + ": Eagle woke up")
total_volume = 0
symbols = ','.join(config['currencies'])
url = "http://api.coinlayer.com/api/live?access_key=" + config['coinlayer'] + "&target=EUR&symbols=" + symbols
with request.urlopen(url) as response:
rates = json.loads(response.read().decode('utf-8'))['rates']
for currency in config['currencies'].keys():
if currency not in rates:
print("Cryptocurrency", currency, "does not exist.")
continue
total_volume += rates[currency] * config['currencies'][currency]['balance']
print("Total euro : " + str(total_volume) + " eur")
| from __future__ import division
import urllib.request as request, json, os.path
import json, time
if os.path.exists('config/config.json'):
config_file = open('config/config.json')
config = json.load(config_file)
else:
print('Please copy the config.json.template file to config.json and fill in the file.')
exit()
print(time.strftime("%x") + ": Eagle woke up")
total_volume = 0
symbols = ','.join(config['currencies'])
url = "http://api.coinlayer.com/api/live?access_key=" + config['coinlayer'] + "&target=EUR&symbols=" + symbols
with request.urlopen(url) as response:
rates = json.loads(response.read().decode('utf-8'))['rates']
for currency in config['currencies'].keys():
if currency not in rates:
print("Cryptocurrency", currency, "does not exist.")
continue
total_volume += rates[currency] * config['currencies'][currency]['balance']
print("Total euro : " + str(total_volume) + " eur")
| Change print statement about config | Change print statement about config
| Python | mit | pkakelas/eagle | from __future__ import division
import urllib.request as request, json, os.path
import json, time
if os.path.exists('config/config.json'):
config_file = open('config/config.json')
config = json.load(config_file)
else:
print('Please copy the config.json file to config-local.json and fill in the file.')
exit()
print(time.strftime("%x") + ": Eagle woke up")
total_volume = 0
symbols = ','.join(config['currencies'])
url = "http://api.coinlayer.com/api/live?access_key=" + config['coinlayer'] + "&target=EUR&symbols=" + symbols
with request.urlopen(url) as response:
rates = json.loads(response.read().decode('utf-8'))['rates']
for currency in config['currencies'].keys():
if currency not in rates:
print("Cryptocurrency", currency, "does not exist.")
continue
total_volume += rates[currency] * config['currencies'][currency]['balance']
print("Total euro : " + str(total_volume) + " eur")
Change print statement about config | from __future__ import division
import urllib.request as request, json, os.path
import json, time
if os.path.exists('config/config.json'):
config_file = open('config/config.json')
config = json.load(config_file)
else:
print('Please copy the config.json.template file to config.json and fill in the file.')
exit()
print(time.strftime("%x") + ": Eagle woke up")
total_volume = 0
symbols = ','.join(config['currencies'])
url = "http://api.coinlayer.com/api/live?access_key=" + config['coinlayer'] + "&target=EUR&symbols=" + symbols
with request.urlopen(url) as response:
rates = json.loads(response.read().decode('utf-8'))['rates']
for currency in config['currencies'].keys():
if currency not in rates:
print("Cryptocurrency", currency, "does not exist.")
continue
total_volume += rates[currency] * config['currencies'][currency]['balance']
print("Total euro : " + str(total_volume) + " eur")
| <commit_before>from __future__ import division
import urllib.request as request, json, os.path
import json, time
if os.path.exists('config/config.json'):
config_file = open('config/config.json')
config = json.load(config_file)
else:
print('Please copy the config.json file to config-local.json and fill in the file.')
exit()
print(time.strftime("%x") + ": Eagle woke up")
total_volume = 0
symbols = ','.join(config['currencies'])
url = "http://api.coinlayer.com/api/live?access_key=" + config['coinlayer'] + "&target=EUR&symbols=" + symbols
with request.urlopen(url) as response:
rates = json.loads(response.read().decode('utf-8'))['rates']
for currency in config['currencies'].keys():
if currency not in rates:
print("Cryptocurrency", currency, "does not exist.")
continue
total_volume += rates[currency] * config['currencies'][currency]['balance']
print("Total euro : " + str(total_volume) + " eur")
<commit_msg>Change print statement about config<commit_after> | from __future__ import division
import urllib.request as request, json, os.path
import json, time
if os.path.exists('config/config.json'):
config_file = open('config/config.json')
config = json.load(config_file)
else:
print('Please copy the config.json.template file to config.json and fill in the file.')
exit()
print(time.strftime("%x") + ": Eagle woke up")
total_volume = 0
symbols = ','.join(config['currencies'])
url = "http://api.coinlayer.com/api/live?access_key=" + config['coinlayer'] + "&target=EUR&symbols=" + symbols
with request.urlopen(url) as response:
rates = json.loads(response.read().decode('utf-8'))['rates']
for currency in config['currencies'].keys():
if currency not in rates:
print("Cryptocurrency", currency, "does not exist.")
continue
total_volume += rates[currency] * config['currencies'][currency]['balance']
print("Total euro : " + str(total_volume) + " eur")
| from __future__ import division
import urllib.request as request, json, os.path
import json, time
if os.path.exists('config/config.json'):
config_file = open('config/config.json')
config = json.load(config_file)
else:
print('Please copy the config.json file to config-local.json and fill in the file.')
exit()
print(time.strftime("%x") + ": Eagle woke up")
total_volume = 0
symbols = ','.join(config['currencies'])
url = "http://api.coinlayer.com/api/live?access_key=" + config['coinlayer'] + "&target=EUR&symbols=" + symbols
with request.urlopen(url) as response:
rates = json.loads(response.read().decode('utf-8'))['rates']
for currency in config['currencies'].keys():
if currency not in rates:
print("Cryptocurrency", currency, "does not exist.")
continue
total_volume += rates[currency] * config['currencies'][currency]['balance']
print("Total euro : " + str(total_volume) + " eur")
Change print statement about configfrom __future__ import division
import urllib.request as request, json, os.path
import json, time
if os.path.exists('config/config.json'):
config_file = open('config/config.json')
config = json.load(config_file)
else:
print('Please copy the config.json.template file to config.json and fill in the file.')
exit()
print(time.strftime("%x") + ": Eagle woke up")
total_volume = 0
symbols = ','.join(config['currencies'])
url = "http://api.coinlayer.com/api/live?access_key=" + config['coinlayer'] + "&target=EUR&symbols=" + symbols
with request.urlopen(url) as response:
rates = json.loads(response.read().decode('utf-8'))['rates']
for currency in config['currencies'].keys():
if currency not in rates:
print("Cryptocurrency", currency, "does not exist.")
continue
total_volume += rates[currency] * config['currencies'][currency]['balance']
print("Total euro : " + str(total_volume) + " eur")
| <commit_before>from __future__ import division
import urllib.request as request, json, os.path
import json, time
if os.path.exists('config/config.json'):
config_file = open('config/config.json')
config = json.load(config_file)
else:
print('Please copy the config.json file to config-local.json and fill in the file.')
exit()
print(time.strftime("%x") + ": Eagle woke up")
total_volume = 0
symbols = ','.join(config['currencies'])
url = "http://api.coinlayer.com/api/live?access_key=" + config['coinlayer'] + "&target=EUR&symbols=" + symbols
with request.urlopen(url) as response:
rates = json.loads(response.read().decode('utf-8'))['rates']
for currency in config['currencies'].keys():
if currency not in rates:
print("Cryptocurrency", currency, "does not exist.")
continue
total_volume += rates[currency] * config['currencies'][currency]['balance']
print("Total euro : " + str(total_volume) + " eur")
<commit_msg>Change print statement about config<commit_after>from __future__ import division
import urllib.request as request, json, os.path
import json, time
if os.path.exists('config/config.json'):
config_file = open('config/config.json')
config = json.load(config_file)
else:
print('Please copy the config.json.template file to config.json and fill in the file.')
exit()
print(time.strftime("%x") + ": Eagle woke up")
total_volume = 0
symbols = ','.join(config['currencies'])
url = "http://api.coinlayer.com/api/live?access_key=" + config['coinlayer'] + "&target=EUR&symbols=" + symbols
with request.urlopen(url) as response:
rates = json.loads(response.read().decode('utf-8'))['rates']
for currency in config['currencies'].keys():
if currency not in rates:
print("Cryptocurrency", currency, "does not exist.")
continue
total_volume += rates[currency] * config['currencies'][currency]['balance']
print("Total euro : " + str(total_volume) + " eur")
|
ef8af3637666d854298681a4cdd2f529463c257c | lymph/web/handlers.py | lymph/web/handlers.py | import json
from werkzeug.exceptions import MethodNotAllowed
http_methods = ('get', 'post', 'head', 'options', 'put', 'delete')
class RequestHandler(object):
def __init__(self, interface, request):
self.request = request
self.interface = interface
self._json = None
@property
def allowed_methods(self):
return [method.upper() for method in http_methods if callable(getattr(self, method, None))]
def json(self):
if not "application/json" == self.request.mimetype:
raise ValueError("The request Content-Type is not JSON")
if self._json is None:
self._json = json.loads(self.request.get_data(as_text=True))
return self._json
def dispatch(self, args):
method = self.request.method.lower()
if method not in http_methods:
raise MethodNotAllowed(self.allowed_methods)
try:
func = getattr(self, method)
except AttributeError:
raise MethodNotAllowed(self.allowed_methods)
return func(**args)
| import json
from werkzeug.exceptions import MethodNotAllowed
http_methods = ('get', 'post', 'head', 'options', 'put', 'patch', 'delete')
class RequestHandler(object):
def __init__(self, interface, request):
self.request = request
self.interface = interface
self._json = None
@property
def allowed_methods(self):
return [method.upper() for method in http_methods if callable(getattr(self, method, None))]
def json(self):
if not "application/json" == self.request.mimetype:
raise ValueError("The request Content-Type is not JSON")
if self._json is None:
self._json = json.loads(self.request.get_data(as_text=True))
return self._json
def dispatch(self, args):
method = self.request.method.lower()
if method not in http_methods:
raise MethodNotAllowed(self.allowed_methods)
try:
func = getattr(self, method)
except AttributeError:
raise MethodNotAllowed(self.allowed_methods)
return func(**args)
| Add support for PATCH http method | Add support for PATCH http method
| Python | apache-2.0 | kstrempel/lymph,alazaro/lymph,lyudmildrx/lymph,lyudmildrx/lymph,vpikulik/lymph,mamachanko/lymph,Drahflow/lymph,mouadino/lymph,alazaro/lymph,itakouna/lymph,itakouna/lymph,torte/lymph,mamachanko/lymph,dushyant88/lymph,mamachanko/lymph,alazaro/lymph,mouadino/lymph,deliveryhero/lymph,itakouna/lymph,lyudmildrx/lymph,mouadino/lymph | import json
from werkzeug.exceptions import MethodNotAllowed
http_methods = ('get', 'post', 'head', 'options', 'put', 'delete')
class RequestHandler(object):
def __init__(self, interface, request):
self.request = request
self.interface = interface
self._json = None
@property
def allowed_methods(self):
return [method.upper() for method in http_methods if callable(getattr(self, method, None))]
def json(self):
if not "application/json" == self.request.mimetype:
raise ValueError("The request Content-Type is not JSON")
if self._json is None:
self._json = json.loads(self.request.get_data(as_text=True))
return self._json
def dispatch(self, args):
method = self.request.method.lower()
if method not in http_methods:
raise MethodNotAllowed(self.allowed_methods)
try:
func = getattr(self, method)
except AttributeError:
raise MethodNotAllowed(self.allowed_methods)
return func(**args)
Add support for PATCH http method | import json
from werkzeug.exceptions import MethodNotAllowed
http_methods = ('get', 'post', 'head', 'options', 'put', 'patch', 'delete')
class RequestHandler(object):
def __init__(self, interface, request):
self.request = request
self.interface = interface
self._json = None
@property
def allowed_methods(self):
return [method.upper() for method in http_methods if callable(getattr(self, method, None))]
def json(self):
if not "application/json" == self.request.mimetype:
raise ValueError("The request Content-Type is not JSON")
if self._json is None:
self._json = json.loads(self.request.get_data(as_text=True))
return self._json
def dispatch(self, args):
method = self.request.method.lower()
if method not in http_methods:
raise MethodNotAllowed(self.allowed_methods)
try:
func = getattr(self, method)
except AttributeError:
raise MethodNotAllowed(self.allowed_methods)
return func(**args)
| <commit_before>import json
from werkzeug.exceptions import MethodNotAllowed
http_methods = ('get', 'post', 'head', 'options', 'put', 'delete')
class RequestHandler(object):
def __init__(self, interface, request):
self.request = request
self.interface = interface
self._json = None
@property
def allowed_methods(self):
return [method.upper() for method in http_methods if callable(getattr(self, method, None))]
def json(self):
if not "application/json" == self.request.mimetype:
raise ValueError("The request Content-Type is not JSON")
if self._json is None:
self._json = json.loads(self.request.get_data(as_text=True))
return self._json
def dispatch(self, args):
method = self.request.method.lower()
if method not in http_methods:
raise MethodNotAllowed(self.allowed_methods)
try:
func = getattr(self, method)
except AttributeError:
raise MethodNotAllowed(self.allowed_methods)
return func(**args)
<commit_msg>Add support for PATCH http method<commit_after> | import json
from werkzeug.exceptions import MethodNotAllowed
http_methods = ('get', 'post', 'head', 'options', 'put', 'patch', 'delete')
class RequestHandler(object):
def __init__(self, interface, request):
self.request = request
self.interface = interface
self._json = None
@property
def allowed_methods(self):
return [method.upper() for method in http_methods if callable(getattr(self, method, None))]
def json(self):
if not "application/json" == self.request.mimetype:
raise ValueError("The request Content-Type is not JSON")
if self._json is None:
self._json = json.loads(self.request.get_data(as_text=True))
return self._json
def dispatch(self, args):
method = self.request.method.lower()
if method not in http_methods:
raise MethodNotAllowed(self.allowed_methods)
try:
func = getattr(self, method)
except AttributeError:
raise MethodNotAllowed(self.allowed_methods)
return func(**args)
| import json
from werkzeug.exceptions import MethodNotAllowed
http_methods = ('get', 'post', 'head', 'options', 'put', 'delete')
class RequestHandler(object):
def __init__(self, interface, request):
self.request = request
self.interface = interface
self._json = None
@property
def allowed_methods(self):
return [method.upper() for method in http_methods if callable(getattr(self, method, None))]
def json(self):
if not "application/json" == self.request.mimetype:
raise ValueError("The request Content-Type is not JSON")
if self._json is None:
self._json = json.loads(self.request.get_data(as_text=True))
return self._json
def dispatch(self, args):
method = self.request.method.lower()
if method not in http_methods:
raise MethodNotAllowed(self.allowed_methods)
try:
func = getattr(self, method)
except AttributeError:
raise MethodNotAllowed(self.allowed_methods)
return func(**args)
Add support for PATCH http methodimport json
from werkzeug.exceptions import MethodNotAllowed
http_methods = ('get', 'post', 'head', 'options', 'put', 'patch', 'delete')
class RequestHandler(object):
def __init__(self, interface, request):
self.request = request
self.interface = interface
self._json = None
@property
def allowed_methods(self):
return [method.upper() for method in http_methods if callable(getattr(self, method, None))]
def json(self):
if not "application/json" == self.request.mimetype:
raise ValueError("The request Content-Type is not JSON")
if self._json is None:
self._json = json.loads(self.request.get_data(as_text=True))
return self._json
def dispatch(self, args):
method = self.request.method.lower()
if method not in http_methods:
raise MethodNotAllowed(self.allowed_methods)
try:
func = getattr(self, method)
except AttributeError:
raise MethodNotAllowed(self.allowed_methods)
return func(**args)
| <commit_before>import json
from werkzeug.exceptions import MethodNotAllowed
http_methods = ('get', 'post', 'head', 'options', 'put', 'delete')
class RequestHandler(object):
def __init__(self, interface, request):
self.request = request
self.interface = interface
self._json = None
@property
def allowed_methods(self):
return [method.upper() for method in http_methods if callable(getattr(self, method, None))]
def json(self):
if not "application/json" == self.request.mimetype:
raise ValueError("The request Content-Type is not JSON")
if self._json is None:
self._json = json.loads(self.request.get_data(as_text=True))
return self._json
def dispatch(self, args):
method = self.request.method.lower()
if method not in http_methods:
raise MethodNotAllowed(self.allowed_methods)
try:
func = getattr(self, method)
except AttributeError:
raise MethodNotAllowed(self.allowed_methods)
return func(**args)
<commit_msg>Add support for PATCH http method<commit_after>import json
from werkzeug.exceptions import MethodNotAllowed
http_methods = ('get', 'post', 'head', 'options', 'put', 'patch', 'delete')
class RequestHandler(object):
def __init__(self, interface, request):
self.request = request
self.interface = interface
self._json = None
@property
def allowed_methods(self):
return [method.upper() for method in http_methods if callable(getattr(self, method, None))]
def json(self):
if not "application/json" == self.request.mimetype:
raise ValueError("The request Content-Type is not JSON")
if self._json is None:
self._json = json.loads(self.request.get_data(as_text=True))
return self._json
def dispatch(self, args):
method = self.request.method.lower()
if method not in http_methods:
raise MethodNotAllowed(self.allowed_methods)
try:
func = getattr(self, method)
except AttributeError:
raise MethodNotAllowed(self.allowed_methods)
return func(**args)
|
e39b59ab345d9d72a31d739218d68072d3794cf6 | networkzero/config.py | networkzero/config.py | # -*- coding: utf-8 -*-
"""Common configuration elements for networkzero
"""
ENCODING = "UTF-8"
class _Forever(object):
def __repr__(self): return "<Forever>"
FOREVER = _Forever()
SHORT_WAIT = 1 # 1 second
EVERYTHING = ""
COMMAND_ACK = "ack"
#
# Beacons will broadcast adverts at this frequency
#
BEACON_ADVERT_FREQUENCY_S = 5
#
# Adverts will expire after this many seconds unless
# a fresh broadcast is received. Default it above the
# broadcast frequency so adverts are not forever expiring
# and being recreated by the next received broadcast.
#
ADVERT_TTL_S = 3 * BEACON_ADVERT_FREQUENCY_S
VALID_PORTS = range(0x10000)
DYNAMIC_PORTS = range(0xC000, 0x10000)
| # -*- coding: utf-8 -*-
"""Common configuration elements for networkzero
"""
ENCODING = "UTF-8"
class _Forever(object):
def __repr__(self): return "<Forever>"
FOREVER = _Forever()
SHORT_WAIT = 1 # 1 second
EVERYTHING = ""
COMMAND_ACK = "ack"
#
# Beacons will broadcast adverts at this frequency
#
BEACON_ADVERT_FREQUENCY_S = 2
#
# Adverts will expire after this many seconds unless
# a fresh broadcast is received. Default it above the
# broadcast frequency so adverts are not forever expiring
# and being recreated by the next received broadcast.
#
# NB since adverts are broadcast round-robin (ie only one advert
# is broadcast every BEACON_ADVERT_FREQUENCY_S seconds) we need
# to allow for the possibility that any given name might only
# be advertised, say, once every 5 times.
#
ADVERT_TTL_S = 10 * BEACON_ADVERT_FREQUENCY_S
VALID_PORTS = range(0x10000)
DYNAMIC_PORTS = range(0xC000, 0x10000)
| Speed up the broadcast frequency | Speed up the broadcast frequency
| Python | mit | tjguk/networkzero,tjguk/networkzero,tjguk/networkzero | # -*- coding: utf-8 -*-
"""Common configuration elements for networkzero
"""
ENCODING = "UTF-8"
class _Forever(object):
def __repr__(self): return "<Forever>"
FOREVER = _Forever()
SHORT_WAIT = 1 # 1 second
EVERYTHING = ""
COMMAND_ACK = "ack"
#
# Beacons will broadcast adverts at this frequency
#
BEACON_ADVERT_FREQUENCY_S = 5
#
# Adverts will expire after this many seconds unless
# a fresh broadcast is received. Default it above the
# broadcast frequency so adverts are not forever expiring
# and being recreated by the next received broadcast.
#
ADVERT_TTL_S = 3 * BEACON_ADVERT_FREQUENCY_S
VALID_PORTS = range(0x10000)
DYNAMIC_PORTS = range(0xC000, 0x10000)
Speed up the broadcast frequency | # -*- coding: utf-8 -*-
"""Common configuration elements for networkzero
"""
ENCODING = "UTF-8"
class _Forever(object):
def __repr__(self): return "<Forever>"
FOREVER = _Forever()
SHORT_WAIT = 1 # 1 second
EVERYTHING = ""
COMMAND_ACK = "ack"
#
# Beacons will broadcast adverts at this frequency
#
BEACON_ADVERT_FREQUENCY_S = 2
#
# Adverts will expire after this many seconds unless
# a fresh broadcast is received. Default it above the
# broadcast frequency so adverts are not forever expiring
# and being recreated by the next received broadcast.
#
# NB since adverts are broadcast round-robin (ie only one advert
# is broadcast every BEACON_ADVERT_FREQUENCY_S seconds) we need
# to allow for the possibility that any given name might only
# be advertised, say, once every 5 times.
#
ADVERT_TTL_S = 10 * BEACON_ADVERT_FREQUENCY_S
VALID_PORTS = range(0x10000)
DYNAMIC_PORTS = range(0xC000, 0x10000)
| <commit_before># -*- coding: utf-8 -*-
"""Common configuration elements for networkzero
"""
ENCODING = "UTF-8"
class _Forever(object):
def __repr__(self): return "<Forever>"
FOREVER = _Forever()
SHORT_WAIT = 1 # 1 second
EVERYTHING = ""
COMMAND_ACK = "ack"
#
# Beacons will broadcast adverts at this frequency
#
BEACON_ADVERT_FREQUENCY_S = 5
#
# Adverts will expire after this many seconds unless
# a fresh broadcast is received. Default it above the
# broadcast frequency so adverts are not forever expiring
# and being recreated by the next received broadcast.
#
ADVERT_TTL_S = 3 * BEACON_ADVERT_FREQUENCY_S
VALID_PORTS = range(0x10000)
DYNAMIC_PORTS = range(0xC000, 0x10000)
<commit_msg>Speed up the broadcast frequency<commit_after> | # -*- coding: utf-8 -*-
"""Common configuration elements for networkzero
"""
ENCODING = "UTF-8"
class _Forever(object):
def __repr__(self): return "<Forever>"
FOREVER = _Forever()
SHORT_WAIT = 1 # 1 second
EVERYTHING = ""
COMMAND_ACK = "ack"
#
# Beacons will broadcast adverts at this frequency
#
BEACON_ADVERT_FREQUENCY_S = 2
#
# Adverts will expire after this many seconds unless
# a fresh broadcast is received. Default it above the
# broadcast frequency so adverts are not forever expiring
# and being recreated by the next received broadcast.
#
# NB since adverts are broadcast round-robin (ie only one advert
# is broadcast every BEACON_ADVERT_FREQUENCY_S seconds) we need
# to allow for the possibility that any given name might only
# be advertised, say, once every 5 times.
#
ADVERT_TTL_S = 10 * BEACON_ADVERT_FREQUENCY_S
VALID_PORTS = range(0x10000)
DYNAMIC_PORTS = range(0xC000, 0x10000)
| # -*- coding: utf-8 -*-
"""Common configuration elements for networkzero
"""
ENCODING = "UTF-8"
class _Forever(object):
def __repr__(self): return "<Forever>"
FOREVER = _Forever()
SHORT_WAIT = 1 # 1 second
EVERYTHING = ""
COMMAND_ACK = "ack"
#
# Beacons will broadcast adverts at this frequency
#
BEACON_ADVERT_FREQUENCY_S = 5
#
# Adverts will expire after this many seconds unless
# a fresh broadcast is received. Default it above the
# broadcast frequency so adverts are not forever expiring
# and being recreated by the next received broadcast.
#
ADVERT_TTL_S = 3 * BEACON_ADVERT_FREQUENCY_S
VALID_PORTS = range(0x10000)
DYNAMIC_PORTS = range(0xC000, 0x10000)
Speed up the broadcast frequency# -*- coding: utf-8 -*-
"""Common configuration elements for networkzero
"""
ENCODING = "UTF-8"
class _Forever(object):
def __repr__(self): return "<Forever>"
FOREVER = _Forever()
SHORT_WAIT = 1 # 1 second
EVERYTHING = ""
COMMAND_ACK = "ack"
#
# Beacons will broadcast adverts at this frequency
#
BEACON_ADVERT_FREQUENCY_S = 2
#
# Adverts will expire after this many seconds unless
# a fresh broadcast is received. Default it above the
# broadcast frequency so adverts are not forever expiring
# and being recreated by the next received broadcast.
#
# NB since adverts are broadcast round-robin (ie only one advert
# is broadcast every BEACON_ADVERT_FREQUENCY_S seconds) we need
# to allow for the possibility that any given name might only
# be advertised, say, once every 5 times.
#
ADVERT_TTL_S = 10 * BEACON_ADVERT_FREQUENCY_S
VALID_PORTS = range(0x10000)
DYNAMIC_PORTS = range(0xC000, 0x10000)
| <commit_before># -*- coding: utf-8 -*-
"""Common configuration elements for networkzero
"""
ENCODING = "UTF-8"
class _Forever(object):
def __repr__(self): return "<Forever>"
FOREVER = _Forever()
SHORT_WAIT = 1 # 1 second
EVERYTHING = ""
COMMAND_ACK = "ack"
#
# Beacons will broadcast adverts at this frequency
#
BEACON_ADVERT_FREQUENCY_S = 5
#
# Adverts will expire after this many seconds unless
# a fresh broadcast is received. Default it above the
# broadcast frequency so adverts are not forever expiring
# and being recreated by the next received broadcast.
#
ADVERT_TTL_S = 3 * BEACON_ADVERT_FREQUENCY_S
VALID_PORTS = range(0x10000)
DYNAMIC_PORTS = range(0xC000, 0x10000)
<commit_msg>Speed up the broadcast frequency<commit_after># -*- coding: utf-8 -*-
"""Common configuration elements for networkzero
"""
ENCODING = "UTF-8"
class _Forever(object):
def __repr__(self): return "<Forever>"
FOREVER = _Forever()
SHORT_WAIT = 1 # 1 second
EVERYTHING = ""
COMMAND_ACK = "ack"
#
# Beacons will broadcast adverts at this frequency
#
BEACON_ADVERT_FREQUENCY_S = 2
#
# Adverts will expire after this many seconds unless
# a fresh broadcast is received. Default it above the
# broadcast frequency so adverts are not forever expiring
# and being recreated by the next received broadcast.
#
# NB since adverts are broadcast round-robin (ie only one advert
# is broadcast every BEACON_ADVERT_FREQUENCY_S seconds) we need
# to allow for the possibility that any given name might only
# be advertised, say, once every 5 times.
#
ADVERT_TTL_S = 10 * BEACON_ADVERT_FREQUENCY_S
VALID_PORTS = range(0x10000)
DYNAMIC_PORTS = range(0xC000, 0x10000)
|
d8d92bac1c75e68de3460f82cab6b9a124dd95b5 | Python/SimonSpeckCiphers/setup.py | Python/SimonSpeckCiphers/setup.py | from setuptools import setup, find_packages
setup(
name='SimonSpeckCiphers',
version='0.9.9',
description="Implementations of the NSA's Simon and Speck Block Ciphers",
long_description=open('README.md').read(),
url='https://github.com/inmcm/Simon_Speck_Ciphers',
#scripts=['bin/benchmark_simonspeck.py'],
license='MIT',
author='Calvin McCoy',
author_email='calvin.mccoy@gmail.com',
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Cryptography :: Encryption',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'],
keywords='cryptography cipher encryption decryption',
packages=find_packages(exclude=['tests*']),
setup_requires=['pytest-runner'],
tests_require=['pytest']
)
| from setuptools import setup, find_packages
setup(
name='SimonSpeckCiphers',
version='0.9.9',
description="Implementations of the NSA's Simon and Speck Block Ciphers",
long_description=open('Readme.md').read(),
url='https://github.com/inmcm/Simon_Speck_Ciphers',
#scripts=['bin/benchmark_simonspeck.py'],
license='MIT',
author='Calvin McCoy',
author_email='calvin.mccoy@gmail.com',
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Cryptography :: Encryption',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'],
keywords='cryptography cipher encryption decryption',
packages=find_packages(exclude=['tests*']),
setup_requires=['pytest-runner'],
tests_require=['pytest']
)
| Fix Readme Name In Setup | Fix Readme Name In Setup
| Python | mit | inmcm/Simon_Speck_Ciphers,inmcm/Simon_Speck_Ciphers | from setuptools import setup, find_packages
setup(
name='SimonSpeckCiphers',
version='0.9.9',
description="Implementations of the NSA's Simon and Speck Block Ciphers",
long_description=open('README.md').read(),
url='https://github.com/inmcm/Simon_Speck_Ciphers',
#scripts=['bin/benchmark_simonspeck.py'],
license='MIT',
author='Calvin McCoy',
author_email='calvin.mccoy@gmail.com',
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Cryptography :: Encryption',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'],
keywords='cryptography cipher encryption decryption',
packages=find_packages(exclude=['tests*']),
setup_requires=['pytest-runner'],
tests_require=['pytest']
)
Fix Readme Name In Setup | from setuptools import setup, find_packages
setup(
name='SimonSpeckCiphers',
version='0.9.9',
description="Implementations of the NSA's Simon and Speck Block Ciphers",
long_description=open('Readme.md').read(),
url='https://github.com/inmcm/Simon_Speck_Ciphers',
#scripts=['bin/benchmark_simonspeck.py'],
license='MIT',
author='Calvin McCoy',
author_email='calvin.mccoy@gmail.com',
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Cryptography :: Encryption',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'],
keywords='cryptography cipher encryption decryption',
packages=find_packages(exclude=['tests*']),
setup_requires=['pytest-runner'],
tests_require=['pytest']
)
| <commit_before>from setuptools import setup, find_packages
setup(
name='SimonSpeckCiphers',
version='0.9.9',
description="Implementations of the NSA's Simon and Speck Block Ciphers",
long_description=open('README.md').read(),
url='https://github.com/inmcm/Simon_Speck_Ciphers',
#scripts=['bin/benchmark_simonspeck.py'],
license='MIT',
author='Calvin McCoy',
author_email='calvin.mccoy@gmail.com',
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Cryptography :: Encryption',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'],
keywords='cryptography cipher encryption decryption',
packages=find_packages(exclude=['tests*']),
setup_requires=['pytest-runner'],
tests_require=['pytest']
)
<commit_msg>Fix Readme Name In Setup<commit_after> | from setuptools import setup, find_packages
setup(
name='SimonSpeckCiphers',
version='0.9.9',
description="Implementations of the NSA's Simon and Speck Block Ciphers",
long_description=open('Readme.md').read(),
url='https://github.com/inmcm/Simon_Speck_Ciphers',
#scripts=['bin/benchmark_simonspeck.py'],
license='MIT',
author='Calvin McCoy',
author_email='calvin.mccoy@gmail.com',
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Cryptography :: Encryption',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'],
keywords='cryptography cipher encryption decryption',
packages=find_packages(exclude=['tests*']),
setup_requires=['pytest-runner'],
tests_require=['pytest']
)
| from setuptools import setup, find_packages
setup(
name='SimonSpeckCiphers',
version='0.9.9',
description="Implementations of the NSA's Simon and Speck Block Ciphers",
long_description=open('README.md').read(),
url='https://github.com/inmcm/Simon_Speck_Ciphers',
#scripts=['bin/benchmark_simonspeck.py'],
license='MIT',
author='Calvin McCoy',
author_email='calvin.mccoy@gmail.com',
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Cryptography :: Encryption',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'],
keywords='cryptography cipher encryption decryption',
packages=find_packages(exclude=['tests*']),
setup_requires=['pytest-runner'],
tests_require=['pytest']
)
Fix Readme Name In Setupfrom setuptools import setup, find_packages
setup(
name='SimonSpeckCiphers',
version='0.9.9',
description="Implementations of the NSA's Simon and Speck Block Ciphers",
long_description=open('Readme.md').read(),
url='https://github.com/inmcm/Simon_Speck_Ciphers',
#scripts=['bin/benchmark_simonspeck.py'],
license='MIT',
author='Calvin McCoy',
author_email='calvin.mccoy@gmail.com',
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Cryptography :: Encryption',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'],
keywords='cryptography cipher encryption decryption',
packages=find_packages(exclude=['tests*']),
setup_requires=['pytest-runner'],
tests_require=['pytest']
)
| <commit_before>from setuptools import setup, find_packages
setup(
name='SimonSpeckCiphers',
version='0.9.9',
description="Implementations of the NSA's Simon and Speck Block Ciphers",
long_description=open('README.md').read(),
url='https://github.com/inmcm/Simon_Speck_Ciphers',
#scripts=['bin/benchmark_simonspeck.py'],
license='MIT',
author='Calvin McCoy',
author_email='calvin.mccoy@gmail.com',
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Cryptography :: Encryption',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'],
keywords='cryptography cipher encryption decryption',
packages=find_packages(exclude=['tests*']),
setup_requires=['pytest-runner'],
tests_require=['pytest']
)
<commit_msg>Fix Readme Name In Setup<commit_after>from setuptools import setup, find_packages
setup(
name='SimonSpeckCiphers',
version='0.9.9',
description="Implementations of the NSA's Simon and Speck Block Ciphers",
long_description=open('Readme.md').read(),
url='https://github.com/inmcm/Simon_Speck_Ciphers',
#scripts=['bin/benchmark_simonspeck.py'],
license='MIT',
author='Calvin McCoy',
author_email='calvin.mccoy@gmail.com',
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Cryptography :: Encryption',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'],
keywords='cryptography cipher encryption decryption',
packages=find_packages(exclude=['tests*']),
setup_requires=['pytest-runner'],
tests_require=['pytest']
)
|
d0be9009da99ef8530a0d2927350663b3b89547a | pep8ify/pep8ify.py | pep8ify/pep8ify.py | #!/usr/bin/env python
import sys
from lib2to3.main import main
try:
import pep8ify.fixes
except ImportError:
# if importing pep8ify fails, try to load from parent
# directory to support running without installation
import imp, os
if not hasattr(os, 'getuid') or os.getuid() != 0:
imp.load_module('pep8ify', *imp.find_module('pep8ify',
[os.path.dirname(os.path.dirname(__file__))]))
def _main():
sys.exit(main("pep8ify.fixes"))
if __name__ == '__main__':
_main()
| #!/usr/bin/env python
from lib2to3.main import main
try:
import pep8ify.fixes
except ImportError:
# if importing pep8ify fails, try to load from parent
# directory to support running without installation
import imp, os
if not hasattr(os, 'getuid') or os.getuid() != 0:
imp.load_module('pep8ify', *imp.find_module('pep8ify',
[os.path.dirname(os.path.dirname(__file__))]))
def _main():
raise SystemExit(main("pep8ify.fixes"))
if __name__ == '__main__':
_main()
| Use `raise SystemExit` intead of `sys.exit`. | Clean-up: Use `raise SystemExit` intead of `sys.exit`.
| Python | apache-2.0 | spulec/pep8ify | #!/usr/bin/env python
import sys
from lib2to3.main import main
try:
import pep8ify.fixes
except ImportError:
# if importing pep8ify fails, try to load from parent
# directory to support running without installation
import imp, os
if not hasattr(os, 'getuid') or os.getuid() != 0:
imp.load_module('pep8ify', *imp.find_module('pep8ify',
[os.path.dirname(os.path.dirname(__file__))]))
def _main():
sys.exit(main("pep8ify.fixes"))
if __name__ == '__main__':
_main()
Clean-up: Use `raise SystemExit` intead of `sys.exit`. | #!/usr/bin/env python
from lib2to3.main import main
try:
import pep8ify.fixes
except ImportError:
# if importing pep8ify fails, try to load from parent
# directory to support running without installation
import imp, os
if not hasattr(os, 'getuid') or os.getuid() != 0:
imp.load_module('pep8ify', *imp.find_module('pep8ify',
[os.path.dirname(os.path.dirname(__file__))]))
def _main():
raise SystemExit(main("pep8ify.fixes"))
if __name__ == '__main__':
_main()
| <commit_before>#!/usr/bin/env python
import sys
from lib2to3.main import main
try:
import pep8ify.fixes
except ImportError:
# if importing pep8ify fails, try to load from parent
# directory to support running without installation
import imp, os
if not hasattr(os, 'getuid') or os.getuid() != 0:
imp.load_module('pep8ify', *imp.find_module('pep8ify',
[os.path.dirname(os.path.dirname(__file__))]))
def _main():
sys.exit(main("pep8ify.fixes"))
if __name__ == '__main__':
_main()
<commit_msg>Clean-up: Use `raise SystemExit` intead of `sys.exit`.<commit_after> | #!/usr/bin/env python
from lib2to3.main import main
try:
import pep8ify.fixes
except ImportError:
# if importing pep8ify fails, try to load from parent
# directory to support running without installation
import imp, os
if not hasattr(os, 'getuid') or os.getuid() != 0:
imp.load_module('pep8ify', *imp.find_module('pep8ify',
[os.path.dirname(os.path.dirname(__file__))]))
def _main():
raise SystemExit(main("pep8ify.fixes"))
if __name__ == '__main__':
_main()
| #!/usr/bin/env python
import sys
from lib2to3.main import main
try:
import pep8ify.fixes
except ImportError:
# if importing pep8ify fails, try to load from parent
# directory to support running without installation
import imp, os
if not hasattr(os, 'getuid') or os.getuid() != 0:
imp.load_module('pep8ify', *imp.find_module('pep8ify',
[os.path.dirname(os.path.dirname(__file__))]))
def _main():
sys.exit(main("pep8ify.fixes"))
if __name__ == '__main__':
_main()
Clean-up: Use `raise SystemExit` intead of `sys.exit`.#!/usr/bin/env python
from lib2to3.main import main
try:
import pep8ify.fixes
except ImportError:
# if importing pep8ify fails, try to load from parent
# directory to support running without installation
import imp, os
if not hasattr(os, 'getuid') or os.getuid() != 0:
imp.load_module('pep8ify', *imp.find_module('pep8ify',
[os.path.dirname(os.path.dirname(__file__))]))
def _main():
raise SystemExit(main("pep8ify.fixes"))
if __name__ == '__main__':
_main()
| <commit_before>#!/usr/bin/env python
import sys
from lib2to3.main import main
try:
import pep8ify.fixes
except ImportError:
# if importing pep8ify fails, try to load from parent
# directory to support running without installation
import imp, os
if not hasattr(os, 'getuid') or os.getuid() != 0:
imp.load_module('pep8ify', *imp.find_module('pep8ify',
[os.path.dirname(os.path.dirname(__file__))]))
def _main():
sys.exit(main("pep8ify.fixes"))
if __name__ == '__main__':
_main()
<commit_msg>Clean-up: Use `raise SystemExit` intead of `sys.exit`.<commit_after>#!/usr/bin/env python
from lib2to3.main import main
try:
import pep8ify.fixes
except ImportError:
# if importing pep8ify fails, try to load from parent
# directory to support running without installation
import imp, os
if not hasattr(os, 'getuid') or os.getuid() != 0:
imp.load_module('pep8ify', *imp.find_module('pep8ify',
[os.path.dirname(os.path.dirname(__file__))]))
def _main():
raise SystemExit(main("pep8ify.fixes"))
if __name__ == '__main__':
_main()
|
a9b368a642b21335504210f2a60403659aae688f | apps/common/src/python/mediawords/workflow/client.py | apps/common/src/python/mediawords/workflow/client.py | from temporal.workflow import WorkflowClient
from mediawords.util.network import wait_for_tcp_port_to_open
def workflow_client(namespace: str = 'DEFAULT') -> WorkflowClient:
"""
Connect to Temporal server and return its client.
:param namespace: Namespace to connect to.
:return: WorkflowClient instance.
"""
host = 'temporal-server'
port = 7233
# It's super lame to wait for this port to open, but the Python SDK seems to fail otherwise
wait_for_tcp_port_to_open(hostname=host, port=port)
client = WorkflowClient.new_client(host=host, port=port, namespace=namespace)
return client
| from temporal.workflow import WorkflowClient
from mediawords.util.network import wait_for_tcp_port_to_open
def workflow_client(namespace: str = 'default') -> WorkflowClient:
"""
Connect to Temporal server and return its client.
:param namespace: Namespace to connect to.
:return: WorkflowClient instance.
"""
host = 'temporal-server'
port = 7233
# It's super lame to wait for this port to open, but the Python SDK seems to fail otherwise
wait_for_tcp_port_to_open(hostname=host, port=port)
client = WorkflowClient.new_client(host=host, port=port, namespace=namespace)
return client
| Set the default namespace to lowercase "default" | Set the default namespace to lowercase "default"
| Python | agpl-3.0 | berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud | from temporal.workflow import WorkflowClient
from mediawords.util.network import wait_for_tcp_port_to_open
def workflow_client(namespace: str = 'DEFAULT') -> WorkflowClient:
"""
Connect to Temporal server and return its client.
:param namespace: Namespace to connect to.
:return: WorkflowClient instance.
"""
host = 'temporal-server'
port = 7233
# It's super lame to wait for this port to open, but the Python SDK seems to fail otherwise
wait_for_tcp_port_to_open(hostname=host, port=port)
client = WorkflowClient.new_client(host=host, port=port, namespace=namespace)
return client
Set the default namespace to lowercase "default" | from temporal.workflow import WorkflowClient
from mediawords.util.network import wait_for_tcp_port_to_open
def workflow_client(namespace: str = 'default') -> WorkflowClient:
"""
Connect to Temporal server and return its client.
:param namespace: Namespace to connect to.
:return: WorkflowClient instance.
"""
host = 'temporal-server'
port = 7233
# It's super lame to wait for this port to open, but the Python SDK seems to fail otherwise
wait_for_tcp_port_to_open(hostname=host, port=port)
client = WorkflowClient.new_client(host=host, port=port, namespace=namespace)
return client
| <commit_before>from temporal.workflow import WorkflowClient
from mediawords.util.network import wait_for_tcp_port_to_open
def workflow_client(namespace: str = 'DEFAULT') -> WorkflowClient:
"""
Connect to Temporal server and return its client.
:param namespace: Namespace to connect to.
:return: WorkflowClient instance.
"""
host = 'temporal-server'
port = 7233
# It's super lame to wait for this port to open, but the Python SDK seems to fail otherwise
wait_for_tcp_port_to_open(hostname=host, port=port)
client = WorkflowClient.new_client(host=host, port=port, namespace=namespace)
return client
<commit_msg>Set the default namespace to lowercase "default"<commit_after> | from temporal.workflow import WorkflowClient
from mediawords.util.network import wait_for_tcp_port_to_open
def workflow_client(namespace: str = 'default') -> WorkflowClient:
"""
Connect to Temporal server and return its client.
:param namespace: Namespace to connect to.
:return: WorkflowClient instance.
"""
host = 'temporal-server'
port = 7233
# It's super lame to wait for this port to open, but the Python SDK seems to fail otherwise
wait_for_tcp_port_to_open(hostname=host, port=port)
client = WorkflowClient.new_client(host=host, port=port, namespace=namespace)
return client
| from temporal.workflow import WorkflowClient
from mediawords.util.network import wait_for_tcp_port_to_open
def workflow_client(namespace: str = 'DEFAULT') -> WorkflowClient:
"""
Connect to Temporal server and return its client.
:param namespace: Namespace to connect to.
:return: WorkflowClient instance.
"""
host = 'temporal-server'
port = 7233
# It's super lame to wait for this port to open, but the Python SDK seems to fail otherwise
wait_for_tcp_port_to_open(hostname=host, port=port)
client = WorkflowClient.new_client(host=host, port=port, namespace=namespace)
return client
Set the default namespace to lowercase "default"from temporal.workflow import WorkflowClient
from mediawords.util.network import wait_for_tcp_port_to_open
def workflow_client(namespace: str = 'default') -> WorkflowClient:
"""
Connect to Temporal server and return its client.
:param namespace: Namespace to connect to.
:return: WorkflowClient instance.
"""
host = 'temporal-server'
port = 7233
# It's super lame to wait for this port to open, but the Python SDK seems to fail otherwise
wait_for_tcp_port_to_open(hostname=host, port=port)
client = WorkflowClient.new_client(host=host, port=port, namespace=namespace)
return client
| <commit_before>from temporal.workflow import WorkflowClient
from mediawords.util.network import wait_for_tcp_port_to_open
def workflow_client(namespace: str = 'DEFAULT') -> WorkflowClient:
"""
Connect to Temporal server and return its client.
:param namespace: Namespace to connect to.
:return: WorkflowClient instance.
"""
host = 'temporal-server'
port = 7233
# It's super lame to wait for this port to open, but the Python SDK seems to fail otherwise
wait_for_tcp_port_to_open(hostname=host, port=port)
client = WorkflowClient.new_client(host=host, port=port, namespace=namespace)
return client
<commit_msg>Set the default namespace to lowercase "default"<commit_after>from temporal.workflow import WorkflowClient
from mediawords.util.network import wait_for_tcp_port_to_open
def workflow_client(namespace: str = 'default') -> WorkflowClient:
"""
Connect to Temporal server and return its client.
:param namespace: Namespace to connect to.
:return: WorkflowClient instance.
"""
host = 'temporal-server'
port = 7233
# It's super lame to wait for this port to open, but the Python SDK seems to fail otherwise
wait_for_tcp_port_to_open(hostname=host, port=port)
client = WorkflowClient.new_client(host=host, port=port, namespace=namespace)
return client
|
fc73b74f07254eace14fa761c85524512b3d1222 | opps/images/models.py | opps/images/models.py | # -*- coding: utf-8 -*-
import uuid
import os
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from opps.core.models import Publishable
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "{0}-{1}.{2}".format(uuid.uuid4(), instance.slug, ext)
d = datetime.now()
folder = "images/{0}".format(d.strftime("%Y/%m/%d/"))
return os.path.join(folder, filename)
class Image(Publishable):
title = models.CharField(_(u"Title"), max_length=140)
slug = models.SlugField(_(u"Slug"), max_length=150, blank=True)
image = models.ImageField(upload_to=get_file_path)
description = models.TextField(_(u"Description"), null=True, blank=True)
source = models.ForeignKey('sources.Source', null=True, blank=True)
def __unicode__(self):
return u"{0}-{1}".format(self.id, self.slug)
def get_absolute_url(self):
if self.date_available <= timezone.now() and self.published:
return self.image.url
return u""
| # -*- coding: utf-8 -*-
import uuid
import os
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from taggit.managers import TaggableManager
from opps.core.models import Publishable
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "{0}-{1}.{2}".format(uuid.uuid4(), instance.slug, ext)
d = datetime.now()
folder = "images/{0}".format(d.strftime("%Y/%m/%d/"))
return os.path.join(folder, filename)
class Image(Publishable):
title = models.CharField(_(u"Title"), max_length=140, db_index=True)
slug = models.SlugField(_(u"Slug"), max_length=150, blank=True,
db_index=True)
image = models.ImageField(upload_to=get_file_path)
description = models.TextField(_(u"Description"), null=True, blank=True)
tags = TaggableManager(blank=True)
source = models.ForeignKey('sources.Source', null=True, blank=True)
def __unicode__(self):
return u"{0}-{1}".format(self.id, self.slug)
def get_absolute_url(self):
if self.date_available <= timezone.now() and self.published:
return self.image.url
return u""
| Add tag on image lib | Add tag on image lib
| Python | mit | williamroot/opps,williamroot/opps,YACOWS/opps,williamroot/opps,opps/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,opps/opps,jeanmask/opps,YACOWS/opps,opps/opps,opps/opps,YACOWS/opps,YACOWS/opps | # -*- coding: utf-8 -*-
import uuid
import os
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from opps.core.models import Publishable
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "{0}-{1}.{2}".format(uuid.uuid4(), instance.slug, ext)
d = datetime.now()
folder = "images/{0}".format(d.strftime("%Y/%m/%d/"))
return os.path.join(folder, filename)
class Image(Publishable):
title = models.CharField(_(u"Title"), max_length=140)
slug = models.SlugField(_(u"Slug"), max_length=150, blank=True)
image = models.ImageField(upload_to=get_file_path)
description = models.TextField(_(u"Description"), null=True, blank=True)
source = models.ForeignKey('sources.Source', null=True, blank=True)
def __unicode__(self):
return u"{0}-{1}".format(self.id, self.slug)
def get_absolute_url(self):
if self.date_available <= timezone.now() and self.published:
return self.image.url
return u""
Add tag on image lib | # -*- coding: utf-8 -*-
import uuid
import os
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from taggit.managers import TaggableManager
from opps.core.models import Publishable
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "{0}-{1}.{2}".format(uuid.uuid4(), instance.slug, ext)
d = datetime.now()
folder = "images/{0}".format(d.strftime("%Y/%m/%d/"))
return os.path.join(folder, filename)
class Image(Publishable):
title = models.CharField(_(u"Title"), max_length=140, db_index=True)
slug = models.SlugField(_(u"Slug"), max_length=150, blank=True,
db_index=True)
image = models.ImageField(upload_to=get_file_path)
description = models.TextField(_(u"Description"), null=True, blank=True)
tags = TaggableManager(blank=True)
source = models.ForeignKey('sources.Source', null=True, blank=True)
def __unicode__(self):
return u"{0}-{1}".format(self.id, self.slug)
def get_absolute_url(self):
if self.date_available <= timezone.now() and self.published:
return self.image.url
return u""
| <commit_before># -*- coding: utf-8 -*-
import uuid
import os
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from opps.core.models import Publishable
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "{0}-{1}.{2}".format(uuid.uuid4(), instance.slug, ext)
d = datetime.now()
folder = "images/{0}".format(d.strftime("%Y/%m/%d/"))
return os.path.join(folder, filename)
class Image(Publishable):
title = models.CharField(_(u"Title"), max_length=140)
slug = models.SlugField(_(u"Slug"), max_length=150, blank=True)
image = models.ImageField(upload_to=get_file_path)
description = models.TextField(_(u"Description"), null=True, blank=True)
source = models.ForeignKey('sources.Source', null=True, blank=True)
def __unicode__(self):
return u"{0}-{1}".format(self.id, self.slug)
def get_absolute_url(self):
if self.date_available <= timezone.now() and self.published:
return self.image.url
return u""
<commit_msg>Add tag on image lib<commit_after> | # -*- coding: utf-8 -*-
import uuid
import os
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from taggit.managers import TaggableManager
from opps.core.models import Publishable
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "{0}-{1}.{2}".format(uuid.uuid4(), instance.slug, ext)
d = datetime.now()
folder = "images/{0}".format(d.strftime("%Y/%m/%d/"))
return os.path.join(folder, filename)
class Image(Publishable):
title = models.CharField(_(u"Title"), max_length=140, db_index=True)
slug = models.SlugField(_(u"Slug"), max_length=150, blank=True,
db_index=True)
image = models.ImageField(upload_to=get_file_path)
description = models.TextField(_(u"Description"), null=True, blank=True)
tags = TaggableManager(blank=True)
source = models.ForeignKey('sources.Source', null=True, blank=True)
def __unicode__(self):
return u"{0}-{1}".format(self.id, self.slug)
def get_absolute_url(self):
if self.date_available <= timezone.now() and self.published:
return self.image.url
return u""
| # -*- coding: utf-8 -*-
import uuid
import os
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from opps.core.models import Publishable
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "{0}-{1}.{2}".format(uuid.uuid4(), instance.slug, ext)
d = datetime.now()
folder = "images/{0}".format(d.strftime("%Y/%m/%d/"))
return os.path.join(folder, filename)
class Image(Publishable):
title = models.CharField(_(u"Title"), max_length=140)
slug = models.SlugField(_(u"Slug"), max_length=150, blank=True)
image = models.ImageField(upload_to=get_file_path)
description = models.TextField(_(u"Description"), null=True, blank=True)
source = models.ForeignKey('sources.Source', null=True, blank=True)
def __unicode__(self):
return u"{0}-{1}".format(self.id, self.slug)
def get_absolute_url(self):
if self.date_available <= timezone.now() and self.published:
return self.image.url
return u""
Add tag on image lib# -*- coding: utf-8 -*-
import uuid
import os
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from taggit.managers import TaggableManager
from opps.core.models import Publishable
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "{0}-{1}.{2}".format(uuid.uuid4(), instance.slug, ext)
d = datetime.now()
folder = "images/{0}".format(d.strftime("%Y/%m/%d/"))
return os.path.join(folder, filename)
class Image(Publishable):
title = models.CharField(_(u"Title"), max_length=140, db_index=True)
slug = models.SlugField(_(u"Slug"), max_length=150, blank=True,
db_index=True)
image = models.ImageField(upload_to=get_file_path)
description = models.TextField(_(u"Description"), null=True, blank=True)
tags = TaggableManager(blank=True)
source = models.ForeignKey('sources.Source', null=True, blank=True)
def __unicode__(self):
return u"{0}-{1}".format(self.id, self.slug)
def get_absolute_url(self):
if self.date_available <= timezone.now() and self.published:
return self.image.url
return u""
| <commit_before># -*- coding: utf-8 -*-
import uuid
import os
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from opps.core.models import Publishable
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "{0}-{1}.{2}".format(uuid.uuid4(), instance.slug, ext)
d = datetime.now()
folder = "images/{0}".format(d.strftime("%Y/%m/%d/"))
return os.path.join(folder, filename)
class Image(Publishable):
title = models.CharField(_(u"Title"), max_length=140)
slug = models.SlugField(_(u"Slug"), max_length=150, blank=True)
image = models.ImageField(upload_to=get_file_path)
description = models.TextField(_(u"Description"), null=True, blank=True)
source = models.ForeignKey('sources.Source', null=True, blank=True)
def __unicode__(self):
return u"{0}-{1}".format(self.id, self.slug)
def get_absolute_url(self):
if self.date_available <= timezone.now() and self.published:
return self.image.url
return u""
<commit_msg>Add tag on image lib<commit_after># -*- coding: utf-8 -*-
import uuid
import os
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from taggit.managers import TaggableManager
from opps.core.models import Publishable
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "{0}-{1}.{2}".format(uuid.uuid4(), instance.slug, ext)
d = datetime.now()
folder = "images/{0}".format(d.strftime("%Y/%m/%d/"))
return os.path.join(folder, filename)
class Image(Publishable):
title = models.CharField(_(u"Title"), max_length=140, db_index=True)
slug = models.SlugField(_(u"Slug"), max_length=150, blank=True,
db_index=True)
image = models.ImageField(upload_to=get_file_path)
description = models.TextField(_(u"Description"), null=True, blank=True)
tags = TaggableManager(blank=True)
source = models.ForeignKey('sources.Source', null=True, blank=True)
def __unicode__(self):
return u"{0}-{1}".format(self.id, self.slug)
def get_absolute_url(self):
if self.date_available <= timezone.now() and self.published:
return self.image.url
return u""
|
60d79b03fbb6c1ad70b16d323fe7fa4a77cb0abe | notification/tests.py | notification/tests.py | from django.test import TestCase
# Create your tests here.
| from django.test import TestCase
from django.core.urlresolvers import reverse
from account.factories import AccountFactory, DEFAULT_PASSWORD
class TestNotification(TestCase):
def setUp(self):
account = AccountFactory.create()
self.user = account.user
def test_access_notification_list(self):
self.client.login(username=self.user.username, password=DEFAULT_PASSWORD)
response = self.client.get(reverse('notifications'))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'notification/list.html')
| Add test to list of notification page. | Add test to list of notification page.
| Python | agpl-3.0 | Fleeg/fleeg-platform,Fleeg/fleeg-platform | from django.test import TestCase
# Create your tests here.
Add test to list of notification page. | from django.test import TestCase
from django.core.urlresolvers import reverse
from account.factories import AccountFactory, DEFAULT_PASSWORD
class TestNotification(TestCase):
def setUp(self):
account = AccountFactory.create()
self.user = account.user
def test_access_notification_list(self):
self.client.login(username=self.user.username, password=DEFAULT_PASSWORD)
response = self.client.get(reverse('notifications'))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'notification/list.html')
| <commit_before>from django.test import TestCase
# Create your tests here.
<commit_msg>Add test to list of notification page.<commit_after> | from django.test import TestCase
from django.core.urlresolvers import reverse
from account.factories import AccountFactory, DEFAULT_PASSWORD
class TestNotification(TestCase):
def setUp(self):
account = AccountFactory.create()
self.user = account.user
def test_access_notification_list(self):
self.client.login(username=self.user.username, password=DEFAULT_PASSWORD)
response = self.client.get(reverse('notifications'))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'notification/list.html')
| from django.test import TestCase
# Create your tests here.
Add test to list of notification page.from django.test import TestCase
from django.core.urlresolvers import reverse
from account.factories import AccountFactory, DEFAULT_PASSWORD
class TestNotification(TestCase):
def setUp(self):
account = AccountFactory.create()
self.user = account.user
def test_access_notification_list(self):
self.client.login(username=self.user.username, password=DEFAULT_PASSWORD)
response = self.client.get(reverse('notifications'))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'notification/list.html')
| <commit_before>from django.test import TestCase
# Create your tests here.
<commit_msg>Add test to list of notification page.<commit_after>from django.test import TestCase
from django.core.urlresolvers import reverse
from account.factories import AccountFactory, DEFAULT_PASSWORD
class TestNotification(TestCase):
def setUp(self):
account = AccountFactory.create()
self.user = account.user
def test_access_notification_list(self):
self.client.login(username=self.user.username, password=DEFAULT_PASSWORD)
response = self.client.get(reverse('notifications'))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'notification/list.html')
|
6f729e4c2d9497e0bf9844022667635836cb4a7b | appengine/services/admin_tasks.py | appengine/services/admin_tasks.py | """This module defines a number of tasks related to administration tasks.
TaskCalcImpact needs to be run everytime we update the definition of
total_impact.
"""
import webapp2
import logging
from models import ActivityRecord
class TaskCalcImpact(webapp2.RequestHandler):
"""Force calculate of total_impact with a put()."""
def get(self):
"""."""
logging.info('tasks/calc_impact')
activity_records = ActivityRecord.query()
ar_count = 0
for ar in activity_records:
ar.put()
ar_count += 1
logging.info('tasks/calc_impact calculated %s ar' % ar_count)
| """This module defines a number of tasks related to administration tasks.
TaskCalcImpact needs to be run everytime we update the definition of
total_impact.
"""
import webapp2
import logging
from models import ActivityRecord
class TaskCalcImpact(webapp2.RequestHandler):
"""Force calculate of total_impact with a put()."""
def get(self):
"""."""
logging.info('tasks/calc_impact')
activity_records = ActivityRecord.query()
ar_count = 0
for ar in activity_records:
if ar.deleted is None:
ar.deleted = False
ar.put()
ar_count += 1
logging.info('tasks/calc_impact calculated %s ar' % ar_count)
| Update TaskCalcImpact to also set deleted | Update TaskCalcImpact to also set deleted | Python | apache-2.0 | GoogleDeveloperExperts/experts-app-backend | """This module defines a number of tasks related to administration tasks.
TaskCalcImpact needs to be run everytime we update the definition of
total_impact.
"""
import webapp2
import logging
from models import ActivityRecord
class TaskCalcImpact(webapp2.RequestHandler):
"""Force calculate of total_impact with a put()."""
def get(self):
"""."""
logging.info('tasks/calc_impact')
activity_records = ActivityRecord.query()
ar_count = 0
for ar in activity_records:
ar.put()
ar_count += 1
logging.info('tasks/calc_impact calculated %s ar' % ar_count)
Update TaskCalcImpact to also set deleted | """This module defines a number of tasks related to administration tasks.
TaskCalcImpact needs to be run everytime we update the definition of
total_impact.
"""
import webapp2
import logging
from models import ActivityRecord
class TaskCalcImpact(webapp2.RequestHandler):
"""Force calculate of total_impact with a put()."""
def get(self):
"""."""
logging.info('tasks/calc_impact')
activity_records = ActivityRecord.query()
ar_count = 0
for ar in activity_records:
if ar.deleted is None:
ar.deleted = False
ar.put()
ar_count += 1
logging.info('tasks/calc_impact calculated %s ar' % ar_count)
| <commit_before>"""This module defines a number of tasks related to administration tasks.
TaskCalcImpact needs to be run everytime we update the definition of
total_impact.
"""
import webapp2
import logging
from models import ActivityRecord
class TaskCalcImpact(webapp2.RequestHandler):
"""Force calculate of total_impact with a put()."""
def get(self):
"""."""
logging.info('tasks/calc_impact')
activity_records = ActivityRecord.query()
ar_count = 0
for ar in activity_records:
ar.put()
ar_count += 1
logging.info('tasks/calc_impact calculated %s ar' % ar_count)
<commit_msg>Update TaskCalcImpact to also set deleted<commit_after> | """This module defines a number of tasks related to administration tasks.
TaskCalcImpact needs to be run everytime we update the definition of
total_impact.
"""
import webapp2
import logging
from models import ActivityRecord
class TaskCalcImpact(webapp2.RequestHandler):
"""Force calculate of total_impact with a put()."""
def get(self):
"""."""
logging.info('tasks/calc_impact')
activity_records = ActivityRecord.query()
ar_count = 0
for ar in activity_records:
if ar.deleted is None:
ar.deleted = False
ar.put()
ar_count += 1
logging.info('tasks/calc_impact calculated %s ar' % ar_count)
| """This module defines a number of tasks related to administration tasks.
TaskCalcImpact needs to be run everytime we update the definition of
total_impact.
"""
import webapp2
import logging
from models import ActivityRecord
class TaskCalcImpact(webapp2.RequestHandler):
"""Force calculate of total_impact with a put()."""
def get(self):
"""."""
logging.info('tasks/calc_impact')
activity_records = ActivityRecord.query()
ar_count = 0
for ar in activity_records:
ar.put()
ar_count += 1
logging.info('tasks/calc_impact calculated %s ar' % ar_count)
Update TaskCalcImpact to also set deleted"""This module defines a number of tasks related to administration tasks.
TaskCalcImpact needs to be run everytime we update the definition of
total_impact.
"""
import webapp2
import logging
from models import ActivityRecord
class TaskCalcImpact(webapp2.RequestHandler):
"""Force calculate of total_impact with a put()."""
def get(self):
"""."""
logging.info('tasks/calc_impact')
activity_records = ActivityRecord.query()
ar_count = 0
for ar in activity_records:
if ar.deleted is None:
ar.deleted = False
ar.put()
ar_count += 1
logging.info('tasks/calc_impact calculated %s ar' % ar_count)
| <commit_before>"""This module defines a number of tasks related to administration tasks.
TaskCalcImpact needs to be run everytime we update the definition of
total_impact.
"""
import webapp2
import logging
from models import ActivityRecord
class TaskCalcImpact(webapp2.RequestHandler):
"""Force calculate of total_impact with a put()."""
def get(self):
"""."""
logging.info('tasks/calc_impact')
activity_records = ActivityRecord.query()
ar_count = 0
for ar in activity_records:
ar.put()
ar_count += 1
logging.info('tasks/calc_impact calculated %s ar' % ar_count)
<commit_msg>Update TaskCalcImpact to also set deleted<commit_after>"""This module defines a number of tasks related to administration tasks.
TaskCalcImpact needs to be run everytime we update the definition of
total_impact.
"""
import webapp2
import logging
from models import ActivityRecord
class TaskCalcImpact(webapp2.RequestHandler):
"""Force calculate of total_impact with a put()."""
def get(self):
"""."""
logging.info('tasks/calc_impact')
activity_records = ActivityRecord.query()
ar_count = 0
for ar in activity_records:
if ar.deleted is None:
ar.deleted = False
ar.put()
ar_count += 1
logging.info('tasks/calc_impact calculated %s ar' % ar_count)
|
84d9e707e872782c3cc9b81b098a9027239ed625 | alembic/versions/2507366cb6f2_.py | alembic/versions/2507366cb6f2_.py | """empty message
Revision ID: 2507366cb6f2
Revises: 2a31d97fa618
Create Date: 2013-04-30 00:11:14.194453
"""
# revision identifiers, used by Alembic.
revision = '2507366cb6f2'
down_revision = '2a31d97fa618'
from alembic import op
import sqlalchemy as sa
from models.person import Person
from utils.nlp.utils.translit import translit
person_t = sa.sql.table(
'person',
sa.sql.column('id', sa.Integer),
sa.sql.column('name', sa.Unicode(20)),
sa.sql.column('name_en', sa.String(80))
)
def upgrade():
people = Person.query.all()
for person in people:
name_en = translit(person.name, 'ko', 'en', 'name')
op.execute(person_t.update().\
where(person_t.c.id == person.id).\
values({'name_en': op.inline_literal(name_en)})
)
def downgrade():
op.execute(person_t.update().\
values({'name_en': op.inline_literal('')})
)
| """empty message
Revision ID: 2507366cb6f2
Revises: 2a31d97fa618
Create Date: 2013-04-30 00:11:14.194453
"""
# revision identifiers, used by Alembic.
revision = '2507366cb6f2'
down_revision = '2a31d97fa618'
from os.path import abspath, dirname, join
import sys
from alembic import op
import sqlalchemy as sa
parentdir = dirname(dirname(dirname(abspath(__file__))))
sys.path.insert(0,parentdir)
from models.person import Person
from utils.nlp.utils.translit import translit
person_t = sa.sql.table(
'person',
sa.sql.column('id', sa.Integer),
sa.sql.column('name', sa.Unicode(20)),
sa.sql.column('name_en', sa.String(80))
)
def upgrade():
people = Person.query.all()
for person in people:
name_en = translit(person.name, 'ko', 'en', 'name')
op.execute(person_t.update().\
where(person_t.c.id == person.id).\
values({'name_en': op.inline_literal(name_en)})
)
def downgrade():
op.execute(person_t.update().\
values({'name_en': op.inline_literal('')})
)
| Fix broken alembic revision generation | Fix broken alembic revision generation
| Python | apache-2.0 | teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr | """empty message
Revision ID: 2507366cb6f2
Revises: 2a31d97fa618
Create Date: 2013-04-30 00:11:14.194453
"""
# revision identifiers, used by Alembic.
revision = '2507366cb6f2'
down_revision = '2a31d97fa618'
from alembic import op
import sqlalchemy as sa
from models.person import Person
from utils.nlp.utils.translit import translit
person_t = sa.sql.table(
'person',
sa.sql.column('id', sa.Integer),
sa.sql.column('name', sa.Unicode(20)),
sa.sql.column('name_en', sa.String(80))
)
def upgrade():
people = Person.query.all()
for person in people:
name_en = translit(person.name, 'ko', 'en', 'name')
op.execute(person_t.update().\
where(person_t.c.id == person.id).\
values({'name_en': op.inline_literal(name_en)})
)
def downgrade():
op.execute(person_t.update().\
values({'name_en': op.inline_literal('')})
)
Fix broken alembic revision generation | """empty message
Revision ID: 2507366cb6f2
Revises: 2a31d97fa618
Create Date: 2013-04-30 00:11:14.194453
"""
# revision identifiers, used by Alembic.
revision = '2507366cb6f2'
down_revision = '2a31d97fa618'
from os.path import abspath, dirname, join
import sys
from alembic import op
import sqlalchemy as sa
parentdir = dirname(dirname(dirname(abspath(__file__))))
sys.path.insert(0,parentdir)
from models.person import Person
from utils.nlp.utils.translit import translit
person_t = sa.sql.table(
'person',
sa.sql.column('id', sa.Integer),
sa.sql.column('name', sa.Unicode(20)),
sa.sql.column('name_en', sa.String(80))
)
def upgrade():
people = Person.query.all()
for person in people:
name_en = translit(person.name, 'ko', 'en', 'name')
op.execute(person_t.update().\
where(person_t.c.id == person.id).\
values({'name_en': op.inline_literal(name_en)})
)
def downgrade():
op.execute(person_t.update().\
values({'name_en': op.inline_literal('')})
)
| <commit_before>"""empty message
Revision ID: 2507366cb6f2
Revises: 2a31d97fa618
Create Date: 2013-04-30 00:11:14.194453
"""
# revision identifiers, used by Alembic.
revision = '2507366cb6f2'
down_revision = '2a31d97fa618'
from alembic import op
import sqlalchemy as sa
from models.person import Person
from utils.nlp.utils.translit import translit
person_t = sa.sql.table(
'person',
sa.sql.column('id', sa.Integer),
sa.sql.column('name', sa.Unicode(20)),
sa.sql.column('name_en', sa.String(80))
)
def upgrade():
people = Person.query.all()
for person in people:
name_en = translit(person.name, 'ko', 'en', 'name')
op.execute(person_t.update().\
where(person_t.c.id == person.id).\
values({'name_en': op.inline_literal(name_en)})
)
def downgrade():
op.execute(person_t.update().\
values({'name_en': op.inline_literal('')})
)
<commit_msg>Fix broken alembic revision generation<commit_after> | """empty message
Revision ID: 2507366cb6f2
Revises: 2a31d97fa618
Create Date: 2013-04-30 00:11:14.194453
"""
# revision identifiers, used by Alembic.
revision = '2507366cb6f2'
down_revision = '2a31d97fa618'
from os.path import abspath, dirname, join
import sys
from alembic import op
import sqlalchemy as sa
parentdir = dirname(dirname(dirname(abspath(__file__))))
sys.path.insert(0,parentdir)
from models.person import Person
from utils.nlp.utils.translit import translit
person_t = sa.sql.table(
'person',
sa.sql.column('id', sa.Integer),
sa.sql.column('name', sa.Unicode(20)),
sa.sql.column('name_en', sa.String(80))
)
def upgrade():
people = Person.query.all()
for person in people:
name_en = translit(person.name, 'ko', 'en', 'name')
op.execute(person_t.update().\
where(person_t.c.id == person.id).\
values({'name_en': op.inline_literal(name_en)})
)
def downgrade():
op.execute(person_t.update().\
values({'name_en': op.inline_literal('')})
)
| """empty message
Revision ID: 2507366cb6f2
Revises: 2a31d97fa618
Create Date: 2013-04-30 00:11:14.194453
"""
# revision identifiers, used by Alembic.
revision = '2507366cb6f2'
down_revision = '2a31d97fa618'
from alembic import op
import sqlalchemy as sa
from models.person import Person
from utils.nlp.utils.translit import translit
person_t = sa.sql.table(
'person',
sa.sql.column('id', sa.Integer),
sa.sql.column('name', sa.Unicode(20)),
sa.sql.column('name_en', sa.String(80))
)
def upgrade():
people = Person.query.all()
for person in people:
name_en = translit(person.name, 'ko', 'en', 'name')
op.execute(person_t.update().\
where(person_t.c.id == person.id).\
values({'name_en': op.inline_literal(name_en)})
)
def downgrade():
op.execute(person_t.update().\
values({'name_en': op.inline_literal('')})
)
Fix broken alembic revision generation"""empty message
Revision ID: 2507366cb6f2
Revises: 2a31d97fa618
Create Date: 2013-04-30 00:11:14.194453
"""
# revision identifiers, used by Alembic.
revision = '2507366cb6f2'
down_revision = '2a31d97fa618'
from os.path import abspath, dirname, join
import sys
from alembic import op
import sqlalchemy as sa
parentdir = dirname(dirname(dirname(abspath(__file__))))
sys.path.insert(0,parentdir)
from models.person import Person
from utils.nlp.utils.translit import translit
person_t = sa.sql.table(
'person',
sa.sql.column('id', sa.Integer),
sa.sql.column('name', sa.Unicode(20)),
sa.sql.column('name_en', sa.String(80))
)
def upgrade():
people = Person.query.all()
for person in people:
name_en = translit(person.name, 'ko', 'en', 'name')
op.execute(person_t.update().\
where(person_t.c.id == person.id).\
values({'name_en': op.inline_literal(name_en)})
)
def downgrade():
op.execute(person_t.update().\
values({'name_en': op.inline_literal('')})
)
| <commit_before>"""empty message
Revision ID: 2507366cb6f2
Revises: 2a31d97fa618
Create Date: 2013-04-30 00:11:14.194453
"""
# revision identifiers, used by Alembic.
revision = '2507366cb6f2'
down_revision = '2a31d97fa618'
from alembic import op
import sqlalchemy as sa
from models.person import Person
from utils.nlp.utils.translit import translit
person_t = sa.sql.table(
'person',
sa.sql.column('id', sa.Integer),
sa.sql.column('name', sa.Unicode(20)),
sa.sql.column('name_en', sa.String(80))
)
def upgrade():
people = Person.query.all()
for person in people:
name_en = translit(person.name, 'ko', 'en', 'name')
op.execute(person_t.update().\
where(person_t.c.id == person.id).\
values({'name_en': op.inline_literal(name_en)})
)
def downgrade():
op.execute(person_t.update().\
values({'name_en': op.inline_literal('')})
)
<commit_msg>Fix broken alembic revision generation<commit_after>"""empty message
Revision ID: 2507366cb6f2
Revises: 2a31d97fa618
Create Date: 2013-04-30 00:11:14.194453
"""
# revision identifiers, used by Alembic.
revision = '2507366cb6f2'
down_revision = '2a31d97fa618'
from os.path import abspath, dirname, join
import sys
from alembic import op
import sqlalchemy as sa
parentdir = dirname(dirname(dirname(abspath(__file__))))
sys.path.insert(0,parentdir)
from models.person import Person
from utils.nlp.utils.translit import translit
person_t = sa.sql.table(
'person',
sa.sql.column('id', sa.Integer),
sa.sql.column('name', sa.Unicode(20)),
sa.sql.column('name_en', sa.String(80))
)
def upgrade():
people = Person.query.all()
for person in people:
name_en = translit(person.name, 'ko', 'en', 'name')
op.execute(person_t.update().\
where(person_t.c.id == person.id).\
values({'name_en': op.inline_literal(name_en)})
)
def downgrade():
op.execute(person_t.update().\
values({'name_en': op.inline_literal('')})
)
|
cf17b796cbd8b13c8138802b012f8293b269ab20 | apps/data/tests/test_factories.py | apps/data/tests/test_factories.py | from django.test import TestCase
from .. import factories, models
class RepositoryFactoryTestCase(TestCase):
def test_can_create_repository(self):
qs = models.Repository.objects.all()
self.assertEqual(qs.count(), 0)
repository = factories.RepositoryFactory()
self.assertGreater(len(repository.name), 1)
self.assertGreater(len(repository.url), 1)
self.assertEqual(qs.count(), 1)
class EntryFactoryTestCase(TestCase):
def test_can_create_entry(self):
entry_qs = models.Entry.objects.all()
repository_qs = models.Repository.objects.all()
self.assertEqual(entry_qs.count(), 0)
self.assertEqual(repository_qs.count(), 0)
entry = factories.EntryFactory()
self.assertGreater(len(entry.identifier), 1)
self.assertGreater(len(entry.description), 1)
self.assertGreater(len(entry.url), 1)
self.assertGreater(len(entry.repository.name), 1)
self.assertEqual(entry_qs.count(), 1)
self.assertEqual(repository_qs.count(), 1)
| from django.test import TestCase
from .. import factories, models
class RepositoryFactoryTestCase(TestCase):
def test_can_create_repository(self):
qs = models.Repository.objects.all()
self.assertEqual(qs.count(), 0)
repository = factories.RepositoryFactory()
self.assertGreater(len(repository.name), 0)
self.assertGreater(len(repository.url), 0)
self.assertEqual(qs.count(), 1)
class EntryFactoryTestCase(TestCase):
def test_can_create_entry(self):
entry_qs = models.Entry.objects.all()
repository_qs = models.Repository.objects.all()
self.assertEqual(entry_qs.count(), 0)
self.assertEqual(repository_qs.count(), 0)
entry = factories.EntryFactory()
self.assertGreater(len(entry.identifier), 0)
self.assertGreater(len(entry.description), 0)
self.assertGreater(len(entry.url), 0)
self.assertGreater(len(entry.repository.name), 0)
self.assertEqual(entry_qs.count(), 1)
self.assertEqual(repository_qs.count(), 1)
| Fix random strings minimal expected length | Fix random strings minimal expected length
| Python | bsd-3-clause | Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel | from django.test import TestCase
from .. import factories, models
class RepositoryFactoryTestCase(TestCase):
def test_can_create_repository(self):
qs = models.Repository.objects.all()
self.assertEqual(qs.count(), 0)
repository = factories.RepositoryFactory()
self.assertGreater(len(repository.name), 1)
self.assertGreater(len(repository.url), 1)
self.assertEqual(qs.count(), 1)
class EntryFactoryTestCase(TestCase):
def test_can_create_entry(self):
entry_qs = models.Entry.objects.all()
repository_qs = models.Repository.objects.all()
self.assertEqual(entry_qs.count(), 0)
self.assertEqual(repository_qs.count(), 0)
entry = factories.EntryFactory()
self.assertGreater(len(entry.identifier), 1)
self.assertGreater(len(entry.description), 1)
self.assertGreater(len(entry.url), 1)
self.assertGreater(len(entry.repository.name), 1)
self.assertEqual(entry_qs.count(), 1)
self.assertEqual(repository_qs.count(), 1)
Fix random strings minimal expected length | from django.test import TestCase
from .. import factories, models
class RepositoryFactoryTestCase(TestCase):
def test_can_create_repository(self):
qs = models.Repository.objects.all()
self.assertEqual(qs.count(), 0)
repository = factories.RepositoryFactory()
self.assertGreater(len(repository.name), 0)
self.assertGreater(len(repository.url), 0)
self.assertEqual(qs.count(), 1)
class EntryFactoryTestCase(TestCase):
def test_can_create_entry(self):
entry_qs = models.Entry.objects.all()
repository_qs = models.Repository.objects.all()
self.assertEqual(entry_qs.count(), 0)
self.assertEqual(repository_qs.count(), 0)
entry = factories.EntryFactory()
self.assertGreater(len(entry.identifier), 0)
self.assertGreater(len(entry.description), 0)
self.assertGreater(len(entry.url), 0)
self.assertGreater(len(entry.repository.name), 0)
self.assertEqual(entry_qs.count(), 1)
self.assertEqual(repository_qs.count(), 1)
| <commit_before>from django.test import TestCase
from .. import factories, models
class RepositoryFactoryTestCase(TestCase):
def test_can_create_repository(self):
qs = models.Repository.objects.all()
self.assertEqual(qs.count(), 0)
repository = factories.RepositoryFactory()
self.assertGreater(len(repository.name), 1)
self.assertGreater(len(repository.url), 1)
self.assertEqual(qs.count(), 1)
class EntryFactoryTestCase(TestCase):
def test_can_create_entry(self):
entry_qs = models.Entry.objects.all()
repository_qs = models.Repository.objects.all()
self.assertEqual(entry_qs.count(), 0)
self.assertEqual(repository_qs.count(), 0)
entry = factories.EntryFactory()
self.assertGreater(len(entry.identifier), 1)
self.assertGreater(len(entry.description), 1)
self.assertGreater(len(entry.url), 1)
self.assertGreater(len(entry.repository.name), 1)
self.assertEqual(entry_qs.count(), 1)
self.assertEqual(repository_qs.count(), 1)
<commit_msg>Fix random strings minimal expected length<commit_after> | from django.test import TestCase
from .. import factories, models
class RepositoryFactoryTestCase(TestCase):
def test_can_create_repository(self):
qs = models.Repository.objects.all()
self.assertEqual(qs.count(), 0)
repository = factories.RepositoryFactory()
self.assertGreater(len(repository.name), 0)
self.assertGreater(len(repository.url), 0)
self.assertEqual(qs.count(), 1)
class EntryFactoryTestCase(TestCase):
def test_can_create_entry(self):
entry_qs = models.Entry.objects.all()
repository_qs = models.Repository.objects.all()
self.assertEqual(entry_qs.count(), 0)
self.assertEqual(repository_qs.count(), 0)
entry = factories.EntryFactory()
self.assertGreater(len(entry.identifier), 0)
self.assertGreater(len(entry.description), 0)
self.assertGreater(len(entry.url), 0)
self.assertGreater(len(entry.repository.name), 0)
self.assertEqual(entry_qs.count(), 1)
self.assertEqual(repository_qs.count(), 1)
| from django.test import TestCase
from .. import factories, models
class RepositoryFactoryTestCase(TestCase):
def test_can_create_repository(self):
qs = models.Repository.objects.all()
self.assertEqual(qs.count(), 0)
repository = factories.RepositoryFactory()
self.assertGreater(len(repository.name), 1)
self.assertGreater(len(repository.url), 1)
self.assertEqual(qs.count(), 1)
class EntryFactoryTestCase(TestCase):
def test_can_create_entry(self):
entry_qs = models.Entry.objects.all()
repository_qs = models.Repository.objects.all()
self.assertEqual(entry_qs.count(), 0)
self.assertEqual(repository_qs.count(), 0)
entry = factories.EntryFactory()
self.assertGreater(len(entry.identifier), 1)
self.assertGreater(len(entry.description), 1)
self.assertGreater(len(entry.url), 1)
self.assertGreater(len(entry.repository.name), 1)
self.assertEqual(entry_qs.count(), 1)
self.assertEqual(repository_qs.count(), 1)
Fix random strings minimal expected lengthfrom django.test import TestCase
from .. import factories, models
class RepositoryFactoryTestCase(TestCase):
def test_can_create_repository(self):
qs = models.Repository.objects.all()
self.assertEqual(qs.count(), 0)
repository = factories.RepositoryFactory()
self.assertGreater(len(repository.name), 0)
self.assertGreater(len(repository.url), 0)
self.assertEqual(qs.count(), 1)
class EntryFactoryTestCase(TestCase):
def test_can_create_entry(self):
entry_qs = models.Entry.objects.all()
repository_qs = models.Repository.objects.all()
self.assertEqual(entry_qs.count(), 0)
self.assertEqual(repository_qs.count(), 0)
entry = factories.EntryFactory()
self.assertGreater(len(entry.identifier), 0)
self.assertGreater(len(entry.description), 0)
self.assertGreater(len(entry.url), 0)
self.assertGreater(len(entry.repository.name), 0)
self.assertEqual(entry_qs.count(), 1)
self.assertEqual(repository_qs.count(), 1)
| <commit_before>from django.test import TestCase
from .. import factories, models
class RepositoryFactoryTestCase(TestCase):
def test_can_create_repository(self):
qs = models.Repository.objects.all()
self.assertEqual(qs.count(), 0)
repository = factories.RepositoryFactory()
self.assertGreater(len(repository.name), 1)
self.assertGreater(len(repository.url), 1)
self.assertEqual(qs.count(), 1)
class EntryFactoryTestCase(TestCase):
def test_can_create_entry(self):
entry_qs = models.Entry.objects.all()
repository_qs = models.Repository.objects.all()
self.assertEqual(entry_qs.count(), 0)
self.assertEqual(repository_qs.count(), 0)
entry = factories.EntryFactory()
self.assertGreater(len(entry.identifier), 1)
self.assertGreater(len(entry.description), 1)
self.assertGreater(len(entry.url), 1)
self.assertGreater(len(entry.repository.name), 1)
self.assertEqual(entry_qs.count(), 1)
self.assertEqual(repository_qs.count(), 1)
<commit_msg>Fix random strings minimal expected length<commit_after>from django.test import TestCase
from .. import factories, models
class RepositoryFactoryTestCase(TestCase):
def test_can_create_repository(self):
qs = models.Repository.objects.all()
self.assertEqual(qs.count(), 0)
repository = factories.RepositoryFactory()
self.assertGreater(len(repository.name), 0)
self.assertGreater(len(repository.url), 0)
self.assertEqual(qs.count(), 1)
class EntryFactoryTestCase(TestCase):
def test_can_create_entry(self):
entry_qs = models.Entry.objects.all()
repository_qs = models.Repository.objects.all()
self.assertEqual(entry_qs.count(), 0)
self.assertEqual(repository_qs.count(), 0)
entry = factories.EntryFactory()
self.assertGreater(len(entry.identifier), 0)
self.assertGreater(len(entry.description), 0)
self.assertGreater(len(entry.url), 0)
self.assertGreater(len(entry.repository.name), 0)
self.assertEqual(entry_qs.count(), 1)
self.assertEqual(repository_qs.count(), 1)
|
dc4fb4de0f7a13c33914477f5014cc3490ffbcd1 | config.py | config.py | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = True
WTF_CSRF_ENABLED = False
SESSION_COOKIE_NAME = 'notify_admin_session'
SESSION_COOKIE_PATH = '/admin'
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = True
SECRET_KEY = os.getenv('NOTIFY_ADMIN_FRONTEND_COOKIE_SECRET')
NOTIFY_DATA_API_URL = "http://localhost:6001"
NOTIFY_DATA_API_AUTH_TOKEN = "valid-token"
STATIC_URL_PATH = '/admin/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'header_class': 'with-proposition',
'asset_path': ASSET_PATH
}
class Test(Config):
DEBUG = True
SECRET_KEY = "not-so-secret"
class Development(Config):
DEBUG = True
SESSION_COOKIE_SECURE = False
SECRET_KEY = "not-so-secret"
class Live(Config):
DEBUG = False
class Staging(Config):
DEBUG = False
configs = {
'development': Development,
'preview': Live,
'staging': Staging,
'production': Live,
'test': Test,
}
| import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = True
WTF_CSRF_ENABLED = True
SESSION_COOKIE_NAME = 'notify_admin_session'
SESSION_COOKIE_PATH = '/admin'
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = True
SECRET_KEY = os.getenv('NOTIFY_ADMIN_FRONTEND_COOKIE_SECRET')
NOTIFY_DATA_API_URL = os.getenv('NOTIFY_API_URL', "http://localhost:6001")
NOTIFY_DATA_API_AUTH_TOKEN = os.getenv('NOTIFY_API_TOKEN', "valid-token")
STATIC_URL_PATH = '/admin/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'header_class': 'with-proposition',
'asset_path': ASSET_PATH
}
class Test(Config):
DEBUG = True
SECRET_KEY = "not-so-secret"
class Development(Config):
DEBUG = True
SESSION_COOKIE_SECURE = False
SECRET_KEY = "not-so-secret"
class Live(Config):
DEBUG = False
class Staging(Config):
DEBUG = False
configs = {
'development': Development,
'preview': Live,
'staging': Staging,
'production': Live,
'test': Test,
}
| Read URL and Token from environment | Read URL and Token from environment
| Python | mit | alphagov/notify-frontend,alphagov/notify-frontend,alphagov/notify-frontend,alphagov/notify-frontend | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = True
WTF_CSRF_ENABLED = False
SESSION_COOKIE_NAME = 'notify_admin_session'
SESSION_COOKIE_PATH = '/admin'
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = True
SECRET_KEY = os.getenv('NOTIFY_ADMIN_FRONTEND_COOKIE_SECRET')
NOTIFY_DATA_API_URL = "http://localhost:6001"
NOTIFY_DATA_API_AUTH_TOKEN = "valid-token"
STATIC_URL_PATH = '/admin/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'header_class': 'with-proposition',
'asset_path': ASSET_PATH
}
class Test(Config):
DEBUG = True
SECRET_KEY = "not-so-secret"
class Development(Config):
DEBUG = True
SESSION_COOKIE_SECURE = False
SECRET_KEY = "not-so-secret"
class Live(Config):
DEBUG = False
class Staging(Config):
DEBUG = False
configs = {
'development': Development,
'preview': Live,
'staging': Staging,
'production': Live,
'test': Test,
}
Read URL and Token from environment | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = True
WTF_CSRF_ENABLED = True
SESSION_COOKIE_NAME = 'notify_admin_session'
SESSION_COOKIE_PATH = '/admin'
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = True
SECRET_KEY = os.getenv('NOTIFY_ADMIN_FRONTEND_COOKIE_SECRET')
NOTIFY_DATA_API_URL = os.getenv('NOTIFY_API_URL', "http://localhost:6001")
NOTIFY_DATA_API_AUTH_TOKEN = os.getenv('NOTIFY_API_TOKEN', "valid-token")
STATIC_URL_PATH = '/admin/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'header_class': 'with-proposition',
'asset_path': ASSET_PATH
}
class Test(Config):
DEBUG = True
SECRET_KEY = "not-so-secret"
class Development(Config):
DEBUG = True
SESSION_COOKIE_SECURE = False
SECRET_KEY = "not-so-secret"
class Live(Config):
DEBUG = False
class Staging(Config):
DEBUG = False
configs = {
'development': Development,
'preview': Live,
'staging': Staging,
'production': Live,
'test': Test,
}
| <commit_before>import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = True
WTF_CSRF_ENABLED = False
SESSION_COOKIE_NAME = 'notify_admin_session'
SESSION_COOKIE_PATH = '/admin'
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = True
SECRET_KEY = os.getenv('NOTIFY_ADMIN_FRONTEND_COOKIE_SECRET')
NOTIFY_DATA_API_URL = "http://localhost:6001"
NOTIFY_DATA_API_AUTH_TOKEN = "valid-token"
STATIC_URL_PATH = '/admin/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'header_class': 'with-proposition',
'asset_path': ASSET_PATH
}
class Test(Config):
DEBUG = True
SECRET_KEY = "not-so-secret"
class Development(Config):
DEBUG = True
SESSION_COOKIE_SECURE = False
SECRET_KEY = "not-so-secret"
class Live(Config):
DEBUG = False
class Staging(Config):
DEBUG = False
configs = {
'development': Development,
'preview': Live,
'staging': Staging,
'production': Live,
'test': Test,
}
<commit_msg>Read URL and Token from environment<commit_after> | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = True
WTF_CSRF_ENABLED = True
SESSION_COOKIE_NAME = 'notify_admin_session'
SESSION_COOKIE_PATH = '/admin'
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = True
SECRET_KEY = os.getenv('NOTIFY_ADMIN_FRONTEND_COOKIE_SECRET')
NOTIFY_DATA_API_URL = os.getenv('NOTIFY_API_URL', "http://localhost:6001")
NOTIFY_DATA_API_AUTH_TOKEN = os.getenv('NOTIFY_API_TOKEN', "valid-token")
STATIC_URL_PATH = '/admin/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'header_class': 'with-proposition',
'asset_path': ASSET_PATH
}
class Test(Config):
DEBUG = True
SECRET_KEY = "not-so-secret"
class Development(Config):
DEBUG = True
SESSION_COOKIE_SECURE = False
SECRET_KEY = "not-so-secret"
class Live(Config):
DEBUG = False
class Staging(Config):
DEBUG = False
configs = {
'development': Development,
'preview': Live,
'staging': Staging,
'production': Live,
'test': Test,
}
| import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = True
WTF_CSRF_ENABLED = False
SESSION_COOKIE_NAME = 'notify_admin_session'
SESSION_COOKIE_PATH = '/admin'
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = True
SECRET_KEY = os.getenv('NOTIFY_ADMIN_FRONTEND_COOKIE_SECRET')
NOTIFY_DATA_API_URL = "http://localhost:6001"
NOTIFY_DATA_API_AUTH_TOKEN = "valid-token"
STATIC_URL_PATH = '/admin/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'header_class': 'with-proposition',
'asset_path': ASSET_PATH
}
class Test(Config):
DEBUG = True
SECRET_KEY = "not-so-secret"
class Development(Config):
DEBUG = True
SESSION_COOKIE_SECURE = False
SECRET_KEY = "not-so-secret"
class Live(Config):
DEBUG = False
class Staging(Config):
DEBUG = False
configs = {
'development': Development,
'preview': Live,
'staging': Staging,
'production': Live,
'test': Test,
}
Read URL and Token from environmentimport os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = True
WTF_CSRF_ENABLED = True
SESSION_COOKIE_NAME = 'notify_admin_session'
SESSION_COOKIE_PATH = '/admin'
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = True
SECRET_KEY = os.getenv('NOTIFY_ADMIN_FRONTEND_COOKIE_SECRET')
NOTIFY_DATA_API_URL = os.getenv('NOTIFY_API_URL', "http://localhost:6001")
NOTIFY_DATA_API_AUTH_TOKEN = os.getenv('NOTIFY_API_TOKEN', "valid-token")
STATIC_URL_PATH = '/admin/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'header_class': 'with-proposition',
'asset_path': ASSET_PATH
}
class Test(Config):
DEBUG = True
SECRET_KEY = "not-so-secret"
class Development(Config):
DEBUG = True
SESSION_COOKIE_SECURE = False
SECRET_KEY = "not-so-secret"
class Live(Config):
DEBUG = False
class Staging(Config):
DEBUG = False
configs = {
'development': Development,
'preview': Live,
'staging': Staging,
'production': Live,
'test': Test,
}
| <commit_before>import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = True
WTF_CSRF_ENABLED = False
SESSION_COOKIE_NAME = 'notify_admin_session'
SESSION_COOKIE_PATH = '/admin'
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = True
SECRET_KEY = os.getenv('NOTIFY_ADMIN_FRONTEND_COOKIE_SECRET')
NOTIFY_DATA_API_URL = "http://localhost:6001"
NOTIFY_DATA_API_AUTH_TOKEN = "valid-token"
STATIC_URL_PATH = '/admin/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'header_class': 'with-proposition',
'asset_path': ASSET_PATH
}
class Test(Config):
DEBUG = True
SECRET_KEY = "not-so-secret"
class Development(Config):
DEBUG = True
SESSION_COOKIE_SECURE = False
SECRET_KEY = "not-so-secret"
class Live(Config):
DEBUG = False
class Staging(Config):
DEBUG = False
configs = {
'development': Development,
'preview': Live,
'staging': Staging,
'production': Live,
'test': Test,
}
<commit_msg>Read URL and Token from environment<commit_after>import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = True
WTF_CSRF_ENABLED = True
SESSION_COOKIE_NAME = 'notify_admin_session'
SESSION_COOKIE_PATH = '/admin'
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = True
SECRET_KEY = os.getenv('NOTIFY_ADMIN_FRONTEND_COOKIE_SECRET')
NOTIFY_DATA_API_URL = os.getenv('NOTIFY_API_URL', "http://localhost:6001")
NOTIFY_DATA_API_AUTH_TOKEN = os.getenv('NOTIFY_API_TOKEN', "valid-token")
STATIC_URL_PATH = '/admin/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'header_class': 'with-proposition',
'asset_path': ASSET_PATH
}
class Test(Config):
DEBUG = True
SECRET_KEY = "not-so-secret"
class Development(Config):
DEBUG = True
SESSION_COOKIE_SECURE = False
SECRET_KEY = "not-so-secret"
class Live(Config):
DEBUG = False
class Staging(Config):
DEBUG = False
configs = {
'development': Development,
'preview': Live,
'staging': Staging,
'production': Live,
'test': Test,
}
|
67db0605c054ee0ed6e2a55f818c0c9e4aec9e0d | client/sources/ok_test/__init__.py | client/sources/ok_test/__init__.py | from client import exceptions as ex
from client.sources.ok_test import concept
from client.sources.ok_test import doctest
from client.sources.ok_test import models
from client.sources.common import importing
import logging
import os
log = logging.getLogger(__name__)
SUITES = {
'doctest': doctest.DoctestSuite,
'concept': concept.ConceptSuite,
}
def load(file, parameter, args):
"""Loads an OK-style test from a specified filepath.
PARAMETERS:
file -- str; a filepath to a Python module containing OK-style
tests.
RETURNS:
Test
"""
if not os.path.isfile(file) or not file.endswith('.py'):
log.info('Cannot import {} as an OK test'.format(file))
raise ex.LoadingException('Cannot import {} as an OK test'.format(file))
test = importing.load_module(file).test
try:
return models.OkTest(SUITES, args.verbose, args.interactive,
args.timeout, **test)
except ex.SerializeException:
raise ex.LoadingException('Cannot load OK test {}'.format(file))
| from client import exceptions as ex
from client.sources.ok_test import concept
from client.sources.ok_test import doctest
from client.sources.ok_test import models
from client.sources.common import importing
import logging
import os
log = logging.getLogger(__name__)
SUITES = {
'doctest': doctest.DoctestSuite,
'concept': concept.ConceptSuite,
}
def load(file, parameter, args):
"""Loads an OK-style test from a specified filepath.
PARAMETERS:
file -- str; a filepath to a Python module containing OK-style
tests.
RETURNS:
Test
"""
if not os.path.isfile(file) or not file.endswith('.py'):
log.info('Cannot import {} as an OK test'.format(file))
raise ex.LoadingException('Cannot import {} as an OK test'.format(file))
test = importing.load_module(file).test
try:
return {file: models.OkTest(SUITES, args.verbose, args.interactive,
args.timeout, **test)}
except ex.SerializeException:
raise ex.LoadingException('Cannot load OK test {}'.format(file))
| Fix loading bug in ok_test | Fix loading bug in ok_test
| Python | apache-2.0 | Cal-CS-61A-Staff/ok-client,jathak/ok-client,jackzhao-mj/ok-client | from client import exceptions as ex
from client.sources.ok_test import concept
from client.sources.ok_test import doctest
from client.sources.ok_test import models
from client.sources.common import importing
import logging
import os
log = logging.getLogger(__name__)
SUITES = {
'doctest': doctest.DoctestSuite,
'concept': concept.ConceptSuite,
}
def load(file, parameter, args):
"""Loads an OK-style test from a specified filepath.
PARAMETERS:
file -- str; a filepath to a Python module containing OK-style
tests.
RETURNS:
Test
"""
if not os.path.isfile(file) or not file.endswith('.py'):
log.info('Cannot import {} as an OK test'.format(file))
raise ex.LoadingException('Cannot import {} as an OK test'.format(file))
test = importing.load_module(file).test
try:
return models.OkTest(SUITES, args.verbose, args.interactive,
args.timeout, **test)
except ex.SerializeException:
raise ex.LoadingException('Cannot load OK test {}'.format(file))
Fix loading bug in ok_test | from client import exceptions as ex
from client.sources.ok_test import concept
from client.sources.ok_test import doctest
from client.sources.ok_test import models
from client.sources.common import importing
import logging
import os
log = logging.getLogger(__name__)
SUITES = {
'doctest': doctest.DoctestSuite,
'concept': concept.ConceptSuite,
}
def load(file, parameter, args):
"""Loads an OK-style test from a specified filepath.
PARAMETERS:
file -- str; a filepath to a Python module containing OK-style
tests.
RETURNS:
Test
"""
if not os.path.isfile(file) or not file.endswith('.py'):
log.info('Cannot import {} as an OK test'.format(file))
raise ex.LoadingException('Cannot import {} as an OK test'.format(file))
test = importing.load_module(file).test
try:
return {file: models.OkTest(SUITES, args.verbose, args.interactive,
args.timeout, **test)}
except ex.SerializeException:
raise ex.LoadingException('Cannot load OK test {}'.format(file))
| <commit_before>from client import exceptions as ex
from client.sources.ok_test import concept
from client.sources.ok_test import doctest
from client.sources.ok_test import models
from client.sources.common import importing
import logging
import os
log = logging.getLogger(__name__)
SUITES = {
'doctest': doctest.DoctestSuite,
'concept': concept.ConceptSuite,
}
def load(file, parameter, args):
"""Loads an OK-style test from a specified filepath.
PARAMETERS:
file -- str; a filepath to a Python module containing OK-style
tests.
RETURNS:
Test
"""
if not os.path.isfile(file) or not file.endswith('.py'):
log.info('Cannot import {} as an OK test'.format(file))
raise ex.LoadingException('Cannot import {} as an OK test'.format(file))
test = importing.load_module(file).test
try:
return models.OkTest(SUITES, args.verbose, args.interactive,
args.timeout, **test)
except ex.SerializeException:
raise ex.LoadingException('Cannot load OK test {}'.format(file))
<commit_msg>Fix loading bug in ok_test<commit_after> | from client import exceptions as ex
from client.sources.ok_test import concept
from client.sources.ok_test import doctest
from client.sources.ok_test import models
from client.sources.common import importing
import logging
import os
log = logging.getLogger(__name__)
SUITES = {
'doctest': doctest.DoctestSuite,
'concept': concept.ConceptSuite,
}
def load(file, parameter, args):
"""Loads an OK-style test from a specified filepath.
PARAMETERS:
file -- str; a filepath to a Python module containing OK-style
tests.
RETURNS:
Test
"""
if not os.path.isfile(file) or not file.endswith('.py'):
log.info('Cannot import {} as an OK test'.format(file))
raise ex.LoadingException('Cannot import {} as an OK test'.format(file))
test = importing.load_module(file).test
try:
return {file: models.OkTest(SUITES, args.verbose, args.interactive,
args.timeout, **test)}
except ex.SerializeException:
raise ex.LoadingException('Cannot load OK test {}'.format(file))
| from client import exceptions as ex
from client.sources.ok_test import concept
from client.sources.ok_test import doctest
from client.sources.ok_test import models
from client.sources.common import importing
import logging
import os
log = logging.getLogger(__name__)
SUITES = {
'doctest': doctest.DoctestSuite,
'concept': concept.ConceptSuite,
}
def load(file, parameter, args):
"""Loads an OK-style test from a specified filepath.
PARAMETERS:
file -- str; a filepath to a Python module containing OK-style
tests.
RETURNS:
Test
"""
if not os.path.isfile(file) or not file.endswith('.py'):
log.info('Cannot import {} as an OK test'.format(file))
raise ex.LoadingException('Cannot import {} as an OK test'.format(file))
test = importing.load_module(file).test
try:
return models.OkTest(SUITES, args.verbose, args.interactive,
args.timeout, **test)
except ex.SerializeException:
raise ex.LoadingException('Cannot load OK test {}'.format(file))
Fix loading bug in ok_testfrom client import exceptions as ex
from client.sources.ok_test import concept
from client.sources.ok_test import doctest
from client.sources.ok_test import models
from client.sources.common import importing
import logging
import os
log = logging.getLogger(__name__)
SUITES = {
'doctest': doctest.DoctestSuite,
'concept': concept.ConceptSuite,
}
def load(file, parameter, args):
"""Loads an OK-style test from a specified filepath.
PARAMETERS:
file -- str; a filepath to a Python module containing OK-style
tests.
RETURNS:
Test
"""
if not os.path.isfile(file) or not file.endswith('.py'):
log.info('Cannot import {} as an OK test'.format(file))
raise ex.LoadingException('Cannot import {} as an OK test'.format(file))
test = importing.load_module(file).test
try:
return {file: models.OkTest(SUITES, args.verbose, args.interactive,
args.timeout, **test)}
except ex.SerializeException:
raise ex.LoadingException('Cannot load OK test {}'.format(file))
| <commit_before>from client import exceptions as ex
from client.sources.ok_test import concept
from client.sources.ok_test import doctest
from client.sources.ok_test import models
from client.sources.common import importing
import logging
import os
log = logging.getLogger(__name__)
SUITES = {
'doctest': doctest.DoctestSuite,
'concept': concept.ConceptSuite,
}
def load(file, parameter, args):
"""Loads an OK-style test from a specified filepath.
PARAMETERS:
file -- str; a filepath to a Python module containing OK-style
tests.
RETURNS:
Test
"""
if not os.path.isfile(file) or not file.endswith('.py'):
log.info('Cannot import {} as an OK test'.format(file))
raise ex.LoadingException('Cannot import {} as an OK test'.format(file))
test = importing.load_module(file).test
try:
return models.OkTest(SUITES, args.verbose, args.interactive,
args.timeout, **test)
except ex.SerializeException:
raise ex.LoadingException('Cannot load OK test {}'.format(file))
<commit_msg>Fix loading bug in ok_test<commit_after>from client import exceptions as ex
from client.sources.ok_test import concept
from client.sources.ok_test import doctest
from client.sources.ok_test import models
from client.sources.common import importing
import logging
import os
log = logging.getLogger(__name__)
SUITES = {
'doctest': doctest.DoctestSuite,
'concept': concept.ConceptSuite,
}
def load(file, parameter, args):
"""Loads an OK-style test from a specified filepath.
PARAMETERS:
file -- str; a filepath to a Python module containing OK-style
tests.
RETURNS:
Test
"""
if not os.path.isfile(file) or not file.endswith('.py'):
log.info('Cannot import {} as an OK test'.format(file))
raise ex.LoadingException('Cannot import {} as an OK test'.format(file))
test = importing.load_module(file).test
try:
return {file: models.OkTest(SUITES, args.verbose, args.interactive,
args.timeout, **test)}
except ex.SerializeException:
raise ex.LoadingException('Cannot load OK test {}'.format(file))
|
0725be7d78e8049dd3e3cc1819644443a1a1da3b | backend/uclapi/gunicorn_config.py | backend/uclapi/gunicorn_config.py | import multiprocessing
bind = "127.0.0.1:9000"
# Run cores * 4 + 1 workers in gunicorn
# This is set deliberately high in case of long Oracle transactions locking Django up
workers = multiprocessing.cpu_count() * 4 + 1
threads = multiprocessing.cpu_count() * 4
# Using gaiohttp because of the long blocking calls to the Oracle database
worker_class = "gaiohttp"
daemon = False
proc_name = "uclapi_gunicorn"
timeout = 600 | import multiprocessing
bind = "127.0.0.1:9000"
# Run cores * 4 + 1 workers in gunicorn
# This is set deliberately high in case of long Oracle transactions locking Django up
workers = multiprocessing.cpu_count() * 4 + 1
threads = multiprocessing.cpu_count() * 4
# Using gaiohttp because of the long blocking calls to the Oracle database
worker_class = "gaiohttp"
daemon = False
proc_name = "uclapi_gunicorn"
timeout = 600
greaceful_timeout = 600
| Update gunicorn graceful timeout value to match general timeout | Hotfix: Update gunicorn graceful timeout value to match general timeout
| Python | mit | uclapi/uclapi,uclapi/uclapi,uclapi/uclapi,uclapi/uclapi | import multiprocessing
bind = "127.0.0.1:9000"
# Run cores * 4 + 1 workers in gunicorn
# This is set deliberately high in case of long Oracle transactions locking Django up
workers = multiprocessing.cpu_count() * 4 + 1
threads = multiprocessing.cpu_count() * 4
# Using gaiohttp because of the long blocking calls to the Oracle database
worker_class = "gaiohttp"
daemon = False
proc_name = "uclapi_gunicorn"
timeout = 600Hotfix: Update gunicorn graceful timeout value to match general timeout | import multiprocessing
bind = "127.0.0.1:9000"
# Run cores * 4 + 1 workers in gunicorn
# This is set deliberately high in case of long Oracle transactions locking Django up
workers = multiprocessing.cpu_count() * 4 + 1
threads = multiprocessing.cpu_count() * 4
# Using gaiohttp because of the long blocking calls to the Oracle database
worker_class = "gaiohttp"
daemon = False
proc_name = "uclapi_gunicorn"
timeout = 600
greaceful_timeout = 600
| <commit_before>import multiprocessing
bind = "127.0.0.1:9000"
# Run cores * 4 + 1 workers in gunicorn
# This is set deliberately high in case of long Oracle transactions locking Django up
workers = multiprocessing.cpu_count() * 4 + 1
threads = multiprocessing.cpu_count() * 4
# Using gaiohttp because of the long blocking calls to the Oracle database
worker_class = "gaiohttp"
daemon = False
proc_name = "uclapi_gunicorn"
timeout = 600<commit_msg>Hotfix: Update gunicorn graceful timeout value to match general timeout<commit_after> | import multiprocessing
bind = "127.0.0.1:9000"
# Run cores * 4 + 1 workers in gunicorn
# This is set deliberately high in case of long Oracle transactions locking Django up
workers = multiprocessing.cpu_count() * 4 + 1
threads = multiprocessing.cpu_count() * 4
# Using gaiohttp because of the long blocking calls to the Oracle database
worker_class = "gaiohttp"
daemon = False
proc_name = "uclapi_gunicorn"
timeout = 600
greaceful_timeout = 600
| import multiprocessing
bind = "127.0.0.1:9000"
# Run cores * 4 + 1 workers in gunicorn
# This is set deliberately high in case of long Oracle transactions locking Django up
workers = multiprocessing.cpu_count() * 4 + 1
threads = multiprocessing.cpu_count() * 4
# Using gaiohttp because of the long blocking calls to the Oracle database
worker_class = "gaiohttp"
daemon = False
proc_name = "uclapi_gunicorn"
timeout = 600Hotfix: Update gunicorn graceful timeout value to match general timeoutimport multiprocessing
bind = "127.0.0.1:9000"
# Run cores * 4 + 1 workers in gunicorn
# This is set deliberately high in case of long Oracle transactions locking Django up
workers = multiprocessing.cpu_count() * 4 + 1
threads = multiprocessing.cpu_count() * 4
# Using gaiohttp because of the long blocking calls to the Oracle database
worker_class = "gaiohttp"
daemon = False
proc_name = "uclapi_gunicorn"
timeout = 600
greaceful_timeout = 600
| <commit_before>import multiprocessing
bind = "127.0.0.1:9000"
# Run cores * 4 + 1 workers in gunicorn
# This is set deliberately high in case of long Oracle transactions locking Django up
workers = multiprocessing.cpu_count() * 4 + 1
threads = multiprocessing.cpu_count() * 4
# Using gaiohttp because of the long blocking calls to the Oracle database
worker_class = "gaiohttp"
daemon = False
proc_name = "uclapi_gunicorn"
timeout = 600<commit_msg>Hotfix: Update gunicorn graceful timeout value to match general timeout<commit_after>import multiprocessing
bind = "127.0.0.1:9000"
# Run cores * 4 + 1 workers in gunicorn
# This is set deliberately high in case of long Oracle transactions locking Django up
workers = multiprocessing.cpu_count() * 4 + 1
threads = multiprocessing.cpu_count() * 4
# Using gaiohttp because of the long blocking calls to the Oracle database
worker_class = "gaiohttp"
daemon = False
proc_name = "uclapi_gunicorn"
timeout = 600
greaceful_timeout = 600
|
2d0c87826904889e79f21ae86c4fe7bc1fbc733c | funcs.py | funcs.py | from ctypeslib.codegen import typedesc
def typedef_as_arg(tp):
return tp.name
def fundamental_as_arg(tp):
return tp.name
def structure_as_arg(tp):
return tp.name
def pointer_as_arg(tp):
if isinstance(tp.typ, typedesc.FunctionType):
args = [generic_as_arg(arg) for arg in tp.typ.iterArgTypes()]
if len(args) > 0:
return (generic_as_arg(tp.typ.returns) % '' ) + \
'(*)' + '(%s)' % ", ".join(args)
else:
return generic_as_arg(tp.typ.returns) + ' (*)()'
else:
return '%s *' % generic_as_arg(tp.typ)
def generic_as_arg(tp):
if isinstance(tp, typedesc.FundamentalType):
return fundamental_as_arg(tp)
elif isinstance(tp, typedesc.Typedef):
return typedef_as_arg(tp)
elif isinstance(tp, typedesc.PointerType):
return pointer_as_arg(tp)
elif isinstance(tp, typedesc.CvQualifiedType):
return generic_as_arg(tp.typ)
elif isinstance(tp, typedesc.Structure):
return structure_as_arg(tp)
elif isinstance(tp, typedesc.Enumeration):
return "int"
else:
print "not handled", tp
return None
| from ctypeslib.codegen import typedesc
def typedef_as_arg(tp):
return tp.name
def fundamental_as_arg(tp):
return tp.name
def structure_as_arg(tp):
return tp.name
def pointer_as_arg(tp):
if isinstance(tp.typ, typedesc.FunctionType):
args = [generic_as_arg(arg) for arg in tp.typ.iterArgTypes()]
if len(args) > 0:
return generic_as_arg(tp.typ.returns) + \
' (*)(%s)' % ", ".join(args)
else:
return generic_as_arg(tp.typ.returns) + ' (*)()'
else:
return '%s *' % generic_as_arg(tp.typ)
def generic_as_arg(tp):
if isinstance(tp, typedesc.FundamentalType):
return fundamental_as_arg(tp)
elif isinstance(tp, typedesc.Typedef):
return typedef_as_arg(tp)
elif isinstance(tp, typedesc.PointerType):
return pointer_as_arg(tp)
elif isinstance(tp, typedesc.CvQualifiedType):
return generic_as_arg(tp.typ)
elif isinstance(tp, typedesc.Structure):
return structure_as_arg(tp)
elif isinstance(tp, typedesc.Enumeration):
return "int"
else:
print "not handled", tp
return None
| Fix code generation for function pointer argument . | Fix code generation for function pointer argument .
| Python | mit | cournape/cython-codegen,cournape/cython-codegen | from ctypeslib.codegen import typedesc
def typedef_as_arg(tp):
return tp.name
def fundamental_as_arg(tp):
return tp.name
def structure_as_arg(tp):
return tp.name
def pointer_as_arg(tp):
if isinstance(tp.typ, typedesc.FunctionType):
args = [generic_as_arg(arg) for arg in tp.typ.iterArgTypes()]
if len(args) > 0:
return (generic_as_arg(tp.typ.returns) % '' ) + \
'(*)' + '(%s)' % ", ".join(args)
else:
return generic_as_arg(tp.typ.returns) + ' (*)()'
else:
return '%s *' % generic_as_arg(tp.typ)
def generic_as_arg(tp):
if isinstance(tp, typedesc.FundamentalType):
return fundamental_as_arg(tp)
elif isinstance(tp, typedesc.Typedef):
return typedef_as_arg(tp)
elif isinstance(tp, typedesc.PointerType):
return pointer_as_arg(tp)
elif isinstance(tp, typedesc.CvQualifiedType):
return generic_as_arg(tp.typ)
elif isinstance(tp, typedesc.Structure):
return structure_as_arg(tp)
elif isinstance(tp, typedesc.Enumeration):
return "int"
else:
print "not handled", tp
return None
Fix code generation for function pointer argument . | from ctypeslib.codegen import typedesc
def typedef_as_arg(tp):
return tp.name
def fundamental_as_arg(tp):
return tp.name
def structure_as_arg(tp):
return tp.name
def pointer_as_arg(tp):
if isinstance(tp.typ, typedesc.FunctionType):
args = [generic_as_arg(arg) for arg in tp.typ.iterArgTypes()]
if len(args) > 0:
return generic_as_arg(tp.typ.returns) + \
' (*)(%s)' % ", ".join(args)
else:
return generic_as_arg(tp.typ.returns) + ' (*)()'
else:
return '%s *' % generic_as_arg(tp.typ)
def generic_as_arg(tp):
if isinstance(tp, typedesc.FundamentalType):
return fundamental_as_arg(tp)
elif isinstance(tp, typedesc.Typedef):
return typedef_as_arg(tp)
elif isinstance(tp, typedesc.PointerType):
return pointer_as_arg(tp)
elif isinstance(tp, typedesc.CvQualifiedType):
return generic_as_arg(tp.typ)
elif isinstance(tp, typedesc.Structure):
return structure_as_arg(tp)
elif isinstance(tp, typedesc.Enumeration):
return "int"
else:
print "not handled", tp
return None
| <commit_before>from ctypeslib.codegen import typedesc
def typedef_as_arg(tp):
return tp.name
def fundamental_as_arg(tp):
return tp.name
def structure_as_arg(tp):
return tp.name
def pointer_as_arg(tp):
if isinstance(tp.typ, typedesc.FunctionType):
args = [generic_as_arg(arg) for arg in tp.typ.iterArgTypes()]
if len(args) > 0:
return (generic_as_arg(tp.typ.returns) % '' ) + \
'(*)' + '(%s)' % ", ".join(args)
else:
return generic_as_arg(tp.typ.returns) + ' (*)()'
else:
return '%s *' % generic_as_arg(tp.typ)
def generic_as_arg(tp):
if isinstance(tp, typedesc.FundamentalType):
return fundamental_as_arg(tp)
elif isinstance(tp, typedesc.Typedef):
return typedef_as_arg(tp)
elif isinstance(tp, typedesc.PointerType):
return pointer_as_arg(tp)
elif isinstance(tp, typedesc.CvQualifiedType):
return generic_as_arg(tp.typ)
elif isinstance(tp, typedesc.Structure):
return structure_as_arg(tp)
elif isinstance(tp, typedesc.Enumeration):
return "int"
else:
print "not handled", tp
return None
<commit_msg>Fix code generation for function pointer argument .<commit_after> | from ctypeslib.codegen import typedesc
def typedef_as_arg(tp):
return tp.name
def fundamental_as_arg(tp):
return tp.name
def structure_as_arg(tp):
return tp.name
def pointer_as_arg(tp):
if isinstance(tp.typ, typedesc.FunctionType):
args = [generic_as_arg(arg) for arg in tp.typ.iterArgTypes()]
if len(args) > 0:
return generic_as_arg(tp.typ.returns) + \
' (*)(%s)' % ", ".join(args)
else:
return generic_as_arg(tp.typ.returns) + ' (*)()'
else:
return '%s *' % generic_as_arg(tp.typ)
def generic_as_arg(tp):
if isinstance(tp, typedesc.FundamentalType):
return fundamental_as_arg(tp)
elif isinstance(tp, typedesc.Typedef):
return typedef_as_arg(tp)
elif isinstance(tp, typedesc.PointerType):
return pointer_as_arg(tp)
elif isinstance(tp, typedesc.CvQualifiedType):
return generic_as_arg(tp.typ)
elif isinstance(tp, typedesc.Structure):
return structure_as_arg(tp)
elif isinstance(tp, typedesc.Enumeration):
return "int"
else:
print "not handled", tp
return None
| from ctypeslib.codegen import typedesc
def typedef_as_arg(tp):
return tp.name
def fundamental_as_arg(tp):
return tp.name
def structure_as_arg(tp):
return tp.name
def pointer_as_arg(tp):
if isinstance(tp.typ, typedesc.FunctionType):
args = [generic_as_arg(arg) for arg in tp.typ.iterArgTypes()]
if len(args) > 0:
return (generic_as_arg(tp.typ.returns) % '' ) + \
'(*)' + '(%s)' % ", ".join(args)
else:
return generic_as_arg(tp.typ.returns) + ' (*)()'
else:
return '%s *' % generic_as_arg(tp.typ)
def generic_as_arg(tp):
if isinstance(tp, typedesc.FundamentalType):
return fundamental_as_arg(tp)
elif isinstance(tp, typedesc.Typedef):
return typedef_as_arg(tp)
elif isinstance(tp, typedesc.PointerType):
return pointer_as_arg(tp)
elif isinstance(tp, typedesc.CvQualifiedType):
return generic_as_arg(tp.typ)
elif isinstance(tp, typedesc.Structure):
return structure_as_arg(tp)
elif isinstance(tp, typedesc.Enumeration):
return "int"
else:
print "not handled", tp
return None
Fix code generation for function pointer argument .from ctypeslib.codegen import typedesc
def typedef_as_arg(tp):
return tp.name
def fundamental_as_arg(tp):
return tp.name
def structure_as_arg(tp):
return tp.name
def pointer_as_arg(tp):
if isinstance(tp.typ, typedesc.FunctionType):
args = [generic_as_arg(arg) for arg in tp.typ.iterArgTypes()]
if len(args) > 0:
return generic_as_arg(tp.typ.returns) + \
' (*)(%s)' % ", ".join(args)
else:
return generic_as_arg(tp.typ.returns) + ' (*)()'
else:
return '%s *' % generic_as_arg(tp.typ)
def generic_as_arg(tp):
if isinstance(tp, typedesc.FundamentalType):
return fundamental_as_arg(tp)
elif isinstance(tp, typedesc.Typedef):
return typedef_as_arg(tp)
elif isinstance(tp, typedesc.PointerType):
return pointer_as_arg(tp)
elif isinstance(tp, typedesc.CvQualifiedType):
return generic_as_arg(tp.typ)
elif isinstance(tp, typedesc.Structure):
return structure_as_arg(tp)
elif isinstance(tp, typedesc.Enumeration):
return "int"
else:
print "not handled", tp
return None
| <commit_before>from ctypeslib.codegen import typedesc
def typedef_as_arg(tp):
return tp.name
def fundamental_as_arg(tp):
return tp.name
def structure_as_arg(tp):
return tp.name
def pointer_as_arg(tp):
if isinstance(tp.typ, typedesc.FunctionType):
args = [generic_as_arg(arg) for arg in tp.typ.iterArgTypes()]
if len(args) > 0:
return (generic_as_arg(tp.typ.returns) % '' ) + \
'(*)' + '(%s)' % ", ".join(args)
else:
return generic_as_arg(tp.typ.returns) + ' (*)()'
else:
return '%s *' % generic_as_arg(tp.typ)
def generic_as_arg(tp):
if isinstance(tp, typedesc.FundamentalType):
return fundamental_as_arg(tp)
elif isinstance(tp, typedesc.Typedef):
return typedef_as_arg(tp)
elif isinstance(tp, typedesc.PointerType):
return pointer_as_arg(tp)
elif isinstance(tp, typedesc.CvQualifiedType):
return generic_as_arg(tp.typ)
elif isinstance(tp, typedesc.Structure):
return structure_as_arg(tp)
elif isinstance(tp, typedesc.Enumeration):
return "int"
else:
print "not handled", tp
return None
<commit_msg>Fix code generation for function pointer argument .<commit_after>from ctypeslib.codegen import typedesc
def typedef_as_arg(tp):
return tp.name
def fundamental_as_arg(tp):
return tp.name
def structure_as_arg(tp):
return tp.name
def pointer_as_arg(tp):
if isinstance(tp.typ, typedesc.FunctionType):
args = [generic_as_arg(arg) for arg in tp.typ.iterArgTypes()]
if len(args) > 0:
return generic_as_arg(tp.typ.returns) + \
' (*)(%s)' % ", ".join(args)
else:
return generic_as_arg(tp.typ.returns) + ' (*)()'
else:
return '%s *' % generic_as_arg(tp.typ)
def generic_as_arg(tp):
if isinstance(tp, typedesc.FundamentalType):
return fundamental_as_arg(tp)
elif isinstance(tp, typedesc.Typedef):
return typedef_as_arg(tp)
elif isinstance(tp, typedesc.PointerType):
return pointer_as_arg(tp)
elif isinstance(tp, typedesc.CvQualifiedType):
return generic_as_arg(tp.typ)
elif isinstance(tp, typedesc.Structure):
return structure_as_arg(tp)
elif isinstance(tp, typedesc.Enumeration):
return "int"
else:
print "not handled", tp
return None
|
e27fd32ecb89f5f2de1a784e902fe64d1b73d33c | {{cookiecutter.app_name}}/urls.py | {{cookiecutter.app_name}}/urls.py | from django.conf.urls import patterns, url
from .views import {{ cookiecutter.model_name }}List, {{ cookiecutter.model_name }}Create, {{ cookiecutter.model_name }}Detail, {{ cookiecutter.model_name }}Update, {{ cookiecutter.model_name }}Delete
urlpatterns = patterns(
'',
url(r'^$', {{ cookiecutter.model_name }}List.as_view(), name='{{ cookiecutter.model_name|lower }}_list'),
url(r'^new/$', {{ cookiecutter.model_name }}Create.as_view(), name='{{ cookiecutter.model_name|lower }}_create'),
url(r'^(?P<pk>\d+)/$', {{ cookiecutter.model_name }}Detail.as_view(), name='{{ cookiecutter.model_name|lower }}_detail'),
url(r'^(?P<pk>\d+)/update/$', {{ cookiecutter.model_name }}Update.as_view(), name='{{ cookiecutter.model_name|lower }}_update'),
url(r'^(?P<pk>\d+)/delete/$', {{ cookiecutter.model_name }}Delete.as_view(), name='{{ cookiecutter.model_name|lower }}_delete'),
)
| from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns(
'',
url(r'^$', views.{{ cookiecutter.model_name }}List.as_view(), name='{{ cookiecutter.model_name|lower }}_list'),
url(r'^new/$', views.{{ cookiecutter.model_name }}Create.as_view(), name='{{ cookiecutter.model_name|lower }}_create'),
url(r'^(?P<pk>\d+)/$', views.{{ cookiecutter.model_name }}Detail.as_view(), name='{{ cookiecutter.model_name|lower }}_detail'),
url(r'^(?P<pk>\d+)/update/$', views.{{ cookiecutter.model_name }}Update.as_view(), name='{{ cookiecutter.model_name|lower }}_update'),
url(r'^(?P<pk>\d+)/delete/$', views.{{ cookiecutter.model_name }}Delete.as_view(), name='{{ cookiecutter.model_name|lower }}_delete'),
)
| Use briefer url views import. | Use briefer url views import.
| Python | bsd-3-clause | wildfish/cookiecutter-django-crud,janusnic/cookiecutter-django-crud,wildfish/cookiecutter-django-crud,janusnic/cookiecutter-django-crud | from django.conf.urls import patterns, url
from .views import {{ cookiecutter.model_name }}List, {{ cookiecutter.model_name }}Create, {{ cookiecutter.model_name }}Detail, {{ cookiecutter.model_name }}Update, {{ cookiecutter.model_name }}Delete
urlpatterns = patterns(
'',
url(r'^$', {{ cookiecutter.model_name }}List.as_view(), name='{{ cookiecutter.model_name|lower }}_list'),
url(r'^new/$', {{ cookiecutter.model_name }}Create.as_view(), name='{{ cookiecutter.model_name|lower }}_create'),
url(r'^(?P<pk>\d+)/$', {{ cookiecutter.model_name }}Detail.as_view(), name='{{ cookiecutter.model_name|lower }}_detail'),
url(r'^(?P<pk>\d+)/update/$', {{ cookiecutter.model_name }}Update.as_view(), name='{{ cookiecutter.model_name|lower }}_update'),
url(r'^(?P<pk>\d+)/delete/$', {{ cookiecutter.model_name }}Delete.as_view(), name='{{ cookiecutter.model_name|lower }}_delete'),
)
Use briefer url views import. | from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns(
'',
url(r'^$', views.{{ cookiecutter.model_name }}List.as_view(), name='{{ cookiecutter.model_name|lower }}_list'),
url(r'^new/$', views.{{ cookiecutter.model_name }}Create.as_view(), name='{{ cookiecutter.model_name|lower }}_create'),
url(r'^(?P<pk>\d+)/$', views.{{ cookiecutter.model_name }}Detail.as_view(), name='{{ cookiecutter.model_name|lower }}_detail'),
url(r'^(?P<pk>\d+)/update/$', views.{{ cookiecutter.model_name }}Update.as_view(), name='{{ cookiecutter.model_name|lower }}_update'),
url(r'^(?P<pk>\d+)/delete/$', views.{{ cookiecutter.model_name }}Delete.as_view(), name='{{ cookiecutter.model_name|lower }}_delete'),
)
| <commit_before>from django.conf.urls import patterns, url
from .views import {{ cookiecutter.model_name }}List, {{ cookiecutter.model_name }}Create, {{ cookiecutter.model_name }}Detail, {{ cookiecutter.model_name }}Update, {{ cookiecutter.model_name }}Delete
urlpatterns = patterns(
'',
url(r'^$', {{ cookiecutter.model_name }}List.as_view(), name='{{ cookiecutter.model_name|lower }}_list'),
url(r'^new/$', {{ cookiecutter.model_name }}Create.as_view(), name='{{ cookiecutter.model_name|lower }}_create'),
url(r'^(?P<pk>\d+)/$', {{ cookiecutter.model_name }}Detail.as_view(), name='{{ cookiecutter.model_name|lower }}_detail'),
url(r'^(?P<pk>\d+)/update/$', {{ cookiecutter.model_name }}Update.as_view(), name='{{ cookiecutter.model_name|lower }}_update'),
url(r'^(?P<pk>\d+)/delete/$', {{ cookiecutter.model_name }}Delete.as_view(), name='{{ cookiecutter.model_name|lower }}_delete'),
)
<commit_msg>Use briefer url views import.<commit_after> | from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns(
'',
url(r'^$', views.{{ cookiecutter.model_name }}List.as_view(), name='{{ cookiecutter.model_name|lower }}_list'),
url(r'^new/$', views.{{ cookiecutter.model_name }}Create.as_view(), name='{{ cookiecutter.model_name|lower }}_create'),
url(r'^(?P<pk>\d+)/$', views.{{ cookiecutter.model_name }}Detail.as_view(), name='{{ cookiecutter.model_name|lower }}_detail'),
url(r'^(?P<pk>\d+)/update/$', views.{{ cookiecutter.model_name }}Update.as_view(), name='{{ cookiecutter.model_name|lower }}_update'),
url(r'^(?P<pk>\d+)/delete/$', views.{{ cookiecutter.model_name }}Delete.as_view(), name='{{ cookiecutter.model_name|lower }}_delete'),
)
| from django.conf.urls import patterns, url
from .views import {{ cookiecutter.model_name }}List, {{ cookiecutter.model_name }}Create, {{ cookiecutter.model_name }}Detail, {{ cookiecutter.model_name }}Update, {{ cookiecutter.model_name }}Delete
urlpatterns = patterns(
'',
url(r'^$', {{ cookiecutter.model_name }}List.as_view(), name='{{ cookiecutter.model_name|lower }}_list'),
url(r'^new/$', {{ cookiecutter.model_name }}Create.as_view(), name='{{ cookiecutter.model_name|lower }}_create'),
url(r'^(?P<pk>\d+)/$', {{ cookiecutter.model_name }}Detail.as_view(), name='{{ cookiecutter.model_name|lower }}_detail'),
url(r'^(?P<pk>\d+)/update/$', {{ cookiecutter.model_name }}Update.as_view(), name='{{ cookiecutter.model_name|lower }}_update'),
url(r'^(?P<pk>\d+)/delete/$', {{ cookiecutter.model_name }}Delete.as_view(), name='{{ cookiecutter.model_name|lower }}_delete'),
)
Use briefer url views import.from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns(
'',
url(r'^$', views.{{ cookiecutter.model_name }}List.as_view(), name='{{ cookiecutter.model_name|lower }}_list'),
url(r'^new/$', views.{{ cookiecutter.model_name }}Create.as_view(), name='{{ cookiecutter.model_name|lower }}_create'),
url(r'^(?P<pk>\d+)/$', views.{{ cookiecutter.model_name }}Detail.as_view(), name='{{ cookiecutter.model_name|lower }}_detail'),
url(r'^(?P<pk>\d+)/update/$', views.{{ cookiecutter.model_name }}Update.as_view(), name='{{ cookiecutter.model_name|lower }}_update'),
url(r'^(?P<pk>\d+)/delete/$', views.{{ cookiecutter.model_name }}Delete.as_view(), name='{{ cookiecutter.model_name|lower }}_delete'),
)
| <commit_before>from django.conf.urls import patterns, url
from .views import {{ cookiecutter.model_name }}List, {{ cookiecutter.model_name }}Create, {{ cookiecutter.model_name }}Detail, {{ cookiecutter.model_name }}Update, {{ cookiecutter.model_name }}Delete
urlpatterns = patterns(
'',
url(r'^$', {{ cookiecutter.model_name }}List.as_view(), name='{{ cookiecutter.model_name|lower }}_list'),
url(r'^new/$', {{ cookiecutter.model_name }}Create.as_view(), name='{{ cookiecutter.model_name|lower }}_create'),
url(r'^(?P<pk>\d+)/$', {{ cookiecutter.model_name }}Detail.as_view(), name='{{ cookiecutter.model_name|lower }}_detail'),
url(r'^(?P<pk>\d+)/update/$', {{ cookiecutter.model_name }}Update.as_view(), name='{{ cookiecutter.model_name|lower }}_update'),
url(r'^(?P<pk>\d+)/delete/$', {{ cookiecutter.model_name }}Delete.as_view(), name='{{ cookiecutter.model_name|lower }}_delete'),
)
<commit_msg>Use briefer url views import.<commit_after>from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns(
'',
url(r'^$', views.{{ cookiecutter.model_name }}List.as_view(), name='{{ cookiecutter.model_name|lower }}_list'),
url(r'^new/$', views.{{ cookiecutter.model_name }}Create.as_view(), name='{{ cookiecutter.model_name|lower }}_create'),
url(r'^(?P<pk>\d+)/$', views.{{ cookiecutter.model_name }}Detail.as_view(), name='{{ cookiecutter.model_name|lower }}_detail'),
url(r'^(?P<pk>\d+)/update/$', views.{{ cookiecutter.model_name }}Update.as_view(), name='{{ cookiecutter.model_name|lower }}_update'),
url(r'^(?P<pk>\d+)/delete/$', views.{{ cookiecutter.model_name }}Delete.as_view(), name='{{ cookiecutter.model_name|lower }}_delete'),
)
|
fb0354a22ac3be04729d929540504e374c192a6c | go/apps/bulk_message/definition.py | go/apps/bulk_message/definition.py | from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class BulkSendAction(ConversationAction):
action_name = 'bulk_send'
action_display_name = 'Send Bulk Message'
needs_confirmation = True
needs_group = True
needs_running = True
def perform_action(self, action_data):
return self.send_command(
'bulk_send', batch_id=self._conv.get_latest_batch_key(),
msg_options={}, content=action_data['message'],
delivery_class=self._conv.delivery_class,
dedupe=action_data['dedupe'])
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'bulk_message'
actions = (BulkSendAction,)
| from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class BulkSendAction(ConversationAction):
action_name = 'bulk_send'
action_display_name = 'Send Bulk Message'
needs_confirmation = True
needs_group = True
needs_running = True
def check_disabled(self):
channels = self._conv.get_channels()
for channel in channels:
if channel.supports_generic_sends():
return None
return ("This action needs channels capable of sending"
" messages attached to this conversation.")
def perform_action(self, action_data):
return self.send_command(
'bulk_send', batch_id=self._conv.get_latest_batch_key(),
msg_options={}, content=action_data['message'],
delivery_class=self._conv.delivery_class,
dedupe=action_data['dedupe'])
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'bulk_message'
actions = (BulkSendAction,)
| Disable bulk send action when a bulk send conversation has no suitable channels attached. | Disable bulk send action when a bulk send conversation has no suitable channels attached.
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class BulkSendAction(ConversationAction):
action_name = 'bulk_send'
action_display_name = 'Send Bulk Message'
needs_confirmation = True
needs_group = True
needs_running = True
def perform_action(self, action_data):
return self.send_command(
'bulk_send', batch_id=self._conv.get_latest_batch_key(),
msg_options={}, content=action_data['message'],
delivery_class=self._conv.delivery_class,
dedupe=action_data['dedupe'])
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'bulk_message'
actions = (BulkSendAction,)
Disable bulk send action when a bulk send conversation has no suitable channels attached. | from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class BulkSendAction(ConversationAction):
action_name = 'bulk_send'
action_display_name = 'Send Bulk Message'
needs_confirmation = True
needs_group = True
needs_running = True
def check_disabled(self):
channels = self._conv.get_channels()
for channel in channels:
if channel.supports_generic_sends():
return None
return ("This action needs channels capable of sending"
" messages attached to this conversation.")
def perform_action(self, action_data):
return self.send_command(
'bulk_send', batch_id=self._conv.get_latest_batch_key(),
msg_options={}, content=action_data['message'],
delivery_class=self._conv.delivery_class,
dedupe=action_data['dedupe'])
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'bulk_message'
actions = (BulkSendAction,)
| <commit_before>from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class BulkSendAction(ConversationAction):
action_name = 'bulk_send'
action_display_name = 'Send Bulk Message'
needs_confirmation = True
needs_group = True
needs_running = True
def perform_action(self, action_data):
return self.send_command(
'bulk_send', batch_id=self._conv.get_latest_batch_key(),
msg_options={}, content=action_data['message'],
delivery_class=self._conv.delivery_class,
dedupe=action_data['dedupe'])
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'bulk_message'
actions = (BulkSendAction,)
<commit_msg>Disable bulk send action when a bulk send conversation has no suitable channels attached.<commit_after> | from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class BulkSendAction(ConversationAction):
action_name = 'bulk_send'
action_display_name = 'Send Bulk Message'
needs_confirmation = True
needs_group = True
needs_running = True
def check_disabled(self):
channels = self._conv.get_channels()
for channel in channels:
if channel.supports_generic_sends():
return None
return ("This action needs channels capable of sending"
" messages attached to this conversation.")
def perform_action(self, action_data):
return self.send_command(
'bulk_send', batch_id=self._conv.get_latest_batch_key(),
msg_options={}, content=action_data['message'],
delivery_class=self._conv.delivery_class,
dedupe=action_data['dedupe'])
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'bulk_message'
actions = (BulkSendAction,)
| from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class BulkSendAction(ConversationAction):
action_name = 'bulk_send'
action_display_name = 'Send Bulk Message'
needs_confirmation = True
needs_group = True
needs_running = True
def perform_action(self, action_data):
return self.send_command(
'bulk_send', batch_id=self._conv.get_latest_batch_key(),
msg_options={}, content=action_data['message'],
delivery_class=self._conv.delivery_class,
dedupe=action_data['dedupe'])
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'bulk_message'
actions = (BulkSendAction,)
Disable bulk send action when a bulk send conversation has no suitable channels attached.from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class BulkSendAction(ConversationAction):
action_name = 'bulk_send'
action_display_name = 'Send Bulk Message'
needs_confirmation = True
needs_group = True
needs_running = True
def check_disabled(self):
channels = self._conv.get_channels()
for channel in channels:
if channel.supports_generic_sends():
return None
return ("This action needs channels capable of sending"
" messages attached to this conversation.")
def perform_action(self, action_data):
return self.send_command(
'bulk_send', batch_id=self._conv.get_latest_batch_key(),
msg_options={}, content=action_data['message'],
delivery_class=self._conv.delivery_class,
dedupe=action_data['dedupe'])
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'bulk_message'
actions = (BulkSendAction,)
| <commit_before>from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class BulkSendAction(ConversationAction):
action_name = 'bulk_send'
action_display_name = 'Send Bulk Message'
needs_confirmation = True
needs_group = True
needs_running = True
def perform_action(self, action_data):
return self.send_command(
'bulk_send', batch_id=self._conv.get_latest_batch_key(),
msg_options={}, content=action_data['message'],
delivery_class=self._conv.delivery_class,
dedupe=action_data['dedupe'])
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'bulk_message'
actions = (BulkSendAction,)
<commit_msg>Disable bulk send action when a bulk send conversation has no suitable channels attached.<commit_after>from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class BulkSendAction(ConversationAction):
action_name = 'bulk_send'
action_display_name = 'Send Bulk Message'
needs_confirmation = True
needs_group = True
needs_running = True
def check_disabled(self):
channels = self._conv.get_channels()
for channel in channels:
if channel.supports_generic_sends():
return None
return ("This action needs channels capable of sending"
" messages attached to this conversation.")
def perform_action(self, action_data):
return self.send_command(
'bulk_send', batch_id=self._conv.get_latest_batch_key(),
msg_options={}, content=action_data['message'],
delivery_class=self._conv.delivery_class,
dedupe=action_data['dedupe'])
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'bulk_message'
actions = (BulkSendAction,)
|
0704dd1002e7ef546b718abec41a55c256a49cb2 | examples/test_fail.py | examples/test_fail.py | """ This test was made to fail on purpose to demonstrate the
logging capabilities of the SeleniumBase Test Framework """
from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_find_army_of_robots_on_xkcd_desert_island(self):
self.open("http://xkcd.com/731/")
self.assert_element("div#ARMY_OF_ROBOTS", timeout=0.7)
| """ This test was made to fail on purpose to demonstrate the
logging capabilities of the SeleniumBase Test Framework """
from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_find_army_of_robots_on_xkcd_desert_island(self):
self.open("http://xkcd.com/731/")
print("\n(This test fails on purpose)")
self.assert_element("div#ARMY_OF_ROBOTS", timeout=1)
| Update test that fails on purpose. | Update test that fails on purpose.
| Python | mit | mdmintz/seleniumspot,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/seleniumspot | """ This test was made to fail on purpose to demonstrate the
logging capabilities of the SeleniumBase Test Framework """
from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_find_army_of_robots_on_xkcd_desert_island(self):
self.open("http://xkcd.com/731/")
self.assert_element("div#ARMY_OF_ROBOTS", timeout=0.7)
Update test that fails on purpose. | """ This test was made to fail on purpose to demonstrate the
logging capabilities of the SeleniumBase Test Framework """
from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_find_army_of_robots_on_xkcd_desert_island(self):
self.open("http://xkcd.com/731/")
print("\n(This test fails on purpose)")
self.assert_element("div#ARMY_OF_ROBOTS", timeout=1)
| <commit_before>""" This test was made to fail on purpose to demonstrate the
logging capabilities of the SeleniumBase Test Framework """
from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_find_army_of_robots_on_xkcd_desert_island(self):
self.open("http://xkcd.com/731/")
self.assert_element("div#ARMY_OF_ROBOTS", timeout=0.7)
<commit_msg>Update test that fails on purpose.<commit_after> | """ This test was made to fail on purpose to demonstrate the
logging capabilities of the SeleniumBase Test Framework """
from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_find_army_of_robots_on_xkcd_desert_island(self):
self.open("http://xkcd.com/731/")
print("\n(This test fails on purpose)")
self.assert_element("div#ARMY_OF_ROBOTS", timeout=1)
| """ This test was made to fail on purpose to demonstrate the
logging capabilities of the SeleniumBase Test Framework """
from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_find_army_of_robots_on_xkcd_desert_island(self):
self.open("http://xkcd.com/731/")
self.assert_element("div#ARMY_OF_ROBOTS", timeout=0.7)
Update test that fails on purpose.""" This test was made to fail on purpose to demonstrate the
logging capabilities of the SeleniumBase Test Framework """
from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_find_army_of_robots_on_xkcd_desert_island(self):
self.open("http://xkcd.com/731/")
print("\n(This test fails on purpose)")
self.assert_element("div#ARMY_OF_ROBOTS", timeout=1)
| <commit_before>""" This test was made to fail on purpose to demonstrate the
logging capabilities of the SeleniumBase Test Framework """
from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_find_army_of_robots_on_xkcd_desert_island(self):
self.open("http://xkcd.com/731/")
self.assert_element("div#ARMY_OF_ROBOTS", timeout=0.7)
<commit_msg>Update test that fails on purpose.<commit_after>""" This test was made to fail on purpose to demonstrate the
logging capabilities of the SeleniumBase Test Framework """
from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_find_army_of_robots_on_xkcd_desert_island(self):
self.open("http://xkcd.com/731/")
print("\n(This test fails on purpose)")
self.assert_element("div#ARMY_OF_ROBOTS", timeout=1)
|
39421ab0e74bbcab610aead0924a177a164404a6 | Cura/Qt/MainWindow.py | Cura/Qt/MainWindow.py | from PyQt5.QtCore import pyqtProperty, QObject
from PyQt5.QtGui import QColor
from PyQt5.QtQuick import QQuickWindow, QQuickItem
from OpenGL import GL
class MainWindow(QQuickWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
self._app = None
self._backgroundColor = QColor(204, 204, 204, 255)
self.setClearBeforeRendering(False)
self.beforeRendering.connect(self._render)
def getApplication(self):
return self._app
def setApplication(self, app):
self._app = app
application = pyqtProperty(QObject, fget=getApplication, fset=setApplication)
def getBackgroundColor(self):
return self._backgroundColor
def setBackgroundColor(self, color):
self._backgroundColor = color
backgroundColor = pyqtProperty(QColor, fget=getBackgroundColor, fset=setBackgroundColor)
def _render(self):
GL.glClearColor(self._backgroundColor.redF(), self._backgroundColor.greenF(), self._backgroundColor.blueF(), self._backgroundColor.alphaF())
GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
if self._app:
self._app.getController().getActiveView().render()
| from PyQt5.QtCore import pyqtProperty, QObject
from PyQt5.QtGui import QColor
from PyQt5.QtQuick import QQuickWindow, QQuickItem
from OpenGL import GL
from OpenGL.GL.GREMEDY.string_marker import *
class MainWindow(QQuickWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
self._app = None
self._backgroundColor = QColor(204, 204, 204, 255)
self.setClearBeforeRendering(False)
self.beforeRendering.connect(self._render)
def getApplication(self):
return self._app
def setApplication(self, app):
self._app = app
application = pyqtProperty(QObject, fget=getApplication, fset=setApplication)
def getBackgroundColor(self):
return self._backgroundColor
def setBackgroundColor(self, color):
self._backgroundColor = color
backgroundColor = pyqtProperty(QColor, fget=getBackgroundColor, fset=setBackgroundColor)
def _render(self):
if bool(glStringMarkerGREMEDY):
msg = b"Begin Rendering Background"
glStringMarkerGREMEDY(len(msg), msg)
GL.glClearColor(self._backgroundColor.redF(), self._backgroundColor.greenF(), self._backgroundColor.blueF(), self._backgroundColor.alphaF())
GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
if self._app:
self._app.getController().getActiveView().render()
if bool(glStringMarkerGREMEDY):
msg = "End Rendering Background"
glStringMarkerGREMEDY(len(msg), msg)
| Add some debug markers for more clearly finding our own rendering code | Add some debug markers for more clearly finding our own rendering code
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | from PyQt5.QtCore import pyqtProperty, QObject
from PyQt5.QtGui import QColor
from PyQt5.QtQuick import QQuickWindow, QQuickItem
from OpenGL import GL
class MainWindow(QQuickWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
self._app = None
self._backgroundColor = QColor(204, 204, 204, 255)
self.setClearBeforeRendering(False)
self.beforeRendering.connect(self._render)
def getApplication(self):
return self._app
def setApplication(self, app):
self._app = app
application = pyqtProperty(QObject, fget=getApplication, fset=setApplication)
def getBackgroundColor(self):
return self._backgroundColor
def setBackgroundColor(self, color):
self._backgroundColor = color
backgroundColor = pyqtProperty(QColor, fget=getBackgroundColor, fset=setBackgroundColor)
def _render(self):
GL.glClearColor(self._backgroundColor.redF(), self._backgroundColor.greenF(), self._backgroundColor.blueF(), self._backgroundColor.alphaF())
GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
if self._app:
self._app.getController().getActiveView().render()
Add some debug markers for more clearly finding our own rendering code | from PyQt5.QtCore import pyqtProperty, QObject
from PyQt5.QtGui import QColor
from PyQt5.QtQuick import QQuickWindow, QQuickItem
from OpenGL import GL
from OpenGL.GL.GREMEDY.string_marker import *
class MainWindow(QQuickWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
self._app = None
self._backgroundColor = QColor(204, 204, 204, 255)
self.setClearBeforeRendering(False)
self.beforeRendering.connect(self._render)
def getApplication(self):
return self._app
def setApplication(self, app):
self._app = app
application = pyqtProperty(QObject, fget=getApplication, fset=setApplication)
def getBackgroundColor(self):
return self._backgroundColor
def setBackgroundColor(self, color):
self._backgroundColor = color
backgroundColor = pyqtProperty(QColor, fget=getBackgroundColor, fset=setBackgroundColor)
def _render(self):
if bool(glStringMarkerGREMEDY):
msg = b"Begin Rendering Background"
glStringMarkerGREMEDY(len(msg), msg)
GL.glClearColor(self._backgroundColor.redF(), self._backgroundColor.greenF(), self._backgroundColor.blueF(), self._backgroundColor.alphaF())
GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
if self._app:
self._app.getController().getActiveView().render()
if bool(glStringMarkerGREMEDY):
msg = "End Rendering Background"
glStringMarkerGREMEDY(len(msg), msg)
| <commit_before>from PyQt5.QtCore import pyqtProperty, QObject
from PyQt5.QtGui import QColor
from PyQt5.QtQuick import QQuickWindow, QQuickItem
from OpenGL import GL
class MainWindow(QQuickWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
self._app = None
self._backgroundColor = QColor(204, 204, 204, 255)
self.setClearBeforeRendering(False)
self.beforeRendering.connect(self._render)
def getApplication(self):
return self._app
def setApplication(self, app):
self._app = app
application = pyqtProperty(QObject, fget=getApplication, fset=setApplication)
def getBackgroundColor(self):
return self._backgroundColor
def setBackgroundColor(self, color):
self._backgroundColor = color
backgroundColor = pyqtProperty(QColor, fget=getBackgroundColor, fset=setBackgroundColor)
def _render(self):
GL.glClearColor(self._backgroundColor.redF(), self._backgroundColor.greenF(), self._backgroundColor.blueF(), self._backgroundColor.alphaF())
GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
if self._app:
self._app.getController().getActiveView().render()
<commit_msg>Add some debug markers for more clearly finding our own rendering code<commit_after> | from PyQt5.QtCore import pyqtProperty, QObject
from PyQt5.QtGui import QColor
from PyQt5.QtQuick import QQuickWindow, QQuickItem
from OpenGL import GL
from OpenGL.GL.GREMEDY.string_marker import *
class MainWindow(QQuickWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
self._app = None
self._backgroundColor = QColor(204, 204, 204, 255)
self.setClearBeforeRendering(False)
self.beforeRendering.connect(self._render)
def getApplication(self):
return self._app
def setApplication(self, app):
self._app = app
application = pyqtProperty(QObject, fget=getApplication, fset=setApplication)
def getBackgroundColor(self):
return self._backgroundColor
def setBackgroundColor(self, color):
self._backgroundColor = color
backgroundColor = pyqtProperty(QColor, fget=getBackgroundColor, fset=setBackgroundColor)
def _render(self):
if bool(glStringMarkerGREMEDY):
msg = b"Begin Rendering Background"
glStringMarkerGREMEDY(len(msg), msg)
GL.glClearColor(self._backgroundColor.redF(), self._backgroundColor.greenF(), self._backgroundColor.blueF(), self._backgroundColor.alphaF())
GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
if self._app:
self._app.getController().getActiveView().render()
if bool(glStringMarkerGREMEDY):
msg = "End Rendering Background"
glStringMarkerGREMEDY(len(msg), msg)
| from PyQt5.QtCore import pyqtProperty, QObject
from PyQt5.QtGui import QColor
from PyQt5.QtQuick import QQuickWindow, QQuickItem
from OpenGL import GL
class MainWindow(QQuickWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
self._app = None
self._backgroundColor = QColor(204, 204, 204, 255)
self.setClearBeforeRendering(False)
self.beforeRendering.connect(self._render)
def getApplication(self):
return self._app
def setApplication(self, app):
self._app = app
application = pyqtProperty(QObject, fget=getApplication, fset=setApplication)
def getBackgroundColor(self):
return self._backgroundColor
def setBackgroundColor(self, color):
self._backgroundColor = color
backgroundColor = pyqtProperty(QColor, fget=getBackgroundColor, fset=setBackgroundColor)
def _render(self):
GL.glClearColor(self._backgroundColor.redF(), self._backgroundColor.greenF(), self._backgroundColor.blueF(), self._backgroundColor.alphaF())
GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
if self._app:
self._app.getController().getActiveView().render()
Add some debug markers for more clearly finding our own rendering codefrom PyQt5.QtCore import pyqtProperty, QObject
from PyQt5.QtGui import QColor
from PyQt5.QtQuick import QQuickWindow, QQuickItem
from OpenGL import GL
from OpenGL.GL.GREMEDY.string_marker import *
class MainWindow(QQuickWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
self._app = None
self._backgroundColor = QColor(204, 204, 204, 255)
self.setClearBeforeRendering(False)
self.beforeRendering.connect(self._render)
def getApplication(self):
return self._app
def setApplication(self, app):
self._app = app
application = pyqtProperty(QObject, fget=getApplication, fset=setApplication)
def getBackgroundColor(self):
return self._backgroundColor
def setBackgroundColor(self, color):
self._backgroundColor = color
backgroundColor = pyqtProperty(QColor, fget=getBackgroundColor, fset=setBackgroundColor)
def _render(self):
if bool(glStringMarkerGREMEDY):
msg = b"Begin Rendering Background"
glStringMarkerGREMEDY(len(msg), msg)
GL.glClearColor(self._backgroundColor.redF(), self._backgroundColor.greenF(), self._backgroundColor.blueF(), self._backgroundColor.alphaF())
GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
if self._app:
self._app.getController().getActiveView().render()
if bool(glStringMarkerGREMEDY):
msg = "End Rendering Background"
glStringMarkerGREMEDY(len(msg), msg)
| <commit_before>from PyQt5.QtCore import pyqtProperty, QObject
from PyQt5.QtGui import QColor
from PyQt5.QtQuick import QQuickWindow, QQuickItem
from OpenGL import GL
class MainWindow(QQuickWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
self._app = None
self._backgroundColor = QColor(204, 204, 204, 255)
self.setClearBeforeRendering(False)
self.beforeRendering.connect(self._render)
def getApplication(self):
return self._app
def setApplication(self, app):
self._app = app
application = pyqtProperty(QObject, fget=getApplication, fset=setApplication)
def getBackgroundColor(self):
return self._backgroundColor
def setBackgroundColor(self, color):
self._backgroundColor = color
backgroundColor = pyqtProperty(QColor, fget=getBackgroundColor, fset=setBackgroundColor)
def _render(self):
GL.glClearColor(self._backgroundColor.redF(), self._backgroundColor.greenF(), self._backgroundColor.blueF(), self._backgroundColor.alphaF())
GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
if self._app:
self._app.getController().getActiveView().render()
<commit_msg>Add some debug markers for more clearly finding our own rendering code<commit_after>from PyQt5.QtCore import pyqtProperty, QObject
from PyQt5.QtGui import QColor
from PyQt5.QtQuick import QQuickWindow, QQuickItem
from OpenGL import GL
from OpenGL.GL.GREMEDY.string_marker import *
class MainWindow(QQuickWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
self._app = None
self._backgroundColor = QColor(204, 204, 204, 255)
self.setClearBeforeRendering(False)
self.beforeRendering.connect(self._render)
def getApplication(self):
return self._app
def setApplication(self, app):
self._app = app
application = pyqtProperty(QObject, fget=getApplication, fset=setApplication)
def getBackgroundColor(self):
return self._backgroundColor
def setBackgroundColor(self, color):
self._backgroundColor = color
backgroundColor = pyqtProperty(QColor, fget=getBackgroundColor, fset=setBackgroundColor)
def _render(self):
if bool(glStringMarkerGREMEDY):
msg = b"Begin Rendering Background"
glStringMarkerGREMEDY(len(msg), msg)
GL.glClearColor(self._backgroundColor.redF(), self._backgroundColor.greenF(), self._backgroundColor.blueF(), self._backgroundColor.alphaF())
GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
if self._app:
self._app.getController().getActiveView().render()
if bool(glStringMarkerGREMEDY):
msg = "End Rendering Background"
glStringMarkerGREMEDY(len(msg), msg)
|
4696c2458956fcb5c1cfef168461659262de04c1 | Demo/scripts/mpzpi.py | Demo/scripts/mpzpi.py | #! /usr/bin/env python
# Print digits of pi forever.
#
# The algorithm, using Python's 'long' integers ("bignums"), works
# with continued fractions, and was conceived by Lambert Meertens.
#
# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
# published by Prentice-Hall (UK) Ltd., 1990.
import sys
from mpz import mpz
def main():
mpzone, mpztwo, mpzten = mpz(1), mpz(2), mpz(10)
k, a, b, a1, b1 = mpz(2), mpz(4), mpz(1), mpz(12), mpz(4)
while 1:
# Next approximation
p, q, k = k*k, mpztwo*k+mpzone, k+mpzone
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
# Print common digits
d, d1 = a/b, a1/b1
while d == d1:
output(d)
a, a1 = mpzten*(a%b), mpzten*(a1%b1)
d, d1 = a/b, a1/b1
def output(d):
# Use write() to avoid spaces between the digits
# Use int(d) to avoid a trailing L after each digit
sys.stdout.write(`int(d)`)
# Flush so the output is seen immediately
sys.stdout.flush()
main()
| #! /usr/bin/env python
# Print digits of pi forever.
#
# The algorithm, using Python's 'long' integers ("bignums"), works
# with continued fractions, and was conceived by Lambert Meertens.
#
# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
# published by Prentice-Hall (UK) Ltd., 1990.
import sys
def main():
k, a, b, a1, b1 = 2, 4, 1, 12, 4
while 1:
# Next approximation
p, q, k = k*k, 2*k+1, k+1
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
# Print common digits
d, d1 = a/b, a1/b1
while d == d1:
output(d)
a, a1 = 10*(a%b), 10*(a1%b1)
d, d1 = a/b, a1/b1
def output(d):
# Use write() to avoid spaces between the digits
# Use int(d) to avoid a trailing L after each digit
sys.stdout.write(`int(d)`)
# Flush so the output is seen immediately
sys.stdout.flush()
main()
| Update to use python ints and int/long unification. | Update to use python ints and int/long unification.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | #! /usr/bin/env python
# Print digits of pi forever.
#
# The algorithm, using Python's 'long' integers ("bignums"), works
# with continued fractions, and was conceived by Lambert Meertens.
#
# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
# published by Prentice-Hall (UK) Ltd., 1990.
import sys
from mpz import mpz
def main():
mpzone, mpztwo, mpzten = mpz(1), mpz(2), mpz(10)
k, a, b, a1, b1 = mpz(2), mpz(4), mpz(1), mpz(12), mpz(4)
while 1:
# Next approximation
p, q, k = k*k, mpztwo*k+mpzone, k+mpzone
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
# Print common digits
d, d1 = a/b, a1/b1
while d == d1:
output(d)
a, a1 = mpzten*(a%b), mpzten*(a1%b1)
d, d1 = a/b, a1/b1
def output(d):
# Use write() to avoid spaces between the digits
# Use int(d) to avoid a trailing L after each digit
sys.stdout.write(`int(d)`)
# Flush so the output is seen immediately
sys.stdout.flush()
main()
Update to use python ints and int/long unification. | #! /usr/bin/env python
# Print digits of pi forever.
#
# The algorithm, using Python's 'long' integers ("bignums"), works
# with continued fractions, and was conceived by Lambert Meertens.
#
# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
# published by Prentice-Hall (UK) Ltd., 1990.
import sys
def main():
k, a, b, a1, b1 = 2, 4, 1, 12, 4
while 1:
# Next approximation
p, q, k = k*k, 2*k+1, k+1
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
# Print common digits
d, d1 = a/b, a1/b1
while d == d1:
output(d)
a, a1 = 10*(a%b), 10*(a1%b1)
d, d1 = a/b, a1/b1
def output(d):
# Use write() to avoid spaces between the digits
# Use int(d) to avoid a trailing L after each digit
sys.stdout.write(`int(d)`)
# Flush so the output is seen immediately
sys.stdout.flush()
main()
| <commit_before>#! /usr/bin/env python
# Print digits of pi forever.
#
# The algorithm, using Python's 'long' integers ("bignums"), works
# with continued fractions, and was conceived by Lambert Meertens.
#
# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
# published by Prentice-Hall (UK) Ltd., 1990.
import sys
from mpz import mpz
def main():
mpzone, mpztwo, mpzten = mpz(1), mpz(2), mpz(10)
k, a, b, a1, b1 = mpz(2), mpz(4), mpz(1), mpz(12), mpz(4)
while 1:
# Next approximation
p, q, k = k*k, mpztwo*k+mpzone, k+mpzone
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
# Print common digits
d, d1 = a/b, a1/b1
while d == d1:
output(d)
a, a1 = mpzten*(a%b), mpzten*(a1%b1)
d, d1 = a/b, a1/b1
def output(d):
# Use write() to avoid spaces between the digits
# Use int(d) to avoid a trailing L after each digit
sys.stdout.write(`int(d)`)
# Flush so the output is seen immediately
sys.stdout.flush()
main()
<commit_msg>Update to use python ints and int/long unification.<commit_after> | #! /usr/bin/env python
# Print digits of pi forever.
#
# The algorithm, using Python's 'long' integers ("bignums"), works
# with continued fractions, and was conceived by Lambert Meertens.
#
# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
# published by Prentice-Hall (UK) Ltd., 1990.
import sys
def main():
k, a, b, a1, b1 = 2, 4, 1, 12, 4
while 1:
# Next approximation
p, q, k = k*k, 2*k+1, k+1
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
# Print common digits
d, d1 = a/b, a1/b1
while d == d1:
output(d)
a, a1 = 10*(a%b), 10*(a1%b1)
d, d1 = a/b, a1/b1
def output(d):
# Use write() to avoid spaces between the digits
# Use int(d) to avoid a trailing L after each digit
sys.stdout.write(`int(d)`)
# Flush so the output is seen immediately
sys.stdout.flush()
main()
| #! /usr/bin/env python
# Print digits of pi forever.
#
# The algorithm, using Python's 'long' integers ("bignums"), works
# with continued fractions, and was conceived by Lambert Meertens.
#
# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
# published by Prentice-Hall (UK) Ltd., 1990.
import sys
from mpz import mpz
def main():
mpzone, mpztwo, mpzten = mpz(1), mpz(2), mpz(10)
k, a, b, a1, b1 = mpz(2), mpz(4), mpz(1), mpz(12), mpz(4)
while 1:
# Next approximation
p, q, k = k*k, mpztwo*k+mpzone, k+mpzone
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
# Print common digits
d, d1 = a/b, a1/b1
while d == d1:
output(d)
a, a1 = mpzten*(a%b), mpzten*(a1%b1)
d, d1 = a/b, a1/b1
def output(d):
# Use write() to avoid spaces between the digits
# Use int(d) to avoid a trailing L after each digit
sys.stdout.write(`int(d)`)
# Flush so the output is seen immediately
sys.stdout.flush()
main()
Update to use python ints and int/long unification.#! /usr/bin/env python
# Print digits of pi forever.
#
# The algorithm, using Python's 'long' integers ("bignums"), works
# with continued fractions, and was conceived by Lambert Meertens.
#
# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
# published by Prentice-Hall (UK) Ltd., 1990.
import sys
def main():
k, a, b, a1, b1 = 2, 4, 1, 12, 4
while 1:
# Next approximation
p, q, k = k*k, 2*k+1, k+1
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
# Print common digits
d, d1 = a/b, a1/b1
while d == d1:
output(d)
a, a1 = 10*(a%b), 10*(a1%b1)
d, d1 = a/b, a1/b1
def output(d):
# Use write() to avoid spaces between the digits
# Use int(d) to avoid a trailing L after each digit
sys.stdout.write(`int(d)`)
# Flush so the output is seen immediately
sys.stdout.flush()
main()
| <commit_before>#! /usr/bin/env python
# Print digits of pi forever.
#
# The algorithm, using Python's 'long' integers ("bignums"), works
# with continued fractions, and was conceived by Lambert Meertens.
#
# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
# published by Prentice-Hall (UK) Ltd., 1990.
import sys
from mpz import mpz
def main():
mpzone, mpztwo, mpzten = mpz(1), mpz(2), mpz(10)
k, a, b, a1, b1 = mpz(2), mpz(4), mpz(1), mpz(12), mpz(4)
while 1:
# Next approximation
p, q, k = k*k, mpztwo*k+mpzone, k+mpzone
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
# Print common digits
d, d1 = a/b, a1/b1
while d == d1:
output(d)
a, a1 = mpzten*(a%b), mpzten*(a1%b1)
d, d1 = a/b, a1/b1
def output(d):
# Use write() to avoid spaces between the digits
# Use int(d) to avoid a trailing L after each digit
sys.stdout.write(`int(d)`)
# Flush so the output is seen immediately
sys.stdout.flush()
main()
<commit_msg>Update to use python ints and int/long unification.<commit_after>#! /usr/bin/env python
# Print digits of pi forever.
#
# The algorithm, using Python's 'long' integers ("bignums"), works
# with continued fractions, and was conceived by Lambert Meertens.
#
# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
# published by Prentice-Hall (UK) Ltd., 1990.
import sys
def main():
k, a, b, a1, b1 = 2, 4, 1, 12, 4
while 1:
# Next approximation
p, q, k = k*k, 2*k+1, k+1
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
# Print common digits
d, d1 = a/b, a1/b1
while d == d1:
output(d)
a, a1 = 10*(a%b), 10*(a1%b1)
d, d1 = a/b, a1/b1
def output(d):
# Use write() to avoid spaces between the digits
# Use int(d) to avoid a trailing L after each digit
sys.stdout.write(`int(d)`)
# Flush so the output is seen immediately
sys.stdout.flush()
main()
|
e95ce817417d8d54c5cc561d7d7f70952550bd0e | robotpy_ext/misc/asyncio_policy.py | robotpy_ext/misc/asyncio_policy.py | """
This is a replacement event loop and policy for asyncio that uses FPGA time,
rather than native python time.
"""
from asyncio.events import BaseDefaultEventLoopPolicy
from asyncio import SelectorEventLoop, set_event_loop_policy
from wpilib import Timer
class FPGATimedEventLoop(SelectorEventLoop):
"""An asyncio event loop that uses wpilib time rather than python time"""
def time(self):
return Timer.getFPGATimestamp()
class FPGATimedEventLoopPolicy(BaseDefaultEventLoopPolicy):
"""An asyncio event loop policy that uses FPGATimedEventLoop"""
_loop_factory = FPGATimedEventLoop
def patch_asyncio_policy():
"""
Sets an instance of FPGATimedEventLoopPolicy as the default asyncio event
loop policy
"""
set_event_loop_policy(FPGATimedEventLoopPolicy()) | """
This is a replacement event loop and policy for asyncio that uses FPGA time,
rather than native python time.
"""
from asyncio.events import AbstractEventLoopPolicy
from asyncio import SelectorEventLoop, set_event_loop_policy
from wpilib import Timer
class FPGATimedEventLoop(SelectorEventLoop):
"""An asyncio event loop that uses wpilib time rather than python time"""
def time(self):
return Timer.getFPGATimestamp()
class FPGATimedEventLoopPolicy(AbstractEventLoopPolicy):
"""An asyncio event loop policy that uses FPGATimedEventLoop"""
_loop_factory = FPGATimedEventLoop
def patch_asyncio_policy():
"""
Sets an instance of FPGATimedEventLoopPolicy as the default asyncio event
loop policy
"""
set_event_loop_policy(FPGATimedEventLoopPolicy()) | Update asyncio policy to match newer asyncio version | Update asyncio policy to match newer asyncio version
| Python | bsd-3-clause | Twinters007/robotpy-wpilib-utilities,robotpy/robotpy-wpilib-utilities,robotpy/robotpy-wpilib-utilities,Twinters007/robotpy-wpilib-utilities | """
This is a replacement event loop and policy for asyncio that uses FPGA time,
rather than native python time.
"""
from asyncio.events import BaseDefaultEventLoopPolicy
from asyncio import SelectorEventLoop, set_event_loop_policy
from wpilib import Timer
class FPGATimedEventLoop(SelectorEventLoop):
"""An asyncio event loop that uses wpilib time rather than python time"""
def time(self):
return Timer.getFPGATimestamp()
class FPGATimedEventLoopPolicy(BaseDefaultEventLoopPolicy):
"""An asyncio event loop policy that uses FPGATimedEventLoop"""
_loop_factory = FPGATimedEventLoop
def patch_asyncio_policy():
"""
Sets an instance of FPGATimedEventLoopPolicy as the default asyncio event
loop policy
"""
set_event_loop_policy(FPGATimedEventLoopPolicy())Update asyncio policy to match newer asyncio version | """
This is a replacement event loop and policy for asyncio that uses FPGA time,
rather than native python time.
"""
from asyncio.events import AbstractEventLoopPolicy
from asyncio import SelectorEventLoop, set_event_loop_policy
from wpilib import Timer
class FPGATimedEventLoop(SelectorEventLoop):
"""An asyncio event loop that uses wpilib time rather than python time"""
def time(self):
return Timer.getFPGATimestamp()
class FPGATimedEventLoopPolicy(AbstractEventLoopPolicy):
"""An asyncio event loop policy that uses FPGATimedEventLoop"""
_loop_factory = FPGATimedEventLoop
def patch_asyncio_policy():
"""
Sets an instance of FPGATimedEventLoopPolicy as the default asyncio event
loop policy
"""
set_event_loop_policy(FPGATimedEventLoopPolicy()) | <commit_before>"""
This is a replacement event loop and policy for asyncio that uses FPGA time,
rather than native python time.
"""
from asyncio.events import BaseDefaultEventLoopPolicy
from asyncio import SelectorEventLoop, set_event_loop_policy
from wpilib import Timer
class FPGATimedEventLoop(SelectorEventLoop):
"""An asyncio event loop that uses wpilib time rather than python time"""
def time(self):
return Timer.getFPGATimestamp()
class FPGATimedEventLoopPolicy(BaseDefaultEventLoopPolicy):
"""An asyncio event loop policy that uses FPGATimedEventLoop"""
_loop_factory = FPGATimedEventLoop
def patch_asyncio_policy():
"""
Sets an instance of FPGATimedEventLoopPolicy as the default asyncio event
loop policy
"""
set_event_loop_policy(FPGATimedEventLoopPolicy())<commit_msg>Update asyncio policy to match newer asyncio version<commit_after> | """
This is a replacement event loop and policy for asyncio that uses FPGA time,
rather than native python time.
"""
from asyncio.events import AbstractEventLoopPolicy
from asyncio import SelectorEventLoop, set_event_loop_policy
from wpilib import Timer
class FPGATimedEventLoop(SelectorEventLoop):
"""An asyncio event loop that uses wpilib time rather than python time"""
def time(self):
return Timer.getFPGATimestamp()
class FPGATimedEventLoopPolicy(AbstractEventLoopPolicy):
"""An asyncio event loop policy that uses FPGATimedEventLoop"""
_loop_factory = FPGATimedEventLoop
def patch_asyncio_policy():
"""
Sets an instance of FPGATimedEventLoopPolicy as the default asyncio event
loop policy
"""
set_event_loop_policy(FPGATimedEventLoopPolicy()) | """
This is a replacement event loop and policy for asyncio that uses FPGA time,
rather than native python time.
"""
from asyncio.events import BaseDefaultEventLoopPolicy
from asyncio import SelectorEventLoop, set_event_loop_policy
from wpilib import Timer
class FPGATimedEventLoop(SelectorEventLoop):
"""An asyncio event loop that uses wpilib time rather than python time"""
def time(self):
return Timer.getFPGATimestamp()
class FPGATimedEventLoopPolicy(BaseDefaultEventLoopPolicy):
"""An asyncio event loop policy that uses FPGATimedEventLoop"""
_loop_factory = FPGATimedEventLoop
def patch_asyncio_policy():
"""
Sets an instance of FPGATimedEventLoopPolicy as the default asyncio event
loop policy
"""
set_event_loop_policy(FPGATimedEventLoopPolicy())Update asyncio policy to match newer asyncio version"""
This is a replacement event loop and policy for asyncio that uses FPGA time,
rather than native python time.
"""
from asyncio.events import AbstractEventLoopPolicy
from asyncio import SelectorEventLoop, set_event_loop_policy
from wpilib import Timer
class FPGATimedEventLoop(SelectorEventLoop):
"""An asyncio event loop that uses wpilib time rather than python time"""
def time(self):
return Timer.getFPGATimestamp()
class FPGATimedEventLoopPolicy(AbstractEventLoopPolicy):
"""An asyncio event loop policy that uses FPGATimedEventLoop"""
_loop_factory = FPGATimedEventLoop
def patch_asyncio_policy():
"""
Sets an instance of FPGATimedEventLoopPolicy as the default asyncio event
loop policy
"""
set_event_loop_policy(FPGATimedEventLoopPolicy()) | <commit_before>"""
This is a replacement event loop and policy for asyncio that uses FPGA time,
rather than native python time.
"""
from asyncio.events import BaseDefaultEventLoopPolicy
from asyncio import SelectorEventLoop, set_event_loop_policy
from wpilib import Timer
class FPGATimedEventLoop(SelectorEventLoop):
"""An asyncio event loop that uses wpilib time rather than python time"""
def time(self):
return Timer.getFPGATimestamp()
class FPGATimedEventLoopPolicy(BaseDefaultEventLoopPolicy):
"""An asyncio event loop policy that uses FPGATimedEventLoop"""
_loop_factory = FPGATimedEventLoop
def patch_asyncio_policy():
"""
Sets an instance of FPGATimedEventLoopPolicy as the default asyncio event
loop policy
"""
set_event_loop_policy(FPGATimedEventLoopPolicy())<commit_msg>Update asyncio policy to match newer asyncio version<commit_after>"""
This is a replacement event loop and policy for asyncio that uses FPGA time,
rather than native python time.
"""
from asyncio.events import AbstractEventLoopPolicy
from asyncio import SelectorEventLoop, set_event_loop_policy
from wpilib import Timer
class FPGATimedEventLoop(SelectorEventLoop):
"""An asyncio event loop that uses wpilib time rather than python time"""
def time(self):
return Timer.getFPGATimestamp()
class FPGATimedEventLoopPolicy(AbstractEventLoopPolicy):
"""An asyncio event loop policy that uses FPGATimedEventLoop"""
_loop_factory = FPGATimedEventLoop
def patch_asyncio_policy():
"""
Sets an instance of FPGATimedEventLoopPolicy as the default asyncio event
loop policy
"""
set_event_loop_policy(FPGATimedEventLoopPolicy()) |
1a581a262e4cc388d8b62acdc73d0a7feffdd4ad | Lib/feaTools/writers/baseWriter.py | Lib/feaTools/writers/baseWriter.py | class AbstractFeatureWriter(object):
def feature(self, name):
return self
def lookup(self, name):
return self
def table(self, name, data):
pass
def featureReference(self, name):
pass
def lookupReference(self, name):
pass
def classDefinition(self, name, contents):
pass
def lookupFlag(self, rightToLeft=False, ignoreBaseGlyphs=False, ignoreLigatures=False, ignoreMarks=False):
pass
def gsubType1(self, target, replacement):
pass
def gsubType3(self, target, replacement):
pass
def gsubType4(self, target, replacement):
pass
def gsubType6(self, precedingContext, target, trailingContext, replacement):
pass
def gposType1(self, target, value):
pass
def gposType2(self, target, value):
pass
def languageSystem(self, languageTag, scriptTag):
pass
def script(self, scriptTag):
pass
def language(self, languageTag, includeDefault=True):
pass
def include(self, path):
pass
def subtableBreak(self):
pass
| class AbstractFeatureWriter(object):
def feature(self, name):
return self
def lookup(self, name):
return self
def table(self, name, data):
pass
def featureReference(self, name):
pass
def lookupReference(self, name):
pass
def classDefinition(self, name, contents):
pass
def lookupFlag(self, rightToLeft=False, ignoreBaseGlyphs=False, ignoreLigatures=False, ignoreMarks=False):
pass
def gsubType1(self, target, replacement):
pass
def gsubType3(self, target, replacement):
pass
def gsubType4(self, target, replacement):
pass
def gsubType6(self, precedingContext, target, trailingContext, replacement):
pass
def gposType1(self, target, value):
pass
def gposType2(self, target, value):
pass
def languageSystem(self, languageTag, scriptTag):
pass
def script(self, scriptTag):
pass
def language(self, languageTag, includeDefault=True):
pass
def include(self, path):
pass
def subtableBreak(self):
pass
def rawText(self, text):
pass
| Add a rawText method stub to the base writer | Add a rawText method stub to the base writer
I think this is the only missing method in the base writer.
| Python | mit | anthrotype/feaTools,jamesgk/feaTools,typesupply/feaTools,moyogo/feaTools | class AbstractFeatureWriter(object):
def feature(self, name):
return self
def lookup(self, name):
return self
def table(self, name, data):
pass
def featureReference(self, name):
pass
def lookupReference(self, name):
pass
def classDefinition(self, name, contents):
pass
def lookupFlag(self, rightToLeft=False, ignoreBaseGlyphs=False, ignoreLigatures=False, ignoreMarks=False):
pass
def gsubType1(self, target, replacement):
pass
def gsubType3(self, target, replacement):
pass
def gsubType4(self, target, replacement):
pass
def gsubType6(self, precedingContext, target, trailingContext, replacement):
pass
def gposType1(self, target, value):
pass
def gposType2(self, target, value):
pass
def languageSystem(self, languageTag, scriptTag):
pass
def script(self, scriptTag):
pass
def language(self, languageTag, includeDefault=True):
pass
def include(self, path):
pass
def subtableBreak(self):
pass
Add a rawText method stub to the base writer
I think this is the only missing method in the base writer. | class AbstractFeatureWriter(object):
def feature(self, name):
return self
def lookup(self, name):
return self
def table(self, name, data):
pass
def featureReference(self, name):
pass
def lookupReference(self, name):
pass
def classDefinition(self, name, contents):
pass
def lookupFlag(self, rightToLeft=False, ignoreBaseGlyphs=False, ignoreLigatures=False, ignoreMarks=False):
pass
def gsubType1(self, target, replacement):
pass
def gsubType3(self, target, replacement):
pass
def gsubType4(self, target, replacement):
pass
def gsubType6(self, precedingContext, target, trailingContext, replacement):
pass
def gposType1(self, target, value):
pass
def gposType2(self, target, value):
pass
def languageSystem(self, languageTag, scriptTag):
pass
def script(self, scriptTag):
pass
def language(self, languageTag, includeDefault=True):
pass
def include(self, path):
pass
def subtableBreak(self):
pass
def rawText(self, text):
pass
| <commit_before>class AbstractFeatureWriter(object):
def feature(self, name):
return self
def lookup(self, name):
return self
def table(self, name, data):
pass
def featureReference(self, name):
pass
def lookupReference(self, name):
pass
def classDefinition(self, name, contents):
pass
def lookupFlag(self, rightToLeft=False, ignoreBaseGlyphs=False, ignoreLigatures=False, ignoreMarks=False):
pass
def gsubType1(self, target, replacement):
pass
def gsubType3(self, target, replacement):
pass
def gsubType4(self, target, replacement):
pass
def gsubType6(self, precedingContext, target, trailingContext, replacement):
pass
def gposType1(self, target, value):
pass
def gposType2(self, target, value):
pass
def languageSystem(self, languageTag, scriptTag):
pass
def script(self, scriptTag):
pass
def language(self, languageTag, includeDefault=True):
pass
def include(self, path):
pass
def subtableBreak(self):
pass
<commit_msg>Add a rawText method stub to the base writer
I think this is the only missing method in the base writer.<commit_after> | class AbstractFeatureWriter(object):
def feature(self, name):
return self
def lookup(self, name):
return self
def table(self, name, data):
pass
def featureReference(self, name):
pass
def lookupReference(self, name):
pass
def classDefinition(self, name, contents):
pass
def lookupFlag(self, rightToLeft=False, ignoreBaseGlyphs=False, ignoreLigatures=False, ignoreMarks=False):
pass
def gsubType1(self, target, replacement):
pass
def gsubType3(self, target, replacement):
pass
def gsubType4(self, target, replacement):
pass
def gsubType6(self, precedingContext, target, trailingContext, replacement):
pass
def gposType1(self, target, value):
pass
def gposType2(self, target, value):
pass
def languageSystem(self, languageTag, scriptTag):
pass
def script(self, scriptTag):
pass
def language(self, languageTag, includeDefault=True):
pass
def include(self, path):
pass
def subtableBreak(self):
pass
def rawText(self, text):
pass
| class AbstractFeatureWriter(object):
def feature(self, name):
return self
def lookup(self, name):
return self
def table(self, name, data):
pass
def featureReference(self, name):
pass
def lookupReference(self, name):
pass
def classDefinition(self, name, contents):
pass
def lookupFlag(self, rightToLeft=False, ignoreBaseGlyphs=False, ignoreLigatures=False, ignoreMarks=False):
pass
def gsubType1(self, target, replacement):
pass
def gsubType3(self, target, replacement):
pass
def gsubType4(self, target, replacement):
pass
def gsubType6(self, precedingContext, target, trailingContext, replacement):
pass
def gposType1(self, target, value):
pass
def gposType2(self, target, value):
pass
def languageSystem(self, languageTag, scriptTag):
pass
def script(self, scriptTag):
pass
def language(self, languageTag, includeDefault=True):
pass
def include(self, path):
pass
def subtableBreak(self):
pass
Add a rawText method stub to the base writer
I think this is the only missing method in the base writer.class AbstractFeatureWriter(object):
def feature(self, name):
return self
def lookup(self, name):
return self
def table(self, name, data):
pass
def featureReference(self, name):
pass
def lookupReference(self, name):
pass
def classDefinition(self, name, contents):
pass
def lookupFlag(self, rightToLeft=False, ignoreBaseGlyphs=False, ignoreLigatures=False, ignoreMarks=False):
pass
def gsubType1(self, target, replacement):
pass
def gsubType3(self, target, replacement):
pass
def gsubType4(self, target, replacement):
pass
def gsubType6(self, precedingContext, target, trailingContext, replacement):
pass
def gposType1(self, target, value):
pass
def gposType2(self, target, value):
pass
def languageSystem(self, languageTag, scriptTag):
pass
def script(self, scriptTag):
pass
def language(self, languageTag, includeDefault=True):
pass
def include(self, path):
pass
def subtableBreak(self):
pass
def rawText(self, text):
pass
| <commit_before>class AbstractFeatureWriter(object):
def feature(self, name):
return self
def lookup(self, name):
return self
def table(self, name, data):
pass
def featureReference(self, name):
pass
def lookupReference(self, name):
pass
def classDefinition(self, name, contents):
pass
def lookupFlag(self, rightToLeft=False, ignoreBaseGlyphs=False, ignoreLigatures=False, ignoreMarks=False):
pass
def gsubType1(self, target, replacement):
pass
def gsubType3(self, target, replacement):
pass
def gsubType4(self, target, replacement):
pass
def gsubType6(self, precedingContext, target, trailingContext, replacement):
pass
def gposType1(self, target, value):
pass
def gposType2(self, target, value):
pass
def languageSystem(self, languageTag, scriptTag):
pass
def script(self, scriptTag):
pass
def language(self, languageTag, includeDefault=True):
pass
def include(self, path):
pass
def subtableBreak(self):
pass
<commit_msg>Add a rawText method stub to the base writer
I think this is the only missing method in the base writer.<commit_after>class AbstractFeatureWriter(object):
def feature(self, name):
return self
def lookup(self, name):
return self
def table(self, name, data):
pass
def featureReference(self, name):
pass
def lookupReference(self, name):
pass
def classDefinition(self, name, contents):
pass
def lookupFlag(self, rightToLeft=False, ignoreBaseGlyphs=False, ignoreLigatures=False, ignoreMarks=False):
pass
def gsubType1(self, target, replacement):
pass
def gsubType3(self, target, replacement):
pass
def gsubType4(self, target, replacement):
pass
def gsubType6(self, precedingContext, target, trailingContext, replacement):
pass
def gposType1(self, target, value):
pass
def gposType2(self, target, value):
pass
def languageSystem(self, languageTag, scriptTag):
pass
def script(self, scriptTag):
pass
def language(self, languageTag, includeDefault=True):
pass
def include(self, path):
pass
def subtableBreak(self):
pass
def rawText(self, text):
pass
|
d372a08dda5c5dd956853d4fd1cefae423340a0f | Lib/test/test_json.py | Lib/test/test_json.py | """Tests for json.
The tests for json are defined in the json.tests package;
the test_suite() function there returns a test suite that's ready to
be run.
"""
import json.tests
import test.test_support
def test_main():
test.test_support.run_unittest(json.tests.test_suite())
if __name__ == "__main__":
test_main()
| """Tests for json.
The tests for json are defined in the json.tests package;
the test_suite() function there returns a test suite that's ready to
be run.
"""
import json.tests
import test.test_support
def test_main():
test.test_support.run_unittest(json.tests.test_suite())
test.test_support.run_doctest(json)
if __name__ == "__main__":
test_main()
| Add the examples in the json module docstring as a doctest | Add the examples in the json module docstring as a doctest
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | """Tests for json.
The tests for json are defined in the json.tests package;
the test_suite() function there returns a test suite that's ready to
be run.
"""
import json.tests
import test.test_support
def test_main():
test.test_support.run_unittest(json.tests.test_suite())
if __name__ == "__main__":
test_main()
Add the examples in the json module docstring as a doctest | """Tests for json.
The tests for json are defined in the json.tests package;
the test_suite() function there returns a test suite that's ready to
be run.
"""
import json.tests
import test.test_support
def test_main():
test.test_support.run_unittest(json.tests.test_suite())
test.test_support.run_doctest(json)
if __name__ == "__main__":
test_main()
| <commit_before>"""Tests for json.
The tests for json are defined in the json.tests package;
the test_suite() function there returns a test suite that's ready to
be run.
"""
import json.tests
import test.test_support
def test_main():
test.test_support.run_unittest(json.tests.test_suite())
if __name__ == "__main__":
test_main()
<commit_msg>Add the examples in the json module docstring as a doctest<commit_after> | """Tests for json.
The tests for json are defined in the json.tests package;
the test_suite() function there returns a test suite that's ready to
be run.
"""
import json.tests
import test.test_support
def test_main():
test.test_support.run_unittest(json.tests.test_suite())
test.test_support.run_doctest(json)
if __name__ == "__main__":
test_main()
| """Tests for json.
The tests for json are defined in the json.tests package;
the test_suite() function there returns a test suite that's ready to
be run.
"""
import json.tests
import test.test_support
def test_main():
test.test_support.run_unittest(json.tests.test_suite())
if __name__ == "__main__":
test_main()
Add the examples in the json module docstring as a doctest"""Tests for json.
The tests for json are defined in the json.tests package;
the test_suite() function there returns a test suite that's ready to
be run.
"""
import json.tests
import test.test_support
def test_main():
test.test_support.run_unittest(json.tests.test_suite())
test.test_support.run_doctest(json)
if __name__ == "__main__":
test_main()
| <commit_before>"""Tests for json.
The tests for json are defined in the json.tests package;
the test_suite() function there returns a test suite that's ready to
be run.
"""
import json.tests
import test.test_support
def test_main():
test.test_support.run_unittest(json.tests.test_suite())
if __name__ == "__main__":
test_main()
<commit_msg>Add the examples in the json module docstring as a doctest<commit_after>"""Tests for json.
The tests for json are defined in the json.tests package;
the test_suite() function there returns a test suite that's ready to
be run.
"""
import json.tests
import test.test_support
def test_main():
test.test_support.run_unittest(json.tests.test_suite())
test.test_support.run_doctest(json)
if __name__ == "__main__":
test_main()
|
a444fe6125bac990267fb35f93024abd7386d44a | index.py | index.py | import bottle
import pymongo
import cellarDAO
from bottle import route, run, template, request, redirect
#route index, we will show all our bottle of wine
@route('/')
def wine_index():
bottle_list = cellar.find_bottles()
return template('index', dict(bottles = bottle_list))
#Post new bottle of wine
@route('/bottle/new', method="POST")
def add_bottle():
name = request.forms.get('name')
color = request.forms.get('color')
year = request.forms.get('year')
cellar.insert_bottle(name, color, year)
redirect('/')
#Connection setup
connection_address = "mongodb://localhost"
connection = pymongo.MongoClient(connection_address)
database = connection.bottles
cellar = cellarDAO.CellarDAO(database)
bottle.debug(true)
run(host='localhost', port=8082)
| import pymongo
import cellarDAO
from bottle import route, run, template, request, redirect
#route index, we will show all our bottle of wine
@route('/')
def wine_index():
bottle_list = cellar.find_bottles()
return template('home', dict(bottles = bottle_list))
#Post new bottle of wine
@route('/bottle/new', method="POST")
def add_bottle():
name = request.forms.get('name')
color = request.forms.get('color')
year = request.forms.get('year')
cellar.insert_bottle(name, color, year)
redirect('/')
#Connection setup
connection_address = "mongodb://localhost"
connection = pymongo.MongoClient(connection_address)
database = connection.bottles
cellar = cellarDAO.CellarDAO(database)
run(host='localhost', port=8080, debug=True) | Fix the debug mode activation | Fix the debug mode activation
| Python | mit | djolaq/wine-bottle,djolaq/wine-bottle | import bottle
import pymongo
import cellarDAO
from bottle import route, run, template, request, redirect
#route index, we will show all our bottle of wine
@route('/')
def wine_index():
bottle_list = cellar.find_bottles()
return template('index', dict(bottles = bottle_list))
#Post new bottle of wine
@route('/bottle/new', method="POST")
def add_bottle():
name = request.forms.get('name')
color = request.forms.get('color')
year = request.forms.get('year')
cellar.insert_bottle(name, color, year)
redirect('/')
#Connection setup
connection_address = "mongodb://localhost"
connection = pymongo.MongoClient(connection_address)
database = connection.bottles
cellar = cellarDAO.CellarDAO(database)
bottle.debug(true)
run(host='localhost', port=8082)
Fix the debug mode activation | import pymongo
import cellarDAO
from bottle import route, run, template, request, redirect
#route index, we will show all our bottle of wine
@route('/')
def wine_index():
bottle_list = cellar.find_bottles()
return template('home', dict(bottles = bottle_list))
#Post new bottle of wine
@route('/bottle/new', method="POST")
def add_bottle():
name = request.forms.get('name')
color = request.forms.get('color')
year = request.forms.get('year')
cellar.insert_bottle(name, color, year)
redirect('/')
#Connection setup
connection_address = "mongodb://localhost"
connection = pymongo.MongoClient(connection_address)
database = connection.bottles
cellar = cellarDAO.CellarDAO(database)
run(host='localhost', port=8080, debug=True) | <commit_before>import bottle
import pymongo
import cellarDAO
from bottle import route, run, template, request, redirect
#route index, we will show all our bottle of wine
@route('/')
def wine_index():
bottle_list = cellar.find_bottles()
return template('index', dict(bottles = bottle_list))
#Post new bottle of wine
@route('/bottle/new', method="POST")
def add_bottle():
name = request.forms.get('name')
color = request.forms.get('color')
year = request.forms.get('year')
cellar.insert_bottle(name, color, year)
redirect('/')
#Connection setup
connection_address = "mongodb://localhost"
connection = pymongo.MongoClient(connection_address)
database = connection.bottles
cellar = cellarDAO.CellarDAO(database)
bottle.debug(true)
run(host='localhost', port=8082)
<commit_msg>Fix the debug mode activation<commit_after> | import pymongo
import cellarDAO
from bottle import route, run, template, request, redirect
#route index, we will show all our bottle of wine
@route('/')
def wine_index():
bottle_list = cellar.find_bottles()
return template('home', dict(bottles = bottle_list))
#Post new bottle of wine
@route('/bottle/new', method="POST")
def add_bottle():
name = request.forms.get('name')
color = request.forms.get('color')
year = request.forms.get('year')
cellar.insert_bottle(name, color, year)
redirect('/')
#Connection setup
connection_address = "mongodb://localhost"
connection = pymongo.MongoClient(connection_address)
database = connection.bottles
cellar = cellarDAO.CellarDAO(database)
run(host='localhost', port=8080, debug=True) | import bottle
import pymongo
import cellarDAO
from bottle import route, run, template, request, redirect
#route index, we will show all our bottle of wine
@route('/')
def wine_index():
bottle_list = cellar.find_bottles()
return template('index', dict(bottles = bottle_list))
#Post new bottle of wine
@route('/bottle/new', method="POST")
def add_bottle():
name = request.forms.get('name')
color = request.forms.get('color')
year = request.forms.get('year')
cellar.insert_bottle(name, color, year)
redirect('/')
#Connection setup
connection_address = "mongodb://localhost"
connection = pymongo.MongoClient(connection_address)
database = connection.bottles
cellar = cellarDAO.CellarDAO(database)
bottle.debug(true)
run(host='localhost', port=8082)
Fix the debug mode activationimport pymongo
import cellarDAO
from bottle import route, run, template, request, redirect
#route index, we will show all our bottle of wine
@route('/')
def wine_index():
bottle_list = cellar.find_bottles()
return template('home', dict(bottles = bottle_list))
#Post new bottle of wine
@route('/bottle/new', method="POST")
def add_bottle():
name = request.forms.get('name')
color = request.forms.get('color')
year = request.forms.get('year')
cellar.insert_bottle(name, color, year)
redirect('/')
#Connection setup
connection_address = "mongodb://localhost"
connection = pymongo.MongoClient(connection_address)
database = connection.bottles
cellar = cellarDAO.CellarDAO(database)
run(host='localhost', port=8080, debug=True) | <commit_before>import bottle
import pymongo
import cellarDAO
from bottle import route, run, template, request, redirect
#route index, we will show all our bottle of wine
@route('/')
def wine_index():
bottle_list = cellar.find_bottles()
return template('index', dict(bottles = bottle_list))
#Post new bottle of wine
@route('/bottle/new', method="POST")
def add_bottle():
name = request.forms.get('name')
color = request.forms.get('color')
year = request.forms.get('year')
cellar.insert_bottle(name, color, year)
redirect('/')
#Connection setup
connection_address = "mongodb://localhost"
connection = pymongo.MongoClient(connection_address)
database = connection.bottles
cellar = cellarDAO.CellarDAO(database)
bottle.debug(true)
run(host='localhost', port=8082)
<commit_msg>Fix the debug mode activation<commit_after>import pymongo
import cellarDAO
from bottle import route, run, template, request, redirect
#route index, we will show all our bottle of wine
@route('/')
def wine_index():
bottle_list = cellar.find_bottles()
return template('home', dict(bottles = bottle_list))
#Post new bottle of wine
@route('/bottle/new', method="POST")
def add_bottle():
name = request.forms.get('name')
color = request.forms.get('color')
year = request.forms.get('year')
cellar.insert_bottle(name, color, year)
redirect('/')
#Connection setup
connection_address = "mongodb://localhost"
connection = pymongo.MongoClient(connection_address)
database = connection.bottles
cellar = cellarDAO.CellarDAO(database)
run(host='localhost', port=8080, debug=True) |
aaaaa25b575677a3c0fb7f2dd515a21c5643e995 | falcom/tree/test/test_tree.py | falcom/tree/test/test_tree.py | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from hamcrest import *
import unittest
from ..read_only_tree import Tree
from ..mutable_tree import MutableTree
class GivenNothing (unittest.TestCase):
def test_empty_tree_has_null_value (self):
t = Tree()
assert_that(t.value, is_(none()))
def test_cannot_modify_value_for_empty_tree (self):
t = Tree()
assert_that(calling(setattr).with_args(t, "value", "hi"),
raises(AttributeError))
def test_cannot_init_tree_with_value (self):
assert_that(calling(Tree).with_args(value="hi"),
raises(TypeError))
def test_can_init_from_mutable_tree (self):
mtree = MutableTree(value=1)
mtree.append_value(2)
mtree.append_value(3)
mtree[0].append_value(4)
mtree[0].append_value(5)
mtree[0][0].append_value(6)
t = Tree(mtree)
| # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from hamcrest import *
import unittest
from ..read_only_tree import Tree
from ..mutable_tree import MutableTree
class GivenNothing (unittest.TestCase):
def test_cannot_init_tree_with_value (self):
assert_that(calling(Tree).with_args(value="hi"),
raises(TypeError))
def test_can_init_from_mutable_tree (self):
mtree = MutableTree(value=1)
mtree.append_value(2)
mtree.append_value(3)
mtree[0].append_value(4)
mtree[0].append_value(5)
mtree[0][0].append_value(6)
t = Tree(mtree)
class GivenEmptyTree (unittest.TestCase):
def test_empty_tree_has_null_value (self):
t = Tree()
assert_that(t.value, is_(none()))
def test_cannot_modify_value_for_empty_tree (self):
t = Tree()
assert_that(calling(setattr).with_args(t, "value", "hi"),
raises(AttributeError))
| Move tests into new Given class | Move tests into new Given class
| Python | bsd-3-clause | mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from hamcrest import *
import unittest
from ..read_only_tree import Tree
from ..mutable_tree import MutableTree
class GivenNothing (unittest.TestCase):
def test_empty_tree_has_null_value (self):
t = Tree()
assert_that(t.value, is_(none()))
def test_cannot_modify_value_for_empty_tree (self):
t = Tree()
assert_that(calling(setattr).with_args(t, "value", "hi"),
raises(AttributeError))
def test_cannot_init_tree_with_value (self):
assert_that(calling(Tree).with_args(value="hi"),
raises(TypeError))
def test_can_init_from_mutable_tree (self):
mtree = MutableTree(value=1)
mtree.append_value(2)
mtree.append_value(3)
mtree[0].append_value(4)
mtree[0].append_value(5)
mtree[0][0].append_value(6)
t = Tree(mtree)
Move tests into new Given class | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from hamcrest import *
import unittest
from ..read_only_tree import Tree
from ..mutable_tree import MutableTree
class GivenNothing (unittest.TestCase):
def test_cannot_init_tree_with_value (self):
assert_that(calling(Tree).with_args(value="hi"),
raises(TypeError))
def test_can_init_from_mutable_tree (self):
mtree = MutableTree(value=1)
mtree.append_value(2)
mtree.append_value(3)
mtree[0].append_value(4)
mtree[0].append_value(5)
mtree[0][0].append_value(6)
t = Tree(mtree)
class GivenEmptyTree (unittest.TestCase):
def test_empty_tree_has_null_value (self):
t = Tree()
assert_that(t.value, is_(none()))
def test_cannot_modify_value_for_empty_tree (self):
t = Tree()
assert_that(calling(setattr).with_args(t, "value", "hi"),
raises(AttributeError))
| <commit_before># Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from hamcrest import *
import unittest
from ..read_only_tree import Tree
from ..mutable_tree import MutableTree
class GivenNothing (unittest.TestCase):
def test_empty_tree_has_null_value (self):
t = Tree()
assert_that(t.value, is_(none()))
def test_cannot_modify_value_for_empty_tree (self):
t = Tree()
assert_that(calling(setattr).with_args(t, "value", "hi"),
raises(AttributeError))
def test_cannot_init_tree_with_value (self):
assert_that(calling(Tree).with_args(value="hi"),
raises(TypeError))
def test_can_init_from_mutable_tree (self):
mtree = MutableTree(value=1)
mtree.append_value(2)
mtree.append_value(3)
mtree[0].append_value(4)
mtree[0].append_value(5)
mtree[0][0].append_value(6)
t = Tree(mtree)
<commit_msg>Move tests into new Given class<commit_after> | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from hamcrest import *
import unittest
from ..read_only_tree import Tree
from ..mutable_tree import MutableTree
class GivenNothing (unittest.TestCase):
def test_cannot_init_tree_with_value (self):
assert_that(calling(Tree).with_args(value="hi"),
raises(TypeError))
def test_can_init_from_mutable_tree (self):
mtree = MutableTree(value=1)
mtree.append_value(2)
mtree.append_value(3)
mtree[0].append_value(4)
mtree[0].append_value(5)
mtree[0][0].append_value(6)
t = Tree(mtree)
class GivenEmptyTree (unittest.TestCase):
def test_empty_tree_has_null_value (self):
t = Tree()
assert_that(t.value, is_(none()))
def test_cannot_modify_value_for_empty_tree (self):
t = Tree()
assert_that(calling(setattr).with_args(t, "value", "hi"),
raises(AttributeError))
| # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from hamcrest import *
import unittest
from ..read_only_tree import Tree
from ..mutable_tree import MutableTree
class GivenNothing (unittest.TestCase):
def test_empty_tree_has_null_value (self):
t = Tree()
assert_that(t.value, is_(none()))
def test_cannot_modify_value_for_empty_tree (self):
t = Tree()
assert_that(calling(setattr).with_args(t, "value", "hi"),
raises(AttributeError))
def test_cannot_init_tree_with_value (self):
assert_that(calling(Tree).with_args(value="hi"),
raises(TypeError))
def test_can_init_from_mutable_tree (self):
mtree = MutableTree(value=1)
mtree.append_value(2)
mtree.append_value(3)
mtree[0].append_value(4)
mtree[0].append_value(5)
mtree[0][0].append_value(6)
t = Tree(mtree)
Move tests into new Given class# Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from hamcrest import *
import unittest
from ..read_only_tree import Tree
from ..mutable_tree import MutableTree
class GivenNothing (unittest.TestCase):
def test_cannot_init_tree_with_value (self):
assert_that(calling(Tree).with_args(value="hi"),
raises(TypeError))
def test_can_init_from_mutable_tree (self):
mtree = MutableTree(value=1)
mtree.append_value(2)
mtree.append_value(3)
mtree[0].append_value(4)
mtree[0].append_value(5)
mtree[0][0].append_value(6)
t = Tree(mtree)
class GivenEmptyTree (unittest.TestCase):
def test_empty_tree_has_null_value (self):
t = Tree()
assert_that(t.value, is_(none()))
def test_cannot_modify_value_for_empty_tree (self):
t = Tree()
assert_that(calling(setattr).with_args(t, "value", "hi"),
raises(AttributeError))
| <commit_before># Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from hamcrest import *
import unittest
from ..read_only_tree import Tree
from ..mutable_tree import MutableTree
class GivenNothing (unittest.TestCase):
def test_empty_tree_has_null_value (self):
t = Tree()
assert_that(t.value, is_(none()))
def test_cannot_modify_value_for_empty_tree (self):
t = Tree()
assert_that(calling(setattr).with_args(t, "value", "hi"),
raises(AttributeError))
def test_cannot_init_tree_with_value (self):
assert_that(calling(Tree).with_args(value="hi"),
raises(TypeError))
def test_can_init_from_mutable_tree (self):
mtree = MutableTree(value=1)
mtree.append_value(2)
mtree.append_value(3)
mtree[0].append_value(4)
mtree[0].append_value(5)
mtree[0][0].append_value(6)
t = Tree(mtree)
<commit_msg>Move tests into new Given class<commit_after># Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from hamcrest import *
import unittest
from ..read_only_tree import Tree
from ..mutable_tree import MutableTree
class GivenNothing (unittest.TestCase):
def test_cannot_init_tree_with_value (self):
assert_that(calling(Tree).with_args(value="hi"),
raises(TypeError))
def test_can_init_from_mutable_tree (self):
mtree = MutableTree(value=1)
mtree.append_value(2)
mtree.append_value(3)
mtree[0].append_value(4)
mtree[0].append_value(5)
mtree[0][0].append_value(6)
t = Tree(mtree)
class GivenEmptyTree (unittest.TestCase):
def test_empty_tree_has_null_value (self):
t = Tree()
assert_that(t.value, is_(none()))
def test_cannot_modify_value_for_empty_tree (self):
t = Tree()
assert_that(calling(setattr).with_args(t, "value", "hi"),
raises(AttributeError))
|
50f95bd55a6f9ae6530b93b37655c265be79e1e0 | froide/campaign/validators.py | froide/campaign/validators.py | from django.forms import ValidationError
from .models import Campaign
def validate_not_campaign(data):
subject = data.get('subject', '')
body = data.get('body', '')
text = '\n'.join((subject, body)).strip()
campaigns = Campaign.objects.filter(
active=True, public=True).exclude(request_match='')
for campaign in campaigns:
if campaign.match_text(text):
raise ValidationError(campaign.request_hint)
| from django.forms import ValidationError
from django.utils.translation import gettext_lazy as _
from .models import Campaign
def validate_not_campaign(data):
subject = data.get('subject', '')
body = data.get('body', '')
text = '\n'.join((subject, body)).strip()
campaigns = Campaign.objects.filter(
active=True, public=True).exclude(request_match='')
for campaign in campaigns:
if campaign.match_text(text):
raise ValidationError(campaign.request_hint or _(
'This request seems like it should belong to a campaign. '
'Please use the campaign interface to make the request.')
)
| Add fallback error message on campaign validation | Add fallback error message on campaign validation | Python | mit | fin/froide,fin/froide,fin/froide,fin/froide | from django.forms import ValidationError
from .models import Campaign
def validate_not_campaign(data):
subject = data.get('subject', '')
body = data.get('body', '')
text = '\n'.join((subject, body)).strip()
campaigns = Campaign.objects.filter(
active=True, public=True).exclude(request_match='')
for campaign in campaigns:
if campaign.match_text(text):
raise ValidationError(campaign.request_hint)
Add fallback error message on campaign validation | from django.forms import ValidationError
from django.utils.translation import gettext_lazy as _
from .models import Campaign
def validate_not_campaign(data):
subject = data.get('subject', '')
body = data.get('body', '')
text = '\n'.join((subject, body)).strip()
campaigns = Campaign.objects.filter(
active=True, public=True).exclude(request_match='')
for campaign in campaigns:
if campaign.match_text(text):
raise ValidationError(campaign.request_hint or _(
'This request seems like it should belong to a campaign. '
'Please use the campaign interface to make the request.')
)
| <commit_before>from django.forms import ValidationError
from .models import Campaign
def validate_not_campaign(data):
subject = data.get('subject', '')
body = data.get('body', '')
text = '\n'.join((subject, body)).strip()
campaigns = Campaign.objects.filter(
active=True, public=True).exclude(request_match='')
for campaign in campaigns:
if campaign.match_text(text):
raise ValidationError(campaign.request_hint)
<commit_msg>Add fallback error message on campaign validation<commit_after> | from django.forms import ValidationError
from django.utils.translation import gettext_lazy as _
from .models import Campaign
def validate_not_campaign(data):
subject = data.get('subject', '')
body = data.get('body', '')
text = '\n'.join((subject, body)).strip()
campaigns = Campaign.objects.filter(
active=True, public=True).exclude(request_match='')
for campaign in campaigns:
if campaign.match_text(text):
raise ValidationError(campaign.request_hint or _(
'This request seems like it should belong to a campaign. '
'Please use the campaign interface to make the request.')
)
| from django.forms import ValidationError
from .models import Campaign
def validate_not_campaign(data):
subject = data.get('subject', '')
body = data.get('body', '')
text = '\n'.join((subject, body)).strip()
campaigns = Campaign.objects.filter(
active=True, public=True).exclude(request_match='')
for campaign in campaigns:
if campaign.match_text(text):
raise ValidationError(campaign.request_hint)
Add fallback error message on campaign validationfrom django.forms import ValidationError
from django.utils.translation import gettext_lazy as _
from .models import Campaign
def validate_not_campaign(data):
subject = data.get('subject', '')
body = data.get('body', '')
text = '\n'.join((subject, body)).strip()
campaigns = Campaign.objects.filter(
active=True, public=True).exclude(request_match='')
for campaign in campaigns:
if campaign.match_text(text):
raise ValidationError(campaign.request_hint or _(
'This request seems like it should belong to a campaign. '
'Please use the campaign interface to make the request.')
)
| <commit_before>from django.forms import ValidationError
from .models import Campaign
def validate_not_campaign(data):
subject = data.get('subject', '')
body = data.get('body', '')
text = '\n'.join((subject, body)).strip()
campaigns = Campaign.objects.filter(
active=True, public=True).exclude(request_match='')
for campaign in campaigns:
if campaign.match_text(text):
raise ValidationError(campaign.request_hint)
<commit_msg>Add fallback error message on campaign validation<commit_after>from django.forms import ValidationError
from django.utils.translation import gettext_lazy as _
from .models import Campaign
def validate_not_campaign(data):
subject = data.get('subject', '')
body = data.get('body', '')
text = '\n'.join((subject, body)).strip()
campaigns = Campaign.objects.filter(
active=True, public=True).exclude(request_match='')
for campaign in campaigns:
if campaign.match_text(text):
raise ValidationError(campaign.request_hint or _(
'This request seems like it should belong to a campaign. '
'Please use the campaign interface to make the request.')
)
|
af4ad27ddf4d5da23590f6b2e297b9d834fa292e | icekit/project/settings/glamkit.py | icekit/project/settings/glamkit.py | from .icekit import *
# DJANGO ######################################################################
INSTALLED_APPS += ('sponsors', )
| from .icekit import *
# DJANGO ######################################################################
INSTALLED_APPS += (
'sponsors',
'icekit_events',
'icekit_events.event_types.simple',
'icekit_events.page_types.eventlistingfordate',
)
| Add ICEKit Events to list of GLAMKit installed apps | Add ICEKit Events to list of GLAMKit installed apps
Add ICEKit events, SimpleEvent event type, and listing page for date
apps to those installed by default for GLAMKit.
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit | from .icekit import *
# DJANGO ######################################################################
INSTALLED_APPS += ('sponsors', )
Add ICEKit Events to list of GLAMKit installed apps
Add ICEKit events, SimpleEvent event type, and listing page for date
apps to those installed by default for GLAMKit. | from .icekit import *
# DJANGO ######################################################################
INSTALLED_APPS += (
'sponsors',
'icekit_events',
'icekit_events.event_types.simple',
'icekit_events.page_types.eventlistingfordate',
)
| <commit_before>from .icekit import *
# DJANGO ######################################################################
INSTALLED_APPS += ('sponsors', )
<commit_msg>Add ICEKit Events to list of GLAMKit installed apps
Add ICEKit events, SimpleEvent event type, and listing page for date
apps to those installed by default for GLAMKit.<commit_after> | from .icekit import *
# DJANGO ######################################################################
INSTALLED_APPS += (
'sponsors',
'icekit_events',
'icekit_events.event_types.simple',
'icekit_events.page_types.eventlistingfordate',
)
| from .icekit import *
# DJANGO ######################################################################
INSTALLED_APPS += ('sponsors', )
Add ICEKit Events to list of GLAMKit installed apps
Add ICEKit events, SimpleEvent event type, and listing page for date
apps to those installed by default for GLAMKit.from .icekit import *
# DJANGO ######################################################################
INSTALLED_APPS += (
'sponsors',
'icekit_events',
'icekit_events.event_types.simple',
'icekit_events.page_types.eventlistingfordate',
)
| <commit_before>from .icekit import *
# DJANGO ######################################################################
INSTALLED_APPS += ('sponsors', )
<commit_msg>Add ICEKit Events to list of GLAMKit installed apps
Add ICEKit events, SimpleEvent event type, and listing page for date
apps to those installed by default for GLAMKit.<commit_after>from .icekit import *
# DJANGO ######################################################################
INSTALLED_APPS += (
'sponsors',
'icekit_events',
'icekit_events.event_types.simple',
'icekit_events.page_types.eventlistingfordate',
)
|
f69a2dc9530fef44e5b67d64496bcec9eceaf0e4 | config.py | config.py | import os
import datetime
register_title_api = os.environ['REGISTER_TITLE_API']
login_api = os.environ['LOGIN_API']
logging_config_file_path = os.environ['LOGGING_CONFIG_FILE_PATH']
google_analytics_api_key = os.environ['GOOGLE_ANALYTICS_API_KEY']
secret_key = os.environ['APPLICATION_SECRET_KEY']
session_cookie_secure = os.environ['SESSION_COOKIE_SECURE'] != 'False'
CONFIG_DICT = {
'DEBUG': False,
'LOGGING': True,
'REGISTER_TITLE_API': register_title_api,
'LOGGING_CONFIG_FILE_PATH': logging_config_file_path,
'GOOGLE_ANALYTICS_API_KEY': google_analytics_api_key,
'LOGIN_API': login_api,
'PERMANENT_SESSION_LIFETIME': datetime.timedelta(minutes=15),
'SECRET_KEY': secret_key,
'SESSION_COOKIE_SECURE': session_cookie_secure,
}
settings = os.environ.get('SETTINGS')
if settings == 'dev':
CONFIG_DICT['DEBUG'] = True
elif settings == 'test':
# We do NOT set TESTING to True here as it turns off authentication, and we
# want to make sure the app behaves the same when running tests locally
# as it does in production.
CONFIG_DICT['LOGGING'] = False
CONFIG_DICT['DEBUG'] = True
CONFIG_DICT['SLEEP_BETWEEN_LOGINS'] = False
CONFIG_DICT['DISABLE_CSRF_PREVENTION'] = True
| import os
import datetime
register_title_api = os.environ['REGISTER_TITLE_API']
login_api = os.environ['LOGIN_API']
logging_config_file_path = os.environ['LOGGING_CONFIG_FILE_PATH']
google_analytics_api_key = os.environ['GOOGLE_ANALYTICS_API_KEY']
secret_key = os.environ['APPLICATION_SECRET_KEY']
session_cookie_secure = os.environ['SESSION_COOKIE_SECURE'].lower() != 'false'
CONFIG_DICT = {
'DEBUG': False,
'LOGGING': True,
'REGISTER_TITLE_API': register_title_api,
'LOGGING_CONFIG_FILE_PATH': logging_config_file_path,
'GOOGLE_ANALYTICS_API_KEY': google_analytics_api_key,
'LOGIN_API': login_api,
'PERMANENT_SESSION_LIFETIME': datetime.timedelta(minutes=15),
'SECRET_KEY': secret_key,
'SESSION_COOKIE_SECURE': session_cookie_secure,
}
settings = os.environ.get('SETTINGS')
if settings == 'dev':
CONFIG_DICT['DEBUG'] = True
elif settings == 'test':
# We do NOT set TESTING to True here as it turns off authentication, and we
# want to make sure the app behaves the same when running tests locally
# as it does in production.
CONFIG_DICT['LOGGING'] = False
CONFIG_DICT['DEBUG'] = True
CONFIG_DICT['SLEEP_BETWEEN_LOGINS'] = False
CONFIG_DICT['DISABLE_CSRF_PREVENTION'] = True
| Make the secure session cookie setting case-insensitive | Make the secure session cookie setting case-insensitive
| Python | mit | LandRegistry/digital-register-frontend,LandRegistry/digital-register-frontend,LandRegistry/digital-register-frontend,LandRegistry/digital-register-frontend | import os
import datetime
register_title_api = os.environ['REGISTER_TITLE_API']
login_api = os.environ['LOGIN_API']
logging_config_file_path = os.environ['LOGGING_CONFIG_FILE_PATH']
google_analytics_api_key = os.environ['GOOGLE_ANALYTICS_API_KEY']
secret_key = os.environ['APPLICATION_SECRET_KEY']
session_cookie_secure = os.environ['SESSION_COOKIE_SECURE'] != 'False'
CONFIG_DICT = {
'DEBUG': False,
'LOGGING': True,
'REGISTER_TITLE_API': register_title_api,
'LOGGING_CONFIG_FILE_PATH': logging_config_file_path,
'GOOGLE_ANALYTICS_API_KEY': google_analytics_api_key,
'LOGIN_API': login_api,
'PERMANENT_SESSION_LIFETIME': datetime.timedelta(minutes=15),
'SECRET_KEY': secret_key,
'SESSION_COOKIE_SECURE': session_cookie_secure,
}
settings = os.environ.get('SETTINGS')
if settings == 'dev':
CONFIG_DICT['DEBUG'] = True
elif settings == 'test':
# We do NOT set TESTING to True here as it turns off authentication, and we
# want to make sure the app behaves the same when running tests locally
# as it does in production.
CONFIG_DICT['LOGGING'] = False
CONFIG_DICT['DEBUG'] = True
CONFIG_DICT['SLEEP_BETWEEN_LOGINS'] = False
CONFIG_DICT['DISABLE_CSRF_PREVENTION'] = True
Make the secure session cookie setting case-insensitive | import os
import datetime
register_title_api = os.environ['REGISTER_TITLE_API']
login_api = os.environ['LOGIN_API']
logging_config_file_path = os.environ['LOGGING_CONFIG_FILE_PATH']
google_analytics_api_key = os.environ['GOOGLE_ANALYTICS_API_KEY']
secret_key = os.environ['APPLICATION_SECRET_KEY']
session_cookie_secure = os.environ['SESSION_COOKIE_SECURE'].lower() != 'false'
CONFIG_DICT = {
'DEBUG': False,
'LOGGING': True,
'REGISTER_TITLE_API': register_title_api,
'LOGGING_CONFIG_FILE_PATH': logging_config_file_path,
'GOOGLE_ANALYTICS_API_KEY': google_analytics_api_key,
'LOGIN_API': login_api,
'PERMANENT_SESSION_LIFETIME': datetime.timedelta(minutes=15),
'SECRET_KEY': secret_key,
'SESSION_COOKIE_SECURE': session_cookie_secure,
}
settings = os.environ.get('SETTINGS')
if settings == 'dev':
CONFIG_DICT['DEBUG'] = True
elif settings == 'test':
# We do NOT set TESTING to True here as it turns off authentication, and we
# want to make sure the app behaves the same when running tests locally
# as it does in production.
CONFIG_DICT['LOGGING'] = False
CONFIG_DICT['DEBUG'] = True
CONFIG_DICT['SLEEP_BETWEEN_LOGINS'] = False
CONFIG_DICT['DISABLE_CSRF_PREVENTION'] = True
| <commit_before>import os
import datetime
register_title_api = os.environ['REGISTER_TITLE_API']
login_api = os.environ['LOGIN_API']
logging_config_file_path = os.environ['LOGGING_CONFIG_FILE_PATH']
google_analytics_api_key = os.environ['GOOGLE_ANALYTICS_API_KEY']
secret_key = os.environ['APPLICATION_SECRET_KEY']
session_cookie_secure = os.environ['SESSION_COOKIE_SECURE'] != 'False'
CONFIG_DICT = {
'DEBUG': False,
'LOGGING': True,
'REGISTER_TITLE_API': register_title_api,
'LOGGING_CONFIG_FILE_PATH': logging_config_file_path,
'GOOGLE_ANALYTICS_API_KEY': google_analytics_api_key,
'LOGIN_API': login_api,
'PERMANENT_SESSION_LIFETIME': datetime.timedelta(minutes=15),
'SECRET_KEY': secret_key,
'SESSION_COOKIE_SECURE': session_cookie_secure,
}
settings = os.environ.get('SETTINGS')
if settings == 'dev':
CONFIG_DICT['DEBUG'] = True
elif settings == 'test':
# We do NOT set TESTING to True here as it turns off authentication, and we
# want to make sure the app behaves the same when running tests locally
# as it does in production.
CONFIG_DICT['LOGGING'] = False
CONFIG_DICT['DEBUG'] = True
CONFIG_DICT['SLEEP_BETWEEN_LOGINS'] = False
CONFIG_DICT['DISABLE_CSRF_PREVENTION'] = True
<commit_msg>Make the secure session cookie setting case-insensitive<commit_after> | import os
import datetime
register_title_api = os.environ['REGISTER_TITLE_API']
login_api = os.environ['LOGIN_API']
logging_config_file_path = os.environ['LOGGING_CONFIG_FILE_PATH']
google_analytics_api_key = os.environ['GOOGLE_ANALYTICS_API_KEY']
secret_key = os.environ['APPLICATION_SECRET_KEY']
session_cookie_secure = os.environ['SESSION_COOKIE_SECURE'].lower() != 'false'
CONFIG_DICT = {
'DEBUG': False,
'LOGGING': True,
'REGISTER_TITLE_API': register_title_api,
'LOGGING_CONFIG_FILE_PATH': logging_config_file_path,
'GOOGLE_ANALYTICS_API_KEY': google_analytics_api_key,
'LOGIN_API': login_api,
'PERMANENT_SESSION_LIFETIME': datetime.timedelta(minutes=15),
'SECRET_KEY': secret_key,
'SESSION_COOKIE_SECURE': session_cookie_secure,
}
settings = os.environ.get('SETTINGS')
if settings == 'dev':
CONFIG_DICT['DEBUG'] = True
elif settings == 'test':
# We do NOT set TESTING to True here as it turns off authentication, and we
# want to make sure the app behaves the same when running tests locally
# as it does in production.
CONFIG_DICT['LOGGING'] = False
CONFIG_DICT['DEBUG'] = True
CONFIG_DICT['SLEEP_BETWEEN_LOGINS'] = False
CONFIG_DICT['DISABLE_CSRF_PREVENTION'] = True
| import os
import datetime
register_title_api = os.environ['REGISTER_TITLE_API']
login_api = os.environ['LOGIN_API']
logging_config_file_path = os.environ['LOGGING_CONFIG_FILE_PATH']
google_analytics_api_key = os.environ['GOOGLE_ANALYTICS_API_KEY']
secret_key = os.environ['APPLICATION_SECRET_KEY']
session_cookie_secure = os.environ['SESSION_COOKIE_SECURE'] != 'False'
CONFIG_DICT = {
'DEBUG': False,
'LOGGING': True,
'REGISTER_TITLE_API': register_title_api,
'LOGGING_CONFIG_FILE_PATH': logging_config_file_path,
'GOOGLE_ANALYTICS_API_KEY': google_analytics_api_key,
'LOGIN_API': login_api,
'PERMANENT_SESSION_LIFETIME': datetime.timedelta(minutes=15),
'SECRET_KEY': secret_key,
'SESSION_COOKIE_SECURE': session_cookie_secure,
}
settings = os.environ.get('SETTINGS')
if settings == 'dev':
CONFIG_DICT['DEBUG'] = True
elif settings == 'test':
# We do NOT set TESTING to True here as it turns off authentication, and we
# want to make sure the app behaves the same when running tests locally
# as it does in production.
CONFIG_DICT['LOGGING'] = False
CONFIG_DICT['DEBUG'] = True
CONFIG_DICT['SLEEP_BETWEEN_LOGINS'] = False
CONFIG_DICT['DISABLE_CSRF_PREVENTION'] = True
Make the secure session cookie setting case-insensitiveimport os
import datetime
register_title_api = os.environ['REGISTER_TITLE_API']
login_api = os.environ['LOGIN_API']
logging_config_file_path = os.environ['LOGGING_CONFIG_FILE_PATH']
google_analytics_api_key = os.environ['GOOGLE_ANALYTICS_API_KEY']
secret_key = os.environ['APPLICATION_SECRET_KEY']
session_cookie_secure = os.environ['SESSION_COOKIE_SECURE'].lower() != 'false'
CONFIG_DICT = {
'DEBUG': False,
'LOGGING': True,
'REGISTER_TITLE_API': register_title_api,
'LOGGING_CONFIG_FILE_PATH': logging_config_file_path,
'GOOGLE_ANALYTICS_API_KEY': google_analytics_api_key,
'LOGIN_API': login_api,
'PERMANENT_SESSION_LIFETIME': datetime.timedelta(minutes=15),
'SECRET_KEY': secret_key,
'SESSION_COOKIE_SECURE': session_cookie_secure,
}
settings = os.environ.get('SETTINGS')
if settings == 'dev':
CONFIG_DICT['DEBUG'] = True
elif settings == 'test':
# We do NOT set TESTING to True here as it turns off authentication, and we
# want to make sure the app behaves the same when running tests locally
# as it does in production.
CONFIG_DICT['LOGGING'] = False
CONFIG_DICT['DEBUG'] = True
CONFIG_DICT['SLEEP_BETWEEN_LOGINS'] = False
CONFIG_DICT['DISABLE_CSRF_PREVENTION'] = True
| <commit_before>import os
import datetime
register_title_api = os.environ['REGISTER_TITLE_API']
login_api = os.environ['LOGIN_API']
logging_config_file_path = os.environ['LOGGING_CONFIG_FILE_PATH']
google_analytics_api_key = os.environ['GOOGLE_ANALYTICS_API_KEY']
secret_key = os.environ['APPLICATION_SECRET_KEY']
session_cookie_secure = os.environ['SESSION_COOKIE_SECURE'] != 'False'
CONFIG_DICT = {
'DEBUG': False,
'LOGGING': True,
'REGISTER_TITLE_API': register_title_api,
'LOGGING_CONFIG_FILE_PATH': logging_config_file_path,
'GOOGLE_ANALYTICS_API_KEY': google_analytics_api_key,
'LOGIN_API': login_api,
'PERMANENT_SESSION_LIFETIME': datetime.timedelta(minutes=15),
'SECRET_KEY': secret_key,
'SESSION_COOKIE_SECURE': session_cookie_secure,
}
settings = os.environ.get('SETTINGS')
if settings == 'dev':
CONFIG_DICT['DEBUG'] = True
elif settings == 'test':
# We do NOT set TESTING to True here as it turns off authentication, and we
# want to make sure the app behaves the same when running tests locally
# as it does in production.
CONFIG_DICT['LOGGING'] = False
CONFIG_DICT['DEBUG'] = True
CONFIG_DICT['SLEEP_BETWEEN_LOGINS'] = False
CONFIG_DICT['DISABLE_CSRF_PREVENTION'] = True
<commit_msg>Make the secure session cookie setting case-insensitive<commit_after>import os
import datetime
register_title_api = os.environ['REGISTER_TITLE_API']
login_api = os.environ['LOGIN_API']
logging_config_file_path = os.environ['LOGGING_CONFIG_FILE_PATH']
google_analytics_api_key = os.environ['GOOGLE_ANALYTICS_API_KEY']
secret_key = os.environ['APPLICATION_SECRET_KEY']
session_cookie_secure = os.environ['SESSION_COOKIE_SECURE'].lower() != 'false'
CONFIG_DICT = {
'DEBUG': False,
'LOGGING': True,
'REGISTER_TITLE_API': register_title_api,
'LOGGING_CONFIG_FILE_PATH': logging_config_file_path,
'GOOGLE_ANALYTICS_API_KEY': google_analytics_api_key,
'LOGIN_API': login_api,
'PERMANENT_SESSION_LIFETIME': datetime.timedelta(minutes=15),
'SECRET_KEY': secret_key,
'SESSION_COOKIE_SECURE': session_cookie_secure,
}
settings = os.environ.get('SETTINGS')
if settings == 'dev':
CONFIG_DICT['DEBUG'] = True
elif settings == 'test':
# We do NOT set TESTING to True here as it turns off authentication, and we
# want to make sure the app behaves the same when running tests locally
# as it does in production.
CONFIG_DICT['LOGGING'] = False
CONFIG_DICT['DEBUG'] = True
CONFIG_DICT['SLEEP_BETWEEN_LOGINS'] = False
CONFIG_DICT['DISABLE_CSRF_PREVENTION'] = True
|
ea504e682263bb6c7681bf690bed8a34e0ee1612 | chandra_aca/tests/test_dark_scale.py | chandra_aca/tests/test_dark_scale.py | import numpy as np
from .. import dark_scale
def test_dark_temp_scale():
scale = dark_scale.dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_scale.dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
| import numpy as np
from ..dark_model import dark_temp_scale
def test_dark_temp_scale():
scale = dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
| Update path to dark_temp_scale in test | Update path to dark_temp_scale in test
| Python | bsd-2-clause | sot/chandra_aca,sot/chandra_aca | import numpy as np
from .. import dark_scale
def test_dark_temp_scale():
scale = dark_scale.dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_scale.dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
Update path to dark_temp_scale in test | import numpy as np
from ..dark_model import dark_temp_scale
def test_dark_temp_scale():
scale = dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
| <commit_before>import numpy as np
from .. import dark_scale
def test_dark_temp_scale():
scale = dark_scale.dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_scale.dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
<commit_msg>Update path to dark_temp_scale in test<commit_after> | import numpy as np
from ..dark_model import dark_temp_scale
def test_dark_temp_scale():
scale = dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
| import numpy as np
from .. import dark_scale
def test_dark_temp_scale():
scale = dark_scale.dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_scale.dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
Update path to dark_temp_scale in testimport numpy as np
from ..dark_model import dark_temp_scale
def test_dark_temp_scale():
scale = dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
| <commit_before>import numpy as np
from .. import dark_scale
def test_dark_temp_scale():
scale = dark_scale.dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_scale.dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
<commit_msg>Update path to dark_temp_scale in test<commit_after>import numpy as np
from ..dark_model import dark_temp_scale
def test_dark_temp_scale():
scale = dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
|
d19ad115124179d75cf00806f2861f17f01f5ff9 | drogher/package/base.py | drogher/package/base.py | import re
class Package(object):
barcode = None
barcode_pattern = None
shipper = None
def __init__(self, barcode):
self.barcode = barcode
def __repr__(self):
return "%s('%s')" % ('package.' + self.__class__.__name__, self.barcode)
@property
def is_valid(self):
if self.matches_barcode and self.valid_checksum:
return True
return False
@property
def matches_barcode(self):
return bool(re.match(self.barcode_pattern, self.barcode))
@property
def tracking_number(self):
return self.barcode
@property
def valid_checksum(self):
return False
class Unknown(Package):
shipper = 'Unknown'
@property
def matches_barcode(self):
return False
| import re
class Package(object):
barcode = ''
barcode_pattern = ''
shipper = ''
def __init__(self, barcode):
self.barcode = barcode
def __repr__(self):
return "%s('%s')" % ('package.' + self.__class__.__name__, self.barcode)
@property
def is_valid(self):
if self.matches_barcode and self.valid_checksum:
return True
return False
@property
def matches_barcode(self):
if self.barcode_pattern and self.barcode:
return bool(re.match(self.barcode_pattern, self.barcode))
return False
@property
def tracking_number(self):
return self.barcode
@property
def valid_checksum(self):
return False
class Unknown(Package):
shipper = 'Unknown'
| Test for pattern and barcode before matching barcode | Test for pattern and barcode before matching barcode
| Python | bsd-3-clause | jbittel/drogher | import re
class Package(object):
barcode = None
barcode_pattern = None
shipper = None
def __init__(self, barcode):
self.barcode = barcode
def __repr__(self):
return "%s('%s')" % ('package.' + self.__class__.__name__, self.barcode)
@property
def is_valid(self):
if self.matches_barcode and self.valid_checksum:
return True
return False
@property
def matches_barcode(self):
return bool(re.match(self.barcode_pattern, self.barcode))
@property
def tracking_number(self):
return self.barcode
@property
def valid_checksum(self):
return False
class Unknown(Package):
shipper = 'Unknown'
@property
def matches_barcode(self):
return False
Test for pattern and barcode before matching barcode | import re
class Package(object):
barcode = ''
barcode_pattern = ''
shipper = ''
def __init__(self, barcode):
self.barcode = barcode
def __repr__(self):
return "%s('%s')" % ('package.' + self.__class__.__name__, self.barcode)
@property
def is_valid(self):
if self.matches_barcode and self.valid_checksum:
return True
return False
@property
def matches_barcode(self):
if self.barcode_pattern and self.barcode:
return bool(re.match(self.barcode_pattern, self.barcode))
return False
@property
def tracking_number(self):
return self.barcode
@property
def valid_checksum(self):
return False
class Unknown(Package):
shipper = 'Unknown'
| <commit_before>import re
class Package(object):
barcode = None
barcode_pattern = None
shipper = None
def __init__(self, barcode):
self.barcode = barcode
def __repr__(self):
return "%s('%s')" % ('package.' + self.__class__.__name__, self.barcode)
@property
def is_valid(self):
if self.matches_barcode and self.valid_checksum:
return True
return False
@property
def matches_barcode(self):
return bool(re.match(self.barcode_pattern, self.barcode))
@property
def tracking_number(self):
return self.barcode
@property
def valid_checksum(self):
return False
class Unknown(Package):
shipper = 'Unknown'
@property
def matches_barcode(self):
return False
<commit_msg>Test for pattern and barcode before matching barcode<commit_after> | import re
class Package(object):
barcode = ''
barcode_pattern = ''
shipper = ''
def __init__(self, barcode):
self.barcode = barcode
def __repr__(self):
return "%s('%s')" % ('package.' + self.__class__.__name__, self.barcode)
@property
def is_valid(self):
if self.matches_barcode and self.valid_checksum:
return True
return False
@property
def matches_barcode(self):
if self.barcode_pattern and self.barcode:
return bool(re.match(self.barcode_pattern, self.barcode))
return False
@property
def tracking_number(self):
return self.barcode
@property
def valid_checksum(self):
return False
class Unknown(Package):
shipper = 'Unknown'
| import re
class Package(object):
barcode = None
barcode_pattern = None
shipper = None
def __init__(self, barcode):
self.barcode = barcode
def __repr__(self):
return "%s('%s')" % ('package.' + self.__class__.__name__, self.barcode)
@property
def is_valid(self):
if self.matches_barcode and self.valid_checksum:
return True
return False
@property
def matches_barcode(self):
return bool(re.match(self.barcode_pattern, self.barcode))
@property
def tracking_number(self):
return self.barcode
@property
def valid_checksum(self):
return False
class Unknown(Package):
shipper = 'Unknown'
@property
def matches_barcode(self):
return False
Test for pattern and barcode before matching barcodeimport re
class Package(object):
barcode = ''
barcode_pattern = ''
shipper = ''
def __init__(self, barcode):
self.barcode = barcode
def __repr__(self):
return "%s('%s')" % ('package.' + self.__class__.__name__, self.barcode)
@property
def is_valid(self):
if self.matches_barcode and self.valid_checksum:
return True
return False
@property
def matches_barcode(self):
if self.barcode_pattern and self.barcode:
return bool(re.match(self.barcode_pattern, self.barcode))
return False
@property
def tracking_number(self):
return self.barcode
@property
def valid_checksum(self):
return False
class Unknown(Package):
shipper = 'Unknown'
| <commit_before>import re
class Package(object):
barcode = None
barcode_pattern = None
shipper = None
def __init__(self, barcode):
self.barcode = barcode
def __repr__(self):
return "%s('%s')" % ('package.' + self.__class__.__name__, self.barcode)
@property
def is_valid(self):
if self.matches_barcode and self.valid_checksum:
return True
return False
@property
def matches_barcode(self):
return bool(re.match(self.barcode_pattern, self.barcode))
@property
def tracking_number(self):
return self.barcode
@property
def valid_checksum(self):
return False
class Unknown(Package):
shipper = 'Unknown'
@property
def matches_barcode(self):
return False
<commit_msg>Test for pattern and barcode before matching barcode<commit_after>import re
class Package(object):
barcode = ''
barcode_pattern = ''
shipper = ''
def __init__(self, barcode):
self.barcode = barcode
def __repr__(self):
return "%s('%s')" % ('package.' + self.__class__.__name__, self.barcode)
@property
def is_valid(self):
if self.matches_barcode and self.valid_checksum:
return True
return False
@property
def matches_barcode(self):
if self.barcode_pattern and self.barcode:
return bool(re.match(self.barcode_pattern, self.barcode))
return False
@property
def tracking_number(self):
return self.barcode
@property
def valid_checksum(self):
return False
class Unknown(Package):
shipper = 'Unknown'
|
b9df853ec27106a31d67600483bec660d274d674 | saleor/menu/models.py | saleor/menu/models.py | from django.db import models
from django.utils.translation import pgettext_lazy
from mptt.managers import TreeManager
from mptt.models import MPTTModel
class Menu(models.Model):
slug = models.SlugField(max_length=50)
class Meta:
permissions = (
('view_menu',
pgettext_lazy('Permission description', 'Can view menus')),
('edit_menu',
pgettext_lazy('Permission description', 'Can edit menus')))
def __str__(self):
return self.slug
class MenuItem(MPTTModel):
menu = models.ForeignKey(
Menu, related_name='items', on_delete=models.CASCADE)
name = models.CharField(max_length=128)
sort_order = models.PositiveIntegerField(editable=False)
url = models.URLField(max_length=256)
parent = models.ForeignKey(
'self', null=True, blank=True, related_name='children',
on_delete=models.CASCADE)
objects = models.Manager()
tree = TreeManager()
class Meta:
ordering = ('sort_order',)
app_label = 'menu'
def __str__(self):
return self.name
| from django.db import models
from django.db.models import Max
from django.utils.translation import pgettext_lazy
from mptt.managers import TreeManager
from mptt.models import MPTTModel
class Menu(models.Model):
slug = models.SlugField(max_length=50)
class Meta:
permissions = (
('view_menu',
pgettext_lazy('Permission description', 'Can view menus')),
('edit_menu',
pgettext_lazy('Permission description', 'Can edit menus')))
def __str__(self):
return self.slug
class MenuItem(MPTTModel):
menu = models.ForeignKey(
Menu, related_name='items', on_delete=models.CASCADE)
name = models.CharField(max_length=128)
sort_order = models.PositiveIntegerField(editable=False)
url = models.URLField(max_length=256)
parent = models.ForeignKey(
'self', null=True, blank=True, related_name='children',
on_delete=models.CASCADE)
objects = models.Manager()
tree = TreeManager()
class Meta:
ordering = ('sort_order',)
app_label = 'menu'
def __str__(self):
return self.name
def get_ordering_queryset(self):
return (
self.menu.items.all() if not self.parent
else self.parent.children.all())
def save(self, *args, **kwargs):
if self.sort_order is None:
qs = self.get_ordering_queryset()
existing_max = qs.aggregate(Max('sort_order'))
existing_max = existing_max.get('sort_order__max')
self.sort_order = 0 if existing_max is None else existing_max + 1
super().save(*args, **kwargs)
| Save sorting order on MenuItem | Save sorting order on MenuItem
| Python | bsd-3-clause | maferelo/saleor,UITools/saleor,UITools/saleor,UITools/saleor,UITools/saleor,maferelo/saleor,mociepka/saleor,UITools/saleor,mociepka/saleor,maferelo/saleor,mociepka/saleor | from django.db import models
from django.utils.translation import pgettext_lazy
from mptt.managers import TreeManager
from mptt.models import MPTTModel
class Menu(models.Model):
slug = models.SlugField(max_length=50)
class Meta:
permissions = (
('view_menu',
pgettext_lazy('Permission description', 'Can view menus')),
('edit_menu',
pgettext_lazy('Permission description', 'Can edit menus')))
def __str__(self):
return self.slug
class MenuItem(MPTTModel):
menu = models.ForeignKey(
Menu, related_name='items', on_delete=models.CASCADE)
name = models.CharField(max_length=128)
sort_order = models.PositiveIntegerField(editable=False)
url = models.URLField(max_length=256)
parent = models.ForeignKey(
'self', null=True, blank=True, related_name='children',
on_delete=models.CASCADE)
objects = models.Manager()
tree = TreeManager()
class Meta:
ordering = ('sort_order',)
app_label = 'menu'
def __str__(self):
return self.name
Save sorting order on MenuItem | from django.db import models
from django.db.models import Max
from django.utils.translation import pgettext_lazy
from mptt.managers import TreeManager
from mptt.models import MPTTModel
class Menu(models.Model):
slug = models.SlugField(max_length=50)
class Meta:
permissions = (
('view_menu',
pgettext_lazy('Permission description', 'Can view menus')),
('edit_menu',
pgettext_lazy('Permission description', 'Can edit menus')))
def __str__(self):
return self.slug
class MenuItem(MPTTModel):
menu = models.ForeignKey(
Menu, related_name='items', on_delete=models.CASCADE)
name = models.CharField(max_length=128)
sort_order = models.PositiveIntegerField(editable=False)
url = models.URLField(max_length=256)
parent = models.ForeignKey(
'self', null=True, blank=True, related_name='children',
on_delete=models.CASCADE)
objects = models.Manager()
tree = TreeManager()
class Meta:
ordering = ('sort_order',)
app_label = 'menu'
def __str__(self):
return self.name
def get_ordering_queryset(self):
return (
self.menu.items.all() if not self.parent
else self.parent.children.all())
def save(self, *args, **kwargs):
if self.sort_order is None:
qs = self.get_ordering_queryset()
existing_max = qs.aggregate(Max('sort_order'))
existing_max = existing_max.get('sort_order__max')
self.sort_order = 0 if existing_max is None else existing_max + 1
super().save(*args, **kwargs)
| <commit_before>from django.db import models
from django.utils.translation import pgettext_lazy
from mptt.managers import TreeManager
from mptt.models import MPTTModel
class Menu(models.Model):
slug = models.SlugField(max_length=50)
class Meta:
permissions = (
('view_menu',
pgettext_lazy('Permission description', 'Can view menus')),
('edit_menu',
pgettext_lazy('Permission description', 'Can edit menus')))
def __str__(self):
return self.slug
class MenuItem(MPTTModel):
menu = models.ForeignKey(
Menu, related_name='items', on_delete=models.CASCADE)
name = models.CharField(max_length=128)
sort_order = models.PositiveIntegerField(editable=False)
url = models.URLField(max_length=256)
parent = models.ForeignKey(
'self', null=True, blank=True, related_name='children',
on_delete=models.CASCADE)
objects = models.Manager()
tree = TreeManager()
class Meta:
ordering = ('sort_order',)
app_label = 'menu'
def __str__(self):
return self.name
<commit_msg>Save sorting order on MenuItem<commit_after> | from django.db import models
from django.db.models import Max
from django.utils.translation import pgettext_lazy
from mptt.managers import TreeManager
from mptt.models import MPTTModel
class Menu(models.Model):
slug = models.SlugField(max_length=50)
class Meta:
permissions = (
('view_menu',
pgettext_lazy('Permission description', 'Can view menus')),
('edit_menu',
pgettext_lazy('Permission description', 'Can edit menus')))
def __str__(self):
return self.slug
class MenuItem(MPTTModel):
menu = models.ForeignKey(
Menu, related_name='items', on_delete=models.CASCADE)
name = models.CharField(max_length=128)
sort_order = models.PositiveIntegerField(editable=False)
url = models.URLField(max_length=256)
parent = models.ForeignKey(
'self', null=True, blank=True, related_name='children',
on_delete=models.CASCADE)
objects = models.Manager()
tree = TreeManager()
class Meta:
ordering = ('sort_order',)
app_label = 'menu'
def __str__(self):
return self.name
def get_ordering_queryset(self):
return (
self.menu.items.all() if not self.parent
else self.parent.children.all())
def save(self, *args, **kwargs):
if self.sort_order is None:
qs = self.get_ordering_queryset()
existing_max = qs.aggregate(Max('sort_order'))
existing_max = existing_max.get('sort_order__max')
self.sort_order = 0 if existing_max is None else existing_max + 1
super().save(*args, **kwargs)
| from django.db import models
from django.utils.translation import pgettext_lazy
from mptt.managers import TreeManager
from mptt.models import MPTTModel
class Menu(models.Model):
slug = models.SlugField(max_length=50)
class Meta:
permissions = (
('view_menu',
pgettext_lazy('Permission description', 'Can view menus')),
('edit_menu',
pgettext_lazy('Permission description', 'Can edit menus')))
def __str__(self):
return self.slug
class MenuItem(MPTTModel):
menu = models.ForeignKey(
Menu, related_name='items', on_delete=models.CASCADE)
name = models.CharField(max_length=128)
sort_order = models.PositiveIntegerField(editable=False)
url = models.URLField(max_length=256)
parent = models.ForeignKey(
'self', null=True, blank=True, related_name='children',
on_delete=models.CASCADE)
objects = models.Manager()
tree = TreeManager()
class Meta:
ordering = ('sort_order',)
app_label = 'menu'
def __str__(self):
return self.name
Save sorting order on MenuItemfrom django.db import models
from django.db.models import Max
from django.utils.translation import pgettext_lazy
from mptt.managers import TreeManager
from mptt.models import MPTTModel
class Menu(models.Model):
slug = models.SlugField(max_length=50)
class Meta:
permissions = (
('view_menu',
pgettext_lazy('Permission description', 'Can view menus')),
('edit_menu',
pgettext_lazy('Permission description', 'Can edit menus')))
def __str__(self):
return self.slug
class MenuItem(MPTTModel):
menu = models.ForeignKey(
Menu, related_name='items', on_delete=models.CASCADE)
name = models.CharField(max_length=128)
sort_order = models.PositiveIntegerField(editable=False)
url = models.URLField(max_length=256)
parent = models.ForeignKey(
'self', null=True, blank=True, related_name='children',
on_delete=models.CASCADE)
objects = models.Manager()
tree = TreeManager()
class Meta:
ordering = ('sort_order',)
app_label = 'menu'
def __str__(self):
return self.name
def get_ordering_queryset(self):
return (
self.menu.items.all() if not self.parent
else self.parent.children.all())
def save(self, *args, **kwargs):
if self.sort_order is None:
qs = self.get_ordering_queryset()
existing_max = qs.aggregate(Max('sort_order'))
existing_max = existing_max.get('sort_order__max')
self.sort_order = 0 if existing_max is None else existing_max + 1
super().save(*args, **kwargs)
| <commit_before>from django.db import models
from django.utils.translation import pgettext_lazy
from mptt.managers import TreeManager
from mptt.models import MPTTModel
class Menu(models.Model):
slug = models.SlugField(max_length=50)
class Meta:
permissions = (
('view_menu',
pgettext_lazy('Permission description', 'Can view menus')),
('edit_menu',
pgettext_lazy('Permission description', 'Can edit menus')))
def __str__(self):
return self.slug
class MenuItem(MPTTModel):
menu = models.ForeignKey(
Menu, related_name='items', on_delete=models.CASCADE)
name = models.CharField(max_length=128)
sort_order = models.PositiveIntegerField(editable=False)
url = models.URLField(max_length=256)
parent = models.ForeignKey(
'self', null=True, blank=True, related_name='children',
on_delete=models.CASCADE)
objects = models.Manager()
tree = TreeManager()
class Meta:
ordering = ('sort_order',)
app_label = 'menu'
def __str__(self):
return self.name
<commit_msg>Save sorting order on MenuItem<commit_after>from django.db import models
from django.db.models import Max
from django.utils.translation import pgettext_lazy
from mptt.managers import TreeManager
from mptt.models import MPTTModel
class Menu(models.Model):
slug = models.SlugField(max_length=50)
class Meta:
permissions = (
('view_menu',
pgettext_lazy('Permission description', 'Can view menus')),
('edit_menu',
pgettext_lazy('Permission description', 'Can edit menus')))
def __str__(self):
return self.slug
class MenuItem(MPTTModel):
menu = models.ForeignKey(
Menu, related_name='items', on_delete=models.CASCADE)
name = models.CharField(max_length=128)
sort_order = models.PositiveIntegerField(editable=False)
url = models.URLField(max_length=256)
parent = models.ForeignKey(
'self', null=True, blank=True, related_name='children',
on_delete=models.CASCADE)
objects = models.Manager()
tree = TreeManager()
class Meta:
ordering = ('sort_order',)
app_label = 'menu'
def __str__(self):
return self.name
def get_ordering_queryset(self):
return (
self.menu.items.all() if not self.parent
else self.parent.children.all())
def save(self, *args, **kwargs):
if self.sort_order is None:
qs = self.get_ordering_queryset()
existing_max = qs.aggregate(Max('sort_order'))
existing_max = existing_max.get('sort_order__max')
self.sort_order = 0 if existing_max is None else existing_max + 1
super().save(*args, **kwargs)
|
350380095b84bce5bd06e1ac046d9036fd7ab0cd | bluebottle/partners/serializers.py | bluebottle/partners/serializers.py | from bluebottle.bluebottle_drf2.serializers import ImageSerializer
from bluebottle.projects.models import PartnerOrganization
from bluebottle.projects.serializers import ProjectSerializer, ProjectPreviewSerializer
from rest_framework import serializers
class PartnerOrganizationSerializer(serializers.ModelSerializer):
id = serializers.CharField(source='slug', read_only=True)
projects = ProjectPreviewSerializer(source='projects')
description = serializers.CharField(source='description')
image = ImageSerializer(required=False)
class Meta:
model = PartnerOrganization
fields = ('id', 'name', 'projects', 'description', 'image')
| from bluebottle.bluebottle_drf2.serializers import ImageSerializer
from bluebottle.projects.models import PartnerOrganization
from bluebottle.bb_projects.serializers import ProjectPreviewSerializer
from rest_framework import serializers
class PartnerOrganizationSerializer(serializers.ModelSerializer):
id = serializers.CharField(source='slug', read_only=True)
projects = ProjectPreviewSerializer(source='projects')
description = serializers.CharField(source='description')
image = ImageSerializer(required=False)
class Meta:
model = PartnerOrganization
fields = ('id', 'name', 'projects', 'description', 'image')
| Use a simpler serializer that does not require people_requested/people_registered annotations / fields | Use a simpler serializer that does not require people_requested/people_registered annotations / fields
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle | from bluebottle.bluebottle_drf2.serializers import ImageSerializer
from bluebottle.projects.models import PartnerOrganization
from bluebottle.projects.serializers import ProjectSerializer, ProjectPreviewSerializer
from rest_framework import serializers
class PartnerOrganizationSerializer(serializers.ModelSerializer):
id = serializers.CharField(source='slug', read_only=True)
projects = ProjectPreviewSerializer(source='projects')
description = serializers.CharField(source='description')
image = ImageSerializer(required=False)
class Meta:
model = PartnerOrganization
fields = ('id', 'name', 'projects', 'description', 'image')
Use a simpler serializer that does not require people_requested/people_registered annotations / fields | from bluebottle.bluebottle_drf2.serializers import ImageSerializer
from bluebottle.projects.models import PartnerOrganization
from bluebottle.bb_projects.serializers import ProjectPreviewSerializer
from rest_framework import serializers
class PartnerOrganizationSerializer(serializers.ModelSerializer):
id = serializers.CharField(source='slug', read_only=True)
projects = ProjectPreviewSerializer(source='projects')
description = serializers.CharField(source='description')
image = ImageSerializer(required=False)
class Meta:
model = PartnerOrganization
fields = ('id', 'name', 'projects', 'description', 'image')
| <commit_before>from bluebottle.bluebottle_drf2.serializers import ImageSerializer
from bluebottle.projects.models import PartnerOrganization
from bluebottle.projects.serializers import ProjectSerializer, ProjectPreviewSerializer
from rest_framework import serializers
class PartnerOrganizationSerializer(serializers.ModelSerializer):
id = serializers.CharField(source='slug', read_only=True)
projects = ProjectPreviewSerializer(source='projects')
description = serializers.CharField(source='description')
image = ImageSerializer(required=False)
class Meta:
model = PartnerOrganization
fields = ('id', 'name', 'projects', 'description', 'image')
<commit_msg>Use a simpler serializer that does not require people_requested/people_registered annotations / fields<commit_after> | from bluebottle.bluebottle_drf2.serializers import ImageSerializer
from bluebottle.projects.models import PartnerOrganization
from bluebottle.bb_projects.serializers import ProjectPreviewSerializer
from rest_framework import serializers
class PartnerOrganizationSerializer(serializers.ModelSerializer):
id = serializers.CharField(source='slug', read_only=True)
projects = ProjectPreviewSerializer(source='projects')
description = serializers.CharField(source='description')
image = ImageSerializer(required=False)
class Meta:
model = PartnerOrganization
fields = ('id', 'name', 'projects', 'description', 'image')
| from bluebottle.bluebottle_drf2.serializers import ImageSerializer
from bluebottle.projects.models import PartnerOrganization
from bluebottle.projects.serializers import ProjectSerializer, ProjectPreviewSerializer
from rest_framework import serializers
class PartnerOrganizationSerializer(serializers.ModelSerializer):
id = serializers.CharField(source='slug', read_only=True)
projects = ProjectPreviewSerializer(source='projects')
description = serializers.CharField(source='description')
image = ImageSerializer(required=False)
class Meta:
model = PartnerOrganization
fields = ('id', 'name', 'projects', 'description', 'image')
Use a simpler serializer that does not require people_requested/people_registered annotations / fieldsfrom bluebottle.bluebottle_drf2.serializers import ImageSerializer
from bluebottle.projects.models import PartnerOrganization
from bluebottle.bb_projects.serializers import ProjectPreviewSerializer
from rest_framework import serializers
class PartnerOrganizationSerializer(serializers.ModelSerializer):
id = serializers.CharField(source='slug', read_only=True)
projects = ProjectPreviewSerializer(source='projects')
description = serializers.CharField(source='description')
image = ImageSerializer(required=False)
class Meta:
model = PartnerOrganization
fields = ('id', 'name', 'projects', 'description', 'image')
| <commit_before>from bluebottle.bluebottle_drf2.serializers import ImageSerializer
from bluebottle.projects.models import PartnerOrganization
from bluebottle.projects.serializers import ProjectSerializer, ProjectPreviewSerializer
from rest_framework import serializers
class PartnerOrganizationSerializer(serializers.ModelSerializer):
id = serializers.CharField(source='slug', read_only=True)
projects = ProjectPreviewSerializer(source='projects')
description = serializers.CharField(source='description')
image = ImageSerializer(required=False)
class Meta:
model = PartnerOrganization
fields = ('id', 'name', 'projects', 'description', 'image')
<commit_msg>Use a simpler serializer that does not require people_requested/people_registered annotations / fields<commit_after>from bluebottle.bluebottle_drf2.serializers import ImageSerializer
from bluebottle.projects.models import PartnerOrganization
from bluebottle.bb_projects.serializers import ProjectPreviewSerializer
from rest_framework import serializers
class PartnerOrganizationSerializer(serializers.ModelSerializer):
id = serializers.CharField(source='slug', read_only=True)
projects = ProjectPreviewSerializer(source='projects')
description = serializers.CharField(source='description')
image = ImageSerializer(required=False)
class Meta:
model = PartnerOrganization
fields = ('id', 'name', 'projects', 'description', 'image')
|
ded371a8cb63077e57cfcde401df56bddf078f5a | project/user/forms.py | project/user/forms.py | from flask_wtf import Form
from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired, Email, Length, EqualTo
from project.models import User
class LoginForm(Form):
email = TextField('email', validators=[DataRequired(), Email()])
password = PasswordField('password', validators=[DataRequired()])
class RegisterForm(Form):
email = TextField(
'email',
validators=[DataRequired(), Email(message=None), Length(min=6, max=40)])
password = PasswordField(
'password',
validators=[DataRequired(), Length(min=6, max=25)]
)
confirm = PasswordField(
'Repeat password',
validators=[
DataRequired(),
EqualTo('password', message='Passwords must match.')
]
)
def validate(self):
initial_validation = super(RegisterForm, self).validate()
if not initial_validation:
return False
user = User.query.filter_by(email=self.email.data).first()
if user:
self.email.errors.append("Email already registered")
return False
return True
class ChangePasswordForm(Form):
password = PasswordField(
'password',
validators=[DataRequired(), Length(min=6, max=25)]
)
confirm = PasswordField(
'Repeat password',
validators=[
DataRequired(),
EqualTo('password', message='Passwords must match.')
]
)
| from flask_wtf import Form
from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired, Email, Length, EqualTo
from project.models import User
class LoginForm(Form):
email = TextField('email', validators=[DataRequired(), Email()])
password = PasswordField('password', validators=[DataRequired()])
class RegisterForm(Form):
email = TextField(
'email',
validators=[DataRequired(), Email(message=None), Length(min=6, max=40)])
password = PasswordField(
'password',
validators=[DataRequired(), Length(min=6, max=25)]
)
confirm = PasswordField(
'Repeat password',
validators=[
DataRequired(),
EqualTo('password', message='Passwords must match.')
]
)
def validate(self):
initial_validation = super(RegisterForm, self).validate()
if not initial_validation:
return False
user = User.query.filter_by(email=self.email.data).first()
if user:
self.email.errors.append("Email already registered")
return False
return True
class ResetPasswordForm(Form):
email = TextField(
'email', validators=[DataRequired(), Email(message=None), Length(min=6, max=40)])
class ChangePasswordForm(Form):
password = PasswordField(
'password',
validators=[DataRequired(), Length(min=6, max=25)]
)
confirm = PasswordField(
'Repeat password',
validators=[
DataRequired(),
EqualTo('password', message='Passwords must match.')
]
)
| Create basic password reset form | Create basic password reset form
| Python | mit | dylanshine/streamschool,dylanshine/streamschool | from flask_wtf import Form
from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired, Email, Length, EqualTo
from project.models import User
class LoginForm(Form):
email = TextField('email', validators=[DataRequired(), Email()])
password = PasswordField('password', validators=[DataRequired()])
class RegisterForm(Form):
email = TextField(
'email',
validators=[DataRequired(), Email(message=None), Length(min=6, max=40)])
password = PasswordField(
'password',
validators=[DataRequired(), Length(min=6, max=25)]
)
confirm = PasswordField(
'Repeat password',
validators=[
DataRequired(),
EqualTo('password', message='Passwords must match.')
]
)
def validate(self):
initial_validation = super(RegisterForm, self).validate()
if not initial_validation:
return False
user = User.query.filter_by(email=self.email.data).first()
if user:
self.email.errors.append("Email already registered")
return False
return True
class ChangePasswordForm(Form):
password = PasswordField(
'password',
validators=[DataRequired(), Length(min=6, max=25)]
)
confirm = PasswordField(
'Repeat password',
validators=[
DataRequired(),
EqualTo('password', message='Passwords must match.')
]
)
Create basic password reset form | from flask_wtf import Form
from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired, Email, Length, EqualTo
from project.models import User
class LoginForm(Form):
email = TextField('email', validators=[DataRequired(), Email()])
password = PasswordField('password', validators=[DataRequired()])
class RegisterForm(Form):
email = TextField(
'email',
validators=[DataRequired(), Email(message=None), Length(min=6, max=40)])
password = PasswordField(
'password',
validators=[DataRequired(), Length(min=6, max=25)]
)
confirm = PasswordField(
'Repeat password',
validators=[
DataRequired(),
EqualTo('password', message='Passwords must match.')
]
)
def validate(self):
initial_validation = super(RegisterForm, self).validate()
if not initial_validation:
return False
user = User.query.filter_by(email=self.email.data).first()
if user:
self.email.errors.append("Email already registered")
return False
return True
class ResetPasswordForm(Form):
email = TextField(
'email', validators=[DataRequired(), Email(message=None), Length(min=6, max=40)])
class ChangePasswordForm(Form):
password = PasswordField(
'password',
validators=[DataRequired(), Length(min=6, max=25)]
)
confirm = PasswordField(
'Repeat password',
validators=[
DataRequired(),
EqualTo('password', message='Passwords must match.')
]
)
| <commit_before>from flask_wtf import Form
from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired, Email, Length, EqualTo
from project.models import User
class LoginForm(Form):
email = TextField('email', validators=[DataRequired(), Email()])
password = PasswordField('password', validators=[DataRequired()])
class RegisterForm(Form):
email = TextField(
'email',
validators=[DataRequired(), Email(message=None), Length(min=6, max=40)])
password = PasswordField(
'password',
validators=[DataRequired(), Length(min=6, max=25)]
)
confirm = PasswordField(
'Repeat password',
validators=[
DataRequired(),
EqualTo('password', message='Passwords must match.')
]
)
def validate(self):
initial_validation = super(RegisterForm, self).validate()
if not initial_validation:
return False
user = User.query.filter_by(email=self.email.data).first()
if user:
self.email.errors.append("Email already registered")
return False
return True
class ChangePasswordForm(Form):
password = PasswordField(
'password',
validators=[DataRequired(), Length(min=6, max=25)]
)
confirm = PasswordField(
'Repeat password',
validators=[
DataRequired(),
EqualTo('password', message='Passwords must match.')
]
)
<commit_msg>Create basic password reset form<commit_after> | from flask_wtf import Form
from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired, Email, Length, EqualTo
from project.models import User
class LoginForm(Form):
email = TextField('email', validators=[DataRequired(), Email()])
password = PasswordField('password', validators=[DataRequired()])
class RegisterForm(Form):
email = TextField(
'email',
validators=[DataRequired(), Email(message=None), Length(min=6, max=40)])
password = PasswordField(
'password',
validators=[DataRequired(), Length(min=6, max=25)]
)
confirm = PasswordField(
'Repeat password',
validators=[
DataRequired(),
EqualTo('password', message='Passwords must match.')
]
)
def validate(self):
initial_validation = super(RegisterForm, self).validate()
if not initial_validation:
return False
user = User.query.filter_by(email=self.email.data).first()
if user:
self.email.errors.append("Email already registered")
return False
return True
class ResetPasswordForm(Form):
email = TextField(
'email', validators=[DataRequired(), Email(message=None), Length(min=6, max=40)])
class ChangePasswordForm(Form):
password = PasswordField(
'password',
validators=[DataRequired(), Length(min=6, max=25)]
)
confirm = PasswordField(
'Repeat password',
validators=[
DataRequired(),
EqualTo('password', message='Passwords must match.')
]
)
| from flask_wtf import Form
from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired, Email, Length, EqualTo
from project.models import User
class LoginForm(Form):
email = TextField('email', validators=[DataRequired(), Email()])
password = PasswordField('password', validators=[DataRequired()])
class RegisterForm(Form):
email = TextField(
'email',
validators=[DataRequired(), Email(message=None), Length(min=6, max=40)])
password = PasswordField(
'password',
validators=[DataRequired(), Length(min=6, max=25)]
)
confirm = PasswordField(
'Repeat password',
validators=[
DataRequired(),
EqualTo('password', message='Passwords must match.')
]
)
def validate(self):
initial_validation = super(RegisterForm, self).validate()
if not initial_validation:
return False
user = User.query.filter_by(email=self.email.data).first()
if user:
self.email.errors.append("Email already registered")
return False
return True
class ChangePasswordForm(Form):
password = PasswordField(
'password',
validators=[DataRequired(), Length(min=6, max=25)]
)
confirm = PasswordField(
'Repeat password',
validators=[
DataRequired(),
EqualTo('password', message='Passwords must match.')
]
)
Create basic password reset formfrom flask_wtf import Form
from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired, Email, Length, EqualTo
from project.models import User
class LoginForm(Form):
email = TextField('email', validators=[DataRequired(), Email()])
password = PasswordField('password', validators=[DataRequired()])
class RegisterForm(Form):
email = TextField(
'email',
validators=[DataRequired(), Email(message=None), Length(min=6, max=40)])
password = PasswordField(
'password',
validators=[DataRequired(), Length(min=6, max=25)]
)
confirm = PasswordField(
'Repeat password',
validators=[
DataRequired(),
EqualTo('password', message='Passwords must match.')
]
)
def validate(self):
initial_validation = super(RegisterForm, self).validate()
if not initial_validation:
return False
user = User.query.filter_by(email=self.email.data).first()
if user:
self.email.errors.append("Email already registered")
return False
return True
class ResetPasswordForm(Form):
email = TextField(
'email', validators=[DataRequired(), Email(message=None), Length(min=6, max=40)])
class ChangePasswordForm(Form):
password = PasswordField(
'password',
validators=[DataRequired(), Length(min=6, max=25)]
)
confirm = PasswordField(
'Repeat password',
validators=[
DataRequired(),
EqualTo('password', message='Passwords must match.')
]
)
| <commit_before>from flask_wtf import Form
from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired, Email, Length, EqualTo
from project.models import User
class LoginForm(Form):
email = TextField('email', validators=[DataRequired(), Email()])
password = PasswordField('password', validators=[DataRequired()])
class RegisterForm(Form):
email = TextField(
'email',
validators=[DataRequired(), Email(message=None), Length(min=6, max=40)])
password = PasswordField(
'password',
validators=[DataRequired(), Length(min=6, max=25)]
)
confirm = PasswordField(
'Repeat password',
validators=[
DataRequired(),
EqualTo('password', message='Passwords must match.')
]
)
def validate(self):
initial_validation = super(RegisterForm, self).validate()
if not initial_validation:
return False
user = User.query.filter_by(email=self.email.data).first()
if user:
self.email.errors.append("Email already registered")
return False
return True
class ChangePasswordForm(Form):
password = PasswordField(
'password',
validators=[DataRequired(), Length(min=6, max=25)]
)
confirm = PasswordField(
'Repeat password',
validators=[
DataRequired(),
EqualTo('password', message='Passwords must match.')
]
)
<commit_msg>Create basic password reset form<commit_after>from flask_wtf import Form
from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired, Email, Length, EqualTo
from project.models import User
class LoginForm(Form):
email = TextField('email', validators=[DataRequired(), Email()])
password = PasswordField('password', validators=[DataRequired()])
class RegisterForm(Form):
email = TextField(
'email',
validators=[DataRequired(), Email(message=None), Length(min=6, max=40)])
password = PasswordField(
'password',
validators=[DataRequired(), Length(min=6, max=25)]
)
confirm = PasswordField(
'Repeat password',
validators=[
DataRequired(),
EqualTo('password', message='Passwords must match.')
]
)
def validate(self):
initial_validation = super(RegisterForm, self).validate()
if not initial_validation:
return False
user = User.query.filter_by(email=self.email.data).first()
if user:
self.email.errors.append("Email already registered")
return False
return True
class ResetPasswordForm(Form):
email = TextField(
'email', validators=[DataRequired(), Email(message=None), Length(min=6, max=40)])
class ChangePasswordForm(Form):
password = PasswordField(
'password',
validators=[DataRequired(), Length(min=6, max=25)]
)
confirm = PasswordField(
'Repeat password',
validators=[
DataRequired(),
EqualTo('password', message='Passwords must match.')
]
)
|
59069062b1cf8af3790fea8c9a44972b1b1218e7 | services/models/unit_connection.py | services/models/unit_connection.py | from django.db import models
from .unit import Unit
SECTION_TYPES = (
(1, 'PHONE_OR_EMAIL'),
(2, 'LINK'),
(3, 'TOPICAL'),
(4, 'OTHER_INFO'),
(5, 'OPENING_HOURS'),
(6, 'SOCIAL_MEDIA_LINK'),
(7, 'OTHER_ADDRESS'),
)
class UnitConnection(models.Model):
unit = models.ForeignKey(Unit, db_index=True, related_name='connections')
name = models.CharField(max_length=400)
www = models.URLField(null=True, max_length=400)
section_type = models.PositiveSmallIntegerField(choices=SECTION_TYPES, null=True)
email = models.EmailField(max_length=100, null=True)
phone = models.CharField(max_length=50, null=True)
contact_person = models.CharField(max_length=80, null=True)
order = models.PositiveSmallIntegerField(default=0)
class Meta:
ordering = ['order'] | from django.db import models
from .unit import Unit
SECTION_TYPES = (
(1, 'PHONE_OR_EMAIL'),
(2, 'LINK'),
(3, 'TOPICAL'),
(4, 'OTHER_INFO'),
(5, 'OPENING_HOURS'),
(6, 'SOCIAL_MEDIA_LINK'),
(7, 'OTHER_ADDRESS'),
(8, 'HIGHLIGHT'),
)
class UnitConnection(models.Model):
unit = models.ForeignKey(Unit, db_index=True, related_name='connections')
name = models.CharField(max_length=400)
www = models.URLField(null=True, max_length=400)
section_type = models.PositiveSmallIntegerField(choices=SECTION_TYPES, null=True)
email = models.EmailField(max_length=100, null=True)
phone = models.CharField(max_length=50, null=True)
contact_person = models.CharField(max_length=80, null=True)
order = models.PositiveSmallIntegerField(default=0)
class Meta:
ordering = ['order']
| Add missing connection section type value HIGHLIGHT | Add missing connection section type value HIGHLIGHT
| Python | agpl-3.0 | City-of-Helsinki/smbackend,City-of-Helsinki/smbackend | from django.db import models
from .unit import Unit
SECTION_TYPES = (
(1, 'PHONE_OR_EMAIL'),
(2, 'LINK'),
(3, 'TOPICAL'),
(4, 'OTHER_INFO'),
(5, 'OPENING_HOURS'),
(6, 'SOCIAL_MEDIA_LINK'),
(7, 'OTHER_ADDRESS'),
)
class UnitConnection(models.Model):
unit = models.ForeignKey(Unit, db_index=True, related_name='connections')
name = models.CharField(max_length=400)
www = models.URLField(null=True, max_length=400)
section_type = models.PositiveSmallIntegerField(choices=SECTION_TYPES, null=True)
email = models.EmailField(max_length=100, null=True)
phone = models.CharField(max_length=50, null=True)
contact_person = models.CharField(max_length=80, null=True)
order = models.PositiveSmallIntegerField(default=0)
class Meta:
ordering = ['order']Add missing connection section type value HIGHLIGHT | from django.db import models
from .unit import Unit
SECTION_TYPES = (
(1, 'PHONE_OR_EMAIL'),
(2, 'LINK'),
(3, 'TOPICAL'),
(4, 'OTHER_INFO'),
(5, 'OPENING_HOURS'),
(6, 'SOCIAL_MEDIA_LINK'),
(7, 'OTHER_ADDRESS'),
(8, 'HIGHLIGHT'),
)
class UnitConnection(models.Model):
unit = models.ForeignKey(Unit, db_index=True, related_name='connections')
name = models.CharField(max_length=400)
www = models.URLField(null=True, max_length=400)
section_type = models.PositiveSmallIntegerField(choices=SECTION_TYPES, null=True)
email = models.EmailField(max_length=100, null=True)
phone = models.CharField(max_length=50, null=True)
contact_person = models.CharField(max_length=80, null=True)
order = models.PositiveSmallIntegerField(default=0)
class Meta:
ordering = ['order']
| <commit_before>from django.db import models
from .unit import Unit
SECTION_TYPES = (
(1, 'PHONE_OR_EMAIL'),
(2, 'LINK'),
(3, 'TOPICAL'),
(4, 'OTHER_INFO'),
(5, 'OPENING_HOURS'),
(6, 'SOCIAL_MEDIA_LINK'),
(7, 'OTHER_ADDRESS'),
)
class UnitConnection(models.Model):
unit = models.ForeignKey(Unit, db_index=True, related_name='connections')
name = models.CharField(max_length=400)
www = models.URLField(null=True, max_length=400)
section_type = models.PositiveSmallIntegerField(choices=SECTION_TYPES, null=True)
email = models.EmailField(max_length=100, null=True)
phone = models.CharField(max_length=50, null=True)
contact_person = models.CharField(max_length=80, null=True)
order = models.PositiveSmallIntegerField(default=0)
class Meta:
ordering = ['order']<commit_msg>Add missing connection section type value HIGHLIGHT<commit_after> | from django.db import models
from .unit import Unit
SECTION_TYPES = (
(1, 'PHONE_OR_EMAIL'),
(2, 'LINK'),
(3, 'TOPICAL'),
(4, 'OTHER_INFO'),
(5, 'OPENING_HOURS'),
(6, 'SOCIAL_MEDIA_LINK'),
(7, 'OTHER_ADDRESS'),
(8, 'HIGHLIGHT'),
)
class UnitConnection(models.Model):
unit = models.ForeignKey(Unit, db_index=True, related_name='connections')
name = models.CharField(max_length=400)
www = models.URLField(null=True, max_length=400)
section_type = models.PositiveSmallIntegerField(choices=SECTION_TYPES, null=True)
email = models.EmailField(max_length=100, null=True)
phone = models.CharField(max_length=50, null=True)
contact_person = models.CharField(max_length=80, null=True)
order = models.PositiveSmallIntegerField(default=0)
class Meta:
ordering = ['order']
| from django.db import models
from .unit import Unit
SECTION_TYPES = (
(1, 'PHONE_OR_EMAIL'),
(2, 'LINK'),
(3, 'TOPICAL'),
(4, 'OTHER_INFO'),
(5, 'OPENING_HOURS'),
(6, 'SOCIAL_MEDIA_LINK'),
(7, 'OTHER_ADDRESS'),
)
class UnitConnection(models.Model):
unit = models.ForeignKey(Unit, db_index=True, related_name='connections')
name = models.CharField(max_length=400)
www = models.URLField(null=True, max_length=400)
section_type = models.PositiveSmallIntegerField(choices=SECTION_TYPES, null=True)
email = models.EmailField(max_length=100, null=True)
phone = models.CharField(max_length=50, null=True)
contact_person = models.CharField(max_length=80, null=True)
order = models.PositiveSmallIntegerField(default=0)
class Meta:
ordering = ['order']Add missing connection section type value HIGHLIGHTfrom django.db import models
from .unit import Unit
SECTION_TYPES = (
(1, 'PHONE_OR_EMAIL'),
(2, 'LINK'),
(3, 'TOPICAL'),
(4, 'OTHER_INFO'),
(5, 'OPENING_HOURS'),
(6, 'SOCIAL_MEDIA_LINK'),
(7, 'OTHER_ADDRESS'),
(8, 'HIGHLIGHT'),
)
class UnitConnection(models.Model):
unit = models.ForeignKey(Unit, db_index=True, related_name='connections')
name = models.CharField(max_length=400)
www = models.URLField(null=True, max_length=400)
section_type = models.PositiveSmallIntegerField(choices=SECTION_TYPES, null=True)
email = models.EmailField(max_length=100, null=True)
phone = models.CharField(max_length=50, null=True)
contact_person = models.CharField(max_length=80, null=True)
order = models.PositiveSmallIntegerField(default=0)
class Meta:
ordering = ['order']
| <commit_before>from django.db import models
from .unit import Unit
SECTION_TYPES = (
(1, 'PHONE_OR_EMAIL'),
(2, 'LINK'),
(3, 'TOPICAL'),
(4, 'OTHER_INFO'),
(5, 'OPENING_HOURS'),
(6, 'SOCIAL_MEDIA_LINK'),
(7, 'OTHER_ADDRESS'),
)
class UnitConnection(models.Model):
unit = models.ForeignKey(Unit, db_index=True, related_name='connections')
name = models.CharField(max_length=400)
www = models.URLField(null=True, max_length=400)
section_type = models.PositiveSmallIntegerField(choices=SECTION_TYPES, null=True)
email = models.EmailField(max_length=100, null=True)
phone = models.CharField(max_length=50, null=True)
contact_person = models.CharField(max_length=80, null=True)
order = models.PositiveSmallIntegerField(default=0)
class Meta:
ordering = ['order']<commit_msg>Add missing connection section type value HIGHLIGHT<commit_after>from django.db import models
from .unit import Unit
SECTION_TYPES = (
(1, 'PHONE_OR_EMAIL'),
(2, 'LINK'),
(3, 'TOPICAL'),
(4, 'OTHER_INFO'),
(5, 'OPENING_HOURS'),
(6, 'SOCIAL_MEDIA_LINK'),
(7, 'OTHER_ADDRESS'),
(8, 'HIGHLIGHT'),
)
class UnitConnection(models.Model):
unit = models.ForeignKey(Unit, db_index=True, related_name='connections')
name = models.CharField(max_length=400)
www = models.URLField(null=True, max_length=400)
section_type = models.PositiveSmallIntegerField(choices=SECTION_TYPES, null=True)
email = models.EmailField(max_length=100, null=True)
phone = models.CharField(max_length=50, null=True)
contact_person = models.CharField(max_length=80, null=True)
order = models.PositiveSmallIntegerField(default=0)
class Meta:
ordering = ['order']
|
0a5d7873ee536b41907424df2477db3a0b2a0287 | scripts/remove_after_use/node_preprint_es.py | scripts/remove_after_use/node_preprint_es.py | from website.app import setup_django
setup_django()
from website import search
from website.search.elastic_search import delete_doc
from osf.models import Preprint, AbstractNode
import progressbar
# To run: docker-compose run --rm web python -m scripts.remove_after_use.node_preprint_es
def main():
"""
Temporary script for updating elastic search after the node-preprint divorce
- Removes nodes from the index that are categorized as preprints
- Adds these nodes to the index, this time categorized as nodes
- Adds preprints to the index, categorized as preprints
"""
preprints = Preprint.objects
progress_bar = progressbar.ProgressBar(maxval=preprints.count()).start()
for i, p in enumerate(preprints.all(), 1):
progress_bar.update(i)
search.search.update_preprint(p, bulk=False, async=False) # create new index for preprint
if p.node:
delete_doc(p.node._id, p.node, category='preprint') # delete old index for node categorized as a preprint
search.search.update_node(p.node, bulk=False, async=False) # create new index for node (this time categorized as a node)
progress_bar.finish()
if __name__ == '__main__':
main()
| from website.app import setup_django
setup_django()
from website import search
from website.search.elastic_search import delete_doc
from osf.models import Preprint, AbstractNode
import progressbar
# To run: docker-compose run --rm web python -m scripts.remove_after_use.node_preprint_es
def main():
"""
Temporary script for updating elastic search after the node-preprint divorce
- Removes nodes from the index that are categorized as preprints
- Adds these nodes to the index, this time categorized as nodes
- Adds preprints to the index, categorized as preprints
"""
preprints = Preprint.objects
progress_bar = progressbar.ProgressBar(maxval=preprints.count()).start()
for i, p in enumerate(preprints.all(), 1):
progress_bar.update(i)
search.search.update_preprint(p, bulk=False, async=False) # create new index for preprint
if p.node:
delete_doc(p.node._id, p.node, category='preprint') # delete old index for node categorized as a preprint
search.search.update_node(p.node, bulk=False, async_update=False) # create new index for node (this time categorized as a node)
progress_bar.finish()
if __name__ == '__main__':
main()
| Fix ES index script with updated param | Fix ES index script with updated param
| Python | apache-2.0 | mattclark/osf.io,brianjgeiger/osf.io,mfraezz/osf.io,felliott/osf.io,aaxelb/osf.io,cslzchen/osf.io,baylee-d/osf.io,pattisdr/osf.io,brianjgeiger/osf.io,felliott/osf.io,brianjgeiger/osf.io,mfraezz/osf.io,adlius/osf.io,CenterForOpenScience/osf.io,pattisdr/osf.io,mattclark/osf.io,adlius/osf.io,brianjgeiger/osf.io,CenterForOpenScience/osf.io,mattclark/osf.io,cslzchen/osf.io,saradbowman/osf.io,aaxelb/osf.io,aaxelb/osf.io,adlius/osf.io,Johnetordoff/osf.io,baylee-d/osf.io,saradbowman/osf.io,CenterForOpenScience/osf.io,baylee-d/osf.io,adlius/osf.io,mfraezz/osf.io,mfraezz/osf.io,Johnetordoff/osf.io,pattisdr/osf.io,felliott/osf.io,Johnetordoff/osf.io,felliott/osf.io,aaxelb/osf.io,cslzchen/osf.io,CenterForOpenScience/osf.io,Johnetordoff/osf.io,cslzchen/osf.io | from website.app import setup_django
setup_django()
from website import search
from website.search.elastic_search import delete_doc
from osf.models import Preprint, AbstractNode
import progressbar
# To run: docker-compose run --rm web python -m scripts.remove_after_use.node_preprint_es
def main():
"""
Temporary script for updating elastic search after the node-preprint divorce
- Removes nodes from the index that are categorized as preprints
- Adds these nodes to the index, this time categorized as nodes
- Adds preprints to the index, categorized as preprints
"""
preprints = Preprint.objects
progress_bar = progressbar.ProgressBar(maxval=preprints.count()).start()
for i, p in enumerate(preprints.all(), 1):
progress_bar.update(i)
search.search.update_preprint(p, bulk=False, async=False) # create new index for preprint
if p.node:
delete_doc(p.node._id, p.node, category='preprint') # delete old index for node categorized as a preprint
search.search.update_node(p.node, bulk=False, async=False) # create new index for node (this time categorized as a node)
progress_bar.finish()
if __name__ == '__main__':
main()
Fix ES index script with updated param | from website.app import setup_django
setup_django()
from website import search
from website.search.elastic_search import delete_doc
from osf.models import Preprint, AbstractNode
import progressbar
# To run: docker-compose run --rm web python -m scripts.remove_after_use.node_preprint_es
def main():
"""
Temporary script for updating elastic search after the node-preprint divorce
- Removes nodes from the index that are categorized as preprints
- Adds these nodes to the index, this time categorized as nodes
- Adds preprints to the index, categorized as preprints
"""
preprints = Preprint.objects
progress_bar = progressbar.ProgressBar(maxval=preprints.count()).start()
for i, p in enumerate(preprints.all(), 1):
progress_bar.update(i)
search.search.update_preprint(p, bulk=False, async=False) # create new index for preprint
if p.node:
delete_doc(p.node._id, p.node, category='preprint') # delete old index for node categorized as a preprint
search.search.update_node(p.node, bulk=False, async_update=False) # create new index for node (this time categorized as a node)
progress_bar.finish()
if __name__ == '__main__':
main()
| <commit_before>from website.app import setup_django
setup_django()
from website import search
from website.search.elastic_search import delete_doc
from osf.models import Preprint, AbstractNode
import progressbar
# To run: docker-compose run --rm web python -m scripts.remove_after_use.node_preprint_es
def main():
"""
Temporary script for updating elastic search after the node-preprint divorce
- Removes nodes from the index that are categorized as preprints
- Adds these nodes to the index, this time categorized as nodes
- Adds preprints to the index, categorized as preprints
"""
preprints = Preprint.objects
progress_bar = progressbar.ProgressBar(maxval=preprints.count()).start()
for i, p in enumerate(preprints.all(), 1):
progress_bar.update(i)
search.search.update_preprint(p, bulk=False, async=False) # create new index for preprint
if p.node:
delete_doc(p.node._id, p.node, category='preprint') # delete old index for node categorized as a preprint
search.search.update_node(p.node, bulk=False, async=False) # create new index for node (this time categorized as a node)
progress_bar.finish()
if __name__ == '__main__':
main()
<commit_msg>Fix ES index script with updated param<commit_after> | from website.app import setup_django
setup_django()
from website import search
from website.search.elastic_search import delete_doc
from osf.models import Preprint, AbstractNode
import progressbar
# To run: docker-compose run --rm web python -m scripts.remove_after_use.node_preprint_es
def main():
"""
Temporary script for updating elastic search after the node-preprint divorce
- Removes nodes from the index that are categorized as preprints
- Adds these nodes to the index, this time categorized as nodes
- Adds preprints to the index, categorized as preprints
"""
preprints = Preprint.objects
progress_bar = progressbar.ProgressBar(maxval=preprints.count()).start()
for i, p in enumerate(preprints.all(), 1):
progress_bar.update(i)
search.search.update_preprint(p, bulk=False, async=False) # create new index for preprint
if p.node:
delete_doc(p.node._id, p.node, category='preprint') # delete old index for node categorized as a preprint
search.search.update_node(p.node, bulk=False, async_update=False) # create new index for node (this time categorized as a node)
progress_bar.finish()
if __name__ == '__main__':
main()
| from website.app import setup_django
setup_django()
from website import search
from website.search.elastic_search import delete_doc
from osf.models import Preprint, AbstractNode
import progressbar
# To run: docker-compose run --rm web python -m scripts.remove_after_use.node_preprint_es
def main():
"""
Temporary script for updating elastic search after the node-preprint divorce
- Removes nodes from the index that are categorized as preprints
- Adds these nodes to the index, this time categorized as nodes
- Adds preprints to the index, categorized as preprints
"""
preprints = Preprint.objects
progress_bar = progressbar.ProgressBar(maxval=preprints.count()).start()
for i, p in enumerate(preprints.all(), 1):
progress_bar.update(i)
search.search.update_preprint(p, bulk=False, async=False) # create new index for preprint
if p.node:
delete_doc(p.node._id, p.node, category='preprint') # delete old index for node categorized as a preprint
search.search.update_node(p.node, bulk=False, async=False) # create new index for node (this time categorized as a node)
progress_bar.finish()
if __name__ == '__main__':
main()
Fix ES index script with updated paramfrom website.app import setup_django
setup_django()
from website import search
from website.search.elastic_search import delete_doc
from osf.models import Preprint, AbstractNode
import progressbar
# To run: docker-compose run --rm web python -m scripts.remove_after_use.node_preprint_es
def main():
"""
Temporary script for updating elastic search after the node-preprint divorce
- Removes nodes from the index that are categorized as preprints
- Adds these nodes to the index, this time categorized as nodes
- Adds preprints to the index, categorized as preprints
"""
preprints = Preprint.objects
progress_bar = progressbar.ProgressBar(maxval=preprints.count()).start()
for i, p in enumerate(preprints.all(), 1):
progress_bar.update(i)
search.search.update_preprint(p, bulk=False, async=False) # create new index for preprint
if p.node:
delete_doc(p.node._id, p.node, category='preprint') # delete old index for node categorized as a preprint
search.search.update_node(p.node, bulk=False, async_update=False) # create new index for node (this time categorized as a node)
progress_bar.finish()
if __name__ == '__main__':
main()
| <commit_before>from website.app import setup_django
setup_django()
from website import search
from website.search.elastic_search import delete_doc
from osf.models import Preprint, AbstractNode
import progressbar
# To run: docker-compose run --rm web python -m scripts.remove_after_use.node_preprint_es
def main():
"""
Temporary script for updating elastic search after the node-preprint divorce
- Removes nodes from the index that are categorized as preprints
- Adds these nodes to the index, this time categorized as nodes
- Adds preprints to the index, categorized as preprints
"""
preprints = Preprint.objects
progress_bar = progressbar.ProgressBar(maxval=preprints.count()).start()
for i, p in enumerate(preprints.all(), 1):
progress_bar.update(i)
search.search.update_preprint(p, bulk=False, async=False) # create new index for preprint
if p.node:
delete_doc(p.node._id, p.node, category='preprint') # delete old index for node categorized as a preprint
search.search.update_node(p.node, bulk=False, async=False) # create new index for node (this time categorized as a node)
progress_bar.finish()
if __name__ == '__main__':
main()
<commit_msg>Fix ES index script with updated param<commit_after>from website.app import setup_django
setup_django()
from website import search
from website.search.elastic_search import delete_doc
from osf.models import Preprint, AbstractNode
import progressbar
# To run: docker-compose run --rm web python -m scripts.remove_after_use.node_preprint_es
def main():
"""
Temporary script for updating elastic search after the node-preprint divorce
- Removes nodes from the index that are categorized as preprints
- Adds these nodes to the index, this time categorized as nodes
- Adds preprints to the index, categorized as preprints
"""
preprints = Preprint.objects
progress_bar = progressbar.ProgressBar(maxval=preprints.count()).start()
for i, p in enumerate(preprints.all(), 1):
progress_bar.update(i)
search.search.update_preprint(p, bulk=False, async=False) # create new index for preprint
if p.node:
delete_doc(p.node._id, p.node, category='preprint') # delete old index for node categorized as a preprint
search.search.update_node(p.node, bulk=False, async_update=False) # create new index for node (this time categorized as a node)
progress_bar.finish()
if __name__ == '__main__':
main()
|
f4d0b9162241df8c87fb5f918f32f3310361b834 | tests/test_member_access.py | tests/test_member_access.py | from hypothesis import given
import pytest # type: ignore
from ppb_vector import Vector
from utils import vectors
@pytest.fixture()
def vector():
return Vector(10, 20)
def test_class_member_access(vector):
assert vector.x == 10
assert vector.y == 20
@given(v=vectors())
def test_index_access(v: Vector):
assert v[0] == v.x
assert v[1] == v.y
@given(v=vectors())
def test_key_access(v: Vector):
assert v["x"] == v.x
assert v["y"] == v.y
| from hypothesis import given
from ppb_vector import Vector
from utils import floats, vectors
@given(x=floats(), y=floats())
def test_class_member_access(x: float, y: float):
v = Vector(x, y)
assert v.x == x
assert v.y == y
@given(v=vectors())
def test_index_access(v: Vector):
assert v[0] == v.x
assert v[1] == v.y
@given(v=vectors())
def test_key_access(v: Vector):
assert v["x"] == v.x
assert v["y"] == v.y
| Make member_access into an Hypothesis test | tests/member_access: Make member_access into an Hypothesis test
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector | from hypothesis import given
import pytest # type: ignore
from ppb_vector import Vector
from utils import vectors
@pytest.fixture()
def vector():
return Vector(10, 20)
def test_class_member_access(vector):
assert vector.x == 10
assert vector.y == 20
@given(v=vectors())
def test_index_access(v: Vector):
assert v[0] == v.x
assert v[1] == v.y
@given(v=vectors())
def test_key_access(v: Vector):
assert v["x"] == v.x
assert v["y"] == v.y
tests/member_access: Make member_access into an Hypothesis test | from hypothesis import given
from ppb_vector import Vector
from utils import floats, vectors
@given(x=floats(), y=floats())
def test_class_member_access(x: float, y: float):
v = Vector(x, y)
assert v.x == x
assert v.y == y
@given(v=vectors())
def test_index_access(v: Vector):
assert v[0] == v.x
assert v[1] == v.y
@given(v=vectors())
def test_key_access(v: Vector):
assert v["x"] == v.x
assert v["y"] == v.y
| <commit_before>from hypothesis import given
import pytest # type: ignore
from ppb_vector import Vector
from utils import vectors
@pytest.fixture()
def vector():
return Vector(10, 20)
def test_class_member_access(vector):
assert vector.x == 10
assert vector.y == 20
@given(v=vectors())
def test_index_access(v: Vector):
assert v[0] == v.x
assert v[1] == v.y
@given(v=vectors())
def test_key_access(v: Vector):
assert v["x"] == v.x
assert v["y"] == v.y
<commit_msg>tests/member_access: Make member_access into an Hypothesis test<commit_after> | from hypothesis import given
from ppb_vector import Vector
from utils import floats, vectors
@given(x=floats(), y=floats())
def test_class_member_access(x: float, y: float):
v = Vector(x, y)
assert v.x == x
assert v.y == y
@given(v=vectors())
def test_index_access(v: Vector):
assert v[0] == v.x
assert v[1] == v.y
@given(v=vectors())
def test_key_access(v: Vector):
assert v["x"] == v.x
assert v["y"] == v.y
| from hypothesis import given
import pytest # type: ignore
from ppb_vector import Vector
from utils import vectors
@pytest.fixture()
def vector():
return Vector(10, 20)
def test_class_member_access(vector):
assert vector.x == 10
assert vector.y == 20
@given(v=vectors())
def test_index_access(v: Vector):
assert v[0] == v.x
assert v[1] == v.y
@given(v=vectors())
def test_key_access(v: Vector):
assert v["x"] == v.x
assert v["y"] == v.y
tests/member_access: Make member_access into an Hypothesis testfrom hypothesis import given
from ppb_vector import Vector
from utils import floats, vectors
@given(x=floats(), y=floats())
def test_class_member_access(x: float, y: float):
v = Vector(x, y)
assert v.x == x
assert v.y == y
@given(v=vectors())
def test_index_access(v: Vector):
assert v[0] == v.x
assert v[1] == v.y
@given(v=vectors())
def test_key_access(v: Vector):
assert v["x"] == v.x
assert v["y"] == v.y
| <commit_before>from hypothesis import given
import pytest # type: ignore
from ppb_vector import Vector
from utils import vectors
@pytest.fixture()
def vector():
return Vector(10, 20)
def test_class_member_access(vector):
assert vector.x == 10
assert vector.y == 20
@given(v=vectors())
def test_index_access(v: Vector):
assert v[0] == v.x
assert v[1] == v.y
@given(v=vectors())
def test_key_access(v: Vector):
assert v["x"] == v.x
assert v["y"] == v.y
<commit_msg>tests/member_access: Make member_access into an Hypothesis test<commit_after>from hypothesis import given
from ppb_vector import Vector
from utils import floats, vectors
@given(x=floats(), y=floats())
def test_class_member_access(x: float, y: float):
v = Vector(x, y)
assert v.x == x
assert v.y == y
@given(v=vectors())
def test_index_access(v: Vector):
assert v[0] == v.x
assert v[1] == v.y
@given(v=vectors())
def test_key_access(v: Vector):
assert v["x"] == v.x
assert v["y"] == v.y
|
d93af9d0dcf09cd49071fc7f46d40e8fda30f96e | python/setup_fsurfer_backend.py | python/setup_fsurfer_backend.py | #!/usr/bin/env python
# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurf on OSG Connect login
from distutils.core import setup
setup(name='fsurfer-backend',
version='PKG_VERSION',
description='Scripts to handle background freesurfer processing',
author='Suchandra Thapa',
author_email='sthapa@ci.uchicago.edu',
url='https://github.com/OSGConnect/freesurfer_workflow',
scripts=['process_mri.py',
'update_fsurf_job.py',
'purge_inputs.py',
'purge_results.py',
'warn_purge.py',
'delete_jobs.py',
'fsurf_user_admin.py'],
license='Apache 2.0')
| #!/usr/bin/env python
# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurf on OSG Connect login
from distutils.core import setup
setup(name='fsurfer-backend',
version='PKG_VERSION',
description='Scripts to handle background freesurfer processing',
author='Suchandra Thapa',
author_email='sthapa@ci.uchicago.edu',
url='https://github.com/OSGConnect/freesurfer_workflow',
scripts=['process_mri.py',
'update_fsurf_job.py',
'purge_inputs.py',
'purge_results.py',
'warn_purge.py',
'delete_jobs.py',
'task_completed.py',
'fsurf_user_admin.py'],
license='Apache 2.0')
| Include new script in packaging | Include new script in packaging
| Python | apache-2.0 | OSGConnect/freesurfer_workflow,OSGConnect/freesurfer_workflow | #!/usr/bin/env python
# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurf on OSG Connect login
from distutils.core import setup
setup(name='fsurfer-backend',
version='PKG_VERSION',
description='Scripts to handle background freesurfer processing',
author='Suchandra Thapa',
author_email='sthapa@ci.uchicago.edu',
url='https://github.com/OSGConnect/freesurfer_workflow',
scripts=['process_mri.py',
'update_fsurf_job.py',
'purge_inputs.py',
'purge_results.py',
'warn_purge.py',
'delete_jobs.py',
'fsurf_user_admin.py'],
license='Apache 2.0')
Include new script in packaging | #!/usr/bin/env python
# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurf on OSG Connect login
from distutils.core import setup
setup(name='fsurfer-backend',
version='PKG_VERSION',
description='Scripts to handle background freesurfer processing',
author='Suchandra Thapa',
author_email='sthapa@ci.uchicago.edu',
url='https://github.com/OSGConnect/freesurfer_workflow',
scripts=['process_mri.py',
'update_fsurf_job.py',
'purge_inputs.py',
'purge_results.py',
'warn_purge.py',
'delete_jobs.py',
'task_completed.py',
'fsurf_user_admin.py'],
license='Apache 2.0')
| <commit_before>#!/usr/bin/env python
# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurf on OSG Connect login
from distutils.core import setup
setup(name='fsurfer-backend',
version='PKG_VERSION',
description='Scripts to handle background freesurfer processing',
author='Suchandra Thapa',
author_email='sthapa@ci.uchicago.edu',
url='https://github.com/OSGConnect/freesurfer_workflow',
scripts=['process_mri.py',
'update_fsurf_job.py',
'purge_inputs.py',
'purge_results.py',
'warn_purge.py',
'delete_jobs.py',
'fsurf_user_admin.py'],
license='Apache 2.0')
<commit_msg>Include new script in packaging<commit_after> | #!/usr/bin/env python
# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurf on OSG Connect login
from distutils.core import setup
setup(name='fsurfer-backend',
version='PKG_VERSION',
description='Scripts to handle background freesurfer processing',
author='Suchandra Thapa',
author_email='sthapa@ci.uchicago.edu',
url='https://github.com/OSGConnect/freesurfer_workflow',
scripts=['process_mri.py',
'update_fsurf_job.py',
'purge_inputs.py',
'purge_results.py',
'warn_purge.py',
'delete_jobs.py',
'task_completed.py',
'fsurf_user_admin.py'],
license='Apache 2.0')
| #!/usr/bin/env python
# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurf on OSG Connect login
from distutils.core import setup
setup(name='fsurfer-backend',
version='PKG_VERSION',
description='Scripts to handle background freesurfer processing',
author='Suchandra Thapa',
author_email='sthapa@ci.uchicago.edu',
url='https://github.com/OSGConnect/freesurfer_workflow',
scripts=['process_mri.py',
'update_fsurf_job.py',
'purge_inputs.py',
'purge_results.py',
'warn_purge.py',
'delete_jobs.py',
'fsurf_user_admin.py'],
license='Apache 2.0')
Include new script in packaging#!/usr/bin/env python
# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurf on OSG Connect login
from distutils.core import setup
setup(name='fsurfer-backend',
version='PKG_VERSION',
description='Scripts to handle background freesurfer processing',
author='Suchandra Thapa',
author_email='sthapa@ci.uchicago.edu',
url='https://github.com/OSGConnect/freesurfer_workflow',
scripts=['process_mri.py',
'update_fsurf_job.py',
'purge_inputs.py',
'purge_results.py',
'warn_purge.py',
'delete_jobs.py',
'task_completed.py',
'fsurf_user_admin.py'],
license='Apache 2.0')
| <commit_before>#!/usr/bin/env python
# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurf on OSG Connect login
from distutils.core import setup
setup(name='fsurfer-backend',
version='PKG_VERSION',
description='Scripts to handle background freesurfer processing',
author='Suchandra Thapa',
author_email='sthapa@ci.uchicago.edu',
url='https://github.com/OSGConnect/freesurfer_workflow',
scripts=['process_mri.py',
'update_fsurf_job.py',
'purge_inputs.py',
'purge_results.py',
'warn_purge.py',
'delete_jobs.py',
'fsurf_user_admin.py'],
license='Apache 2.0')
<commit_msg>Include new script in packaging<commit_after>#!/usr/bin/env python
# Copyright 2015 University of Chicago
# Available under Apache 2.0 License
# setup for fsurf on OSG Connect login
from distutils.core import setup
setup(name='fsurfer-backend',
version='PKG_VERSION',
description='Scripts to handle background freesurfer processing',
author='Suchandra Thapa',
author_email='sthapa@ci.uchicago.edu',
url='https://github.com/OSGConnect/freesurfer_workflow',
scripts=['process_mri.py',
'update_fsurf_job.py',
'purge_inputs.py',
'purge_results.py',
'warn_purge.py',
'delete_jobs.py',
'task_completed.py',
'fsurf_user_admin.py'],
license='Apache 2.0')
|
12cfaa0bf758a78d854e917f357ac2913d4e73c6 | tools/win32build/doall.py | tools/win32build/doall.py | import subprocess
import os
PYVER = "2.5"
# Bootstrap
subprocess.check_call(['python', 'prepare_bootstrap.py'])
# Build binaries
subprocess.check_call(['python', 'build.py', '-p', PYVER], cwd = 'bootstrap-%s' % PYVER)
# Build installer using nsis
subprocess.check_call(['makensis', 'numpy-superinstaller.nsi'], cwd = 'bootstrap-%s' % PYVER)
| import subprocess
import os
PYVER = "2.5"
# Bootstrap
subprocess.check_call(['python', 'prepare_bootstrap.py', '-p', PYVER])
# Build binaries
subprocess.check_call(['python', 'build.py', '-p', PYVER], cwd = 'bootstrap-%s' % PYVER)
# Build installer using nsis
subprocess.check_call(['makensis', 'numpy-superinstaller.nsi'], cwd = 'bootstrap-%s' % PYVER)
| Handle python version in prepare_bootstrap script. | Handle python version in prepare_bootstrap script.
| Python | bsd-3-clause | BabeNovelty/numpy,matthew-brett/numpy,empeeu/numpy,hainm/numpy,GrimDerp/numpy,tdsmith/numpy,mhvk/numpy,rmcgibbo/numpy,mindw/numpy,ogrisel/numpy,stefanv/numpy,trankmichael/numpy,brandon-rhodes/numpy,GaZ3ll3/numpy,GrimDerp/numpy,ajdawson/numpy,jschueller/numpy,tdsmith/numpy,endolith/numpy,sonnyhu/numpy,rgommers/numpy,cowlicks/numpy,madphysicist/numpy,cjermain/numpy,sigma-random/numpy,dimasad/numpy,sigma-random/numpy,tacaswell/numpy,pizzathief/numpy,ddasilva/numpy,rherault-insa/numpy,jankoslavic/numpy,bmorris3/numpy,kirillzhuravlev/numpy,CMartelLML/numpy,ddasilva/numpy,SunghanKim/numpy,bertrand-l/numpy,rgommers/numpy,yiakwy/numpy,dato-code/numpy,dimasad/numpy,pelson/numpy,embray/numpy,WarrenWeckesser/numpy,KaelChen/numpy,ESSS/numpy,pizzathief/numpy,WillieMaddox/numpy,ajdawson/numpy,tdsmith/numpy,rudimeier/numpy,pbrod/numpy,AustereCuriosity/numpy,CMartelLML/numpy,dato-code/numpy,empeeu/numpy,hainm/numpy,Anwesh43/numpy,ChristopherHogan/numpy,endolith/numpy,KaelChen/numpy,ChristopherHogan/numpy,cjermain/numpy,chatcannon/numpy,ajdawson/numpy,ssanderson/numpy,jakirkham/numpy,mingwpy/numpy,ogrisel/numpy,Eric89GXL/numpy,grlee77/numpy,ChristopherHogan/numpy,drasmuss/numpy,astrofrog/numpy,dwf/numpy,shoyer/numpy,WarrenWeckesser/numpy,mwiebe/numpy,bertrand-l/numpy,dato-code/numpy,joferkington/numpy,solarjoe/numpy,charris/numpy,ESSS/numpy,ogrisel/numpy,bringingheavendown/numpy,mingwpy/numpy,mortada/numpy,endolith/numpy,ChanderG/numpy,astrofrog/numpy,nbeaver/numpy,empeeu/numpy,tynn/numpy,ddasilva/numpy,nguyentu1602/numpy,behzadnouri/numpy,dato-code/numpy,charris/numpy,pbrod/numpy,BMJHayward/numpy,numpy/numpy,charris/numpy,argriffing/numpy,Yusa95/numpy,MSeifert04/numpy,skwbc/numpy,MaPePeR/numpy,Eric89GXL/numpy,ahaldane/numpy,mhvk/numpy,mattip/numpy,argriffing/numpy,MaPePeR/numpy,dimasad/numpy,rajathkumarmp/numpy,mhvk/numpy,naritta/numpy,embray/numpy,sinhrks/numpy,grlee77/numpy,nbeaver/numpy,mattip/numpy,bringingheavendown/numpy,rgommers/numpy,empeeu/numpy,astrofrog/numpy,trankmichael/numpy,stuarteberg/numpy,mindw/numpy,moreati/numpy,has2k1/numpy,nbeaver/numpy,sinhrks/numpy,SunghanKim/numpy,nguyentu1602/numpy,NextThought/pypy-numpy,yiakwy/numpy,sigma-random/numpy,felipebetancur/numpy,dch312/numpy,naritta/numpy,pizzathief/numpy,MaPePeR/numpy,njase/numpy,njase/numpy,gfyoung/numpy,anntzer/numpy,andsor/numpy,felipebetancur/numpy,pbrod/numpy,WillieMaddox/numpy,rherault-insa/numpy,shoyer/numpy,dch312/numpy,BMJHayward/numpy,chatcannon/numpy,ewmoore/numpy,ssanderson/numpy,ContinuumIO/numpy,bmorris3/numpy,gmcastil/numpy,drasmuss/numpy,simongibbons/numpy,jschueller/numpy,madphysicist/numpy,ChanderG/numpy,yiakwy/numpy,Srisai85/numpy,has2k1/numpy,chatcannon/numpy,embray/numpy,ogrisel/numpy,kirillzhuravlev/numpy,brandon-rhodes/numpy,maniteja123/numpy,jankoslavic/numpy,drasmuss/numpy,sigma-random/numpy,jakirkham/numpy,dwillmer/numpy,GrimDerp/numpy,behzadnouri/numpy,groutr/numpy,pyparallel/numpy,madphysicist/numpy,mattip/numpy,shoyer/numpy,dch312/numpy,NextThought/pypy-numpy,andsor/numpy,simongibbons/numpy,ahaldane/numpy,mathdd/numpy,rudimeier/numpy,BMJHayward/numpy,jorisvandenbossche/numpy,kirillzhuravlev/numpy,ahaldane/numpy,githubmlai/numpy,dwillmer/numpy,CMartelLML/numpy,rhythmsosad/numpy,Dapid/numpy,simongibbons/numpy,anntzer/numpy,jorisvandenbossche/numpy,trankmichael/numpy,gmcastil/numpy,andsor/numpy,rajathkumarmp/numpy,seberg/numpy,dimasad/numpy,githubmlai/numpy,seberg/numpy,chiffa/numpy,kirillzhuravlev/numpy,cowlicks/numpy,ekalosak/numpy,cjermain/numpy,ahaldane/numpy,shoyer/numpy,jonathanunderwood/numpy,jakirkham/numpy,mortada/numpy,KaelChen/numpy,joferkington/numpy,MichaelAquilina/numpy,Linkid/numpy,pyparallel/numpy,numpy/numpy-refactor,felipebetancur/numpy,pelson/numpy,musically-ut/numpy,jorisvandenbossche/numpy,grlee77/numpy,endolith/numpy,stefanv/numpy,pdebuyl/numpy,Linkid/numpy,ViralLeadership/numpy,sonnyhu/numpy,SiccarPoint/numpy,ContinuumIO/numpy,numpy/numpy,SiccarPoint/numpy,dwf/numpy,stuarteberg/numpy,rhythmsosad/numpy,pbrod/numpy,anntzer/numpy,larsmans/numpy,rajathkumarmp/numpy,numpy/numpy,musically-ut/numpy,simongibbons/numpy,ChanderG/numpy,Linkid/numpy,pelson/numpy,joferkington/numpy,jankoslavic/numpy,sonnyhu/numpy,stefanv/numpy,pizzathief/numpy,b-carter/numpy,BMJHayward/numpy,mortada/numpy,ekalosak/numpy,joferkington/numpy,ewmoore/numpy,abalkin/numpy,pdebuyl/numpy,cjermain/numpy,numpy/numpy-refactor,ewmoore/numpy,Linkid/numpy,dwf/numpy,pelson/numpy,NextThought/pypy-numpy,simongibbons/numpy,anntzer/numpy,SunghanKim/numpy,cowlicks/numpy,BabeNovelty/numpy,Eric89GXL/numpy,b-carter/numpy,mattip/numpy,stefanv/numpy,mingwpy/numpy,kiwifb/numpy,argriffing/numpy,embray/numpy,mathdd/numpy,jankoslavic/numpy,larsmans/numpy,BabeNovelty/numpy,skymanaditya1/numpy,musically-ut/numpy,charris/numpy,bmorris3/numpy,nguyentu1602/numpy,skymanaditya1/numpy,mwiebe/numpy,ChanderG/numpy,ahaldane/numpy,MSeifert04/numpy,kiwifb/numpy,ekalosak/numpy,jonathanunderwood/numpy,njase/numpy,MSeifert04/numpy,GaZ3ll3/numpy,pbrod/numpy,mingwpy/numpy,stefanv/numpy,Anwesh43/numpy,skwbc/numpy,rmcgibbo/numpy,Srisai85/numpy,rmcgibbo/numpy,dwillmer/numpy,SiccarPoint/numpy,grlee77/numpy,tynn/numpy,maniteja123/numpy,embray/numpy,rhythmsosad/numpy,ajdawson/numpy,AustereCuriosity/numpy,kiwifb/numpy,naritta/numpy,ESSS/numpy,madphysicist/numpy,tacaswell/numpy,skwbc/numpy,dwf/numpy,dwf/numpy,immerrr/numpy,behzadnouri/numpy,githubmlai/numpy,bertrand-l/numpy,MichaelAquilina/numpy,pizzathief/numpy,GaZ3ll3/numpy,mathdd/numpy,Dapid/numpy,SiccarPoint/numpy,WarrenWeckesser/numpy,mindw/numpy,Anwesh43/numpy,Anwesh43/numpy,solarjoe/numpy,nguyentu1602/numpy,ViralLeadership/numpy,mathdd/numpy,madphysicist/numpy,astrofrog/numpy,groutr/numpy,felipebetancur/numpy,mhvk/numpy,moreati/numpy,MSeifert04/numpy,jonathanunderwood/numpy,skymanaditya1/numpy,trankmichael/numpy,numpy/numpy,maniteja123/numpy,larsmans/numpy,Dapid/numpy,rajathkumarmp/numpy,jakirkham/numpy,numpy/numpy-refactor,dwillmer/numpy,bmorris3/numpy,pelson/numpy,larsmans/numpy,chiffa/numpy,numpy/numpy-refactor,Eric89GXL/numpy,matthew-brett/numpy,brandon-rhodes/numpy,abalkin/numpy,naritta/numpy,BabeNovelty/numpy,MSeifert04/numpy,Srisai85/numpy,immerrr/numpy,skymanaditya1/numpy,pyparallel/numpy,pdebuyl/numpy,grlee77/numpy,utke1/numpy,Yusa95/numpy,mhvk/numpy,hainm/numpy,hainm/numpy,leifdenby/numpy,matthew-brett/numpy,dch312/numpy,rudimeier/numpy,mwiebe/numpy,seberg/numpy,matthew-brett/numpy,SunghanKim/numpy,seberg/numpy,WarrenWeckesser/numpy,leifdenby/numpy,moreati/numpy,jorisvandenbossche/numpy,solarjoe/numpy,WarrenWeckesser/numpy,stuarteberg/numpy,ekalosak/numpy,GrimDerp/numpy,Yusa95/numpy,GaZ3ll3/numpy,mortada/numpy,rgommers/numpy,pdebuyl/numpy,ewmoore/numpy,tacaswell/numpy,rmcgibbo/numpy,Srisai85/numpy,b-carter/numpy,ViralLeadership/numpy,sonnyhu/numpy,tynn/numpy,has2k1/numpy,ogrisel/numpy,NextThought/pypy-numpy,astrofrog/numpy,MaPePeR/numpy,cowlicks/numpy,tdsmith/numpy,gfyoung/numpy,ChristopherHogan/numpy,jschueller/numpy,jakirkham/numpy,numpy/numpy-refactor,sinhrks/numpy,jorisvandenbossche/numpy,KaelChen/numpy,jschueller/numpy,sinhrks/numpy,ewmoore/numpy,stuarteberg/numpy,rudimeier/numpy,ContinuumIO/numpy,AustereCuriosity/numpy,matthew-brett/numpy,utke1/numpy,has2k1/numpy,utke1/numpy,mindw/numpy,rherault-insa/numpy,gfyoung/numpy,MichaelAquilina/numpy,ssanderson/numpy,bringingheavendown/numpy,chiffa/numpy,yiakwy/numpy,groutr/numpy,brandon-rhodes/numpy,immerrr/numpy,musically-ut/numpy,andsor/numpy,shoyer/numpy,Yusa95/numpy,leifdenby/numpy,abalkin/numpy,githubmlai/numpy,MichaelAquilina/numpy,rhythmsosad/numpy,immerrr/numpy,CMartelLML/numpy,gmcastil/numpy,WillieMaddox/numpy | import subprocess
import os
PYVER = "2.5"
# Bootstrap
subprocess.check_call(['python', 'prepare_bootstrap.py'])
# Build binaries
subprocess.check_call(['python', 'build.py', '-p', PYVER], cwd = 'bootstrap-%s' % PYVER)
# Build installer using nsis
subprocess.check_call(['makensis', 'numpy-superinstaller.nsi'], cwd = 'bootstrap-%s' % PYVER)
Handle python version in prepare_bootstrap script. | import subprocess
import os
PYVER = "2.5"
# Bootstrap
subprocess.check_call(['python', 'prepare_bootstrap.py', '-p', PYVER])
# Build binaries
subprocess.check_call(['python', 'build.py', '-p', PYVER], cwd = 'bootstrap-%s' % PYVER)
# Build installer using nsis
subprocess.check_call(['makensis', 'numpy-superinstaller.nsi'], cwd = 'bootstrap-%s' % PYVER)
| <commit_before>import subprocess
import os
PYVER = "2.5"
# Bootstrap
subprocess.check_call(['python', 'prepare_bootstrap.py'])
# Build binaries
subprocess.check_call(['python', 'build.py', '-p', PYVER], cwd = 'bootstrap-%s' % PYVER)
# Build installer using nsis
subprocess.check_call(['makensis', 'numpy-superinstaller.nsi'], cwd = 'bootstrap-%s' % PYVER)
<commit_msg>Handle python version in prepare_bootstrap script.<commit_after> | import subprocess
import os
PYVER = "2.5"
# Bootstrap
subprocess.check_call(['python', 'prepare_bootstrap.py', '-p', PYVER])
# Build binaries
subprocess.check_call(['python', 'build.py', '-p', PYVER], cwd = 'bootstrap-%s' % PYVER)
# Build installer using nsis
subprocess.check_call(['makensis', 'numpy-superinstaller.nsi'], cwd = 'bootstrap-%s' % PYVER)
| import subprocess
import os
PYVER = "2.5"
# Bootstrap
subprocess.check_call(['python', 'prepare_bootstrap.py'])
# Build binaries
subprocess.check_call(['python', 'build.py', '-p', PYVER], cwd = 'bootstrap-%s' % PYVER)
# Build installer using nsis
subprocess.check_call(['makensis', 'numpy-superinstaller.nsi'], cwd = 'bootstrap-%s' % PYVER)
Handle python version in prepare_bootstrap script.import subprocess
import os
PYVER = "2.5"
# Bootstrap
subprocess.check_call(['python', 'prepare_bootstrap.py', '-p', PYVER])
# Build binaries
subprocess.check_call(['python', 'build.py', '-p', PYVER], cwd = 'bootstrap-%s' % PYVER)
# Build installer using nsis
subprocess.check_call(['makensis', 'numpy-superinstaller.nsi'], cwd = 'bootstrap-%s' % PYVER)
| <commit_before>import subprocess
import os
PYVER = "2.5"
# Bootstrap
subprocess.check_call(['python', 'prepare_bootstrap.py'])
# Build binaries
subprocess.check_call(['python', 'build.py', '-p', PYVER], cwd = 'bootstrap-%s' % PYVER)
# Build installer using nsis
subprocess.check_call(['makensis', 'numpy-superinstaller.nsi'], cwd = 'bootstrap-%s' % PYVER)
<commit_msg>Handle python version in prepare_bootstrap script.<commit_after>import subprocess
import os
PYVER = "2.5"
# Bootstrap
subprocess.check_call(['python', 'prepare_bootstrap.py', '-p', PYVER])
# Build binaries
subprocess.check_call(['python', 'build.py', '-p', PYVER], cwd = 'bootstrap-%s' % PYVER)
# Build installer using nsis
subprocess.check_call(['makensis', 'numpy-superinstaller.nsi'], cwd = 'bootstrap-%s' % PYVER)
|
9a154b8893a3306e5350a9118e9cfb582d295322 | traccar_graphql/schema.py | traccar_graphql/schema.py | import os, graphene, requests
from flask_jwt_extended import get_jwt_identity, get_jwt_claims
from graphql import GraphQLError
from traccar_graphql.models import ServerType, UserType
from traccar_graphql.mutations import LoginType, RegisterType
from traccar_graphql.utils import request2object
TRACCAR_BACKEND = os.environ.get('TRACCAR_BACKEND')
class Query(graphene.ObjectType):
server = graphene.Field(lambda: ServerType)
me = graphene.Field(lambda: UserType)
def resolve_server(self, args, context, info):
r = requests.get("{}/api/server".format(TRACCAR_BACKEND))
return request2object(r, 'ServerType')
def resolve_me(self, args, context, info):
claims = get_jwt_claims()
if 'session' not in claims:
raise GraphQLError('Authentication required')
headers = { 'Cookie': claims['session'] }
r = requests.get("{}/api/session".format(TRACCAR_BACKEND), headers=headers)
return request2object(r, 'UserType')
class Mutation(graphene.ObjectType):
login = LoginType.Field()
register = RegisterType.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
| import os, graphene, requests
from flask_jwt_extended import get_jwt_identity, get_jwt_claims
from graphql import GraphQLError
from traccar_graphql.models import ServerType, UserType
from traccar_graphql.mutations import LoginType, RegisterType
from traccar_graphql.utils import request2object
TRACCAR_BACKEND = os.environ.get('TRACCAR_BACKEND')
class Query(graphene.ObjectType):
server = graphene.Field(lambda: ServerType)
def resolve_server(self, args, context, info):
r = requests.get("{}/api/server".format(TRACCAR_BACKEND))
return request2object(r, 'ServerType')
me = graphene.Field(lambda: UserType)
def resolve_me(self, args, context, info):
claims = get_jwt_claims()
if 'session' not in claims:
raise GraphQLError('Authentication required')
headers = { 'Cookie': claims['session'] }
r = requests.get("{}/api/session".format(TRACCAR_BACKEND), headers=headers)
if r.status_code == 404:
raise GraphQLError('Authentication required')
return request2object(r, 'UserType')
class Mutation(graphene.ObjectType):
login = LoginType.Field()
register = RegisterType.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
| Handle sign in failure from traccar | Handle sign in failure from traccar
| Python | mit | sunhoww/traccar_graphql | import os, graphene, requests
from flask_jwt_extended import get_jwt_identity, get_jwt_claims
from graphql import GraphQLError
from traccar_graphql.models import ServerType, UserType
from traccar_graphql.mutations import LoginType, RegisterType
from traccar_graphql.utils import request2object
TRACCAR_BACKEND = os.environ.get('TRACCAR_BACKEND')
class Query(graphene.ObjectType):
server = graphene.Field(lambda: ServerType)
me = graphene.Field(lambda: UserType)
def resolve_server(self, args, context, info):
r = requests.get("{}/api/server".format(TRACCAR_BACKEND))
return request2object(r, 'ServerType')
def resolve_me(self, args, context, info):
claims = get_jwt_claims()
if 'session' not in claims:
raise GraphQLError('Authentication required')
headers = { 'Cookie': claims['session'] }
r = requests.get("{}/api/session".format(TRACCAR_BACKEND), headers=headers)
return request2object(r, 'UserType')
class Mutation(graphene.ObjectType):
login = LoginType.Field()
register = RegisterType.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
Handle sign in failure from traccar | import os, graphene, requests
from flask_jwt_extended import get_jwt_identity, get_jwt_claims
from graphql import GraphQLError
from traccar_graphql.models import ServerType, UserType
from traccar_graphql.mutations import LoginType, RegisterType
from traccar_graphql.utils import request2object
TRACCAR_BACKEND = os.environ.get('TRACCAR_BACKEND')
class Query(graphene.ObjectType):
server = graphene.Field(lambda: ServerType)
def resolve_server(self, args, context, info):
r = requests.get("{}/api/server".format(TRACCAR_BACKEND))
return request2object(r, 'ServerType')
me = graphene.Field(lambda: UserType)
def resolve_me(self, args, context, info):
claims = get_jwt_claims()
if 'session' not in claims:
raise GraphQLError('Authentication required')
headers = { 'Cookie': claims['session'] }
r = requests.get("{}/api/session".format(TRACCAR_BACKEND), headers=headers)
if r.status_code == 404:
raise GraphQLError('Authentication required')
return request2object(r, 'UserType')
class Mutation(graphene.ObjectType):
login = LoginType.Field()
register = RegisterType.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
| <commit_before>import os, graphene, requests
from flask_jwt_extended import get_jwt_identity, get_jwt_claims
from graphql import GraphQLError
from traccar_graphql.models import ServerType, UserType
from traccar_graphql.mutations import LoginType, RegisterType
from traccar_graphql.utils import request2object
TRACCAR_BACKEND = os.environ.get('TRACCAR_BACKEND')
class Query(graphene.ObjectType):
server = graphene.Field(lambda: ServerType)
me = graphene.Field(lambda: UserType)
def resolve_server(self, args, context, info):
r = requests.get("{}/api/server".format(TRACCAR_BACKEND))
return request2object(r, 'ServerType')
def resolve_me(self, args, context, info):
claims = get_jwt_claims()
if 'session' not in claims:
raise GraphQLError('Authentication required')
headers = { 'Cookie': claims['session'] }
r = requests.get("{}/api/session".format(TRACCAR_BACKEND), headers=headers)
return request2object(r, 'UserType')
class Mutation(graphene.ObjectType):
login = LoginType.Field()
register = RegisterType.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
<commit_msg>Handle sign in failure from traccar<commit_after> | import os, graphene, requests
from flask_jwt_extended import get_jwt_identity, get_jwt_claims
from graphql import GraphQLError
from traccar_graphql.models import ServerType, UserType
from traccar_graphql.mutations import LoginType, RegisterType
from traccar_graphql.utils import request2object
TRACCAR_BACKEND = os.environ.get('TRACCAR_BACKEND')
class Query(graphene.ObjectType):
server = graphene.Field(lambda: ServerType)
def resolve_server(self, args, context, info):
r = requests.get("{}/api/server".format(TRACCAR_BACKEND))
return request2object(r, 'ServerType')
me = graphene.Field(lambda: UserType)
def resolve_me(self, args, context, info):
claims = get_jwt_claims()
if 'session' not in claims:
raise GraphQLError('Authentication required')
headers = { 'Cookie': claims['session'] }
r = requests.get("{}/api/session".format(TRACCAR_BACKEND), headers=headers)
if r.status_code == 404:
raise GraphQLError('Authentication required')
return request2object(r, 'UserType')
class Mutation(graphene.ObjectType):
login = LoginType.Field()
register = RegisterType.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
| import os, graphene, requests
from flask_jwt_extended import get_jwt_identity, get_jwt_claims
from graphql import GraphQLError
from traccar_graphql.models import ServerType, UserType
from traccar_graphql.mutations import LoginType, RegisterType
from traccar_graphql.utils import request2object
TRACCAR_BACKEND = os.environ.get('TRACCAR_BACKEND')
class Query(graphene.ObjectType):
server = graphene.Field(lambda: ServerType)
me = graphene.Field(lambda: UserType)
def resolve_server(self, args, context, info):
r = requests.get("{}/api/server".format(TRACCAR_BACKEND))
return request2object(r, 'ServerType')
def resolve_me(self, args, context, info):
claims = get_jwt_claims()
if 'session' not in claims:
raise GraphQLError('Authentication required')
headers = { 'Cookie': claims['session'] }
r = requests.get("{}/api/session".format(TRACCAR_BACKEND), headers=headers)
return request2object(r, 'UserType')
class Mutation(graphene.ObjectType):
login = LoginType.Field()
register = RegisterType.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
Handle sign in failure from traccarimport os, graphene, requests
from flask_jwt_extended import get_jwt_identity, get_jwt_claims
from graphql import GraphQLError
from traccar_graphql.models import ServerType, UserType
from traccar_graphql.mutations import LoginType, RegisterType
from traccar_graphql.utils import request2object
TRACCAR_BACKEND = os.environ.get('TRACCAR_BACKEND')
class Query(graphene.ObjectType):
server = graphene.Field(lambda: ServerType)
def resolve_server(self, args, context, info):
r = requests.get("{}/api/server".format(TRACCAR_BACKEND))
return request2object(r, 'ServerType')
me = graphene.Field(lambda: UserType)
def resolve_me(self, args, context, info):
claims = get_jwt_claims()
if 'session' not in claims:
raise GraphQLError('Authentication required')
headers = { 'Cookie': claims['session'] }
r = requests.get("{}/api/session".format(TRACCAR_BACKEND), headers=headers)
if r.status_code == 404:
raise GraphQLError('Authentication required')
return request2object(r, 'UserType')
class Mutation(graphene.ObjectType):
login = LoginType.Field()
register = RegisterType.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
| <commit_before>import os, graphene, requests
from flask_jwt_extended import get_jwt_identity, get_jwt_claims
from graphql import GraphQLError
from traccar_graphql.models import ServerType, UserType
from traccar_graphql.mutations import LoginType, RegisterType
from traccar_graphql.utils import request2object
TRACCAR_BACKEND = os.environ.get('TRACCAR_BACKEND')
class Query(graphene.ObjectType):
server = graphene.Field(lambda: ServerType)
me = graphene.Field(lambda: UserType)
def resolve_server(self, args, context, info):
r = requests.get("{}/api/server".format(TRACCAR_BACKEND))
return request2object(r, 'ServerType')
def resolve_me(self, args, context, info):
claims = get_jwt_claims()
if 'session' not in claims:
raise GraphQLError('Authentication required')
headers = { 'Cookie': claims['session'] }
r = requests.get("{}/api/session".format(TRACCAR_BACKEND), headers=headers)
return request2object(r, 'UserType')
class Mutation(graphene.ObjectType):
login = LoginType.Field()
register = RegisterType.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
<commit_msg>Handle sign in failure from traccar<commit_after>import os, graphene, requests
from flask_jwt_extended import get_jwt_identity, get_jwt_claims
from graphql import GraphQLError
from traccar_graphql.models import ServerType, UserType
from traccar_graphql.mutations import LoginType, RegisterType
from traccar_graphql.utils import request2object
TRACCAR_BACKEND = os.environ.get('TRACCAR_BACKEND')
class Query(graphene.ObjectType):
server = graphene.Field(lambda: ServerType)
def resolve_server(self, args, context, info):
r = requests.get("{}/api/server".format(TRACCAR_BACKEND))
return request2object(r, 'ServerType')
me = graphene.Field(lambda: UserType)
def resolve_me(self, args, context, info):
claims = get_jwt_claims()
if 'session' not in claims:
raise GraphQLError('Authentication required')
headers = { 'Cookie': claims['session'] }
r = requests.get("{}/api/session".format(TRACCAR_BACKEND), headers=headers)
if r.status_code == 404:
raise GraphQLError('Authentication required')
return request2object(r, 'UserType')
class Mutation(graphene.ObjectType):
login = LoginType.Field()
register = RegisterType.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
|
66035a6e3e7729c53278193d4307751b36ace6eb | fullcalendar/admin.py | fullcalendar/admin.py | from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import TabularDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(TabularDynamicInlineAdmin):
model = Occurrence
extra = 1
fields = ('start_time', 'end_time', 'description')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'event_category')
list_filter = ('event_category',)
search_fields = ('title', 'description', 'content', 'keywords')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
| from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(StackedDynamicInlineAdmin):
model = Occurrence
extra = 1
fields = ('start_time', 'end_time', 'description', 'location')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'event_category')
list_filter = ('event_category',)
search_fields = ('title', 'description', 'content', 'keywords')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
| Change to stacked inline for occurrences, also display location. | Change to stacked inline for occurrences, also display location.
| Python | mit | jonge-democraten/mezzanine-fullcalendar | from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import TabularDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(TabularDynamicInlineAdmin):
model = Occurrence
extra = 1
fields = ('start_time', 'end_time', 'description')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'event_category')
list_filter = ('event_category',)
search_fields = ('title', 'description', 'content', 'keywords')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
Change to stacked inline for occurrences, also display location. | from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(StackedDynamicInlineAdmin):
model = Occurrence
extra = 1
fields = ('start_time', 'end_time', 'description', 'location')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'event_category')
list_filter = ('event_category',)
search_fields = ('title', 'description', 'content', 'keywords')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
| <commit_before>from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import TabularDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(TabularDynamicInlineAdmin):
model = Occurrence
extra = 1
fields = ('start_time', 'end_time', 'description')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'event_category')
list_filter = ('event_category',)
search_fields = ('title', 'description', 'content', 'keywords')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
<commit_msg>Change to stacked inline for occurrences, also display location.<commit_after> | from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(StackedDynamicInlineAdmin):
model = Occurrence
extra = 1
fields = ('start_time', 'end_time', 'description', 'location')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'event_category')
list_filter = ('event_category',)
search_fields = ('title', 'description', 'content', 'keywords')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
| from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import TabularDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(TabularDynamicInlineAdmin):
model = Occurrence
extra = 1
fields = ('start_time', 'end_time', 'description')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'event_category')
list_filter = ('event_category',)
search_fields = ('title', 'description', 'content', 'keywords')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
Change to stacked inline for occurrences, also display location.from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(StackedDynamicInlineAdmin):
model = Occurrence
extra = 1
fields = ('start_time', 'end_time', 'description', 'location')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'event_category')
list_filter = ('event_category',)
search_fields = ('title', 'description', 'content', 'keywords')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
| <commit_before>from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import TabularDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(TabularDynamicInlineAdmin):
model = Occurrence
extra = 1
fields = ('start_time', 'end_time', 'description')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'event_category')
list_filter = ('event_category',)
search_fields = ('title', 'description', 'content', 'keywords')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
<commit_msg>Change to stacked inline for occurrences, also display location.<commit_after>from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(StackedDynamicInlineAdmin):
model = Occurrence
extra = 1
fields = ('start_time', 'end_time', 'description', 'location')
class EventAdmin(DisplayableAdmin):
list_display = ('title', 'event_category')
list_filter = ('event_category',)
search_fields = ('title', 'description', 'content', 'keywords')
fieldsets = (
(None, {
"fields": [
"title", "status", ("publish_date", "expiry_date"),
"event_category", "content"
]
}),
(_("Meta data"), {
"fields": [
"_meta_title", "slug",
("description", "gen_description"),
"keywords", "in_sitemap"
],
"classes": ("collapse-closed",)
}),
)
inlines = [OccurrenceInline]
admin.site.register(Event, EventAdmin)
admin.site.register(EventCategory, EventCategoryAdmin)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.