commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4 values | license stringclasses 13 values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
dc50a4ec058f9893e87a069bc64e4715ecfa0bea | haas_rest_test/plugins/assertions.py | haas_rest_test/plugins/assertions.py | # -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
class StatusCodeAssertion(object):
_schema = {
}
def __init__(self, valid_codes):
super(StatusCodeAssertion, self).__init__()
self.valid_codes = valid_codes
@classmethod
def from_dict(cls, data):
# FIXME: Validate input with jsonschema
return cls(valid_codes=data['expected'])
| # -*- coding: utf-8 -*-
# Copyright (c) 2014 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
from jsonschema.exceptions import ValidationError
import jsonschema
from ..exceptions import YamlParseError
class StatusCodeAssertion(object):
_schema = {
'$schema': 'http://json-schema.org/draft-04/schema#',
'title': 'Assertion on status code ',
'description': 'Test case markup for Haas Rest Test',
'type': 'object',
'properties': {
'expected': {
'type': 'integer',
},
},
'required': ['expected']
}
def __init__(self, expected_status):
super(StatusCodeAssertion, self).__init__()
self.expected_status = expected_status
@classmethod
def from_dict(cls, data):
try:
jsonschema.validate(data, cls._schema)
except ValidationError as e:
raise YamlParseError(str(e))
return cls(expected_status=data['expected'])
def run(self, case, response):
case.fail()
| Add initial status code assertion | Add initial status code assertion
| Python | bsd-3-clause | sjagoe/usagi | ---
+++
@@ -6,17 +6,38 @@
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import, unicode_literals
+from jsonschema.exceptions import ValidationError
+import jsonschema
+
+from ..exceptions import YamlParseError
+
class StatusCodeAssertion(object):
_schema = {
+ '$schema': 'http://json-schema.org/draft-04/schema#',
+ 'title': 'Assertion on status code ',
+ 'description': 'Test case markup for Haas Rest Test',
+ 'type': 'object',
+ 'properties': {
+ 'expected': {
+ 'type': 'integer',
+ },
+ },
+ 'required': ['expected']
}
- def __init__(self, valid_codes):
+ def __init__(self, expected_status):
super(StatusCodeAssertion, self).__init__()
- self.valid_codes = valid_codes
+ self.expected_status = expected_status
@classmethod
def from_dict(cls, data):
- # FIXME: Validate input with jsonschema
- return cls(valid_codes=data['expected'])
+ try:
+ jsonschema.validate(data, cls._schema)
+ except ValidationError as e:
+ raise YamlParseError(str(e))
+ return cls(expected_status=data['expected'])
+
+ def run(self, case, response):
+ case.fail() |
dbec204b242ab643de162046ba73dca32043c6c2 | space-age/space_age.py | space-age/space_age.py | class SpaceAge(object):
def __init__(self, seconds):
self.seconds = seconds
@property
def years(self):
return self.seconds/31557600
def on_earth(self):
return round(self.years, 2)
def on_mercury(self):
return round(self.years/0.2408467, 2)
def on_venus(self):
return round(self.years/0.6151976, 2)
def on_mars(self):
return round(self.years/1.8808158, 2)
def on_jupiter(self):
return round(self.years/11.862615, 2)
def on_saturn(self):
return round(self.years/29.447498, 2)
def on_uranus(self):
return round(self.years/84.016846, 2)
def on_neptune(self):
return round(self.years/164.79132, 2)
| class SpaceAge(object):
YEARS = {"on_earth": 1,
"on_mercury": 0.2408467,
"on_venus": 0.61519726,
"on_mars": 1.8808158,
"on_jupiter": 11.862615,
"on_saturn": 29.447498,
"on_uranus": 84.016846,
"on_neptune": 164.79132}
def __init__(self, seconds):
self.seconds = seconds
@property
def years(self):
return self.seconds/31557600
def __getattr__(self, on_planet):
if on_planet in SpaceAge.YEARS:
return lambda: round(self.years/SpaceAge.YEARS[on_planet], 2)
else:
raise AttributeError
| Implement __getattr__ to reduce code | Implement __getattr__ to reduce code
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | ---
+++
@@ -1,4 +1,13 @@
class SpaceAge(object):
+ YEARS = {"on_earth": 1,
+ "on_mercury": 0.2408467,
+ "on_venus": 0.61519726,
+ "on_mars": 1.8808158,
+ "on_jupiter": 11.862615,
+ "on_saturn": 29.447498,
+ "on_uranus": 84.016846,
+ "on_neptune": 164.79132}
+
def __init__(self, seconds):
self.seconds = seconds
@@ -6,26 +15,8 @@
def years(self):
return self.seconds/31557600
- def on_earth(self):
- return round(self.years, 2)
-
- def on_mercury(self):
- return round(self.years/0.2408467, 2)
-
- def on_venus(self):
- return round(self.years/0.6151976, 2)
-
- def on_mars(self):
- return round(self.years/1.8808158, 2)
-
- def on_jupiter(self):
- return round(self.years/11.862615, 2)
-
- def on_saturn(self):
- return round(self.years/29.447498, 2)
-
- def on_uranus(self):
- return round(self.years/84.016846, 2)
-
- def on_neptune(self):
- return round(self.years/164.79132, 2)
+ def __getattr__(self, on_planet):
+ if on_planet in SpaceAge.YEARS:
+ return lambda: round(self.years/SpaceAge.YEARS[on_planet], 2)
+ else:
+ raise AttributeError |
ea8cbcaf41f01a46390882fbc99e6e14d70a49d1 | src/mmw/apps/user/models.py | src/mmw/apps/user/models.py | # -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.db import models
class ItsiUserManager(models.Manager):
def create_itsi_user(self, user, itsi_id):
itsi_user = self.create(user=user, itsi_id=itsi_id)
return itsi_user
class ItsiUser(models.Model):
user = models.OneToOneField(User, primary_key=True)
itsi_id = models.IntegerField()
objects = ItsiUserManager()
def __unicode__(self):
return unicode(self.user.username)
| # -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
"""
Create an auth token for every newly created user.
"""
if created:
Token.objects.create(user=instance)
class ItsiUserManager(models.Manager):
def create_itsi_user(self, user, itsi_id):
itsi_user = self.create(user=user, itsi_id=itsi_id)
return itsi_user
class ItsiUser(models.Model):
user = models.OneToOneField(User, primary_key=True)
itsi_id = models.IntegerField()
objects = ItsiUserManager()
def __unicode__(self):
return unicode(self.user.username)
| Create an API auth token for every newly created user | Create an API auth token for every newly created user
* Add a post_save signal to add a new authtoken for every new user. For use with
the Geoprocessing API
| Python | apache-2.0 | WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed | ---
+++
@@ -1,6 +1,21 @@
# -*- coding: utf-8 -*-
+
+from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
+from django.db.models.signals import post_save
+from django.dispatch import receiver
+
+from rest_framework.authtoken.models import Token
+
+
+@receiver(post_save, sender=settings.AUTH_USER_MODEL)
+def create_auth_token(sender, instance=None, created=False, **kwargs):
+ """
+ Create an auth token for every newly created user.
+ """
+ if created:
+ Token.objects.create(user=instance)
class ItsiUserManager(models.Manager): |
137271045313a12bbe9388ab1ac6c8cb786b32b7 | guardian/testapp/tests/test_management.py | guardian/testapp/tests/test_management.py | from __future__ import absolute_import
from __future__ import unicode_literals
from guardian.compat import get_user_model
from guardian.compat import mock
from guardian.compat import unittest
from guardian.management import create_anonymous_user
import django
mocked_get_init_anon = mock.Mock()
class TestGetAnonymousUser(unittest.TestCase):
@unittest.skipUnless(django.VERSION >= (1, 5), "Django >= 1.5 only")
@mock.patch('guardian.management.guardian_settings')
def test_uses_custom_function(self, guardian_settings):
path = 'guardian.testapp.tests.test_management.mocked_get_init_anon'
guardian_settings.GET_INIT_ANONYMOUS_USER = path
guardian_settings.ANONYMOUS_USER_ID = 219
User = get_user_model()
anon = mocked_get_init_anon.return_value = mock.Mock()
create_anonymous_user('sender')
mocked_get_init_anon.assert_called_once_with(User)
self.assertEqual(anon.pk, 219)
anon.save.assert_called_once_with()
| from __future__ import absolute_import
from __future__ import unicode_literals
from guardian.compat import get_user_model
from guardian.compat import mock
from guardian.compat import unittest
from guardian.management import create_anonymous_user
import django
mocked_get_init_anon = mock.Mock()
class TestGetAnonymousUser(unittest.TestCase):
@unittest.skipUnless(django.VERSION >= (1, 5), "Django >= 1.5 only")
@mock.patch('guardian.management.guardian_settings')
def test_uses_custom_function(self, guardian_settings):
mocked_get_init_anon.reset_mock()
path = 'guardian.testapp.tests.test_management.mocked_get_init_anon'
guardian_settings.GET_INIT_ANONYMOUS_USER = path
guardian_settings.ANONYMOUS_USER_ID = 219
User = get_user_model()
anon = mocked_get_init_anon.return_value = mock.Mock()
create_anonymous_user('sender')
mocked_get_init_anon.assert_called_once_with(User)
self.assertEqual(anon.pk, 219)
anon.save.assert_called_once_with()
| Reset mock befor running test. | Reset mock befor running test.
Not strictly required however ensures test doesn't fail if run multiple
times in succession.
| Python | bsd-2-clause | benkonrath/django-guardian,benkonrath/django-guardian,rmgorman/django-guardian,lukaszb/django-guardian,lukaszb/django-guardian,rmgorman/django-guardian,lukaszb/django-guardian,rmgorman/django-guardian,benkonrath/django-guardian | ---
+++
@@ -16,6 +16,8 @@
@unittest.skipUnless(django.VERSION >= (1, 5), "Django >= 1.5 only")
@mock.patch('guardian.management.guardian_settings')
def test_uses_custom_function(self, guardian_settings):
+ mocked_get_init_anon.reset_mock()
+
path = 'guardian.testapp.tests.test_management.mocked_get_init_anon'
guardian_settings.GET_INIT_ANONYMOUS_USER = path
guardian_settings.ANONYMOUS_USER_ID = 219 |
30020d3826a2460288b6a57963753787020a945a | temporenc/temporenc.py | temporenc/temporenc.py |
def packb(type=None, year=None, month=None, day=None):
raise NotImplementedError()
|
import struct
SUPPORTED_TYPES = set([
'D',
'T',
'DT',
'DTZ',
'DTS',
'DTSZ',
])
STRUCT_32 = struct.Struct('>L')
def packb(type=None, year=None, month=None, day=None):
"""
Pack date and time information into a byte string.
:return: encoded temporenc value
:rtype: bytes
"""
# Input validation
if type not in SUPPORTED_TYPES:
raise ValueError("invalid temporenc type: {0!r}".format(type))
if year is None:
year = 4095
elif not 0 <= year <= 4094:
raise ValueError("'year' not in supported range")
if month is None:
month = 15
elif not 1 <= month <= 12:
raise ValueError("'month' not in supported range")
if day is None:
day = 31
elif not 1 <= day <= 31:
raise ValueError("'day' not in supported range")
# Component packing
if 'D' in type:
d = (year << 9) | (month - 1 << 5) | (day - 1)
# Byte packing
if type == 'D':
# Format: 100DDDDD DDDDDDDD DDDDDDDD
return STRUCT_32.pack(0b100 << 21 | d)[1:]
raise NotImplementedError()
| Implement support for the 'D' type in packb() | Implement support for the 'D' type in packb()
| Python | bsd-3-clause | wbolster/temporenc-python | ---
+++
@@ -1,3 +1,52 @@
+
+import struct
+
+SUPPORTED_TYPES = set([
+ 'D',
+ 'T',
+ 'DT',
+ 'DTZ',
+ 'DTS',
+ 'DTSZ',
+])
+
+STRUCT_32 = struct.Struct('>L')
+
def packb(type=None, year=None, month=None, day=None):
+ """
+ Pack date and time information into a byte string.
+
+ :return: encoded temporenc value
+ :rtype: bytes
+ """
+
+ # Input validation
+ if type not in SUPPORTED_TYPES:
+ raise ValueError("invalid temporenc type: {0!r}".format(type))
+
+ if year is None:
+ year = 4095
+ elif not 0 <= year <= 4094:
+ raise ValueError("'year' not in supported range")
+
+ if month is None:
+ month = 15
+ elif not 1 <= month <= 12:
+ raise ValueError("'month' not in supported range")
+
+ if day is None:
+ day = 31
+ elif not 1 <= day <= 31:
+ raise ValueError("'day' not in supported range")
+
+ # Component packing
+ if 'D' in type:
+ d = (year << 9) | (month - 1 << 5) | (day - 1)
+
+ # Byte packing
+ if type == 'D':
+ # Format: 100DDDDD DDDDDDDD DDDDDDDD
+ return STRUCT_32.pack(0b100 << 21 | d)[1:]
+
raise NotImplementedError() |
ce83a4fb2f650380b7683ea688791e078b6fe7ec | src/sleepy/web/views.py | src/sleepy/web/views.py | from django.contrib import messages
from django.contrib.auth import REDIRECT_FIELD_NAME, logout
from django.core.urlresolvers import reverse_lazy
from django.views.generic import RedirectView, TemplateView
from django.utils.http import is_safe_url
from django.utils.translation import ugettext
class IndexView(TemplateView):
"""View for the index page"""
template_name = 'sleepy/web/index.html'
class LogoutView(RedirectView):
url = reverse_lazy('home')
permanent = False
def dispatch(self, request, *args, **kwargs):
if request.user.is_authenticated():
logout(self.request)
messages.success(request, ugettext('You have successfully logged out.'))
return super(LogoutView, self).get(request, *args, **kwargs)
def get_redirect_url(self, *args, **kwargs):
url = super(LogoutView, self).get_redirect_url(*args, **kwargs)
next_url = self.request.REQUEST.get(REDIRECT_FIELD_NAME, None)
if next_url and is_safe_url(url=next_url, host=self.request.get_host()):
url = next_url
return url
| from django.contrib import messages
from django.contrib.auth import REDIRECT_FIELD_NAME, logout
from django.core.urlresolvers import reverse_lazy
from django.views.generic import RedirectView, TemplateView
from django.utils.http import is_safe_url
from django.utils.translation import ugettext
class IndexView(TemplateView):
"""View for the index page"""
template_name = 'sleepy/web/index.html'
class LogoutView(RedirectView):
url = reverse_lazy('sleepy-home')
permanent = False
def dispatch(self, request, *args, **kwargs):
if request.user.is_authenticated():
logout(self.request)
messages.success(request, ugettext('You have successfully logged out.'))
return super(LogoutView, self).get(request, *args, **kwargs)
def get_redirect_url(self, *args, **kwargs):
url = super(LogoutView, self).get_redirect_url(*args, **kwargs)
next_url = self.request.REQUEST.get(REDIRECT_FIELD_NAME, None)
if next_url and is_safe_url(url=next_url, host=self.request.get_host()):
url = next_url
return url
| Fix wrong redirect on logout | Fix wrong redirect on logout
| Python | bsd-3-clause | YouNeedToSleep/sleepy,YouNeedToSleep/sleepy,YouNeedToSleep/sleepy | ---
+++
@@ -12,7 +12,7 @@
class LogoutView(RedirectView):
- url = reverse_lazy('home')
+ url = reverse_lazy('sleepy-home')
permanent = False
def dispatch(self, request, *args, **kwargs): |
7b746d2d4ae732ee1eae326254f3a6df676a7973 | components/table.py | components/table.py | """A class to store tables."""
class SgTable:
"""A class to store tables."""
def __init__(self):
self._fields = []
self._table = []
def __len__(self):
return len(self._table)
def __iter__(self):
for row in self._table:
yield row
def __getitem__(self, key):
if not ((type(key) == int or type(key) == long) and key >= 0 and key < len(self._table)):
raise ValueError("Index illegal")
else:
return self._table[key]
def __setitem__(self, key, value):
if not ((type(key) == int or type(key) == long) and key >= 0 and key < len(self._table)):
raise ValueError("Index illegal")
else:
self._table[key] = value
def Append(self, row):
self._table.append(row)
def GetTable(self):
return self._table
def SetTable(self, table):
self._table = table
def GetFields(self):
return self._fields
def SetFields(self, fields):
self._fields = fields
| """A class to store tables."""
class SgTable:
"""A class to store tables."""
def __init__(self):
self._fields = []
self._table = []
def __len__(self):
return len(self._table)
def __iter__(self):
for row in self._table:
yield row
def __getitem__(self, key):
if not ((type(key) == int or type(key) == long) and key >= 0 and key < len(self._table)):
raise ValueError("Index illegal")
else:
return self._table[key]
def __setitem__(self, key, value):
if not ((type(key) == int or type(key) == long) and key >= 0 and key < len(self._table)):
raise ValueError("Index illegal")
else:
self._table[key] = value
def __str__(self):
ret = str(self._fields)
for row in self._table:
ret += "\n" + str(row)
return ret
def Append(self, row):
self._table.append(row)
def GetTable(self):
return self._table
def SetTable(self, table):
self._table = table
def GetFields(self):
return self._fields
def SetFields(self, fields):
self._fields = fields
| Add __str__ function for SgTable | Add __str__ function for SgTable
| Python | mit | lnishan/SQLGitHub | ---
+++
@@ -26,6 +26,12 @@
raise ValueError("Index illegal")
else:
self._table[key] = value
+
+ def __str__(self):
+ ret = str(self._fields)
+ for row in self._table:
+ ret += "\n" + str(row)
+ return ret
def Append(self, row):
self._table.append(row) |
0c160c8e787a9019571f358b70633efa13cad466 | inbox/util/__init__.py | inbox/util/__init__.py | """ Non-server-specific utility modules. These shouldn't depend on any code
from the inbox module tree!
Don't add new code here! Find the relevant submodule, or use misc.py if
there's really no other place.
"""
| """ Non-server-specific utility modules. These shouldn't depend on any code
from the inbox module tree!
Don't add new code here! Find the relevant submodule, or use misc.py if
there's really no other place.
"""
# Allow out-of-tree submodules.
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
| Support for inbox.util.eas in the /inbox-eas repo; this is where EAS-specific util code would live. | Support for inbox.util.eas in the /inbox-eas repo; this is where EAS-specific util code would live.
Summary: As above.
Test Plan: Sync runs as before.
Reviewers: spang
Differential Revision: https://review.inboxapp.com/D226
| Python | agpl-3.0 | gale320/sync-engine,Eagles2F/sync-engine,jobscore/sync-engine,wakermahmud/sync-engine,EthanBlackburn/sync-engine,jobscore/sync-engine,Eagles2F/sync-engine,PriviPK/privipk-sync-engine,wakermahmud/sync-engine,Eagles2F/sync-engine,closeio/nylas,Eagles2F/sync-engine,wakermahmud/sync-engine,ErinCall/sync-engine,rmasters/inbox,gale320/sync-engine,closeio/nylas,Eagles2F/sync-engine,ErinCall/sync-engine,PriviPK/privipk-sync-engine,wakermahmud/sync-engine,gale320/sync-engine,closeio/nylas,ErinCall/sync-engine,closeio/nylas,jobscore/sync-engine,EthanBlackburn/sync-engine,PriviPK/privipk-sync-engine,ErinCall/sync-engine,EthanBlackburn/sync-engine,nylas/sync-engine,nylas/sync-engine,nylas/sync-engine,EthanBlackburn/sync-engine,PriviPK/privipk-sync-engine,nylas/sync-engine,gale320/sync-engine,ErinCall/sync-engine,rmasters/inbox,jobscore/sync-engine,rmasters/inbox,gale320/sync-engine,EthanBlackburn/sync-engine,rmasters/inbox,wakermahmud/sync-engine,PriviPK/privipk-sync-engine | ---
+++
@@ -4,3 +4,6 @@
Don't add new code here! Find the relevant submodule, or use misc.py if
there's really no other place.
"""
+# Allow out-of-tree submodules.
+from pkgutil import extend_path
+__path__ = extend_path(__path__, __name__) |
933a082a76c6c9b72aaf275f45f0d155f66eeacf | asv/__init__.py | asv/__init__.py | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
| # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import sys
if sys.version_info >= (3, 3):
# OS X framework builds of Python 3.3 can not call other 3.3
# virtualenvs as a subprocess because `__PYENV_LAUNCHER__` is
# inherited.
if os.environ.get('__PYVENV_LAUNCHER__'):
os.unsetenv('__PYVENV_LAUNCHER__')
| Fix Python 3.3 calling another virtualenv as a subprocess. | Fix Python 3.3 calling another virtualenv as a subprocess.
| Python | bsd-3-clause | waylonflinn/asv,airspeed-velocity/asv,edisongustavo/asv,giltis/asv,giltis/asv,qwhelan/asv,edisongustavo/asv,pv/asv,edisongustavo/asv,waylonflinn/asv,mdboom/asv,qwhelan/asv,cpcloud/asv,spacetelescope/asv,qwhelan/asv,pv/asv,giltis/asv,ericdill/asv,cpcloud/asv,mdboom/asv,mdboom/asv,ericdill/asv,cpcloud/asv,pv/asv,airspeed-velocity/asv,spacetelescope/asv,airspeed-velocity/asv,airspeed-velocity/asv,spacetelescope/asv,mdboom/asv,qwhelan/asv,spacetelescope/asv,ericdill/asv,waylonflinn/asv,pv/asv,ericdill/asv | ---
+++
@@ -3,3 +3,12 @@
from __future__ import (absolute_import, division, print_function,
unicode_literals)
+
+import sys
+
+if sys.version_info >= (3, 3):
+ # OS X framework builds of Python 3.3 can not call other 3.3
+ # virtualenvs as a subprocess because `__PYENV_LAUNCHER__` is
+ # inherited.
+ if os.environ.get('__PYVENV_LAUNCHER__'):
+ os.unsetenv('__PYVENV_LAUNCHER__') |
52873e4238a54cb93f403d509d2bebef8971ec9b | django_assets/filter/cssutils/__init__.py | django_assets/filter/cssutils/__init__.py | import logging
import logging.handlers
from django.conf import settings
from django_assets.filter import BaseFilter
__all__ = ('CSSUtilsFilter',)
class CSSUtilsFilter(BaseFilter):
"""Minifies CSS by removing whitespace, comments etc., using the Python
`cssutils <http://cthedot.de/cssutils/>`_ library.
Note that since this works as a parser on the syntax level, so invalid
CSS input could potentially result in data loss.
"""
name = 'cssutils'
def setup(self):
import cssutils
self.cssutils = cssutils
try:
# cssutils logs to stdout by default, hide that in production
if not settings.DEBUG:
log = logging.getLogger('assets.cssutils')
log.addHandler(logging.handlers.MemoryHandler(10))
cssutils.log.setlog(log)
except ImportError:
# During doc generation, Django is not going to be setup and will
# fail when the settings object is accessed. That's ok though.
pass
def apply(self, _in, out):
sheet = self.cssutils.parseString(_in.read())
self.cssutils.ser.prefs.useMinified()
out.write(sheet.cssText) | import logging
import logging.handlers
from django.conf import settings
from django_assets.filter import BaseFilter
__all__ = ('CSSUtilsFilter',)
class CSSUtilsFilter(BaseFilter):
"""Minifies CSS by removing whitespace, comments etc., using the Python
`cssutils <http://cthedot.de/cssutils/>`_ library.
Note that since this works as a parser on the syntax level, so invalid
CSS input could potentially result in data loss.
"""
name = 'cssutils'
def setup(self):
import cssutils
self.cssutils = cssutils
try:
# cssutils logs to stdout by default, hide that in production
if not settings.DEBUG:
log = logging.getLogger('assets.cssutils')
log.addHandler(logging.handlers.MemoryHandler(10))
# Newer versions of cssutils print a deprecation warning
# for 'setlog'.
if hasattr(cssutils.log, 'setLog'):
func = cssutils.log.setLog
else:
func = cssutils.log.setlog
func(log)
except ImportError:
# During doc generation, Django is not going to be setup and will
# fail when the settings object is accessed. That's ok though.
pass
def apply(self, _in, out):
sheet = self.cssutils.parseString(_in.read())
self.cssutils.ser.prefs.useMinified()
out.write(sheet.cssText) | Work around deprecation warning with new cssutils versions. | Work around deprecation warning with new cssutils versions.
| Python | bsd-2-clause | 0x1997/webassets,rs/webassets,scorphus/webassets,wijerasa/webassets,heynemann/webassets,aconrad/webassets,scorphus/webassets,florianjacob/webassets,aconrad/webassets,0x1997/webassets,glorpen/webassets,aconrad/webassets,heynemann/webassets,wijerasa/webassets,glorpen/webassets,JDeuce/webassets,heynemann/webassets,florianjacob/webassets,JDeuce/webassets,glorpen/webassets,john2x/webassets,john2x/webassets | ---
+++
@@ -27,7 +27,14 @@
if not settings.DEBUG:
log = logging.getLogger('assets.cssutils')
log.addHandler(logging.handlers.MemoryHandler(10))
- cssutils.log.setlog(log)
+
+ # Newer versions of cssutils print a deprecation warning
+ # for 'setlog'.
+ if hasattr(cssutils.log, 'setLog'):
+ func = cssutils.log.setLog
+ else:
+ func = cssutils.log.setlog
+ func(log)
except ImportError:
# During doc generation, Django is not going to be setup and will
# fail when the settings object is accessed. That's ok though. |
b1eb69620bbe875d117498ed95e009a019e54fab | votes/urls.py | votes/urls.py | from django.conf.urls import include, url
from django.views.generic import TemplateView
from votes.views import VoteView, results, system_home
urlpatterns = [
url(r'^$', system_home, name="system"),
url(r'^(?P<vote_name>[\w-]+)$', VoteView.as_view(), name="vote"),
url(r'^(?P<vote_name>[\w-]+)/results$', results, name="results"),
]
| from django.conf.urls import include, url
from django.views.generic import TemplateView
from votes.views import VoteView, results, system_home
urlpatterns = [
url(r'^$', system_home, name="system"),
url(r'^(?P<vote_name>[\w-]+)/$', VoteView.as_view(), name="vote"),
url(r'^(?P<vote_name>[\w-]+)/results/$', results, name="results"),
]
| Fix vote app URL patterns | Fix vote app URL patterns
| Python | mit | kuboschek/jay,OpenJUB/jay,kuboschek/jay,OpenJUB/jay,OpenJUB/jay,kuboschek/jay | ---
+++
@@ -6,6 +6,6 @@
urlpatterns = [
url(r'^$', system_home, name="system"),
- url(r'^(?P<vote_name>[\w-]+)$', VoteView.as_view(), name="vote"),
- url(r'^(?P<vote_name>[\w-]+)/results$', results, name="results"),
+ url(r'^(?P<vote_name>[\w-]+)/$', VoteView.as_view(), name="vote"),
+ url(r'^(?P<vote_name>[\w-]+)/results/$', results, name="results"),
] |
6a27bd99352e4dc7f38c6f819a8a45b37c1a094c | start-active-players.py | start-active-players.py | """
Start active players for the week
Ideas:
- Include the names of players who cannot be started
- And maybe the full roster on those dates
TODO:
- Add required packages in requirements.txt
"""
import requests
from bs4 import BeautifulSoup
# TODO: Configure this somewhere better (as a direct argument to the script, probably
TEAM_URL = 'http://basketball.fantasysports.yahoo.com/nba/178276/6/'
headers = {
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.99 Safari/537.36'
}
response = requests.get(TEAM_URL, headers=headers)
soup = BeautifulSoup(response.text)
inputs = soup.find(id='hiddens').findAll('input')
fields = {input['name']: input['value'] for input in inputs}
print(fields)
| """
Start active players for the week
Ideas:
- Include the names of players who cannot be started
- And maybe the full roster on those dates
"""
import requests
from bs4 import BeautifulSoup
# TODO: Configure this somewhere better (as a direct argument to the script, probably
TEAM_URL = 'http://basketball.fantasysports.yahoo.com/nba/178276/6/'
headers = {
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.99 Safari/537.36'
}
response = requests.get(TEAM_URL, headers=headers)
soup = BeautifulSoup(response.text)
inputs = soup.find(id='hiddens').findAll('input')
fields = {input['name']: input['value'] for input in inputs}
print(fields)
| Remove TODO to add requirements.txt | Remove TODO to add requirements.txt
| Python | mit | jbrudvik/yahoo-fantasy-basketball | ---
+++
@@ -4,9 +4,6 @@
Ideas:
- Include the names of players who cannot be started
- And maybe the full roster on those dates
-
-TODO:
-- Add required packages in requirements.txt
"""
import requests |
20e8ef6bd68100a70b9d50013630ff71d8b7ec94 | changes/artifacts/__init__.py | changes/artifacts/__init__.py | from __future__ import absolute_import, print_function
from .manager import Manager
from .coverage import CoverageHandler
from .xunit import XunitHandler
manager = Manager()
manager.register(CoverageHandler, ['coverage.xml'])
manager.register(XunitHandler, ['xunit.xml', 'junit.xml'])
| from __future__ import absolute_import, print_function
from .manager import Manager
from .coverage import CoverageHandler
from .xunit import XunitHandler
manager = Manager()
manager.register(CoverageHandler, ['coverage.xml', '*.coverage.xml'])
manager.register(XunitHandler, ['xunit.xml', 'junit.xml', '*.xunit.xml', '*.junit.xml'])
| Support wildcard matches on coverage/junit results | Support wildcard matches on coverage/junit results
| Python | apache-2.0 | dropbox/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes | ---
+++
@@ -6,5 +6,5 @@
manager = Manager()
-manager.register(CoverageHandler, ['coverage.xml'])
-manager.register(XunitHandler, ['xunit.xml', 'junit.xml'])
+manager.register(CoverageHandler, ['coverage.xml', '*.coverage.xml'])
+manager.register(XunitHandler, ['xunit.xml', 'junit.xml', '*.xunit.xml', '*.junit.xml']) |
ae8f9c39cd75d837a4cb5a4cea4d3d11fd1cabed | tests/test_comments.py | tests/test_comments.py | from hypothesis_auto import auto_pytest_magic
from isort import comments
auto_pytest_magic(comments.parse)
auto_pytest_magic(comments.add_to_line)
| from hypothesis_auto import auto_pytest_magic
from isort import comments
auto_pytest_magic(comments.parse)
auto_pytest_magic(comments.add_to_line)
def test_add_to_line():
assert comments.add_to_line([], "import os # comment", removed=True).strip() == "import os"
| Add additional test case for comments | Add additional test case for comments
| Python | mit | PyCQA/isort,PyCQA/isort | ---
+++
@@ -4,3 +4,7 @@
auto_pytest_magic(comments.parse)
auto_pytest_magic(comments.add_to_line)
+
+
+def test_add_to_line():
+ assert comments.add_to_line([], "import os # comment", removed=True).strip() == "import os" |
270c8ca68357f92999474fbf110fed7b01cdfdf2 | cqlengine/__init__.py | cqlengine/__init__.py | import os
from cqlengine.columns import *
from cqlengine.functions import *
from cqlengine.models import Model
from cqlengine.query import BatchQuery
__cqlengine_version_path__ = os.path.realpath(__file__ + '/../VERSION')
__version__ = open(__cqlengine_version_path__, 'r').readline().strip()
# compaction
SizeTieredCompactionStrategy = "SizeTieredCompactionStrategy"
LeveledCompactionStrategy = "LeveledCompactionStrategy"
ANY = "ANY"
ONE = "ONE"
TWO = "TWO"
THREE = "THREE"
QUORUM = "QUORUM"
LOCAL_QUORUM = "LOCAL_QUORUM"
EACH_QUORUM = "EACH_QUORUM"
ALL = "ALL"
| import os
import pkg_resources
from cqlengine.columns import *
from cqlengine.functions import *
from cqlengine.models import Model
from cqlengine.query import BatchQuery
__cqlengine_version_path__ = pkg_resources.resource_filename('cqlengine',
'VERSION')
__version__ = open(__cqlengine_version_path__, 'r').readline().strip()
# compaction
SizeTieredCompactionStrategy = "SizeTieredCompactionStrategy"
LeveledCompactionStrategy = "LeveledCompactionStrategy"
ANY = "ANY"
ONE = "ONE"
TWO = "TWO"
THREE = "THREE"
QUORUM = "QUORUM"
LOCAL_QUORUM = "LOCAL_QUORUM"
EACH_QUORUM = "EACH_QUORUM"
ALL = "ALL"
| Use proper way to access package resources. | Use proper way to access package resources.
| Python | apache-2.0 | bbirand/python-driver,mike-tr-adamson/python-driver,HackerEarth/cassandra-python-driver,vipjml/python-driver,coldeasy/python-driver,jregovic/python-driver,jregovic/python-driver,datastax/python-driver,thobbs/python-driver,stef1927/python-driver,markflorisson/python-driver,coldeasy/python-driver,bbirand/python-driver,jfelectron/python-driver,sontek/python-driver,mambocab/python-driver,datastax/python-driver,tempbottle/python-driver,mobify/python-driver,sontek/python-driver,yi719/python-driver,tempbottle/python-driver,HackerEarth/cassandra-python-driver,jfelectron/python-driver,kracekumar/python-driver,thelastpickle/python-driver,mambocab/python-driver,kracekumar/python-driver,beobal/python-driver,thobbs/python-driver,thelastpickle/python-driver,yi719/python-driver,kishkaru/python-driver,vipjml/python-driver,mobify/python-driver,cqlengine/cqlengine,beobal/python-driver,markflorisson/python-driver,kishkaru/python-driver,stef1927/python-driver,mike-tr-adamson/python-driver | ---
+++
@@ -1,11 +1,14 @@
import os
+import pkg_resources
from cqlengine.columns import *
from cqlengine.functions import *
from cqlengine.models import Model
from cqlengine.query import BatchQuery
-__cqlengine_version_path__ = os.path.realpath(__file__ + '/../VERSION')
+
+__cqlengine_version_path__ = pkg_resources.resource_filename('cqlengine',
+ 'VERSION')
__version__ = open(__cqlengine_version_path__, 'r').readline().strip()
# compaction |
374c386a6b2dd1ad1ba75ba70009de6c7ee3c3fc | restalchemy/api/applications.py | restalchemy/api/applications.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2014 Eugene Frolov <eugene@frolov.net.ru>
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from webob import dec
from restalchemy.api import resources
from restalchemy.api import routes
DEFAULT_CONTENT_TYPE = 'application/json'
class WSGIApp(object):
def __init__(self, route_class):
super(WSGIApp, self).__init__()
self._main_route = routes.route(route_class)
resources.ResourceMap.set_resource_map(
routes.Route.build_resource_map(route_class))
@dec.wsgify
def __call__(self, req):
return self._main_route(req).do()
Application = WSGIApp
| # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2014 Eugene Frolov <eugene@frolov.net.ru>
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from webob import dec
from restalchemy.api import resources
from restalchemy.api import routes
DEFAULT_CONTENT_TYPE = 'application/json'
class WSGIApp(object):
def __init__(self, route_class):
super(WSGIApp, self).__init__()
self._main_route = routes.route(route_class)
resources.ResourceMap.set_resource_map(
routes.Route.build_resource_map(route_class))
def process_request(self, req):
return self._main_route(req).do()
@dec.wsgify
def __call__(self, req):
return self.process_request(req)
Application = WSGIApp
| Add process_request method to Application | Add process_request method to Application
This allows to override a process_request method without having to
add webob to child project.
Change-Id: Ic5369076704f1ba459b2872ed0f4632a15b75c25
| Python | apache-2.0 | phantomii/restalchemy | ---
+++
@@ -33,9 +33,12 @@
resources.ResourceMap.set_resource_map(
routes.Route.build_resource_map(route_class))
+ def process_request(self, req):
+ return self._main_route(req).do()
+
@dec.wsgify
def __call__(self, req):
- return self._main_route(req).do()
+ return self.process_request(req)
Application = WSGIApp |
a84dde598297495fe6f0f8b233b3a3761b0df7d4 | tests/functional/test_warning.py | tests/functional/test_warning.py |
def test_environ(script, tmpdir):
"""$PYTHONWARNINGS was added in python2.7"""
demo = tmpdir.join('warnings_demo.py')
demo.write('''
from pip._internal.utils import deprecation
deprecation.install_warning_logger()
from logging import basicConfig
basicConfig()
from warnings import warn
warn("deprecated!", deprecation.PipDeprecationWarning)
''')
result = script.run('python', demo, expect_stderr=True)
assert result.stderr == \
'ERROR:pip._internal.deprecations:DEPRECATION: deprecated!\n'
script.environ['PYTHONWARNINGS'] = 'ignore'
result = script.run('python', demo)
assert result.stderr == ''
| import textwrap
def test_environ(script, tmpdir):
"""$PYTHONWARNINGS was added in python2.7"""
demo = tmpdir.join('warnings_demo.py')
demo.write(textwrap.dedent('''
from logging import basicConfig
from pip._internal.utils import deprecation
deprecation.install_warning_logger()
basicConfig()
deprecation.deprecated("deprecated!", replacement=None, gone_in=None)
'''))
result = script.run('python', demo, expect_stderr=True)
expected = 'WARNING:pip._internal.deprecations:DEPRECATION: deprecated!\n'
assert result.stderr == expected
script.environ['PYTHONWARNINGS'] = 'ignore'
result = script.run('python', demo)
assert result.stderr == ''
| Update test to check newer logic | Update test to check newer logic
| Python | mit | pypa/pip,pfmoore/pip,pypa/pip,pradyunsg/pip,rouge8/pip,xavfernandez/pip,pradyunsg/pip,rouge8/pip,xavfernandez/pip,xavfernandez/pip,rouge8/pip,sbidoul/pip,sbidoul/pip,techtonik/pip,techtonik/pip,techtonik/pip,pfmoore/pip | ---
+++
@@ -1,21 +1,22 @@
+import textwrap
+
def test_environ(script, tmpdir):
"""$PYTHONWARNINGS was added in python2.7"""
demo = tmpdir.join('warnings_demo.py')
- demo.write('''
-from pip._internal.utils import deprecation
-deprecation.install_warning_logger()
+ demo.write(textwrap.dedent('''
+ from logging import basicConfig
+ from pip._internal.utils import deprecation
-from logging import basicConfig
-basicConfig()
+ deprecation.install_warning_logger()
+ basicConfig()
-from warnings import warn
-warn("deprecated!", deprecation.PipDeprecationWarning)
-''')
+ deprecation.deprecated("deprecated!", replacement=None, gone_in=None)
+ '''))
result = script.run('python', demo, expect_stderr=True)
- assert result.stderr == \
- 'ERROR:pip._internal.deprecations:DEPRECATION: deprecated!\n'
+ expected = 'WARNING:pip._internal.deprecations:DEPRECATION: deprecated!\n'
+ assert result.stderr == expected
script.environ['PYTHONWARNINGS'] = 'ignore'
result = script.run('python', demo) |
b79a80d894bdc39c8fa6f76fe50e222567f00df1 | config_default.py | config_default.py | # -*- coding: utf-8 -*-
"""
Created on 2015-10-23 08:06:00
@author: Tran Huu Cuong <tranhuucuong91@gmail.com>
"""
import os
# Blog configuration values.
# You may consider using a one-way hash to generate the password, and then
# use the hash again in the login view to perform the comparison. This is just
# for simplicity.
ADMIN_PASSWORD = 'admin@secret'
APP_DIR = os.path.dirname(os.path.realpath(__file__))
PATH_SQLITE_DB=os.path.join(APP_DIR, 'blog.db')
# The playhouse.flask_utils.FlaskDB object accepts database URL configuration.
DATABASE = 'sqliteext:///{}'.format(PATH_SQLITE_DB)
DEBUG = False
# The secret key is used internally by Flask to encrypt session data stored
# in cookies. Make this unique for your app.
SECRET_KEY = 'shhh, secret!'
# This is used by micawber, which will attempt to generate rich media
# embedded objects with maxwidth=800.
SITE_WIDTH = 800
APP_HOST='127.0.0.1'
APP_PORT=5000
| # -*- coding: utf-8 -*-
"""
Created on 2015-10-23 08:06:00
@author: Tran Huu Cuong <tranhuucuong91@gmail.com>
"""
import os
# Blog configuration values.
# You may consider using a one-way hash to generate the password, and then
# use the hash again in the login view to perform the comparison. This is just
# for simplicity.
ADMIN_PASSWORD = 'admin@secret'
APP_DIR = os.path.dirname(os.path.realpath(__file__))
PATH_SQLITE_DB=os.path.join(APP_DIR, 'blog.db')
# The playhouse.flask_utils.FlaskDB object accepts database URL configuration.
DATABASE = 'sqliteext:///{}'.format(PATH_SQLITE_DB)
DEBUG = False
# The secret key is used internally by Flask to encrypt session data stored
# in cookies. Make this unique for your app.
SECRET_KEY = 'shhh, secret!'
# This is used by micawber, which will attempt to generate rich media
# embedded objects with maxwidth=800.
SITE_WIDTH = 800
APP_HOST='127.0.0.1'
APP_PORT=5000
ES_HOST = {
"host": "172.17.42.1",
"port": 9200
}
ES_INDEX_NAME = 'notebooks'
ES_TYPE_NAME = 'notebooks'
| Update cofnig_default: add elastic search config | Update cofnig_default: add elastic search config
| Python | mit | tranhuucuong91/simple-notebooks,tranhuucuong91/simple-notebooks,tranhuucuong91/simple-notebooks | ---
+++
@@ -30,3 +30,12 @@
APP_HOST='127.0.0.1'
APP_PORT=5000
+
+ES_HOST = {
+ "host": "172.17.42.1",
+ "port": 9200
+}
+
+ES_INDEX_NAME = 'notebooks'
+ES_TYPE_NAME = 'notebooks'
+ |
e7c462af8382a5eb7f5fee2abfc04f002e36b193 | tests/mcp/test_datautils.py | tests/mcp/test_datautils.py | from spock.mcp import datautils
from spock.utils import BoundBuffer
def test_unpack_varint():
largebuff = BoundBuffer(b'\x80\x94\xeb\xdc\x03')
smallbuff = BoundBuffer(b'\x14')
assert datautils.unpack_varint(smallbuff) == 20
assert datautils.unpack_varint(largebuff) == 1000000000
def test_pack_varint():
assert datautils.pack_varint(20) == b'\x14'
assert datautils.pack_varint(1000000000) == b'\x80\x94\xeb\xdc\x03'
assert datautils.pack_varint(-10000000000) is None
assert datautils.pack_varint(10000000000) is None
def test_unpack_varlong():
largebuff = BoundBuffer(b'\x80\xc8\xaf\xa0%')
smallbuff = BoundBuffer(b'\x14')
assert datautils.unpack_varlong(smallbuff) == 20
assert datautils.unpack_varlong(largebuff) == 10000000000
pass
def test_pack_varlong():
assert datautils.pack_varlong(20) == b'\x14'
assert datautils.pack_varlong(10000000000) == b'\x80\xc8\xaf\xa0%'
assert datautils.pack_varlong(10000000000000000000) is None
assert datautils.pack_varlong(-10000000000000000000) is None
| Add varint and varlong tests | Add varint and varlong tests
| Python | mit | SpockBotMC/SpockBot,nickelpro/SpockBot,gamingrobot/SpockBot,MrSwiss/SpockBot,Gjum/SpockBot,luken/SpockBot | ---
+++
@@ -0,0 +1,31 @@
+from spock.mcp import datautils
+from spock.utils import BoundBuffer
+
+
+def test_unpack_varint():
+ largebuff = BoundBuffer(b'\x80\x94\xeb\xdc\x03')
+ smallbuff = BoundBuffer(b'\x14')
+ assert datautils.unpack_varint(smallbuff) == 20
+ assert datautils.unpack_varint(largebuff) == 1000000000
+
+
+def test_pack_varint():
+ assert datautils.pack_varint(20) == b'\x14'
+ assert datautils.pack_varint(1000000000) == b'\x80\x94\xeb\xdc\x03'
+ assert datautils.pack_varint(-10000000000) is None
+ assert datautils.pack_varint(10000000000) is None
+
+
+def test_unpack_varlong():
+ largebuff = BoundBuffer(b'\x80\xc8\xaf\xa0%')
+ smallbuff = BoundBuffer(b'\x14')
+ assert datautils.unpack_varlong(smallbuff) == 20
+ assert datautils.unpack_varlong(largebuff) == 10000000000
+pass
+
+
+def test_pack_varlong():
+ assert datautils.pack_varlong(20) == b'\x14'
+ assert datautils.pack_varlong(10000000000) == b'\x80\xc8\xaf\xa0%'
+ assert datautils.pack_varlong(10000000000000000000) is None
+ assert datautils.pack_varlong(-10000000000000000000) is None | |
d13204abb2cf5d341eff78416dd442c303042697 | classes/room.py | classes/room.py | class Room(object):
def __init__(self, room_name, room_type, max_persons):
self.room_name = room_name
self.room_type = room_type
self.max_persons = max_persons
self.persons = []
def add_occupant(self, person):
if len(self.persons) < self.max_persons:
self.persons.append(person)
print (person.person_type.title() + " " + person.person_name.title() + " " + person.person_surname.title() + " has been allocated " + self.room_type + " " + self.room_name.title())
else:
raise Exception(self.room_type.title() + " " + self.room_name.title() + " is at full capacity")
| class Room(object):
def __init__(self, room_name, room_type, max_persons):
self.room_name = room_name
self.room_type = room_type
self.max_persons = max_persons
self.persons = []
def add_occupant(self, person):
if person not in self.persons:
if len(self.persons) < self.max_persons:
self.persons.append(person)
print (person.person_type.title() + " " + person.person_name.title() + " " + person.person_surname.title() + " has been allocated " + self.room_type + " " + self.room_name.title())
else:
raise Exception(self.room_type.title() + " " + self.room_name.title() + " is at full capacity")
else:
raise Exception(person.person_type.title() + " " + person.person_name.title() + " " + person.person_surname.title() + " is already among the occupants in " + self.room_type + " " + self.room_name.title())
| Modify add_occupant method to raise exception in case of a duplicate | Modify add_occupant method to raise exception in case of a duplicate
| Python | mit | peterpaints/room-allocator | ---
+++
@@ -6,8 +6,11 @@
self.persons = []
def add_occupant(self, person):
- if len(self.persons) < self.max_persons:
- self.persons.append(person)
- print (person.person_type.title() + " " + person.person_name.title() + " " + person.person_surname.title() + " has been allocated " + self.room_type + " " + self.room_name.title())
+ if person not in self.persons:
+ if len(self.persons) < self.max_persons:
+ self.persons.append(person)
+ print (person.person_type.title() + " " + person.person_name.title() + " " + person.person_surname.title() + " has been allocated " + self.room_type + " " + self.room_name.title())
+ else:
+ raise Exception(self.room_type.title() + " " + self.room_name.title() + " is at full capacity")
else:
- raise Exception(self.room_type.title() + " " + self.room_name.title() + " is at full capacity")
+ raise Exception(person.person_type.title() + " " + person.person_name.title() + " " + person.person_surname.title() + " is already among the occupants in " + self.room_type + " " + self.room_name.title()) |
90d3f00cd8fea8fab9274069ac06ea461f8e4dfd | channels/ooo_b_r/app.py | channels/ooo_b_r/app.py | #encoding:utf-8
from utils import get_url, weighted_random_subreddit
# Group chat https://yal.sh/dvdahoy
t_channel = '-1001065558871'
subreddit = weighted_random_subreddit({
'ANormalDayInRussia': 1.0,
'ANormalDayInAmerica': 0.1,
'ANormalDayInJapan': 0.01
})
def send_post(submission, r2t):
what, url, ext = get_url(submission)
title = submission.title
link = submission.shortlink
text = '{}\n{}'.format(title, link)
if what == 'text':
return False
elif what == 'other':
return False
elif what == 'album':
r2t.send_album(url)
return True
elif what in ('gif', 'img'):
return r2t.send_gif_img(what, url, ext, text)
else:
return False
| #encoding:utf-8
from utils import get_url, weighted_random_subreddit
# Group chat https://yal.sh/dvdahoy
t_channel = '-1001065558871'
subreddit = weighted_random_subreddit({
'ANormalDayInRussia': 1.0,
'ANormalDayInAmerica': 0.1,
'ANormalDayInJapan': 0.01
})
def send_post(submission, r2t):
what, url, ext = get_url(submission)
title = submission.title
link = submission.shortlink
text = '{}\n{}'.format(title, link)
return r2t.send_gif_img(what, url, ext, text)
| Send only pics and gifs to OOO_B_R. | Send only pics and gifs to OOO_B_R. | Python | mit | nsiregar/reddit2telegram,Fillll/reddit2telegram,nsiregar/reddit2telegram,Fillll/reddit2telegram | ---
+++
@@ -18,14 +18,4 @@
link = submission.shortlink
text = '{}\n{}'.format(title, link)
- if what == 'text':
- return False
- elif what == 'other':
- return False
- elif what == 'album':
- r2t.send_album(url)
- return True
- elif what in ('gif', 'img'):
- return r2t.send_gif_img(what, url, ext, text)
- else:
- return False
+ return r2t.send_gif_img(what, url, ext, text) |
d966b0973da71f5c883697ddd12c2728b2a04cce | ci/cleanup-binary-tags.py | ci/cleanup-binary-tags.py | #!/usr/bin/env python3
import os
import subprocess
import re
import semver
def tag_to_version(tag):
version = re.sub(r'binary-', '', tag)
version = re.sub(r'-[x86|i686].*', '', version)
return version
subprocess.check_call('git pull --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True)
| #!/usr/bin/env python3
import os
import subprocess
import re
import semver
def tag_to_version(tag):
return tag.split('-')[1].lstrip('v')
subprocess.check_call('git pull --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True)
| Improve git tag to version conversion | Improve git tag to version conversion
There is also aarch64 arch.
| Python | mit | autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim | ---
+++
@@ -7,9 +7,7 @@
def tag_to_version(tag):
- version = re.sub(r'binary-', '', tag)
- version = re.sub(r'-[x86|i686].*', '', version)
- return version
+ return tag.split('-')[1].lstrip('v')
subprocess.check_call('git pull --tags', shell=True) |
e660953c1df2dc9de6b3038e4ddb1d77768b2b51 | tools/pyhande/setup.py | tools/pyhande/setup.py | from distutils.core import setup
setup(
name='pyhande',
version='0.1',
author='HANDE developers',
packages=('pyhande',),
license='Modified BSD license',
description='Analysis framework for HANDE calculations',
long_description=open('README.rst').read(),
requires=['numpy', 'pandas (>= 0.13)', 'pyblock',],
)
| from distutils.core import setup
setup(
name='pyhande',
version='0.1',
author='HANDE developers',
packages=('pyhande',),
license='Modified BSD license',
description='Analysis framework for HANDE calculations',
long_description=open('README.rst').read(),
install_requires=['numpy', 'scipy', 'pandas', 'pyblock', 'matplotlib'],
)
| Correct pyhande dependencies (broken for some time) | Correct pyhande dependencies (broken for some time)
This allows pyhande to be installed in a virtualenv again...
| Python | lgpl-2.1 | hande-qmc/hande,hande-qmc/hande,hande-qmc/hande,hande-qmc/hande,hande-qmc/hande | ---
+++
@@ -8,5 +8,5 @@
license='Modified BSD license',
description='Analysis framework for HANDE calculations',
long_description=open('README.rst').read(),
- requires=['numpy', 'pandas (>= 0.13)', 'pyblock',],
+ install_requires=['numpy', 'scipy', 'pandas', 'pyblock', 'matplotlib'],
) |
0ea32a2b51438b55130082e54f30fc9c97bd9d85 | cloudkitty/db/__init__.py | cloudkitty/db/__init__.py | # -*- coding: utf-8 -*-
# Copyright 2014 Objectif Libre
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
from oslo_config import cfg
from oslo_db.sqlalchemy import session
_FACADE = None
def _create_facade_lazily():
global _FACADE
if _FACADE is None:
_FACADE = session.EngineFacade.from_config(cfg.CONF, sqlite_fk=True)
return _FACADE
def get_engine():
facade = _create_facade_lazily()
return facade.get_engine()
def get_session(**kwargs):
facade = _create_facade_lazily()
return facade.get_session(**kwargs)
| # -*- coding: utf-8 -*-
# Copyright 2014 Objectif Libre
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
from oslo_config import cfg
from oslo_db.sqlalchemy import session
_FACADE = None
def _create_facade_lazily():
global _FACADE
if _FACADE is None:
# FIXME(priteau): Remove autocommit=True (and ideally use of
# LegacyEngineFacade) asap since it's not compatible with SQLAlchemy
# 2.0.
_FACADE = session.EngineFacade.from_config(cfg.CONF, sqlite_fk=True,
autocommit=True)
return _FACADE
def get_engine():
facade = _create_facade_lazily()
return facade.get_engine()
def get_session(**kwargs):
facade = _create_facade_lazily()
return facade.get_session(**kwargs)
| Fix compatibility with oslo.db 12.1.0 | Fix compatibility with oslo.db 12.1.0
oslo.db 12.1.0 has changed the default value for the 'autocommit'
parameter of 'LegacyEngineFacade' from 'True' to 'False'. This is a
necessary step to ensure compatibility with SQLAlchemy 2.0. However, we
are currently relying on the autocommit behavior and need changes to
explicitly manage sessions. Until that happens, we need to override the
default.
Co-Authored-By: Stephen Finucane <4725dc7f3632bf126d9fbdc30c347e91e8d2fe16@redhat.com>
Change-Id: Ia0e9696dcaafd90f9c6daeb68c72fa2b184823fb
| Python | apache-2.0 | openstack/cloudkitty,openstack/cloudkitty | ---
+++
@@ -22,7 +22,11 @@
def _create_facade_lazily():
global _FACADE
if _FACADE is None:
- _FACADE = session.EngineFacade.from_config(cfg.CONF, sqlite_fk=True)
+ # FIXME(priteau): Remove autocommit=True (and ideally use of
+ # LegacyEngineFacade) asap since it's not compatible with SQLAlchemy
+ # 2.0.
+ _FACADE = session.EngineFacade.from_config(cfg.CONF, sqlite_fk=True,
+ autocommit=True)
return _FACADE
|
72941398fd2e78cbf5d994b4bf8683c4bdefaab9 | utils/travis_runner.py | utils/travis_runner.py | #!/usr/bin/env python
"""This script manages all tasks for the TRAVIS build server."""
import os
import subprocess
if __name__ == "__main__":
os.chdir("promotion/grmpy_tutorial_notebook")
cmd = [
"jupyter",
"nbconvert",
"--execute",
"grmpy_tutorial_notebook.ipynb",
"--ExecutePreprocessor.timeout=-1",
]
subprocess.check_call(cmd)
os.chdir("../..")
if __name__ == "__main__":
os.chdir("promotion/grmpy_tutorial_notebook")
cmd = [
"jupyter",
"nbconvert",
"--execute",
"tutorial_semipar_notebook.ipynb",
"--ExecutePreprocessor.timeout=-1",
]
subprocess.check_call(cmd)
| #!/usr/bin/env python
"""This script manages all tasks for the TRAVIS build server."""
import os
import subprocess
if __name__ == "__main__":
os.chdir("promotion/grmpy_tutorial_notebook")
cmd = [
"jupyter",
"nbconvert",
"--execute",
"grmpy_tutorial_notebook.ipynb",
"--ExecutePreprocessor.timeout=-1",
]
subprocess.check_call(cmd)
os.chdir("../..")
# if __name__ == "__main__":
# os.chdir("promotion/grmpy_tutorial_notebook")
# cmd = [
# "jupyter",
# "nbconvert",
# "--execute",
# "tutorial_semipar_notebook.ipynb",
# "--ExecutePreprocessor.timeout=-1",
# ]
# subprocess.check_call(cmd)
| Comment out semipar notebook in travis runner until pip build us updated. | Comment out semipar notebook in travis runner until pip build us updated.
| Python | mit | grmToolbox/grmpy | ---
+++
@@ -16,13 +16,13 @@
os.chdir("../..")
-if __name__ == "__main__":
- os.chdir("promotion/grmpy_tutorial_notebook")
- cmd = [
- "jupyter",
- "nbconvert",
- "--execute",
- "tutorial_semipar_notebook.ipynb",
- "--ExecutePreprocessor.timeout=-1",
- ]
- subprocess.check_call(cmd)
+# if __name__ == "__main__":
+# os.chdir("promotion/grmpy_tutorial_notebook")
+# cmd = [
+# "jupyter",
+# "nbconvert",
+# "--execute",
+# "tutorial_semipar_notebook.ipynb",
+# "--ExecutePreprocessor.timeout=-1",
+# ]
+# subprocess.check_call(cmd) |
be929d518ff320ed8e16f57da55f0855800f7408 | src/engine/file_loader.py | src/engine/file_loader.py | import os
import json
from lib import contract
data_dir = os.path.join(os.environ['PORTER'], 'data')
@contract.accepts(str)
@contract.returns(list)
def read_and_parse_json(data_type):
sub_dir = os.path.join(data_dir, data_type)
def full_path(file_name):
return os.path.join(sub_dir, file_name)
def only_json(file_name):
return file_name.endswith('.json')
def load_json(json_file_name):
with open(json_file_name) as json_file:
return json.load(json_file)
return map(load_json, filter(only_json, map(full_path, os.listdir(sub_dir))))
@contract.accepts(str)
@contract.returns(dict)
def load_enum(struct_name):
def create_enum_map(enum_map, args):
enumeration, enum_type = args
enum_map[str(enum_type)] = enumeration
return enum_map
return reduce(create_enum_map, enumerate(read_and_parse_json(struct_name)[0]), {})
@contract.accepts(str)
@contract.returns(dict)
def load_struct(struct_name):
def create_struct_map(struct_map, struct_):
struct_map[str(struct_['name'])] = struct_
return struct_map
return reduce(create_struct_map, read_and_parse_json(struct_name), {})
| import os
import json
from lib import contract, functional
data_dir = os.path.join(os.environ['PORTER'], 'data')
@contract.accepts(str)
@contract.returns(list)
def read_and_parse_json(data_type):
sub_dir = os.path.join(data_dir, data_type)
def full_path(file_name):
return os.path.join(sub_dir, file_name)
def only_json(file_name):
return file_name.endswith('.json')
def load_json(json_file_name):
with open(json_file_name) as json_file:
return json.load(json_file)
return map(load_json, filter(only_json, map(full_path, os.listdir(sub_dir))))
@contract.accepts(str)
@contract.returns(dict)
def load_enum(struct_name):
def create_enum_map(enum_map, enumeration, enum_type):
enum_map[str(enum_type)] = enumeration
return enum_map
return functional.multi_reduce(
create_enum_map, enumerate(read_and_parse_json(struct_name)[0]), {})
@contract.accepts(str)
@contract.returns(dict)
def load_struct(struct_name):
def create_struct_map(struct_map, struct_):
struct_map[str(struct_['name'])] = struct_
return struct_map
return reduce(create_struct_map, read_and_parse_json(struct_name), {})
| Use mutli_reduce instead of reduce in enum file loading | Use mutli_reduce instead of reduce in enum file loading
| Python | mit | Tactique/game_engine,Tactique/game_engine | ---
+++
@@ -1,7 +1,7 @@
import os
import json
-from lib import contract
+from lib import contract, functional
data_dir = os.path.join(os.environ['PORTER'], 'data')
@@ -27,12 +27,12 @@
@contract.accepts(str)
@contract.returns(dict)
def load_enum(struct_name):
- def create_enum_map(enum_map, args):
- enumeration, enum_type = args
+ def create_enum_map(enum_map, enumeration, enum_type):
enum_map[str(enum_type)] = enumeration
return enum_map
- return reduce(create_enum_map, enumerate(read_and_parse_json(struct_name)[0]), {})
+ return functional.multi_reduce(
+ create_enum_map, enumerate(read_and_parse_json(struct_name)[0]), {})
@contract.accepts(str) |
1b726978e1604269c8c4d2728a6f7ce774e5d16d | src/ggrc/models/control_assessment.py | src/ggrc/models/control_assessment.py | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
from ggrc import db
from .mixins import (
deferred, BusinessObject, Timeboxed, CustomAttributable, TestPlanned
)
from .object_document import Documentable
from .object_owner import Ownable
from .object_person import Personable
from .relationship import Relatable
from .track_object_state import HasObjectState, track_state_for_class
from ggrc.models.reflection import PublishOnly
class ControlAssessment(HasObjectState, TestPlanned, CustomAttributable,
Documentable, Personable, Timeboxed, Ownable,
Relatable, BusinessObject, db.Model):
__tablename__ = 'control_assessments'
design = deferred(db.Column(db.String), 'ControlAssessment')
operationally = deferred(db.Column(db.String), 'ControlAssessment')
control_id = db.Column(db.Integer, db.ForeignKey('controls.id'))
control = db.relationship('Control', foreign_keys=[control_id])
# REST properties
_publish_attrs = [
'design',
'operationally',
'control'
]
track_state_for_class(ControlAssessment)
| # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
from ggrc import db
from .mixins import (
deferred, BusinessObject, Timeboxed, CustomAttributable, TestPlanned
)
from .object_document import Documentable
from .object_owner import Ownable
from .object_person import Personable
from .relationship import Relatable
from .track_object_state import HasObjectState, track_state_for_class
from ggrc.models.reflection import PublishOnly
class ControlAssessment(HasObjectState, TestPlanned, CustomAttributable,
Documentable, Personable, Timeboxed, Ownable,
Relatable, BusinessObject, db.Model):
__tablename__ = 'control_assessments'
design = deferred(db.Column(db.String), 'ControlAssessment')
operationally = deferred(db.Column(db.String), 'ControlAssessment')
control_id = db.Column(db.Integer, db.ForeignKey('controls.id'))
control = db.relationship('Control', foreign_keys=[control_id])
audit = {} # we add this for the sake of client side error checking
# REST properties
_publish_attrs = [
'design',
'operationally',
'control',
PublishOnly('audit')
]
track_state_for_class(ControlAssessment)
| Fix edit control assessment modal | Fix edit control assessment modal
This works, because our client side verification checks only if the
audit attr exists.
ref: core-1643
| Python | apache-2.0 | kr41/ggrc-core,kr41/ggrc-core,vladan-m/ggrc-core,vladan-m/ggrc-core,vladan-m/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,VinnieJohns/ggrc-core,prasannav7/ggrc-core,andrei-karalionak/ggrc-core,andrei-karalionak/ggrc-core,jmakov/ggrc-core,AleksNeStu/ggrc-core,uskudnik/ggrc-core,uskudnik/ggrc-core,selahssea/ggrc-core,hasanalom/ggrc-core,j0gurt/ggrc-core,NejcZupec/ggrc-core,AleksNeStu/ggrc-core,prasannav7/ggrc-core,hyperNURb/ggrc-core,kr41/ggrc-core,AleksNeStu/ggrc-core,uskudnik/ggrc-core,uskudnik/ggrc-core,hasanalom/ggrc-core,hyperNURb/ggrc-core,prasannav7/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,josthkko/ggrc-core,NejcZupec/ggrc-core,uskudnik/ggrc-core,edofic/ggrc-core,josthkko/ggrc-core,j0gurt/ggrc-core,plamut/ggrc-core,josthkko/ggrc-core,jmakov/ggrc-core,hasanalom/ggrc-core,andrei-karalionak/ggrc-core,vladan-m/ggrc-core,j0gurt/ggrc-core,plamut/ggrc-core,VinnieJohns/ggrc-core,edofic/ggrc-core,VinnieJohns/ggrc-core,j0gurt/ggrc-core,plamut/ggrc-core,jmakov/ggrc-core,edofic/ggrc-core,hasanalom/ggrc-core,kr41/ggrc-core,prasannav7/ggrc-core,vladan-m/ggrc-core,hasanalom/ggrc-core,andrei-karalionak/ggrc-core,edofic/ggrc-core,selahssea/ggrc-core,hyperNURb/ggrc-core,hyperNURb/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,jmakov/ggrc-core,hyperNURb/ggrc-core,NejcZupec/ggrc-core,NejcZupec/ggrc-core,jmakov/ggrc-core | ---
+++
@@ -26,11 +26,14 @@
control_id = db.Column(db.Integer, db.ForeignKey('controls.id'))
control = db.relationship('Control', foreign_keys=[control_id])
+ audit = {} # we add this for the sake of client side error checking
+
# REST properties
_publish_attrs = [
'design',
'operationally',
- 'control'
+ 'control',
+ PublishOnly('audit')
]
track_state_for_class(ControlAssessment) |
52239a9b6cd017127d52c29ac0e2a0d3818e7d9e | cms_lab_members/admin.py | cms_lab_members/admin.py | from django.contrib import admin
from cms.admin.placeholderadmin import PlaceholderAdminMixin
from lab_members.models import Scientist
from lab_members.admin import ScientistAdmin
class CMSScientistAdmin(PlaceholderAdminMixin, ScientistAdmin):
fieldsets = [
ScientistAdmin.fieldset_basic,
ScientistAdmin.fieldset_advanced,
]
admin.site.unregister(Scientist)
admin.site.register(Scientist, CMSScientistAdmin)
| from django.contrib import admin
from cms.admin.placeholderadmin import PlaceholderAdminMixin
from lab_members.models import Scientist
from lab_members.admin import ScientistAdmin
class CMSScientistAdmin(PlaceholderAdminMixin, ScientistAdmin):
fieldsets = [
ScientistAdmin.fieldset_basic,
ScientistAdmin.fieldset_website,
ScientistAdmin.fieldset_advanced,
]
admin.site.unregister(Scientist)
admin.site.register(Scientist, CMSScientistAdmin)
| Add new lab_members fieldset_website to fieldsets for cms_lab_members | Add new lab_members fieldset_website to fieldsets for cms_lab_members
| Python | bsd-3-clause | mfcovington/djangocms-lab-members,mfcovington/djangocms-lab-members | ---
+++
@@ -7,6 +7,7 @@
class CMSScientistAdmin(PlaceholderAdminMixin, ScientistAdmin):
fieldsets = [
ScientistAdmin.fieldset_basic,
+ ScientistAdmin.fieldset_website,
ScientistAdmin.fieldset_advanced,
]
|
3026d78dc6e2a0f6f391819370f2369df94e77eb | ckanext/nhm/settings.py | ckanext/nhm/settings.py | #!/usr/bin/env python
# encoding: utf-8
#
# This file is part of ckanext-nhm
# Created by the Natural History Museum in London, UK
from collections import OrderedDict
# the order here matters as the default option should always be first in the dict so that it is
# automatically selected in combo boxes that use this list as a source for options
COLLECTION_CONTACTS = OrderedDict([
('Data Portal / Other', 'data@nhm.ac.uk'),
('Algae, Fungi & Plants', 'm.carine@nhm.ac.uk'),
('Economic & Environmental Earth Sciences', 'g.miller@nhm.ac.uk'),
('Fossil Invertebrates & Plants', 'z.hughes@nhm.ac.uk'),
('Fossil Vertebrates & Anthropology', 'm.richter@nhm.ac.uk'),
('Insects', 'g.broad@nhm.ac.uk'),
('Invertebrates', 'm.lowe@nhm.ac.uk'),
('Library & Archives', 'library@nhm.ac.uk'),
('Mineral & Planetary Sciences', 'm.rumsey@nhm.ac.uk'),
('Vertebrates', 'simon.loader@nhm.ac.uk'),
])
| #!/usr/bin/env python
# encoding: utf-8
#
# This file is part of ckanext-nhm
# Created by the Natural History Museum in London, UK
from collections import OrderedDict
# the order here matters as the default option should always be first in the dict so that it is
# automatically selected in combo boxes that use this list as a source for options
COLLECTION_CONTACTS = OrderedDict([
('Algae, Fungi & Plants', 'm.carine@nhm.ac.uk'),
('Economic & Environmental Earth Sciences', 'g.miller@nhm.ac.uk'),
('Fossil Invertebrates & Plants', 'z.hughes@nhm.ac.uk'),
('Fossil Vertebrates & Anthropology', 'm.richter@nhm.ac.uk'),
('Insects', 'g.broad@nhm.ac.uk'),
('Invertebrates', 'm.lowe@nhm.ac.uk'),
('Library & Archives', 'library@nhm.ac.uk'),
('Mineral & Planetary Sciences', 'm.rumsey@nhm.ac.uk'),
('Vertebrates', 'simon.loader@nhm.ac.uk'),
('Data Portal / Other', 'data@nhm.ac.uk'),
])
| Move Data Portal / Other to bottom of contact select | Move Data Portal / Other to bottom of contact select
| Python | mit | NaturalHistoryMuseum/ckanext-nhm,NaturalHistoryMuseum/ckanext-nhm,NaturalHistoryMuseum/ckanext-nhm | ---
+++
@@ -8,7 +8,6 @@
# the order here matters as the default option should always be first in the dict so that it is
# automatically selected in combo boxes that use this list as a source for options
COLLECTION_CONTACTS = OrderedDict([
- ('Data Portal / Other', 'data@nhm.ac.uk'),
('Algae, Fungi & Plants', 'm.carine@nhm.ac.uk'),
('Economic & Environmental Earth Sciences', 'g.miller@nhm.ac.uk'),
('Fossil Invertebrates & Plants', 'z.hughes@nhm.ac.uk'),
@@ -18,4 +17,5 @@
('Library & Archives', 'library@nhm.ac.uk'),
('Mineral & Planetary Sciences', 'm.rumsey@nhm.ac.uk'),
('Vertebrates', 'simon.loader@nhm.ac.uk'),
+ ('Data Portal / Other', 'data@nhm.ac.uk'),
]) |
34fa7433ea6f04089a420e0392605147669801d1 | dummy.py | dummy.py | import os
def foo():
"""
This is crappy function. should be removed using git checkout
"""
if True == True:
return True
else:
return False
def main():
pass
if __name__ == '__main__':
main()
| import os
def foo():
"""
This is crappy function. should be removed using git checkout
"""
return None
def main():
pass
if __name__ == '__main__':
main()
| Revert "added more crappy codes" | Revert "added more crappy codes"
This reverts commit 6f10d506bf36572b53f0325fef6dc8a1bac5f4fd.
| Python | apache-2.0 | kp89/do-git | ---
+++
@@ -4,11 +4,7 @@
"""
This is crappy function. should be removed using git checkout
"""
- if True == True:
- return True
- else:
- return False
-
+ return None
def main():
pass |
178bde1703bbb044f8af8c70a57517af4490a3c0 | databot/handlers/download.py | databot/handlers/download.py | import time
import requests
import bs4
from databot.recursive import call
class DownloadErrror(Exception):
pass
def dump_response(response):
return {
'headers': dict(response.headers),
'cookies': dict(response.cookies),
'status_code': response.status_code,
'encoding': response.encoding,
'content': response.content,
}
def download(url, delay=None, update=None, **kwargs):
update = update or {}
def func(row):
if delay is not None:
time.sleep(delay)
kw = call(kwargs, row)
_url = url(row)
response = requests.get(_url, **kw)
if response.status_code == 200:
value = dump_response(response)
for k, fn in update.items():
value[k] = fn(row)
yield _url, value
else:
raise DownloadErrror('Error while downloading %s, returned status code was %s, response content:\n\n%s' % (
_url, response.status_code, response.content,
))
return func
def get_content(data):
content_type = data.get('headers', {}).get('Content-Type')
if content_type == 'text/html':
soup = bs4.BeautifulSoup(data['content'], 'lxml')
return data['content'].decode(soup.original_encoding)
else:
return data['content']
| import time
import requests
import bs4
import cgi
from databot.recursive import call
class DownloadErrror(Exception):
pass
def dump_response(response):
return {
'headers': dict(response.headers),
'cookies': response.cookies.get_dict(),
'status_code': response.status_code,
'encoding': response.encoding,
'content': response.content,
}
def download(url, delay=None, update=None, **kwargs):
update = update or {}
def func(row):
if delay is not None:
time.sleep(delay)
kw = call(kwargs, row)
_url = url(row)
response = requests.get(_url, **kw)
if response.status_code == 200:
value = dump_response(response)
for k, fn in update.items():
value[k] = fn(row)
yield _url, value
else:
raise DownloadErrror('Error while downloading %s, returned status code was %s, response content:\n\n%s' % (
_url, response.status_code, response.content,
))
return func
def get_content(data):
content_type_header = data.get('headers', {}).get('Content-Type', '')
content_type, params = cgi.parse_header(content_type_header)
if content_type == 'text/html':
soup = bs4.BeautifulSoup(data['content'], 'lxml')
return data['content'].decode(soup.original_encoding)
else:
return data['content']
| Fix duplicate cookie issue and header parsing | Fix duplicate cookie issue and header parsing
| Python | agpl-3.0 | sirex/databot,sirex/databot | ---
+++
@@ -1,6 +1,7 @@
import time
import requests
import bs4
+import cgi
from databot.recursive import call
@@ -12,7 +13,7 @@
def dump_response(response):
return {
'headers': dict(response.headers),
- 'cookies': dict(response.cookies),
+ 'cookies': response.cookies.get_dict(),
'status_code': response.status_code,
'encoding': response.encoding,
'content': response.content,
@@ -42,7 +43,8 @@
def get_content(data):
- content_type = data.get('headers', {}).get('Content-Type')
+ content_type_header = data.get('headers', {}).get('Content-Type', '')
+ content_type, params = cgi.parse_header(content_type_header)
if content_type == 'text/html':
soup = bs4.BeautifulSoup(data['content'], 'lxml')
return data['content'].decode(soup.original_encoding) |
cbae828ee9eb91a2373a415f1a1521fb5dee3100 | datac/main.py | datac/main.py | # -*- coding: utf-8 -*-
import copy
| # -*- coding: utf-8 -*-
import copy
def init_abscissa(params, abscissae, abscissa_name):
"""
List of dicts to initialize object w/ calc method
This method generates a list of dicts; each dict is sufficient to initialize an object featuring a calculator method of interest. This list can be thought of as the abscissae of a set of data. Each dict will contain data which remains constant for each calculation, but it nonetheless required to initialize the object. Each dict will also contain a datum which is the abscissa for the calculation and is also required to initialize the object.
:param dict params: Static parameters required to initialize the object featuring the ordinate calculator method.
:param list abscissae: Independent variable also required to initialize object featuring the ordinate calculator method.
:param str abscissa_name: Dictionary key for the abscissa name.
"""
dict_list = []
for abscissa in abscissae:
param_dict = copy.copy(params)
param_dict[abscissa_name] = abscissa
param_dict["abscissa_name"] = abscissa_name
dict_list.append(param_dict)
return dict_list
| Add method to generate list of abscissa dicts | Add method to generate list of abscissa dicts
This method will generate a list of dicts which can initialize an
object which features a method to calculate the ordinates the user
wants.
| Python | mit | jrsmith3/datac,jrsmith3/datac | ---
+++
@@ -1,2 +1,22 @@
# -*- coding: utf-8 -*-
import copy
+
+def init_abscissa(params, abscissae, abscissa_name):
+ """
+ List of dicts to initialize object w/ calc method
+
+ This method generates a list of dicts; each dict is sufficient to initialize an object featuring a calculator method of interest. This list can be thought of as the abscissae of a set of data. Each dict will contain data which remains constant for each calculation, but it nonetheless required to initialize the object. Each dict will also contain a datum which is the abscissa for the calculation and is also required to initialize the object.
+
+ :param dict params: Static parameters required to initialize the object featuring the ordinate calculator method.
+ :param list abscissae: Independent variable also required to initialize object featuring the ordinate calculator method.
+ :param str abscissa_name: Dictionary key for the abscissa name.
+ """
+ dict_list = []
+
+ for abscissa in abscissae:
+ param_dict = copy.copy(params)
+ param_dict[abscissa_name] = abscissa
+ param_dict["abscissa_name"] = abscissa_name
+ dict_list.append(param_dict)
+
+ return dict_list |
cd5053ac36e13b57e95eeb1241032c97b48a4a85 | planetstack/openstack_observer/backend.py | planetstack/openstack_observer/backend.py | import threading
import time
from observer.event_loop import PlanetStackObserver
from observer.event_manager import EventListener
from util.logger import Logger, logging
logger = Logger(level=logging.INFO)
class Backend:
def run(self):
try:
# start the openstack observer
observer = PlanetStackObserver()
observer_thread = threading.Thread(target=observer.run)
observer_thread.start()
# start event listene
event_manager = EventListener(wake_up=observer.wake_up)
event_manager_thread = threading.Thread(target=event_manager.run)
event_manager_thread.start()
except:
logger.log_exc("Exception in child thread")
| import threading
import time
from observer.event_loop import PlanetStackObserver
from observer.event_manager import EventListener
from util.logger import Logger, logging
logger = Logger(level=logging.INFO)
class Backend:
def run(self):
# start the openstack observer
observer = PlanetStackObserver()
observer_thread = threading.Thread(target=observer.run)
observer_thread.start()
# start event listene
event_manager = EventListener(wake_up=observer.wake_up)
event_manager_thread = threading.Thread(target=event_manager.run)
event_manager_thread.start()
| Drop try/catch that causes uncaught errors in the Observer to be silently ignored | Drop try/catch that causes uncaught errors in the Observer to be silently ignored
| Python | apache-2.0 | wathsalav/xos,wathsalav/xos,wathsalav/xos,wathsalav/xos | ---
+++
@@ -9,7 +9,6 @@
class Backend:
def run(self):
- try:
# start the openstack observer
observer = PlanetStackObserver()
observer_thread = threading.Thread(target=observer.run)
@@ -19,6 +18,4 @@
event_manager = EventListener(wake_up=observer.wake_up)
event_manager_thread = threading.Thread(target=event_manager.run)
event_manager_thread.start()
- except:
- logger.log_exc("Exception in child thread")
|
37fa40a9b5260f8090adaa8c15d3767c0867574f | python/fusion_engine_client/messages/__init__.py | python/fusion_engine_client/messages/__init__.py | from .core import *
from . import ros
message_type_to_class = {
# Navigation solution messages.
PoseMessage.MESSAGE_TYPE: PoseMessage,
PoseAuxMessage.MESSAGE_TYPE: PoseAuxMessage,
GNSSInfoMessage.MESSAGE_TYPE: GNSSInfoMessage,
GNSSSatelliteMessage.MESSAGE_TYPE: GNSSSatelliteMessage,
# Sensor measurement messages.
IMUMeasurement.MESSAGE_TYPE: IMUMeasurement,
# ROS messages.
ros.PoseMessage.MESSAGE_TYPE: ros.PoseMessage,
ros.GPSFixMessage.MESSAGE_TYPE: ros.GPSFixMessage,
ros.IMUMessage.MESSAGE_TYPE: ros.IMUMessage,
# Command and control messages.
CommandResponseMessage.MESSAGE_TYPE: CommandResponseMessage,
MessageRequest.MESSAGE_TYPE: MessageRequest,
ResetRequest.MESSAGE_TYPE: ResetRequest,
VersionInfoMessage.MESSAGE_TYPE: VersionInfoMessage,
EventNotificationMessage.MESSAGE_TYPE: EventNotificationMessage,
}
| from .core import *
from . import ros
message_type_to_class = {
# Navigation solution messages.
PoseMessage.MESSAGE_TYPE: PoseMessage,
PoseAuxMessage.MESSAGE_TYPE: PoseAuxMessage,
GNSSInfoMessage.MESSAGE_TYPE: GNSSInfoMessage,
GNSSSatelliteMessage.MESSAGE_TYPE: GNSSSatelliteMessage,
# Sensor measurement messages.
IMUMeasurement.MESSAGE_TYPE: IMUMeasurement,
# ROS messages.
ros.PoseMessage.MESSAGE_TYPE: ros.PoseMessage,
ros.GPSFixMessage.MESSAGE_TYPE: ros.GPSFixMessage,
ros.IMUMessage.MESSAGE_TYPE: ros.IMUMessage,
# Command and control messages.
CommandResponseMessage.MESSAGE_TYPE: CommandResponseMessage,
MessageRequest.MESSAGE_TYPE: MessageRequest,
ResetRequest.MESSAGE_TYPE: ResetRequest,
VersionInfoMessage.MESSAGE_TYPE: VersionInfoMessage,
EventNotificationMessage.MESSAGE_TYPE: EventNotificationMessage,
}
messages_with_system_time = [t for t, c in message_type_to_class.items() if hasattr(c(), 'system_time_ns')]
| Create a list of messages that contain system time. | Create a list of messages that contain system time.
| Python | mit | PointOneNav/fusion-engine-client,PointOneNav/fusion-engine-client,PointOneNav/fusion-engine-client | ---
+++
@@ -23,3 +23,5 @@
VersionInfoMessage.MESSAGE_TYPE: VersionInfoMessage,
EventNotificationMessage.MESSAGE_TYPE: EventNotificationMessage,
}
+
+messages_with_system_time = [t for t, c in message_type_to_class.items() if hasattr(c(), 'system_time_ns')] |
68c4f723f5eea2802209862d323825f33a445154 | eventex/subscriptions/urls.py | eventex/subscriptions/urls.py | from django.urls import path
import eventex.subscriptions.views as s
app_name = 'subscriptions'
urlpatterns = [
path('', s.new, name='new'),
path('<int:id>/', s.detail, name='detail'),
path('json/donut/', s.paid_list_json, name='paid_list_json'),
path('json/column/', s.paid_column_json, name='paid_column_json'),
path('graphic/', s.graphic, name='graphic'),
]
| from django.urls import path
import eventex.subscriptions.views as s
app_name = 'subscriptions'
urlpatterns = [
path('', s.new, name='new'),
path('<int:pk>/', s.detail, name='detail'),
path('json/donut/', s.paid_list_json, name='paid_list_json'),
path('json/column/', s.paid_column_json, name='paid_column_json'),
path('graphic/', s.graphic, name='graphic'),
]
| Fix url id to pk. | Fix url id to pk.
| Python | mit | rg3915/wttd2,rg3915/wttd2,rg3915/wttd2,rg3915/wttd2 | ---
+++
@@ -7,7 +7,7 @@
urlpatterns = [
path('', s.new, name='new'),
- path('<int:id>/', s.detail, name='detail'),
+ path('<int:pk>/', s.detail, name='detail'),
path('json/donut/', s.paid_list_json, name='paid_list_json'),
path('json/column/', s.paid_column_json, name='paid_column_json'),
path('graphic/', s.graphic, name='graphic'), |
05939b0b797780ac1d265c8415f72f1ca44be53d | coco/dashboard/views.py | coco/dashboard/views.py | # -*- coding: utf-8 -*-
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from posts.models import Post, Tag
@login_required
def index(request):
context = {'posts': Post.objects.all()}
return render(request, 'dashboard/index.html', context)
@login_required
def tagged_posts(request, tag_name=""):
context = {'posts': Post.objects.filter(tags__name=tag_name)}
return render(request, 'dashboard/search_result.html', context)
| # -*- coding: utf-8 -*-
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from posts.models import Post, Tag
@login_required
def index(request):
context = {'posts': Post.objects.all()}
return render(request, 'dashboard/index.html', context)
@login_required
def tagged_posts(request, tag_name=""):
context = {
'tag': tag_name,
'posts': Post.objects.filter(tags__name=tag_name)
}
return render(request, 'dashboard/search_result.html', context)
| Modify return tag search data with tag_name | Modify return tag search data with tag_name
| Python | mit | NA5G/coco-server-was,NA5G/coco-server-was,NA5G/coco-server-was | ---
+++
@@ -11,5 +11,8 @@
@login_required
def tagged_posts(request, tag_name=""):
- context = {'posts': Post.objects.filter(tags__name=tag_name)}
+ context = {
+ 'tag': tag_name,
+ 'posts': Post.objects.filter(tags__name=tag_name)
+ }
return render(request, 'dashboard/search_result.html', context) |
c81393a8de27595f61cffc09fa6fa8352bb54b9c | palindrome-products/palindrome_products.py | palindrome-products/palindrome_products.py | from collections import defaultdict
def largest_palindrome(max_factor, min_factor=0):
return _palindromes(max_factor, min_factor, max)
def smallest_palindrome(max_factor, min_factor=0):
return _palindromes(max_factor, min_factor, min)
def _palindromes(max_factor, min_factor, minmax):
pals = defaultdict(set)
for i in range(min_factor, max_factor+1):
for j in range(min_factor, max_factor+1):
p = i * j
if is_palindrome(p):
pals[p].add(tuple(sorted([i,j])))
value = minmax(pals)
factors = pals[value]
return (value, factors)
def is_palindrome(n):
return str(n) == str(n)[::-1]
| import random
from collections import defaultdict
def largest_palindrome(max_factor, min_factor=0):
return _palindromes(max_factor, min_factor, max)
def smallest_palindrome(max_factor, min_factor=0):
return _palindromes(max_factor, min_factor, min)
def _palindromes(max_factor, min_factor, minmax):
pals = defaultdict(set)
for i in range(min_factor, max_factor+1):
for j in range(min_factor, max_factor+1):
p = i * j
if is_palindrome(p):
pals[p].add(tuple(sorted([i,j])))
value = minmax(pals)
factors = random.choice(list(pals[value]))
return (value, factors)
def is_palindrome(n):
return str(n) == str(n)[::-1]
| Return a random set of factors | Return a random set of factors
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | ---
+++
@@ -1,3 +1,4 @@
+import random
from collections import defaultdict
@@ -19,7 +20,7 @@
pals[p].add(tuple(sorted([i,j])))
value = minmax(pals)
- factors = pals[value]
+ factors = random.choice(list(pals[value]))
return (value, factors)
|
9de0a05d28c83742224c0e708e80b8add198a8a8 | froide/comments/apps.py | froide/comments/apps.py | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class CommentConfig(AppConfig):
name = 'froide.comments'
verbose_name = _('Comments')
def ready(self):
from froide.account import account_canceled
account_canceled.connect(cancel_user)
def cancel_user(sender, user=None, **kwargs):
from .models import FroideComment
if user is None:
return
FroideComment.objects.filter(user=user).update(
user_name='',
user_email='',
user_url=''
)
| import json
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class CommentConfig(AppConfig):
name = 'froide.comments'
verbose_name = _('Comments')
def ready(self):
from froide.account import account_canceled
from froide.account.export import registry
account_canceled.connect(cancel_user)
registry.register(export_user_data)
def cancel_user(sender, user=None, **kwargs):
from .models import FroideComment
if user is None:
return
FroideComment.objects.filter(user=user).update(
user_name='',
user_email='',
user_url=''
)
def export_user_data(user):
from .models import FroideComment
comments = FroideComment.objects.filter(user=user)
if not comments:
return
yield ('comments.json', json.dumps([
{
'submit_date': (
c.submit_date.isoformat() if c.submit_date else None
),
'comment': c.comment,
'is_public': c.is_public,
'is_removed': c.is_removed,
'url': c.get_absolute_url(),
}
for c in comments]).encode('utf-8')
)
| Add user data export for comments | Add user data export for comments | Python | mit | stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide | ---
+++
@@ -1,3 +1,5 @@
+import json
+
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
@@ -8,8 +10,10 @@
def ready(self):
from froide.account import account_canceled
+ from froide.account.export import registry
account_canceled.connect(cancel_user)
+ registry.register(export_user_data)
def cancel_user(sender, user=None, **kwargs):
@@ -22,3 +26,23 @@
user_email='',
user_url=''
)
+
+
+def export_user_data(user):
+ from .models import FroideComment
+
+ comments = FroideComment.objects.filter(user=user)
+ if not comments:
+ return
+ yield ('comments.json', json.dumps([
+ {
+ 'submit_date': (
+ c.submit_date.isoformat() if c.submit_date else None
+ ),
+ 'comment': c.comment,
+ 'is_public': c.is_public,
+ 'is_removed': c.is_removed,
+ 'url': c.get_absolute_url(),
+ }
+ for c in comments]).encode('utf-8')
+ ) |
07aca8e96d5e93edb684d0c4684ef8f837e8fc58 | readthedocs/doc_builder/loader.py | readthedocs/doc_builder/loader.py | from django.utils.importlib import import_module
from django.conf import settings
# Managers
mkdocs = import_module(getattr(settings, 'MKDOCS_BACKEND', 'doc_builder.backends.mkdocs'))
sphinx = import_module(getattr(settings, 'SPHINX_BACKEND', 'doc_builder.backends.sphinx'))
loading = {
# Possible HTML Builders
'sphinx': sphinx.HtmlBuilderComments,
'sphinx_htmldir': sphinx.HtmlDirBuilder,
'sphinx_singlehtml': sphinx.SingleHtmlBuilder,
# Other Sphinx Builders
'sphinx_pdf': sphinx.PdfBuilder,
'sphinx_epub': sphinx.EpubBuilder,
'sphinx_search': sphinx.SearchBuilder,
'sphinx_singlehtmllocalmedia': sphinx.LocalMediaBuilder,
# Other markup
'mkdocs': mkdocs.MkdocsHTML,
'mkdocs_json': mkdocs.MkdocsJSON,
}
| from django.utils.importlib import import_module
from django.conf import settings
# Managers
mkdocs = import_module(getattr(settings, 'MKDOCS_BACKEND', 'doc_builder.backends.mkdocs'))
sphinx = import_module(getattr(settings, 'SPHINX_BACKEND', 'doc_builder.backends.sphinx'))
loading = {
# Possible HTML Builders
'sphinx': sphinx.HtmlBuilderComments,
'sphinx_htmldir': sphinx.HtmlDirBuilderComments,
'sphinx_singlehtml': sphinx.SingleHtmlBuilder,
# Other Sphinx Builders
'sphinx_pdf': sphinx.PdfBuilder,
'sphinx_epub': sphinx.EpubBuilder,
'sphinx_search': sphinx.SearchBuilder,
'sphinx_singlehtmllocalmedia': sphinx.LocalMediaBuilder,
# Other markup
'mkdocs': mkdocs.MkdocsHTML,
'mkdocs_json': mkdocs.MkdocsJSON,
}
| Use comment builder for dirhtml too | Use comment builder for dirhtml too
| Python | mit | sunnyzwh/readthedocs.org,hach-que/readthedocs.org,kenwang76/readthedocs.org,singingwolfboy/readthedocs.org,sid-kap/readthedocs.org,michaelmcandrew/readthedocs.org,dirn/readthedocs.org,sid-kap/readthedocs.org,espdev/readthedocs.org,tddv/readthedocs.org,mrshoki/readthedocs.org,SteveViss/readthedocs.org,sils1297/readthedocs.org,Tazer/readthedocs.org,raven47git/readthedocs.org,gjtorikian/readthedocs.org,kenwang76/readthedocs.org,VishvajitP/readthedocs.org,kenshinthebattosai/readthedocs.org,pombredanne/readthedocs.org,emawind84/readthedocs.org,clarkperkins/readthedocs.org,soulshake/readthedocs.org,stevepiercy/readthedocs.org,emawind84/readthedocs.org,kdkeyser/readthedocs.org,nikolas/readthedocs.org,soulshake/readthedocs.org,mhils/readthedocs.org,techtonik/readthedocs.org,LukasBoersma/readthedocs.org,sils1297/readthedocs.org,safwanrahman/readthedocs.org,royalwang/readthedocs.org,SteveViss/readthedocs.org,kenshinthebattosai/readthedocs.org,CedarLogic/readthedocs.org,VishvajitP/readthedocs.org,techtonik/readthedocs.org,jerel/readthedocs.org,attakei/readthedocs-oauth,takluyver/readthedocs.org,Tazer/readthedocs.org,techtonik/readthedocs.org,kenwang76/readthedocs.org,CedarLogic/readthedocs.org,clarkperkins/readthedocs.org,fujita-shintaro/readthedocs.org,soulshake/readthedocs.org,clarkperkins/readthedocs.org,titiushko/readthedocs.org,GovReady/readthedocs.org,tddv/readthedocs.org,Tazer/readthedocs.org,michaelmcandrew/readthedocs.org,royalwang/readthedocs.org,hach-que/readthedocs.org,d0ugal/readthedocs.org,asampat3090/readthedocs.org,wanghaven/readthedocs.org,LukasBoersma/readthedocs.org,Carreau/readthedocs.org,safwanrahman/readthedocs.org,istresearch/readthedocs.org,cgourlay/readthedocs.org,GovReady/readthedocs.org,agjohnson/readthedocs.org,mhils/readthedocs.org,dirn/readthedocs.org,Carreau/readthedocs.org,istresearch/readthedocs.org,atsuyim/readthedocs.org,pombredanne/readthedocs.org,fujita-shintaro/readthedocs.org,titiushko/readthedocs.org,wanghaven/readthedocs.org,safwanrahman/readthedocs.org,agjohnson/readthedocs.org,istresearch/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,laplaceliu/readthedocs.org,hach-que/readthedocs.org,cgourlay/readthedocs.org,davidfischer/readthedocs.org,stevepiercy/readthedocs.org,CedarLogic/readthedocs.org,royalwang/readthedocs.org,Tazer/readthedocs.org,rtfd/readthedocs.org,clarkperkins/readthedocs.org,raven47git/readthedocs.org,dirn/readthedocs.org,gjtorikian/readthedocs.org,sils1297/readthedocs.org,emawind84/readthedocs.org,singingwolfboy/readthedocs.org,jerel/readthedocs.org,safwanrahman/readthedocs.org,nikolas/readthedocs.org,mrshoki/readthedocs.org,wijerasa/readthedocs.org,wijerasa/readthedocs.org,royalwang/readthedocs.org,KamranMackey/readthedocs.org,espdev/readthedocs.org,Carreau/readthedocs.org,istresearch/readthedocs.org,titiushko/readthedocs.org,davidfischer/readthedocs.org,espdev/readthedocs.org,laplaceliu/readthedocs.org,emawind84/readthedocs.org,d0ugal/readthedocs.org,atsuyim/readthedocs.org,SteveViss/readthedocs.org,singingwolfboy/readthedocs.org,KamranMackey/readthedocs.org,atsuyim/readthedocs.org,attakei/readthedocs-oauth,fujita-shintaro/readthedocs.org,mhils/readthedocs.org,sid-kap/readthedocs.org,davidfischer/readthedocs.org,laplaceliu/readthedocs.org,singingwolfboy/readthedocs.org,VishvajitP/readthedocs.org,jerel/readthedocs.org,sid-kap/readthedocs.org,d0ugal/readthedocs.org,atsuyim/readthedocs.org,raven47git/readthedocs.org,attakei/readthedocs-oauth,kenwang76/readthedocs.org,LukasBoersma/readthedocs.org,asampat3090/readthedocs.org,takluyver/readthedocs.org,stevepiercy/readthedocs.org,kenshinthebattosai/readthedocs.org,asampat3090/readthedocs.org,takluyver/readthedocs.org,hach-que/readthedocs.org,sils1297/readthedocs.org,rtfd/readthedocs.org,gjtorikian/readthedocs.org,sunnyzwh/readthedocs.org,VishvajitP/readthedocs.org,titiushko/readthedocs.org,mrshoki/readthedocs.org,espdev/readthedocs.org,michaelmcandrew/readthedocs.org,agjohnson/readthedocs.org,kdkeyser/readthedocs.org,techtonik/readthedocs.org,SteveViss/readthedocs.org,raven47git/readthedocs.org,agjohnson/readthedocs.org,cgourlay/readthedocs.org,pombredanne/readthedocs.org,wanghaven/readthedocs.org,wanghaven/readthedocs.org,asampat3090/readthedocs.org,espdev/readthedocs.org,takluyver/readthedocs.org,GovReady/readthedocs.org,dirn/readthedocs.org,wijerasa/readthedocs.org,sunnyzwh/readthedocs.org,michaelmcandrew/readthedocs.org,gjtorikian/readthedocs.org,KamranMackey/readthedocs.org,wijerasa/readthedocs.org,jerel/readthedocs.org,stevepiercy/readthedocs.org,fujita-shintaro/readthedocs.org,attakei/readthedocs-oauth,Carreau/readthedocs.org,d0ugal/readthedocs.org,nikolas/readthedocs.org,kenshinthebattosai/readthedocs.org,nikolas/readthedocs.org,sunnyzwh/readthedocs.org,KamranMackey/readthedocs.org,kdkeyser/readthedocs.org,kdkeyser/readthedocs.org,LukasBoersma/readthedocs.org,CedarLogic/readthedocs.org,mrshoki/readthedocs.org,tddv/readthedocs.org,mhils/readthedocs.org,cgourlay/readthedocs.org,laplaceliu/readthedocs.org,GovReady/readthedocs.org,davidfischer/readthedocs.org,soulshake/readthedocs.org | ---
+++
@@ -8,7 +8,7 @@
loading = {
# Possible HTML Builders
'sphinx': sphinx.HtmlBuilderComments,
- 'sphinx_htmldir': sphinx.HtmlDirBuilder,
+ 'sphinx_htmldir': sphinx.HtmlDirBuilderComments,
'sphinx_singlehtml': sphinx.SingleHtmlBuilder,
# Other Sphinx Builders
'sphinx_pdf': sphinx.PdfBuilder, |
c3b0d4b05314dc9fd51c790a86d30659d09c5250 | wagtailgeowidget/helpers.py | wagtailgeowidget/helpers.py | import re
geos_ptrn = re.compile(
"^SRID=([0-9]{1,});POINT\(([0-9\.]{1,})\s([0-9\.]{1,})\)$"
)
def geosgeometry_str_to_struct(value):
'''
Parses a geosgeometry string into struct.
Example:
SRID=5432;POINT(12.0 13.0)
Returns:
>> [5432, 12.0, 13.0]
'''
result = geos_ptrn.match(value)
if not result:
return None
return {
'srid': result.group(1),
'x': result.group(2),
'y': result.group(3),
}
| import re
geos_ptrn = re.compile(
"^SRID=([0-9]{1,});POINT\((-?[0-9\.]{1,})\s(-?[0-9\.]{1,})\)$"
)
def geosgeometry_str_to_struct(value):
'''
Parses a geosgeometry string into struct.
Example:
SRID=5432;POINT(12.0 13.0)
Returns:
>> [5432, 12.0, 13.0]
'''
result = geos_ptrn.match(value)
if not result:
return None
return {
'srid': result.group(1),
'x': result.group(2),
'y': result.group(3),
}
| Allow negative numbers in the GEOS string | Allow negative numbers in the GEOS string
The regular expression for parsing the GEOS string did not accept
negative numbers. This means if you selected a location in most parts of
the world the retrieve would fail and the map would center around the
default location.
Add optional hypen symbol to the GEOS regular expression.
| Python | mit | Frojd/wagtail-geo-widget,Frojd/wagtail-geo-widget,Frojd/wagtail-geo-widget,Frojd/wagtail-geo-widget | ---
+++
@@ -1,7 +1,7 @@
import re
geos_ptrn = re.compile(
- "^SRID=([0-9]{1,});POINT\(([0-9\.]{1,})\s([0-9\.]{1,})\)$"
+ "^SRID=([0-9]{1,});POINT\((-?[0-9\.]{1,})\s(-?[0-9\.]{1,})\)$"
)
|
7e45a26f86095ee2f6972e08697aa132e642636e | csympy/tests/test_arit.py | csympy/tests/test_arit.py | from csympy import Symbol, Integer
def test_arit1():
x = Symbol("x")
y = Symbol("y")
e = x + y
e = x * y
e = Integer(2)*x
e = 2*x
def test_arit2():
x = Symbol("x")
y = Symbol("y")
assert x+x == Integer(2) * x
assert x+x != Integer(3) * x
assert x+x == 2 * x
| from nose.tools import raises
from csympy import Symbol, Integer
def test_arit1():
x = Symbol("x")
y = Symbol("y")
e = x + y
e = x * y
e = Integer(2)*x
e = 2*x
def test_arit2():
x = Symbol("x")
y = Symbol("y")
assert x+x == Integer(2) * x
assert x+x != Integer(3) * x
assert x+x == 2 * x
@raises(TypeError)
def test_arit3():
x = Symbol("x")
y = Symbol("y")
e = "x"*x
| Test for types in __mul__ | Test for types in __mul__
| Python | mit | bjodah/symengine.py,bjodah/symengine.py,symengine/symengine.py,bjodah/symengine.py,symengine/symengine.py,symengine/symengine.py | ---
+++
@@ -1,3 +1,5 @@
+from nose.tools import raises
+
from csympy import Symbol, Integer
def test_arit1():
@@ -14,3 +16,9 @@
assert x+x == Integer(2) * x
assert x+x != Integer(3) * x
assert x+x == 2 * x
+
+@raises(TypeError)
+def test_arit3():
+ x = Symbol("x")
+ y = Symbol("y")
+ e = "x"*x |
34db4460aa67fc9abfaaaf2c48a6ea7c5b801ff0 | examples/libtest/imports/__init__.py | examples/libtest/imports/__init__.py |
exec_order = []
class Imports(object):
exec_order = exec_order
def __init__(self):
self.v = 1
imports = Imports()
overrideme = "not overridden"
from . import cls as loccls
from .imports import cls as upcls
def conditional_func():
return "not overridden"
if True:
def conditional_func():
return "overridden"
|
exec_order = []
class Imports(object):
exec_order = exec_order
def __init__(self):
self.v = 1
imports = Imports()
overrideme = "not overridden"
from . import cls as loccls
# This is not valid since Python 2.6!
try:
from .imports import cls as upcls
except ImportError:
upcls = loccls
def conditional_func():
return "not overridden"
if True:
def conditional_func():
return "overridden"
| Fix for libtest for cpython 2.6 / jython / pypy | Fix for libtest for cpython 2.6 / jython / pypy
| Python | apache-2.0 | spaceone/pyjs,minghuascode/pyj,pombredanne/pyjs,lancezlin/pyjs,Hasimir/pyjs,gpitel/pyjs,pyjs/pyjs,anandology/pyjamas,gpitel/pyjs,pombredanne/pyjs,minghuascode/pyj,minghuascode/pyj,lancezlin/pyjs,pyjs/pyjs,pyjs/pyjs,pyjs/pyjs,minghuascode/pyj,spaceone/pyjs,spaceone/pyjs,anandology/pyjamas,Hasimir/pyjs,pombredanne/pyjs,pombredanne/pyjs,gpitel/pyjs,anandology/pyjamas,Hasimir/pyjs,spaceone/pyjs,Hasimir/pyjs,lancezlin/pyjs,lancezlin/pyjs,anandology/pyjamas,gpitel/pyjs | ---
+++
@@ -11,7 +11,12 @@
overrideme = "not overridden"
from . import cls as loccls
-from .imports import cls as upcls
+
+# This is not valid since Python 2.6!
+try:
+ from .imports import cls as upcls
+except ImportError:
+ upcls = loccls
def conditional_func():
return "not overridden" |
586418860c0441eaebadd0fe79989d6d9f90fa28 | src/bda/plone/productshop/vocabularies.py | src/bda/plone/productshop/vocabularies.py | from zope.interface import directlyProvides
from zope.schema.interfaces import IVocabularyFactory
from zope.schema.vocabulary import (
SimpleVocabulary,
SimpleTerm,
)
from zope.i18nmessageid import MessageFactory
from .utils import (
dotted_name,
available_variant_aspects,
)
#added by espen
from zope.component import getUtility
from plone.dexterity.interfaces import IDexterityFTI
from zope.component import ComponentLookupError
_ = MessageFactory('bda.plone.productshop')
def AvailableVariantAspectsVocabulary(context):
terms = list()
for definition in available_variant_aspects():
terms.append(SimpleTerm(value=dotted_name(definition.interface),
title=definition.title))
return SimpleVocabulary(terms)
directlyProvides(AvailableVariantAspectsVocabulary, IVocabularyFactory)
def RtfFieldsVocabulary(context):
try:
type = getUtility(IDexterityFTI, name='bda.plone.productshop.product')
fields = type.lookupSchema()
terms = [ SimpleTerm(value=pair, token=pair, title=pair) for pair in fields]
return SimpleVocabulary(terms)
except KeyError:
pass
finally:
pass
directlyProvides(RtfFieldsVocabulary, IVocabularyFactory)
| from zope.interface import directlyProvides
from zope.schema.interfaces import IVocabularyFactory
from zope.schema.vocabulary import (
SimpleVocabulary,
SimpleTerm,
)
from zope.i18nmessageid import MessageFactory
from .utils import (
dotted_name,
available_variant_aspects,
)
#added by espen
from zope.component import getUtility
from plone.dexterity.interfaces import IDexterityFTI
_ = MessageFactory('bda.plone.productshop')
def AvailableVariantAspectsVocabulary(context):
terms = list()
for definition in available_variant_aspects():
terms.append(SimpleTerm(value=dotted_name(definition.interface),
title=definition.title))
return SimpleVocabulary(terms)
directlyProvides(AvailableVariantAspectsVocabulary, IVocabularyFactory)
def RtfFieldsVocabulary(context):
try:
fields = getUtility(IDexterityFTI, name='bda.plone.productshop.product').lookupSchema()
except:
fields = ['Datasheet', ]
terms = [ SimpleTerm(value=pair, token=pair, title=pair) for pair in fields]
return SimpleVocabulary(terms)
directlyProvides(RtfFieldsVocabulary, IVocabularyFactory)
| Fix for the component lookup error in vocabulary | Fix for the component lookup error in vocabulary
| Python | bsd-3-clause | espenmn/bda.plone.productshop,espenmn/bda.plone.productshop,espenmn/bda.plone.productshop | ---
+++
@@ -13,7 +13,6 @@
#added by espen
from zope.component import getUtility
from plone.dexterity.interfaces import IDexterityFTI
-from zope.component import ComponentLookupError
_ = MessageFactory('bda.plone.productshop')
@@ -32,14 +31,11 @@
def RtfFieldsVocabulary(context):
try:
- type = getUtility(IDexterityFTI, name='bda.plone.productshop.product')
- fields = type.lookupSchema()
- terms = [ SimpleTerm(value=pair, token=pair, title=pair) for pair in fields]
- return SimpleVocabulary(terms)
- except KeyError:
- pass
- finally:
- pass
+ fields = getUtility(IDexterityFTI, name='bda.plone.productshop.product').lookupSchema()
+ except:
+ fields = ['Datasheet', ]
+ terms = [ SimpleTerm(value=pair, token=pair, title=pair) for pair in fields]
+ return SimpleVocabulary(terms)
directlyProvides(RtfFieldsVocabulary, IVocabularyFactory)
|
a364196814c3b33e7fd51a42b4c3a48a3aaeaee8 | volaparrot/constants.py | volaparrot/constants.py | ADMINFAG = ["RealDolos"]
PARROTFAG = "Parrot"
BLACKFAGS = [i.casefold() for i in (
"kalyx", "merc", "loliq", "annoying", "bot", "RootBeats", "JEW2FORU", "quag", "mire", "perici")]
OBAMAS = [i.casefold() for i in (
"counselor", "briseis", "apha", "bread", "ark3", "jizzbomb", "acid", "elkoalemos", "tarta")]
BLACKROOMS = "e7u-CG", "jAzmc3", "f66jeG", "24_zFd"
WHITEROOMS = "9pdLvy"
| ADMINFAG = ["RealDolos"]
PARROTFAG = "Parrot"
BLACKFAGS = [i.casefold() for i in (
"kalyx", "merc", "loliq", "annoying", "RootBeats", "JEW2FORU", "quag", "mire", "perici", "Voldemort", "briseis", "brisis", "GNUsuks", "rhooes", "n1sm4n", "honeyhole", "Printer", "yume1")]
OBAMAS = [i.casefold() for i in (
"counselor", "briseis", "apha", "bread", "ark3", "jizzbomb", "acid", "elkoalemos", "tarta", "counselor", "myon")]
BLACKROOMS = "e7u-CG", "jAzmc3", "f66jeG", "24_zFd", "BHfjGvT", "BHI0pxg",
WHITEROOMS = "BEEPi",
| Update list of extraordinary gentlemen | Update list of extraordinary gentlemen
| Python | mit | RealDolos/volaparrot | ---
+++
@@ -2,9 +2,9 @@
PARROTFAG = "Parrot"
BLACKFAGS = [i.casefold() for i in (
- "kalyx", "merc", "loliq", "annoying", "bot", "RootBeats", "JEW2FORU", "quag", "mire", "perici")]
+ "kalyx", "merc", "loliq", "annoying", "RootBeats", "JEW2FORU", "quag", "mire", "perici", "Voldemort", "briseis", "brisis", "GNUsuks", "rhooes", "n1sm4n", "honeyhole", "Printer", "yume1")]
OBAMAS = [i.casefold() for i in (
- "counselor", "briseis", "apha", "bread", "ark3", "jizzbomb", "acid", "elkoalemos", "tarta")]
+ "counselor", "briseis", "apha", "bread", "ark3", "jizzbomb", "acid", "elkoalemos", "tarta", "counselor", "myon")]
-BLACKROOMS = "e7u-CG", "jAzmc3", "f66jeG", "24_zFd"
-WHITEROOMS = "9pdLvy"
+BLACKROOMS = "e7u-CG", "jAzmc3", "f66jeG", "24_zFd", "BHfjGvT", "BHI0pxg",
+WHITEROOMS = "BEEPi", |
72b3642953d0e14d4b4c9ec03560a96d259f7d16 | contones/srs.py | contones/srs.py | """Spatial reference systems"""
from osgeo import osr
# Monkey patch SpatialReference since inheriting from SWIG classes is a hack
def srid(self):
"""Returns the EPSG ID as int if it exists."""
epsg_id = (self.GetAuthorityCode('PROJCS') or
self.GetAuthorityCode('GEOGCS'))
try:
return int(epsg_id)
except TypeError:
return
osr.SpatialReference.srid = property(srid)
def wkt(self):
"""Returns this projection in WKT format."""
return self.ExportToWkt()
osr.SpatialReference.wkt = property(wkt)
def proj4(self):
"""Returns this projection as a proj4 string."""
return self.ExportToProj4()
osr.SpatialReference.proj4 = property(proj4)
def __repr__(self): return self.wkt
osr.SpatialReference.__repr__ = __repr__
class SpatialReference(object):
def __new__(cls, sref):
sr = osr.SpatialReference()
if isinstance(sref, int):
sr.ImportFromEPSG(sref)
elif isinstance(sref, str):
if sref.strip().startswith('+proj='):
sr.ImportFromProj4(sref)
else:
sr.ImportFromWkt(sref)
# Add EPSG authority if applicable
sr.AutoIdentifyEPSG()
else:
raise TypeError('Cannot create SpatialReference '
'from {}'.format(str(sref)))
return sr
| """Spatial reference systems"""
from osgeo import osr
class BaseSpatialReference(osr.SpatialReference):
"""Base class for extending osr.SpatialReference."""
def __repr__(self):
return self.wkt
@property
def srid(self):
"""Returns the EPSG ID as int if it exists."""
epsg_id = (self.GetAuthorityCode('PROJCS') or
self.GetAuthorityCode('GEOGCS'))
try:
return int(epsg_id)
except TypeError:
return
@property
def wkt(self):
"""Returns this projection in WKT format."""
return self.ExportToWkt()
@property
def proj4(self):
"""Returns this projection as a proj4 string."""
return self.ExportToProj4()
class SpatialReference(object):
"""A spatial reference."""
def __new__(cls, sref):
"""Returns a new BaseSpatialReference instance
This allows for customized construction of osr.SpatialReference which
has no init method which precludes the use of super().
"""
sr = BaseSpatialReference()
if isinstance(sref, int):
sr.ImportFromEPSG(sref)
elif isinstance(sref, str):
if sref.strip().startswith('+proj='):
sr.ImportFromProj4(sref)
else:
sr.ImportFromWkt(sref)
# Add EPSG authority if applicable
sr.AutoIdentifyEPSG()
else:
raise TypeError('Cannot create SpatialReference '
'from {}'.format(str(sref)))
return sr
| Remove monkey patching in favor of inheritance for SpatialReference | Remove monkey patching in favor of inheritance for SpatialReference
| Python | bsd-3-clause | bkg/greenwich | ---
+++
@@ -2,35 +2,43 @@
from osgeo import osr
-# Monkey patch SpatialReference since inheriting from SWIG classes is a hack
-def srid(self):
- """Returns the EPSG ID as int if it exists."""
- epsg_id = (self.GetAuthorityCode('PROJCS') or
- self.GetAuthorityCode('GEOGCS'))
- try:
- return int(epsg_id)
- except TypeError:
- return
-osr.SpatialReference.srid = property(srid)
+class BaseSpatialReference(osr.SpatialReference):
+ """Base class for extending osr.SpatialReference."""
-def wkt(self):
- """Returns this projection in WKT format."""
- return self.ExportToWkt()
-osr.SpatialReference.wkt = property(wkt)
+ def __repr__(self):
+ return self.wkt
-def proj4(self):
- """Returns this projection as a proj4 string."""
- return self.ExportToProj4()
-osr.SpatialReference.proj4 = property(proj4)
+ @property
+ def srid(self):
+ """Returns the EPSG ID as int if it exists."""
+ epsg_id = (self.GetAuthorityCode('PROJCS') or
+ self.GetAuthorityCode('GEOGCS'))
+ try:
+ return int(epsg_id)
+ except TypeError:
+ return
-def __repr__(self): return self.wkt
-osr.SpatialReference.__repr__ = __repr__
+ @property
+ def wkt(self):
+ """Returns this projection in WKT format."""
+ return self.ExportToWkt()
+
+ @property
+ def proj4(self):
+ """Returns this projection as a proj4 string."""
+ return self.ExportToProj4()
class SpatialReference(object):
+ """A spatial reference."""
def __new__(cls, sref):
- sr = osr.SpatialReference()
+ """Returns a new BaseSpatialReference instance
+
+ This allows for customized construction of osr.SpatialReference which
+ has no init method which precludes the use of super().
+ """
+ sr = BaseSpatialReference()
if isinstance(sref, int):
sr.ImportFromEPSG(sref)
elif isinstance(sref, str): |
d994337007eb9cfe41edef591cbd30765660a822 | yarn_api_client/__init__.py | yarn_api_client/__init__.py | # -*- coding: utf-8 -*-
__version__ = '0.3.7'
__all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager']
from .application_master import ApplicationMaster
from .history_server import HistoryServer
from .node_manager import NodeManager
from .resource_manager import ResourceManager
| # -*- coding: utf-8 -*-
__version__ = '0.3.8.dev'
__all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager']
from .application_master import ApplicationMaster
from .history_server import HistoryServer
from .node_manager import NodeManager
from .resource_manager import ResourceManager
| Prepare for next development iteration | Prepare for next development iteration
| Python | bsd-3-clause | toidi/hadoop-yarn-api-python-client | ---
+++
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-__version__ = '0.3.7'
+__version__ = '0.3.8.dev'
__all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager']
from .application_master import ApplicationMaster |
6fae23c1d442880256ed2d4298844a50d6a7968e | fabfile.py | fabfile.py | import fabric.api as fab
def generate_type_hierarchy():
"""
Generate a document containing the available variable types.
"""
fab.local('./env/bin/python -m puresnmp.types > docs/typetree.rst')
@fab.task
def doc():
generate_type_hierarchy()
fab.local('sphinx-apidoc '
'-o docs/developer_guide/api '
'-f '
'-e '
'puresnmp '
'puresnmp/test')
with fab.lcd('docs'):
fab.local('make html')
@fab.task
def publish():
fab.local('python3 setup.py bdist_wheel --universal')
fab.local('python3 setup.py sdist')
fab.local('twine upload dist/*')
| import fabric.api as fab
def generate_type_hierarchy():
"""
Generate a document containing the available variable types.
"""
fab.local('./env/bin/python -m puresnmp.types > docs/typetree.rst')
@fab.task
def doc():
generate_type_hierarchy()
fab.local('sphinx-apidoc '
'-o docs/developer_guide/api '
'-f '
'-e '
'puresnmp '
'puresnmp/test')
with fab.lcd('docs'):
fab.local('make html')
@fab.task
def publish():
fab.local('rm -rf dist')
fab.local('python3 setup.py bdist_wheel --universal')
fab.local('python3 setup.py sdist')
fab.local('twine upload dist/*')
| Make sure "fab publish" cleans the dist folder | Make sure "fab publish" cleans the dist folder
This avoids accidentally uploading a package twice
| Python | mit | exhuma/puresnmp,exhuma/puresnmp | ---
+++
@@ -23,6 +23,7 @@
@fab.task
def publish():
+ fab.local('rm -rf dist')
fab.local('python3 setup.py bdist_wheel --universal')
fab.local('python3 setup.py sdist')
fab.local('twine upload dist/*') |
0ca727f0ce5877ba2ca3ef74c9309c752a51fbf6 | src/sentry/web/frontend/project_plugin_enable.py | src/sentry/web/frontend/project_plugin_enable.py | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.plugins import plugins
from sentry.web.frontend.base import ProjectView
class ProjectPluginEnableView(ProjectView):
required_scope = 'project:write'
def post(self, request, organization, team, project, slug):
try:
plugin = plugins.get(slug)
except KeyError:
return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug]))
if not plugin.is_enabled(project):
return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug]))
plugin.enable(project=project)
return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug]))
| from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.plugins import plugins
from sentry.web.frontend.base import ProjectView
class ProjectPluginEnableView(ProjectView):
required_scope = 'project:write'
def post(self, request, organization, team, project, slug):
try:
plugin = plugins.get(slug)
except KeyError:
return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug]))
if plugin.is_enabled(project):
return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug]))
plugin.enable(project=project)
return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug]))
| Fix enable action on plugins | Fix enable action on plugins
| Python | bsd-3-clause | looker/sentry,looker/sentry,jean/sentry,ifduyue/sentry,jean/sentry,BuildingLink/sentry,fotinakis/sentry,zenefits/sentry,BuildingLink/sentry,jean/sentry,fotinakis/sentry,daevaorn/sentry,looker/sentry,alexm92/sentry,fotinakis/sentry,beeftornado/sentry,JackDanger/sentry,nicholasserra/sentry,BuildingLink/sentry,mvaled/sentry,gencer/sentry,nicholasserra/sentry,BuildingLink/sentry,gencer/sentry,zenefits/sentry,fotinakis/sentry,daevaorn/sentry,mvaled/sentry,jean/sentry,zenefits/sentry,JackDanger/sentry,zenefits/sentry,JamesMura/sentry,jean/sentry,imankulov/sentry,imankulov/sentry,alexm92/sentry,JackDanger/sentry,gencer/sentry,gencer/sentry,mitsuhiko/sentry,beeftornado/sentry,JamesMura/sentry,gencer/sentry,beeftornado/sentry,daevaorn/sentry,ifduyue/sentry,nicholasserra/sentry,mvaled/sentry,mvaled/sentry,ifduyue/sentry,mvaled/sentry,alexm92/sentry,BuildingLink/sentry,ifduyue/sentry,looker/sentry,zenefits/sentry,JamesMura/sentry,mitsuhiko/sentry,JamesMura/sentry,mvaled/sentry,JamesMura/sentry,imankulov/sentry,looker/sentry,daevaorn/sentry,ifduyue/sentry | ---
+++
@@ -15,7 +15,7 @@
except KeyError:
return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug]))
- if not plugin.is_enabled(project):
+ if plugin.is_enabled(project):
return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug]))
plugin.enable(project=project) |
2cf4a0b93db423207798ffd93b2e91cdb73b6d2b | tx_salaries/utils/transformers/ut_brownsville.py | tx_salaries/utils/transformers/ut_brownsville.py | from . import base
from . import mixins
class TransformedRecord(mixins.GenericCompensationMixin,
mixins.GenericDepartmentMixin, mixins.GenericIdentifierMixin,
mixins.GenericJobTitleMixin, mixins.GenericPersonMixin,
mixins.MembershipMixin, mixins.OrganizationMixin, mixins.PostMixin,
mixins.RaceMixin, base.BaseTransformedRecord):
MAP = {
'last_name': 'Last Name',
'first_name': 'First Name',
'department': 'Department',
'job_title': 'Title',
'hire_date': 'Hire Date',
'status': 'LABEL FOR FT/PT STATUS',
'compensation': 'Annualized',
'race': 'Race',
'gender': 'Gender'
}
NAME_FIELDS = ('first_name', 'last_name', )
ORGANIZATION_NAME = 'University of Texas at Brownsville'
ORGANIZATION_CLASSIFICATION = 'University'
# TODO not given on spreadsheet, but they appear to give part time
compensation_type = 'Full Time'
@property
def is_valid(self):
# Adjust to return False on invalid fields. For example:
return self.last_name.strip() != ''
transform = base.transform_factory(TransformedRecord)
| from . import base
from . import mixins
class TransformedRecord(mixins.GenericCompensationMixin,
mixins.GenericDepartmentMixin, mixins.GenericIdentifierMixin,
mixins.GenericJobTitleMixin, mixins.GenericPersonMixin,
mixins.MembershipMixin, mixins.OrganizationMixin, mixins.PostMixin,
mixins.RaceMixin, base.BaseTransformedRecord):
MAP = {
'last_name': 'Last Name',
'first_name': 'First Name',
'middle_name': 'Middle Name',
'department': 'Department',
'job_title': 'Title',
'hire_date': 'Hire Date',
'compensation': 'Annualized',
'race': 'Race',
'gender': 'Gender'
}
NAME_FIELDS = ('first_name', 'last_name', )
ORGANIZATION_NAME = 'University of Texas at Brownsville'
ORGANIZATION_CLASSIFICATION = 'University'
# TODO not given on spreadsheet, but they appear to give part time
compensation_type = 'Full Time'
@property
def is_valid(self):
# Adjust to return False on invalid fields. For example:
return self.last_name.strip() != ''
@property
def identifier(self):
"""
Identifier for UT Brownsville
"""
excluded = [self.department_key, self.job_title_key,
self.hire_date_key, self.compensation_key]
return {
'scheme': 'tx_salaries_hash',
'identifier': base.create_hash_for_record(self.data,
exclude=excluded)
}
transform = base.transform_factory(TransformedRecord)
| Add identifier for UT Brownsville | Add identifier for UT Brownsville
| Python | apache-2.0 | texastribune/tx_salaries,texastribune/tx_salaries | ---
+++
@@ -10,10 +10,10 @@
MAP = {
'last_name': 'Last Name',
'first_name': 'First Name',
+ 'middle_name': 'Middle Name',
'department': 'Department',
'job_title': 'Title',
'hire_date': 'Hire Date',
- 'status': 'LABEL FOR FT/PT STATUS',
'compensation': 'Annualized',
'race': 'Race',
'gender': 'Gender'
@@ -33,5 +33,18 @@
# Adjust to return False on invalid fields. For example:
return self.last_name.strip() != ''
+ @property
+ def identifier(self):
+ """
+ Identifier for UT Brownsville
+ """
+ excluded = [self.department_key, self.job_title_key,
+ self.hire_date_key, self.compensation_key]
+ return {
+ 'scheme': 'tx_salaries_hash',
+ 'identifier': base.create_hash_for_record(self.data,
+ exclude=excluded)
+ }
+
transform = base.transform_factory(TransformedRecord) |
825eb37e15e2fb08ac205b7495e93a91acb79c26 | app/utils.py | app/utils.py | import re
from flask import url_for
def register_template_utils(app):
"""Register Jinja 2 helpers (called from __init__.py)."""
@app.template_test()
def equalto(value, other):
return value == other
@app.template_global()
def is_hidden_field(field):
from wtforms.fields import HiddenField
return isinstance(field, HiddenField)
app.add_template_global(index_for_role)
def index_for_role(role):
return url_for(role.index)
def parse_phone_number(phone_number):
"""Make phone number conform to E.164 (https://en.wikipedia.org/wiki/E.164)
"""
stripped = re.sub(r'\D', '', phone_number)
if len(stripped) == 10:
stripped = '1' + stripped
stripped = '+' + stripped
return stripped
| import re
from flask import url_for, flash
def register_template_utils(app):
"""Register Jinja 2 helpers (called from __init__.py)."""
@app.template_test()
def equalto(value, other):
return value == other
@app.template_global()
def is_hidden_field(field):
from wtforms.fields import HiddenField
return isinstance(field, HiddenField)
app.add_template_global(index_for_role)
def index_for_role(role):
return url_for(role.index)
def parse_phone_number(phone_number):
"""Make phone number conform to E.164 (https://en.wikipedia.org/wiki/E.164)
"""
stripped = re.sub(r'\D', '', phone_number)
if len(stripped) == 10:
stripped = '1' + stripped
stripped = '+' + stripped
return stripped
def flash_errors(form):
for field, errors in form.errors.items():
for error in errors:
flash(u"Error in the %s field - %s" % (
getattr(form, field).label.text,
error
))
| Add function for flashing all form errors | Add function for flashing all form errors
| Python | mit | hack4impact/clean-air-council,hack4impact/clean-air-council,hack4impact/clean-air-council | ---
+++
@@ -1,5 +1,5 @@
import re
-from flask import url_for
+from flask import url_for, flash
def register_template_utils(app):
@@ -29,3 +29,12 @@
stripped = '1' + stripped
stripped = '+' + stripped
return stripped
+
+
+def flash_errors(form):
+ for field, errors in form.errors.items():
+ for error in errors:
+ flash(u"Error in the %s field - %s" % (
+ getattr(form, field).label.text,
+ error
+ )) |
c8fa72a130d84d921b23f5973dafb8fa91367381 | cyder/cydns/ptr/forms.py | cyder/cydns/ptr/forms.py | from django import forms
from cyder.cydns.forms import DNSForm
from cyder.cydns.ptr.models import PTR
class PTRForm(DNSForm):
def delete_instance(self, instance):
instance.delete()
class Meta:
model = PTR
exclude = ('ip', 'reverse_domain', 'ip_upper',
'ip_lower')
widgets = {'views': forms.CheckboxSelectMultiple}
| from django import forms
from cyder.cydns.forms import DNSForm
from cyder.cydns.ptr.models import PTR
class PTRForm(DNSForm):
def delete_instance(self, instance):
instance.delete()
class Meta:
model = PTR
exclude = ('ip', 'reverse_domain', 'ip_upper',
'ip_lower')
widgets = {'views': forms.CheckboxSelectMultiple,
'ip_type': forms.RadioSelect}
| Make ip_type a RadioSelect in the PTR form | Make ip_type a RadioSelect in the PTR form
| Python | bsd-3-clause | drkitty/cyder,murrown/cyder,zeeman/cyder,murrown/cyder,OSU-Net/cyder,murrown/cyder,OSU-Net/cyder,akeym/cyder,akeym/cyder,zeeman/cyder,akeym/cyder,murrown/cyder,akeym/cyder,drkitty/cyder,zeeman/cyder,OSU-Net/cyder,zeeman/cyder,drkitty/cyder,OSU-Net/cyder,drkitty/cyder | ---
+++
@@ -12,4 +12,5 @@
model = PTR
exclude = ('ip', 'reverse_domain', 'ip_upper',
'ip_lower')
- widgets = {'views': forms.CheckboxSelectMultiple}
+ widgets = {'views': forms.CheckboxSelectMultiple,
+ 'ip_type': forms.RadioSelect} |
c426ae514227adaf9dd86f6ada6ce05bc76298c2 | catkin/src/portal_config/scripts/serve_config.py | catkin/src/portal_config/scripts/serve_config.py | #!/usr/bin/env python
import rospy
from portal_config.srv import *
class ConfigRequestHandler():
def __init__(self, url):
self.url = url
def get_config(self):
return '{"foo": "bar"}'
def handle_request(self, request):
config = self.get_config()
return PortalConfigResponse(config)
def main():
rospy.init_node('portal_config')
url = rospy.get_param('~url', 'http://lg-head/portal/config.json')
handler = ConfigRequestHandler(url)
s = rospy.Service(
'/portal_config/query',
PortalConfig,
handler.handle_request
)
rospy.spin()
if __name__ == '__main__':
main()
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
| #!/usr/bin/env python
import rospy
import urllib2
from portal_config.srv import *
# XXX TODO: return an error if the config file isn't valid JSON
class ConfigRequestHandler():
def __init__(self, url):
self.url = url
def get_config(self):
response = urllib2.urlopen(self.url)
return response.read()
def handle_request(self, request):
config = self.get_config()
return PortalConfigResponse(config)
def main():
rospy.init_node('portal_config')
url = rospy.get_param('~url', 'http://lg-head/portal/config.json')
handler = ConfigRequestHandler(url)
s = rospy.Service(
'/portal_config/query',
PortalConfig,
handler.handle_request
)
rospy.spin()
if __name__ == '__main__':
main()
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 smartindent
| Make portal_config fetch config from a URL | Make portal_config fetch config from a URL
| Python | apache-2.0 | EndPointCorp/appctl,EndPointCorp/appctl | ---
+++
@@ -1,15 +1,18 @@
#!/usr/bin/env python
import rospy
+import urllib2
from portal_config.srv import *
+# XXX TODO: return an error if the config file isn't valid JSON
class ConfigRequestHandler():
def __init__(self, url):
self.url = url
def get_config(self):
- return '{"foo": "bar"}'
+ response = urllib2.urlopen(self.url)
+ return response.read()
def handle_request(self, request):
config = self.get_config()
@@ -34,4 +37,4 @@
if __name__ == '__main__':
main()
-# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
+# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 smartindent |
5cda63163acec59a43c3975f1320b7268dcf337b | devito/parameters.py | devito/parameters.py | """The parameters dictionary contains global parameter settings."""
__all__ = ['Parameters', 'parameters']
# Be EXTREMELY careful when writing to a Parameters dictionary
# Read here for reference: http://wiki.c2.com/?GlobalVariablesAreBad
# If any issues related to global state arise, the following class should
# be made immutable. It shall only be written to at application startup
# and never modified.
class Parameters(dict):
""" A dictionary-like class to hold global configuration parameters for devito
On top of a normal dict, this provides the option to provide callback functions
so that any interested module can be informed when the configuration changes.
"""
def __init__(self, name=None, **kwargs):
self._name = name
self.update_functions = None
for key, value in iteritems(kwargs):
self[key] = value
def __setitem__(self, key, value):
super(Parameters, self).__setitem__(key, value)
# If a Parameters dictionary is being added as a child,
# ask it to tell us when it is updated
if isinstance(value, Parameters):
child_update = lambda x: self._updated(*x)
value.update_functions.push(child_update)
# Tell everyone we've been updated
self._updated(key, value)
def _updated(self, key, value):
""" Call any provided update functions so everyone knows we've been updated
"""
for f in self.update_functions:
f(key, value)
| """The parameters dictionary contains global parameter settings."""
__all__ = ['Parameters', 'parameters']
# Be EXTREMELY careful when writing to a Parameters dictionary
# Read here for reference: http://wiki.c2.com/?GlobalVariablesAreBad
# https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil
# If any issues related to global state arise, the following class should
# be made immutable. It shall only be written to at application startup
# and never modified.
class Parameters(dict):
""" A dictionary-like class to hold global configuration parameters for devito
On top of a normal dict, this provides the option to provide callback functions
so that any interested module can be informed when the configuration changes.
"""
def __init__(self, name=None, **kwargs):
self._name = name
self.update_functions = None
for key, value in iteritems(kwargs):
self[key] = value
def __setitem__(self, key, value):
super(Parameters, self).__setitem__(key, value)
# If a Parameters dictionary is being added as a child,
# ask it to tell us when it is updated
if isinstance(value, Parameters):
child_update = lambda x: self._updated(*x)
value.update_functions.push(child_update)
# Tell everyone we've been updated
self._updated(key, value)
def _updated(self, key, value):
""" Call any provided update functions so everyone knows we've been updated
"""
for f in self.update_functions:
f(key, value)
parameters = Parameters()
parameters["log_level"] = 'info'
| Add parameter for log level | Add parameter for log level
| Python | mit | opesci/devito,opesci/devito | ---
+++
@@ -4,6 +4,7 @@
# Be EXTREMELY careful when writing to a Parameters dictionary
# Read here for reference: http://wiki.c2.com/?GlobalVariablesAreBad
+# https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil
# If any issues related to global state arise, the following class should
# be made immutable. It shall only be written to at application startup
# and never modified.
@@ -38,3 +39,6 @@
"""
for f in self.update_functions:
f(key, value)
+
+parameters = Parameters()
+parameters["log_level"] = 'info' |
f96989d067f6fd073d04f96bdf2ae314c9b02d49 | uoftscrapers/scrapers/utils/layers.py | uoftscrapers/scrapers/utils/layers.py | import requests
import json
from . import Scraper
class LayersScraper:
"""A superclass for scraping Layers of the UofT Map.
Map is located at http://map.utoronto.ca
"""
host = 'http://map.utoronto.ca/'
s = requests.Session()
@staticmethod
def get_layers_json(campus):
"""Retrieve the JSON structure from host."""
Scraper.logger.info('Retrieving map layers for %s.' % campus.upper())
headers = {
'Referer': LayersScraper.host
}
html = LayersScraper.s.get('%s%s%s' % (
LayersScraper.host,
'data/map/',
campus
), headers=headers).text
data = json.loads(html)
return data['layers']
@staticmethod
def get_value(entry, val, number=False):
"""Retrieve the desired value from the parsed response dictionary."""
if val in entry.keys():
return entry[val]
else:
return 0 if number else ''
| import requests
import json
from . import Scraper
class LayersScraper:
"""A superclass for scraping Layers of the UofT Map.
Map is located at http://map.utoronto.ca
"""
host = 'http://map.utoronto.ca/'
@staticmethod
def get_layers_json(campus):
"""Retrieve the JSON structure from host."""
Scraper.logger.info('Retrieving map layers for %s.' % campus.upper())
headers = {'Referer': LayersScraper.host}
data = Scraper.get('%s%s%s' % (
LayersScraper.host,
'data/map/',
campus
), headers=headers, json=True)
return data['layers']
@staticmethod
def get_value(entry, val, number=False):
"""Retrieve the desired value from the parsed response dictionary."""
if val in entry.keys():
return entry[val]
else:
return 0 if number else ''
| Use request helper function in LayersScraper | Use request helper function in LayersScraper
| Python | mit | kshvmdn/uoft-scrapers,cobalt-uoft/uoft-scrapers,arkon/uoft-scrapers,g3wanghc/uoft-scrapers | ---
+++
@@ -10,7 +10,6 @@
"""
host = 'http://map.utoronto.ca/'
- s = requests.Session()
@staticmethod
def get_layers_json(campus):
@@ -18,16 +17,13 @@
Scraper.logger.info('Retrieving map layers for %s.' % campus.upper())
- headers = {
- 'Referer': LayersScraper.host
- }
- html = LayersScraper.s.get('%s%s%s' % (
+ headers = {'Referer': LayersScraper.host}
+ data = Scraper.get('%s%s%s' % (
LayersScraper.host,
'data/map/',
campus
- ), headers=headers).text
+ ), headers=headers, json=True)
- data = json.loads(html)
return data['layers']
@staticmethod |
4839121f90934f7e52e51c05d052d27124680be7 | pyqode/python/backend/server.py | pyqode/python/backend/server.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Main server script for a pyqode.python backend. You can directly use this
script in your application if it fits your needs or use it as a starting point
for writing your own server.
::
usage: server.py [-h] [-s [SYSPATH [SYSPATH ...]]] port
positional arguments:
port the local tcp port to use to run the server
optional arguments:
-h, --help show this help message and exit
-s [SYSPATH [SYSPATH ...]], --syspath [SYSPATH [SYSPATH ...]]
"""
import argparse
import sys
if __name__ == '__main__':
"""
Server process' entry point
"""
# setup argument parser and parse command line args
parser = argparse.ArgumentParser()
parser.add_argument("port", help="the local tcp port to use to run "
"the server")
parser.add_argument('-s', '--syspath', nargs='*')
args = parser.parse_args()
# add user paths to sys.path
if args.syspath:
for path in args.syspath:
print('append path %s to sys.path\n' % path)
sys.path.append(path)
from pyqode.core import backend
from pyqode.python.backend.workers import JediCompletionProvider
# setup completion providers
backend.CodeCompletionWorker.providers.append(JediCompletionProvider())
backend.CodeCompletionWorker.providers.append(
backend.DocumentWordsProvider())
# starts the server
backend.serve_forever(args)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Main server script for a pyqode.python backend. You can directly use this
script in your application if it fits your needs or use it as a starting point
for writing your own server.
::
usage: server.py [-h] [-s [SYSPATH [SYSPATH ...]]] port
positional arguments:
port the local tcp port to use to run the server
optional arguments:
-h, --help show this help message and exit
-s [SYSPATH [SYSPATH ...]], --syspath [SYSPATH [SYSPATH ...]]
"""
import argparse
import sys
if __name__ == '__main__':
"""
Server process' entry point
"""
# setup argument parser and parse command line args
parser = argparse.ArgumentParser()
parser.add_argument("port", help="the local tcp port to use to run "
"the server")
parser.add_argument('-s', '--syspath', nargs='*')
args = parser.parse_args()
# add user paths to sys.path
if args.syspath:
for path in args.syspath:
print('append path %s to sys.path' % path)
sys.path.append(path)
from pyqode.core import backend
from pyqode.python.backend.workers import JediCompletionProvider
# setup completion providers
backend.CodeCompletionWorker.providers.append(JediCompletionProvider())
backend.CodeCompletionWorker.providers.append(
backend.DocumentWordsProvider())
# starts the server
backend.serve_forever(args)
| Remove confusing and useless "\n" | Remove confusing and useless "\n"
| Python | mit | pyQode/pyqode.python,pyQode/pyqode.python,mmolero/pyqode.python,zwadar/pyqode.python | ---
+++
@@ -35,7 +35,7 @@
# add user paths to sys.path
if args.syspath:
for path in args.syspath:
- print('append path %s to sys.path\n' % path)
+ print('append path %s to sys.path' % path)
sys.path.append(path)
from pyqode.core import backend |
f3724421fa859a5970e66353b6a311aa14b866ec | labs/lab-5/ex5-1.log.py | labs/lab-5/ex5-1.log.py | #!/usr/bin/python
#
# Copyright 2016 BMC Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os
import sys
import time
from log_utils import follow
if __name__ == '__main__':
# We are expecting two arguments
# The first is the name of the script
# The second is a path to a log file
if len(sys.argv) == 2:
# Open our file for reading
log_file = open(sys.argv[1], "r")
# Create our iterable function
log_lines = follow(log_file)
# Process the lines as they are appended
for line in log_lines:
# Strip out the new line an print the line
print("{0}".format(line.strip()))
else:
# Incorrect number of arguments
# Output usage to standard out
sys.stderr.write("usage: {0} <path>\n".format(os.path.basename(sys.argv[0])))
| #!/usr/bin/python
#
# Copyright 2016 BMC Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os
import sys
import time
from log_utils import follow
if __name__ == '__main__':
# We are expecting two arguments
# The first is the name of the script
# The second is a path to a log file
if len(sys.argv) == 2:
# Open our file for reading
log_file = open(sys.argv[1], "r")
# Create our iterable function
log_lines = follow(log_file)
# Process the lines as they are appended
for line in log_lines:
# Strip out the new line an print the line
print("{0}".format(line.strip()))
else:
# Incorrect number of arguments
# Output usage to standard out
sys.stderr.write("usage: {0} <path>\n".format(os.path.basename(sys.argv[0])))
| Add additional spacing to improve readability | Add additional spacing to improve readability
| Python | apache-2.0 | boundary/tsi-lab,jdgwartney/tsi-lab,jdgwartney/tsi-lab,jdgwartney/tsi-lab,jdgwartney/tsi-lab,boundary/tsi-lab,boundary/tsi-lab,boundary/tsi-lab | ---
+++
@@ -26,8 +26,10 @@
if len(sys.argv) == 2:
# Open our file for reading
log_file = open(sys.argv[1], "r")
+
# Create our iterable function
log_lines = follow(log_file)
+
# Process the lines as they are appended
for line in log_lines:
# Strip out the new line an print the line |
377aef17394b2dabd6db7439d3cfcd4e0d54a3c2 | scipy/constants/tests/test_codata.py | scipy/constants/tests/test_codata.py |
import warnings
from scipy.constants import find
from numpy.testing import assert_equal
def test_find():
warnings.simplefilter('ignore', DeprecationWarning)
keys = find('weak mixing', disp=False)
assert_equal(keys, ['weak mixing angle'])
keys = find('qwertyuiop', disp=False)
assert_equal(keys, [])
keys = find('natural unit', disp=False)
assert_equal(keys, sorted(['natural unit of velocity',
'natural unit of action',
'natural unit of action in eV s',
'natural unit of mass',
'natural unit of energy',
'natural unit of energy in MeV',
'natural unit of momentum',
'natural unit of momentum in MeV/c',
'natural unit of length',
'natural unit of time']))
|
import warnings
from scipy.constants import find
from numpy.testing import assert_equal, run_module_suite
def test_find():
warnings.simplefilter('ignore', DeprecationWarning)
keys = find('weak mixing', disp=False)
assert_equal(keys, ['weak mixing angle'])
keys = find('qwertyuiop', disp=False)
assert_equal(keys, [])
keys = find('natural unit', disp=False)
assert_equal(keys, sorted(['natural unit of velocity',
'natural unit of action',
'natural unit of action in eV s',
'natural unit of mass',
'natural unit of energy',
'natural unit of energy in MeV',
'natural unit of momentum',
'natural unit of momentum in MeV/c',
'natural unit of length',
'natural unit of time']))
if __name__ == "__main__":
run_module_suite()
| Allow codata tests to be run as script. | ENH: Allow codata tests to be run as script.
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@6562 d6536bca-fef9-0310-8506-e4c0a848fbcf
| Python | bsd-3-clause | jasonmccampbell/scipy-refactor,scipy/scipy-svn,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn,scipy/scipy-svn,scipy/scipy-svn | ---
+++
@@ -2,7 +2,7 @@
import warnings
from scipy.constants import find
-from numpy.testing import assert_equal
+from numpy.testing import assert_equal, run_module_suite
def test_find():
@@ -25,3 +25,6 @@
'natural unit of momentum in MeV/c',
'natural unit of length',
'natural unit of time']))
+
+if __name__ == "__main__":
+ run_module_suite() |
c8fdcf888f6c34e8396f11b3e7ab3088af59abb6 | distarray/tests/test_utils.py | distarray/tests/test_utils.py | import unittest
from distarray import utils
class TestMultPartitions(unittest.TestCase):
"""
Test the multiplicative parition code.
"""
def test_both_methods(self):
"""
Do the two methods of computing the multiplicative partitions agree?
"""
for s in [2, 3]:
for n in range(2, 512):
self.assertEqual(utils.mult_partitions(n, s),
utils.create_factors(n, s))
if __name__ == '__main__':
unittest.main(verbosity=2)
| import unittest
from distarray import utils
from numpy import arange
from numpy.testing import assert_array_equal
class TestMultPartitions(unittest.TestCase):
"""
Test the multiplicative parition code.
"""
def test_both_methods(self):
"""
Do the two methods of computing the multiplicative partitions agree?
"""
for s in [2, 3]:
for n in range(2, 512):
self.assertEqual(utils.mult_partitions(n, s),
utils.create_factors(n, s))
class TestSanitizeIndices(unittest.TestCase):
def test_point(self):
itype, inds = utils.sanitize_indices(1)
self.assertEqual(itype, 'point')
self.assertEqual(inds, (1,))
def test_slice(self):
itype, inds = utils.sanitize_indices(slice(1,10))
self.assertEqual(itype, 'view')
self.assertEqual(inds, (slice(1,10),))
def test_mixed(self):
provided = (5, 3, slice(7, 10, 2), 99, slice(1,10))
itype, inds = utils.sanitize_indices(provided)
self.assertEqual(itype, 'view')
self.assertEqual(inds, provided)
class TestSliceIntersection(unittest.TestCase):
def test_containment(self):
arr = arange(20)
slc = utils.slice_intersection(slice(1,10), slice(2, 4))
assert_array_equal(arr[slc], arr[slice(2, 4, 1)])
def test_overlapping(self):
arr = arange(20)
slc = utils.slice_intersection(slice(1,10), slice(4, 15))
assert_array_equal(arr[slc], arr[slice(4, 10)])
def test_disjoint(self):
arr = arange(20)
slc = utils.slice_intersection(slice(1,10), slice(11, 15))
assert_array_equal(arr[slc], arr[slice(11, 10)])
if __name__ == '__main__':
unittest.main(verbosity=2)
| Add tests for slice intersection and sanitization. | Add tests for slice intersection and sanitization. | Python | bsd-3-clause | RaoUmer/distarray,enthought/distarray,enthought/distarray,RaoUmer/distarray | ---
+++
@@ -1,5 +1,8 @@
import unittest
from distarray import utils
+
+from numpy import arange
+from numpy.testing import assert_array_equal
class TestMultPartitions(unittest.TestCase):
@@ -17,5 +20,42 @@
utils.create_factors(n, s))
+class TestSanitizeIndices(unittest.TestCase):
+
+ def test_point(self):
+ itype, inds = utils.sanitize_indices(1)
+ self.assertEqual(itype, 'point')
+ self.assertEqual(inds, (1,))
+
+ def test_slice(self):
+ itype, inds = utils.sanitize_indices(slice(1,10))
+ self.assertEqual(itype, 'view')
+ self.assertEqual(inds, (slice(1,10),))
+
+ def test_mixed(self):
+ provided = (5, 3, slice(7, 10, 2), 99, slice(1,10))
+ itype, inds = utils.sanitize_indices(provided)
+ self.assertEqual(itype, 'view')
+ self.assertEqual(inds, provided)
+
+
+class TestSliceIntersection(unittest.TestCase):
+
+ def test_containment(self):
+ arr = arange(20)
+ slc = utils.slice_intersection(slice(1,10), slice(2, 4))
+ assert_array_equal(arr[slc], arr[slice(2, 4, 1)])
+
+ def test_overlapping(self):
+ arr = arange(20)
+ slc = utils.slice_intersection(slice(1,10), slice(4, 15))
+ assert_array_equal(arr[slc], arr[slice(4, 10)])
+
+ def test_disjoint(self):
+ arr = arange(20)
+ slc = utils.slice_intersection(slice(1,10), slice(11, 15))
+ assert_array_equal(arr[slc], arr[slice(11, 10)])
+
+
if __name__ == '__main__':
unittest.main(verbosity=2) |
a8cb15b1983c48547edfeb53bfb63245f7e7c892 | dbaas_zabbix/__init__.py | dbaas_zabbix/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import sys
from dbaas_zabbix.dbaas_api import DatabaseAsAServiceApi
from dbaas_zabbix.provider_factory import ProviderFactory
from pyzabbix import ZabbixAPI
stream = logging.StreamHandler(sys.stdout)
stream.setLevel(logging.DEBUG)
log = logging.getLogger('pyzabbix')
log.addHandler(stream)
log.setLevel(logging.DEBUG)
def factory_for(**kwargs):
databaseinfra = kwargs['databaseinfra']
credentials = kwargs['credentials']
del kwargs['databaseinfra']
del kwargs['credentials']
zabbix_api = ZabbixAPI
if kwargs.get('zabbix_api'):
zabbix_api = kwargs.get('zabbix_api')
del kwargs['zabbix_api']
dbaas_api = DatabaseAsAServiceApi(databaseinfra, credentials)
return ProviderFactory.factory(dbaas_api, zabbix_api=zabbix_api, **kwargs)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from dbaas_zabbix.dbaas_api import DatabaseAsAServiceApi
from dbaas_zabbix.provider_factory import ProviderFactory
from pyzabbix import ZabbixAPI
def factory_for(**kwargs):
databaseinfra = kwargs['databaseinfra']
credentials = kwargs['credentials']
del kwargs['databaseinfra']
del kwargs['credentials']
zabbix_api = ZabbixAPI
if kwargs.get('zabbix_api'):
zabbix_api = kwargs.get('zabbix_api')
del kwargs['zabbix_api']
dbaas_api = DatabaseAsAServiceApi(databaseinfra, credentials)
return ProviderFactory.factory(dbaas_api, zabbix_api=zabbix_api, **kwargs)
| Revert "log integrations with zabbix through pyzabbix" | Revert "log integrations with zabbix through pyzabbix"
This reverts commit 1506b6ad3e35e4a10ca36d42a75f3a572add06b7.
| Python | bsd-3-clause | globocom/dbaas-zabbix,globocom/dbaas-zabbix | ---
+++
@@ -1,17 +1,9 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
-import logging
-import sys
-
from dbaas_zabbix.dbaas_api import DatabaseAsAServiceApi
from dbaas_zabbix.provider_factory import ProviderFactory
from pyzabbix import ZabbixAPI
-stream = logging.StreamHandler(sys.stdout)
-stream.setLevel(logging.DEBUG)
-log = logging.getLogger('pyzabbix')
-log.addHandler(stream)
-log.setLevel(logging.DEBUG)
def factory_for(**kwargs):
databaseinfra = kwargs['databaseinfra'] |
6c11b9cc9b213928e32d883d4f557f7421da6802 | document/api.py | document/api.py | from rest_framework import serializers, viewsets
from document.models import Document, Kamerstuk, Dossier
class DossierSerializer(serializers.HyperlinkedModelSerializer):
documents = serializers.HyperlinkedRelatedField(read_only=True,
view_name='document-detail',
many=True)
class Meta:
model = Dossier
fields = ('id', 'dossier_id', 'title', 'documents')
class DossierViewSet(viewsets.ModelViewSet):
queryset = Dossier.objects.all()
serializer_class = DossierSerializer
class DocumentSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Document
fields = ('id', 'dossier', 'raw_type', 'raw_title', 'publisher', 'date_published', 'document_url')
class DocumentViewSet(viewsets.ModelViewSet):
queryset = Document.objects.all()
serializer_class = DocumentSerializer
class KamerstukSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Kamerstuk
fields = ('id', 'document', 'id_main', 'id_sub', 'type_short', 'type_long')
class KamerstukViewSet(viewsets.ModelViewSet):
queryset = Kamerstuk.objects.all()
serializer_class = KamerstukSerializer
| from rest_framework import serializers, viewsets
from document.models import Document, Kamerstuk, Dossier
class DossierSerializer(serializers.HyperlinkedModelSerializer):
documents = serializers.HyperlinkedRelatedField(read_only=True,
view_name='document-detail',
many=True)
kamerstukken = serializers.HyperlinkedRelatedField(read_only=True,
view_name='kamerstuk-detail',
many=True)
class Meta:
model = Dossier
fields = ('id', 'dossier_id', 'title', 'kamerstukken', 'documents')
class DossierViewSet(viewsets.ModelViewSet):
queryset = Dossier.objects.all()
serializer_class = DossierSerializer
class DocumentSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Document
fields = ('id', 'dossier', 'raw_type', 'raw_title', 'publisher', 'date_published', 'document_url')
class DocumentViewSet(viewsets.ModelViewSet):
queryset = Document.objects.all()
serializer_class = DocumentSerializer
class KamerstukSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Kamerstuk
fields = ('id', 'document', 'id_main', 'id_sub', 'type_short', 'type_long')
class KamerstukViewSet(viewsets.ModelViewSet):
queryset = Kamerstuk.objects.all()
serializer_class = KamerstukSerializer
| Add kamerstukken to dossier API | Add kamerstukken to dossier API
| Python | mit | openkamer/openkamer,openkamer/openkamer,openkamer/openkamer,openkamer/openkamer | ---
+++
@@ -8,9 +8,13 @@
view_name='document-detail',
many=True)
+ kamerstukken = serializers.HyperlinkedRelatedField(read_only=True,
+ view_name='kamerstuk-detail',
+ many=True)
+
class Meta:
model = Dossier
- fields = ('id', 'dossier_id', 'title', 'documents')
+ fields = ('id', 'dossier_id', 'title', 'kamerstukken', 'documents')
class DossierViewSet(viewsets.ModelViewSet): |
788cc159e4d734b972e22ccf06dbcd8ed8f94885 | distutils/_collections.py | distutils/_collections.py | import collections
import itertools
# from jaraco.collections 3.5
class DictStack(list, collections.abc.Mapping):
"""
A stack of dictionaries that behaves as a view on those dictionaries,
giving preference to the last.
>>> stack = DictStack([dict(a=1, c=2), dict(b=2, a=2)])
>>> stack['a']
2
>>> stack['b']
2
>>> stack['c']
2
>>> stack.push(dict(a=3))
>>> stack['a']
3
>>> set(stack.keys()) == set(['a', 'b', 'c'])
True
>>> set(stack.items()) == set([('a', 3), ('b', 2), ('c', 2)])
True
>>> dict(**stack) == dict(stack) == dict(a=3, c=2, b=2)
True
>>> d = stack.pop()
>>> stack['a']
2
>>> d = stack.pop()
>>> stack['a']
1
>>> stack.get('b', None)
>>> 'c' in stack
True
"""
def __iter__(self):
dicts = list.__iter__(self)
return iter(set(itertools.chain.from_iterable(c.keys() for c in dicts)))
def __getitem__(self, key):
for scope in reversed(self):
if key in scope:
return scope[key]
raise KeyError(key)
push = list.append
def __contains__(self, other):
return collections.abc.Mapping.__contains__(self, other)
| import collections
import itertools
# from jaraco.collections 3.5.1
class DictStack(list, collections.abc.Mapping):
"""
A stack of dictionaries that behaves as a view on those dictionaries,
giving preference to the last.
>>> stack = DictStack([dict(a=1, c=2), dict(b=2, a=2)])
>>> stack['a']
2
>>> stack['b']
2
>>> stack['c']
2
>>> len(stack)
3
>>> stack.push(dict(a=3))
>>> stack['a']
3
>>> set(stack.keys()) == set(['a', 'b', 'c'])
True
>>> set(stack.items()) == set([('a', 3), ('b', 2), ('c', 2)])
True
>>> dict(**stack) == dict(stack) == dict(a=3, c=2, b=2)
True
>>> d = stack.pop()
>>> stack['a']
2
>>> d = stack.pop()
>>> stack['a']
1
>>> stack.get('b', None)
>>> 'c' in stack
True
"""
def __iter__(self):
dicts = list.__iter__(self)
return iter(set(itertools.chain.from_iterable(c.keys() for c in dicts)))
def __getitem__(self, key):
for scope in reversed(tuple(list.__iter__(self))):
if key in scope:
return scope[key]
raise KeyError(key)
push = list.append
def __contains__(self, other):
return collections.abc.Mapping.__contains__(self, other)
def __len__(self):
return len(list(iter(self)))
| Update DictStack implementation from jaraco.collections 3.5.1 | Update DictStack implementation from jaraco.collections 3.5.1
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools | ---
+++
@@ -2,7 +2,7 @@
import itertools
-# from jaraco.collections 3.5
+# from jaraco.collections 3.5.1
class DictStack(list, collections.abc.Mapping):
"""
A stack of dictionaries that behaves as a view on those dictionaries,
@@ -15,6 +15,8 @@
2
>>> stack['c']
2
+ >>> len(stack)
+ 3
>>> stack.push(dict(a=3))
>>> stack['a']
3
@@ -40,7 +42,7 @@
return iter(set(itertools.chain.from_iterable(c.keys() for c in dicts)))
def __getitem__(self, key):
- for scope in reversed(self):
+ for scope in reversed(tuple(list.__iter__(self))):
if key in scope:
return scope[key]
raise KeyError(key)
@@ -49,3 +51,6 @@
def __contains__(self, other):
return collections.abc.Mapping.__contains__(self, other)
+
+ def __len__(self):
+ return len(list(iter(self))) |
3ddddbd24bb37c30df80233ec4c70c38b6c29e82 | emstrack/forms.py | emstrack/forms.py | from django.contrib.gis.forms import widgets
class LeafletPointWidget(widgets.BaseGeometryWidget):
template_name = 'leaflet/leaflet.html'
class Media:
css = {
'all': ('https://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css',
'leaflet/css/location_form.css',
'leaflet/css/LeafletWidget.css')
}
js = (
'https://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js',
'leaflet/js/LeafletWidget.js'
)
def render(self, name, value, attrs=None):
# add point
if value:
attrs.update({ 'point': { 'x': value.x,
'y': value.y,
'z': value.z,
'srid': value.srid }
})
return super().render(name, value, attrs)
| from django.contrib.gis.forms import widgets
class LeafletPointWidget(widgets.BaseGeometryWidget):
template_name = 'leaflet/leaflet.html'
class Media:
css = {
'all': ('https://cdnjs.cloudflare.com/ajax/libs/leaflet/v0.7.7/leaflet.css',
'leaflet/css/location_form.css',
'leaflet/css/LeafletWidget.css')
}
js = (
'https://cdnjs.cloudflare.com/ajax/libs/leaflet/v0.7.7/leaflet.js',
'leaflet/js/LeafletWidget.js'
)
def render(self, name, value, attrs=None):
# add point
if value:
attrs.update({ 'point': { 'x': value.x,
'y': value.y,
'z': value.z,
'srid': value.srid }
})
return super().render(name, value, attrs)
| Update leaflet request to be over https | Update leaflet request to be over https
| Python | bsd-3-clause | EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient | ---
+++
@@ -5,12 +5,12 @@
class Media:
css = {
- 'all': ('https://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css',
+ 'all': ('https://cdnjs.cloudflare.com/ajax/libs/leaflet/v0.7.7/leaflet.css',
'leaflet/css/location_form.css',
'leaflet/css/LeafletWidget.css')
}
js = (
- 'https://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js',
+ 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/v0.7.7/leaflet.js',
'leaflet/js/LeafletWidget.js'
)
|
9674a0869c2a333f74178e305677259e7ac379c3 | examples/ignore_websocket.py | examples/ignore_websocket.py | # This script makes mitmproxy switch to passthrough mode for all HTTP
# responses with "Connection: Upgrade" header. This is useful to make
# WebSockets work in untrusted environments.
#
# Note: Chrome (and possibly other browsers), when explicitly configured
# to use a proxy (i.e. mitmproxy's regular mode), send a CONNECT request
# to the proxy before they initiate the websocket connection.
# To make WebSockets work in these cases, supply
# `--ignore :80$` as an additional parameter.
# (see http://mitmproxy.org/doc/features/passthrough.html)
from libmproxy.protocol.http import HTTPRequest
from libmproxy.protocol.tcp import TCPHandler
from libmproxy.protocol import KILL
from libmproxy.script import concurrent
def start(context, argv):
HTTPRequest._headers_to_strip_off.remove("Connection")
HTTPRequest._headers_to_strip_off.remove("Upgrade")
def done(context):
HTTPRequest._headers_to_strip_off.append("Connection")
HTTPRequest._headers_to_strip_off.append("Upgrade")
@concurrent
def response(context, flow):
if flow.response.headers.get_first("Connection", None) == "Upgrade":
# We need to send the response manually now...
flow.client_conn.send(flow.response.assemble())
# ...and then delegate to tcp passthrough.
TCPHandler(flow.live.c, log=False).handle_messages()
flow.reply(KILL) | # This script makes mitmproxy switch to passthrough mode for all HTTP
# responses with "Connection: Upgrade" header. This is useful to make
# WebSockets work in untrusted environments.
#
# Note: Chrome (and possibly other browsers), when explicitly configured
# to use a proxy (i.e. mitmproxy's regular mode), send a CONNECT request
# to the proxy before they initiate the websocket connection.
# To make WebSockets work in these cases, supply
# `--ignore :80$` as an additional parameter.
# (see http://mitmproxy.org/doc/features/passthrough.html)
from libmproxy.protocol.http import HTTPRequest
from libmproxy.protocol.tcp import TCPHandler
from libmproxy.protocol import KILL
from libmproxy.script import concurrent
def start(context, argv):
HTTPRequest._headers_to_strip_off.remove("Connection")
HTTPRequest._headers_to_strip_off.remove("Upgrade")
def done(context):
HTTPRequest._headers_to_strip_off.append("Connection")
HTTPRequest._headers_to_strip_off.append("Upgrade")
@concurrent
def response(context, flow):
value = flow.response.headers.get_first("Connection", None)
if value and value.upper() == "UPGRADE":
# We need to send the response manually now...
flow.client_conn.send(flow.response.assemble())
# ...and then delegate to tcp passthrough.
TCPHandler(flow.live.c, log=False).handle_messages()
flow.reply(KILL) | Make the Websocket's connection header value case-insensitive | Make the Websocket's connection header value case-insensitive
| Python | mit | liorvh/mitmproxy,ccccccccccc/mitmproxy,dwfreed/mitmproxy,mhils/mitmproxy,ryoqun/mitmproxy,Kriechi/mitmproxy,azureplus/mitmproxy,dufferzafar/mitmproxy,ikoz/mitmproxy,jpic/mitmproxy,tfeagle/mitmproxy,rauburtin/mitmproxy,MatthewShao/mitmproxy,pombredanne/mitmproxy,pombredanne/mitmproxy,laurmurclar/mitmproxy,StevenVanAcker/mitmproxy,fimad/mitmproxy,elitest/mitmproxy,claimsmall/mitmproxy,ikoz/mitmproxy,bazzinotti/mitmproxy,liorvh/mitmproxy,zbuc/mitmproxy,devasia1000/mitmproxy,ikoz/mitmproxy,StevenVanAcker/mitmproxy,jvillacorta/mitmproxy,tdickers/mitmproxy,StevenVanAcker/mitmproxy,syjzwjj/mitmproxy,ryoqun/mitmproxy,Endika/mitmproxy,0xwindows/InfoLeak,devasia1000/mitmproxy,elitest/mitmproxy,ParthGanatra/mitmproxy,mitmproxy/mitmproxy,noikiy/mitmproxy,jvillacorta/mitmproxy,onlywade/mitmproxy,sethp-jive/mitmproxy,cortesi/mitmproxy,dweinstein/mitmproxy,azureplus/mitmproxy,dufferzafar/mitmproxy,Fuzion24/mitmproxy,ADemonisis/mitmproxy,noikiy/mitmproxy,scriptmediala/mitmproxy,macmantrl/mitmproxy,guiquanz/mitmproxy,gzzhanghao/mitmproxy,byt3bl33d3r/mitmproxy,cortesi/mitmproxy,owers19856/mitmproxy,tdickers/mitmproxy,devasia1000/mitmproxy,syjzwjj/mitmproxy,Endika/mitmproxy,ccccccccccc/mitmproxy,xbzbing/mitmproxy,ujjwal96/mitmproxy,elitest/mitmproxy,liorvh/mitmproxy,inscriptionweb/mitmproxy,inscriptionweb/mitmproxy,tekii/mitmproxy,guiquanz/mitmproxy,vhaupert/mitmproxy,mosajjal/mitmproxy,ADemonisis/mitmproxy,sethp-jive/mitmproxy,ddworken/mitmproxy,vhaupert/mitmproxy,tfeagle/mitmproxy,jpic/mitmproxy,fimad/mitmproxy,legendtang/mitmproxy,xbzbing/mitmproxy,ujjwal96/mitmproxy,ddworken/mitmproxy,Kriechi/mitmproxy,inscriptionweb/mitmproxy,azureplus/mitmproxy,pombredanne/mitmproxy,tfeagle/mitmproxy,legendtang/mitmproxy,byt3bl33d3r/mitmproxy,rauburtin/mitmproxy,Fuzion24/mitmproxy,gzzhanghao/mitmproxy,noikiy/mitmproxy,elitest/mitmproxy,mhils/mitmproxy,ParthGanatra/mitmproxy,mosajjal/mitmproxy,owers19856/mitmproxy,tekii/mitmproxy,cortesi/mitmproxy,macmantrl/mitmproxy,bazzinotti/mitmproxy,dxq-git/mitmproxy,mitmproxy/mitmproxy,jpic/mitmproxy,mosajjal/mitmproxy,mhils/mitmproxy,dweinstein/mitmproxy,fimad/mitmproxy,dxq-git/mitmproxy,xbzbing/mitmproxy,claimsmall/mitmproxy,dwfreed/mitmproxy,xaxa89/mitmproxy,vhaupert/mitmproxy,ujjwal96/mitmproxy,Endika/mitmproxy,ParthGanatra/mitmproxy,meizhoubao/mitmproxy,meizhoubao/mitmproxy,dweinstein/mitmproxy,mhils/mitmproxy,Fuzion24/mitmproxy,gzzhanghao/mitmproxy,azureplus/mitmproxy,dxq-git/mitmproxy,ddworken/mitmproxy,ADemonisis/mitmproxy,0xwindows/InfoLeak,dufferzafar/mitmproxy,zlorb/mitmproxy,tekii/mitmproxy,scriptmediala/mitmproxy,dwfreed/mitmproxy,zlorb/mitmproxy,bazzinotti/mitmproxy,StevenVanAcker/mitmproxy,syjzwjj/mitmproxy,ccccccccccc/mitmproxy,xbzbing/mitmproxy,syjzwjj/mitmproxy,Endika/mitmproxy,onlywade/mitmproxy,sethp-jive/mitmproxy,xaxa89/mitmproxy,xaxa89/mitmproxy,jpic/mitmproxy,guiquanz/mitmproxy,rauburtin/mitmproxy,jvillacorta/mitmproxy,owers19856/mitmproxy,ZeYt/mitmproxy,ZeYt/mitmproxy,zbuc/mitmproxy,zlorb/mitmproxy,Kriechi/mitmproxy,ZeYt/mitmproxy,Kriechi/mitmproxy,ZeYt/mitmproxy,ryoqun/mitmproxy,devasia1000/mitmproxy,claimsmall/mitmproxy,laurmurclar/mitmproxy,MatthewShao/mitmproxy,noikiy/mitmproxy,onlywade/mitmproxy,macmantrl/mitmproxy,scriptmediala/mitmproxy,mitmproxy/mitmproxy,zlorb/mitmproxy,mhils/mitmproxy,sethp-jive/mitmproxy,dxq-git/mitmproxy,MatthewShao/mitmproxy,mitmproxy/mitmproxy,tdickers/mitmproxy,legendtang/mitmproxy,laurmurclar/mitmproxy,macmantrl/mitmproxy,tfeagle/mitmproxy,byt3bl33d3r/mitmproxy,ujjwal96/mitmproxy,Fuzion24/mitmproxy,owers19856/mitmproxy,ikoz/mitmproxy,mosajjal/mitmproxy,vhaupert/mitmproxy,zbuc/mitmproxy,onlywade/mitmproxy,0xwindows/InfoLeak,mitmproxy/mitmproxy,inscriptionweb/mitmproxy,ParthGanatra/mitmproxy,0xwindows/InfoLeak,guiquanz/mitmproxy,byt3bl33d3r/mitmproxy,meizhoubao/mitmproxy,ryoqun/mitmproxy,legendtang/mitmproxy,tdickers/mitmproxy,laurmurclar/mitmproxy,cortesi/mitmproxy,liorvh/mitmproxy,jvillacorta/mitmproxy,dwfreed/mitmproxy,gzzhanghao/mitmproxy,scriptmediala/mitmproxy,dweinstein/mitmproxy,meizhoubao/mitmproxy,rauburtin/mitmproxy,ccccccccccc/mitmproxy,tekii/mitmproxy,bazzinotti/mitmproxy,zbuc/mitmproxy,pombredanne/mitmproxy,claimsmall/mitmproxy,ddworken/mitmproxy,xaxa89/mitmproxy,fimad/mitmproxy,dufferzafar/mitmproxy,ADemonisis/mitmproxy,MatthewShao/mitmproxy | ---
+++
@@ -26,7 +26,8 @@
@concurrent
def response(context, flow):
- if flow.response.headers.get_first("Connection", None) == "Upgrade":
+ value = flow.response.headers.get_first("Connection", None)
+ if value and value.upper() == "UPGRADE":
# We need to send the response manually now...
flow.client_conn.send(flow.response.assemble())
# ...and then delegate to tcp passthrough. |
6d83f2150f7c6177385b9f2d8abbe48cd2979130 | events/admin.py | events/admin.py | from django.contrib import admin
from .models import Calendar,MonthCache
# Register your models here.
@admin.register(Calendar)
class CalendarAdmin(admin.ModelAdmin):
list_display = ('name','remote_id','css_class')
@admin.register(MonthCache)
class MonthCacheAdmin(admin.ModelAdmin):
list_display = ('calendar','month','data_cached_on')
| from django.contrib import admin
from .models import Calendar,MonthCache
# Register your models here.
@admin.register(Calendar)
class CalendarAdmin(admin.ModelAdmin):
list_display = ('name','remote_id','css_class')
@admin.register(MonthCache)
class MonthCacheAdmin(admin.ModelAdmin):
list_display = ('calendar','month','data_cached_on','is_cache_stale')
| Add staleness to MonthCache Admin display | Add staleness to MonthCache Admin display
| Python | mit | Kromey/fbxnano,Kromey/akwriters,Kromey/akwriters,Kromey/fbxnano,Kromey/fbxnano,Kromey/akwriters,Kromey/fbxnano,Kromey/akwriters | ---
+++
@@ -11,5 +11,5 @@
@admin.register(MonthCache)
class MonthCacheAdmin(admin.ModelAdmin):
- list_display = ('calendar','month','data_cached_on')
+ list_display = ('calendar','month','data_cached_on','is_cache_stale')
|
a6435a8713985464b8c37a438ac035d65f66b4cd | tests/test_large_file.py | tests/test_large_file.py | import logging
import cProfile
from mappyfile.parser import Parser
from mappyfile.pprint import PrettyPrinter
from mappyfile.transformer import MapfileToDict
def output(fn):
"""
Parse, transform, and pretty print
the result
"""
p = Parser()
m = MapfileToDict()
ast = p.parse_file(fn)
# print(ast)
d = m.transform(ast)
# print(d)
pp = PrettyPrinter(indent=0, newlinechar=" ", quote="'")
pp.pprint(d)
def main():
fns = [r"D:\Temp\large_map1.txt", r"D:\Temp\large_map2.txt"]
for fn in fns:
pr = cProfile.Profile()
pr.enable()
output(fn)
pr.disable()
pr.print_stats(sort='time')
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
main()
print("Done!")
| import logging
import os
import cProfile
import glob
import json
import mappyfile
from mappyfile.parser import Parser
from mappyfile.pprint import PrettyPrinter
from mappyfile.transformer import MapfileToDict
from mappyfile.validator import Validator
def output(fn):
"""
Parse, transform, and pretty print
the result
"""
p = Parser(expand_includes=False)
m = MapfileToDict()
v = Validator()
ast = p.parse_file(fn)
# print(ast)
d = m.transform(ast)
assert(v.validate(d))
output_file = fn + ".map"
try:
mappyfile.utils.write(d, output_file)
except Exception:
logging.warning(json.dumps(d, indent=4))
logging.warning("%s could not be successfully re-written", fn)
raise
# now try reading it again
ast = p.parse_file(output_file)
d = m.transform(ast)
assert(v.validate(d))
def main():
sample_dir = os.path.join(os.path.dirname(__file__), "mapfiles")
mapfiles = glob.glob(sample_dir + '/*.txt')
# mapfiles = ["map4.txt"]
for fn in mapfiles:
print("Processing {}".format(fn))
fn = os.path.join(sample_dir, fn)
pr = cProfile.Profile()
pr.enable()
output(fn)
pr.disable()
# pr.print_stats(sort='time')
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
main()
print("Done!")
| Add more user mapfiles and validate | Add more user mapfiles and validate
| Python | mit | geographika/mappyfile,geographika/mappyfile | ---
+++
@@ -1,9 +1,13 @@
import logging
+import os
import cProfile
-
+import glob
+import json
+import mappyfile
from mappyfile.parser import Parser
from mappyfile.pprint import PrettyPrinter
from mappyfile.transformer import MapfileToDict
+from mappyfile.validator import Validator
def output(fn):
@@ -11,26 +15,44 @@
Parse, transform, and pretty print
the result
"""
- p = Parser()
+ p = Parser(expand_includes=False)
m = MapfileToDict()
+ v = Validator()
ast = p.parse_file(fn)
# print(ast)
d = m.transform(ast)
- # print(d)
- pp = PrettyPrinter(indent=0, newlinechar=" ", quote="'")
- pp.pprint(d)
+ assert(v.validate(d))
+
+ output_file = fn + ".map"
+
+ try:
+ mappyfile.utils.write(d, output_file)
+ except Exception:
+ logging.warning(json.dumps(d, indent=4))
+ logging.warning("%s could not be successfully re-written", fn)
+ raise
+
+ # now try reading it again
+ ast = p.parse_file(output_file)
+ d = m.transform(ast)
+
+ assert(v.validate(d))
def main():
- fns = [r"D:\Temp\large_map1.txt", r"D:\Temp\large_map2.txt"]
+ sample_dir = os.path.join(os.path.dirname(__file__), "mapfiles")
+ mapfiles = glob.glob(sample_dir + '/*.txt')
+ # mapfiles = ["map4.txt"]
- for fn in fns:
+ for fn in mapfiles:
+ print("Processing {}".format(fn))
+ fn = os.path.join(sample_dir, fn)
pr = cProfile.Profile()
pr.enable()
output(fn)
pr.disable()
- pr.print_stats(sort='time')
+ # pr.print_stats(sort='time')
if __name__ == "__main__": |
dbce79102efa8fee233af95939f1ff0b9d060b00 | examples/basic.py | examples/basic.py | import time
from simpleflow import (
activity,
Workflow,
futures,
)
@activity.with_attributes(task_list='quickstart', version='example')
def increment(x):
return x + 1
@activity.with_attributes(task_list='quickstart', version='example')
def double(x):
return x * 2
@activity.with_attributes(task_list='quickstart', version='example')
def delay(t, x):
time.sleep(t)
return x
class BasicWorkflow(Workflow):
name = 'basic'
version = 'example'
task_list = 'example'
def run(self, x, t=30):
y = self.submit(increment, x)
yy = self.submit(delay, t, y)
z = self.submit(double, y)
print '({x} + 1) * 2 = {result}'.format(
x=x,
result=z.result)
futures.wait(yy, z)
return z.result
| import time
from simpleflow import (
activity,
Workflow,
futures,
)
@activity.with_attributes(task_list='quickstart', version='example')
def increment(x):
return x + 1
@activity.with_attributes(task_list='quickstart', version='example')
def double(x):
return x * 2
# A simpleflow activity can be any callable, so a function works, but a class
# will also work given the processing happens in __init__()
@activity.with_attributes(task_list='quickstart', version='example')
class Delay(object):
def __init__(self, t, x):
time.sleep(t)
return x
class BasicWorkflow(Workflow):
name = 'basic'
version = 'example'
task_list = 'example'
def run(self, x, t=30):
y = self.submit(increment, x)
yy = self.submit(Delay, t, y)
z = self.submit(double, y)
print '({x} + 1) * 2 = {result}'.format(
x=x,
result=z.result)
futures.wait(yy, z)
return z.result
| Update example workflow to show you can use classes | Update example workflow to show you can use classes
| Python | mit | botify-labs/simpleflow,botify-labs/simpleflow | ---
+++
@@ -16,11 +16,13 @@
def double(x):
return x * 2
-
+# A simpleflow activity can be any callable, so a function works, but a class
+# will also work given the processing happens in __init__()
@activity.with_attributes(task_list='quickstart', version='example')
-def delay(t, x):
- time.sleep(t)
- return x
+class Delay(object):
+ def __init__(self, t, x):
+ time.sleep(t)
+ return x
class BasicWorkflow(Workflow):
@@ -30,7 +32,7 @@
def run(self, x, t=30):
y = self.submit(increment, x)
- yy = self.submit(delay, t, y)
+ yy = self.submit(Delay, t, y)
z = self.submit(double, y)
print '({x} + 1) * 2 = {result}'.format( |
ba1186c47e5f3466faeea9f2d5bf96948d5f7183 | confuzzle.py | confuzzle.py | import sys
import argparse
import yaml
from jinja2 import Template
def render(template_string, context_dict):
template = Template(template_string)
return template.render(**context_dict)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('template', nargs='?', type=argparse.FileType('r'), default=sys.stdin, help="Config file template. If not supplied, stdin is used")
parser.add_argument('config', type=argparse.FileType('r'), help="YAML data file to read")
parser.add_argument('--out', '-o', dest='out', type=argparse.FileType('w'), default=sys.stdout, help="Output file to write. If not supplied, stdout is used")
args = parser.parse_args()
context_dict = yaml.load(args.config.read())
template_string = args.template.read()
rendered = render(template_string, context_dict)
args.out.write(rendered)
if __name__ == "__main__":
main()
| import sys
import argparse
import yaml
import jinja2
def render(template_string, context_dict, strict=False):
template = jinja2.Template(template_string)
if strict:
template.environment.undefined = jinja2.StrictUndefined
return template.render(**context_dict)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('template', nargs='?', type=argparse.FileType('r'), default=sys.stdin, help="Config file template. If not supplied, stdin is used")
parser.add_argument('config', type=argparse.FileType('r'), help="YAML data file to read")
parser.add_argument('--out', '-o', dest='out', type=argparse.FileType('w'), default=sys.stdout, help="Output file to write. If not supplied, stdout is used")
parser.add_argument('--strict', dest='strict', action='store_true', default=False, help="Raise an exception on undefined variables")
args = parser.parse_args()
context_dict = yaml.load(args.config.read())
template_string = args.template.read()
rendered = render(template_string, context_dict, args.strict)
args.out.write(rendered)
if __name__ == "__main__":
main()
| Add --strict flag to raise exception on undefined variables | Add --strict flag to raise exception on undefined variables
| Python | unlicense | j4mie/confuzzle | ---
+++
@@ -1,11 +1,13 @@
import sys
import argparse
import yaml
-from jinja2 import Template
+import jinja2
-def render(template_string, context_dict):
- template = Template(template_string)
+def render(template_string, context_dict, strict=False):
+ template = jinja2.Template(template_string)
+ if strict:
+ template.environment.undefined = jinja2.StrictUndefined
return template.render(**context_dict)
@@ -15,13 +17,14 @@
parser.add_argument('template', nargs='?', type=argparse.FileType('r'), default=sys.stdin, help="Config file template. If not supplied, stdin is used")
parser.add_argument('config', type=argparse.FileType('r'), help="YAML data file to read")
parser.add_argument('--out', '-o', dest='out', type=argparse.FileType('w'), default=sys.stdout, help="Output file to write. If not supplied, stdout is used")
+ parser.add_argument('--strict', dest='strict', action='store_true', default=False, help="Raise an exception on undefined variables")
args = parser.parse_args()
context_dict = yaml.load(args.config.read())
template_string = args.template.read()
- rendered = render(template_string, context_dict)
+ rendered = render(template_string, context_dict, args.strict)
args.out.write(rendered)
|
b336e83a63722b3a3e4d3f1779686149d5cef8d1 | setuptools/tests/test_setopt.py | setuptools/tests/test_setopt.py | # coding: utf-8
from __future__ import unicode_literals
import io
import six
from setuptools.command import setopt
from setuptools.extern.six.moves import configparser
class TestEdit:
@staticmethod
def parse_config(filename):
parser = configparser.ConfigParser()
with io.open(filename, encoding='utf-8') as reader:
(parser.read_file if six.PY3 else parser.readfp)(reader)
return parser
@staticmethod
def write_text(file, content):
with io.open(file, 'wb') as strm:
strm.write(content.encode('utf-8'))
def test_utf8_encoding_retained(self, tmpdir):
"""
When editing a file, non-ASCII characters encoded in
UTF-8 should be retained.
"""
config = tmpdir.join('setup.cfg')
self.write_text(config, '[names]\njaraco=йарацо')
setopt.edit_config(str(config), dict(names=dict(other='yes')))
parser = self.parse_config(str(config))
assert parser['names']['jaraco'] == 'йарацо'
assert parser['names']['other'] == 'yes'
| # coding: utf-8
from __future__ import unicode_literals
import io
import six
from setuptools.command import setopt
from setuptools.extern.six.moves import configparser
class TestEdit:
@staticmethod
def parse_config(filename):
parser = configparser.ConfigParser()
with io.open(filename, encoding='utf-8') as reader:
(parser.read_file if six.PY3 else parser.readfp)(reader)
return parser
@staticmethod
def write_text(file, content):
with io.open(file, 'wb') as strm:
strm.write(content.encode('utf-8'))
def test_utf8_encoding_retained(self, tmpdir):
"""
When editing a file, non-ASCII characters encoded in
UTF-8 should be retained.
"""
config = tmpdir.join('setup.cfg')
self.write_text(str(config), '[names]\njaraco=йарацо')
setopt.edit_config(str(config), dict(names=dict(other='yes')))
parser = self.parse_config(str(config))
assert parser.get('names', 'jaraco') == 'йарацо'
assert parser.get('names', 'other') == 'yes'
| Add compatibility for Python 2 | Add compatibility for Python 2
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools | ---
+++
@@ -29,8 +29,8 @@
UTF-8 should be retained.
"""
config = tmpdir.join('setup.cfg')
- self.write_text(config, '[names]\njaraco=йарацо')
+ self.write_text(str(config), '[names]\njaraco=йарацо')
setopt.edit_config(str(config), dict(names=dict(other='yes')))
parser = self.parse_config(str(config))
- assert parser['names']['jaraco'] == 'йарацо'
- assert parser['names']['other'] == 'yes'
+ assert parser.get('names', 'jaraco') == 'йарацо'
+ assert parser.get('names', 'other') == 'yes' |
c2df896183f80fe3ca0eab259874bc4385d399e9 | tests/test_parallel.py | tests/test_parallel.py | from __future__ import with_statement
from datetime import datetime
import copy
import getpass
import sys
import paramiko
from nose.tools import with_setup
from fudge import (Fake, clear_calls, clear_expectations, patch_object, verify,
with_patched_object, patched_context, with_fakes)
from fabric.context_managers import settings, hide, show
from fabric.network import (HostConnectionCache, join_host_strings, normalize,
denormalize)
from fabric.io import output_loop
import fabric.network # So I can call patch_object correctly. Sigh.
from fabric.state import env, output, _get_system_username
from fabric.operations import run, sudo
from fabric.decorators import parallel
from utils import *
from server import (server, PORT, RESPONSES, PASSWORDS, CLIENT_PRIVKEY, USER,
CLIENT_PRIVKEY_PASSPHRASE)
class TestParallel(FabricTest):
@server()
@parallel
def test_parallel(self):
"""
Want to do a simple call and respond
"""
env.pool_size = 10
cmd = "ls /simple"
with hide('everything'):
eq_(run(cmd), RESPONSES[cmd])
| from __future__ import with_statement
from fabric.api import run, parallel, env, hide
from utils import FabricTest, eq_
from server import server, RESPONSES
class TestParallel(FabricTest):
@server()
@parallel
def test_parallel(self):
"""
Want to do a simple call and respond
"""
env.pool_size = 10
cmd = "ls /simple"
with hide('everything'):
eq_(run(cmd), RESPONSES[cmd])
| Clean up detrius in parallel test file | Clean up detrius in parallel test file
| Python | bsd-2-clause | bitprophet/fabric,MjAbuz/fabric,likesxuqiang/fabric,sdelements/fabric,opavader/fabric,TarasRudnyk/fabric,tekapo/fabric,haridsv/fabric,SamuelMarks/fabric,bspink/fabric,tolbkni/fabric,rane-hs/fabric-py3,mathiasertl/fabric,askulkarni2/fabric,fernandezcuesta/fabric,elijah513/fabric,xLegoz/fabric,raimon49/fabric,amaniak/fabric,pgroudas/fabric,hrubi/fabric,rodrigc/fabric,cgvarela/fabric,cmattoon/fabric,ploxiln/fabric,itoed/fabric,kxxoling/fabric,jaraco/fabric,bitmonk/fabric,felix-d/fabric,rbramwell/fabric,qinrong/fabric,StackStorm/fabric,pashinin/fabric,kmonsoor/fabric,akaariai/fabric,getsentry/fabric | ---
+++
@@ -1,27 +1,10 @@
from __future__ import with_statement
-from datetime import datetime
-import copy
-import getpass
-import sys
+from fabric.api import run, parallel, env, hide
-import paramiko
-from nose.tools import with_setup
-from fudge import (Fake, clear_calls, clear_expectations, patch_object, verify,
- with_patched_object, patched_context, with_fakes)
+from utils import FabricTest, eq_
+from server import server, RESPONSES
-from fabric.context_managers import settings, hide, show
-from fabric.network import (HostConnectionCache, join_host_strings, normalize,
- denormalize)
-from fabric.io import output_loop
-import fabric.network # So I can call patch_object correctly. Sigh.
-from fabric.state import env, output, _get_system_username
-from fabric.operations import run, sudo
-from fabric.decorators import parallel
-
-from utils import *
-from server import (server, PORT, RESPONSES, PASSWORDS, CLIENT_PRIVKEY, USER,
- CLIENT_PRIVKEY_PASSPHRASE)
class TestParallel(FabricTest):
|
0138eacf0d518b86e819a70000b7b527434a6b35 | libretto/signals.py | libretto/signals.py | # coding: utf-8
from __future__ import unicode_literals
from celery_haystack.signals import CelerySignalProcessor
from django.contrib.admin.models import LogEntry
from reversion.models import Version, Revision
from .tasks import auto_invalidate
class CeleryAutoInvalidator(CelerySignalProcessor):
def enqueue(self, action, instance, sender, **kwargs):
if sender in (LogEntry, Revision, Version):
return
auto_invalidate.delay(action, instance)
| # coding: utf-8
from __future__ import unicode_literals
from celery_haystack.signals import CelerySignalProcessor
from django.contrib.admin.models import LogEntry
from django.contrib.sessions.models import Session
from reversion.models import Version, Revision
from .tasks import auto_invalidate
class CeleryAutoInvalidator(CelerySignalProcessor):
def enqueue(self, action, instance, sender, **kwargs):
if sender in (LogEntry, Session, Revision, Version):
return
auto_invalidate.delay(action, instance.__class__, instance.pk)
| Change les arguments passés à celery pour gérer la sérialisation JSON. | Change les arguments passés à celery pour gérer la sérialisation JSON.
| Python | bsd-3-clause | dezede/dezede,dezede/dezede,dezede/dezede,dezede/dezede | ---
+++
@@ -3,13 +3,14 @@
from __future__ import unicode_literals
from celery_haystack.signals import CelerySignalProcessor
from django.contrib.admin.models import LogEntry
+from django.contrib.sessions.models import Session
from reversion.models import Version, Revision
from .tasks import auto_invalidate
class CeleryAutoInvalidator(CelerySignalProcessor):
def enqueue(self, action, instance, sender, **kwargs):
- if sender in (LogEntry, Revision, Version):
+ if sender in (LogEntry, Session, Revision, Version):
return
- auto_invalidate.delay(action, instance)
+ auto_invalidate.delay(action, instance.__class__, instance.pk) |
eb102bb8550d59b34373f1806633a6079f7064a8 | devserver/utils/http.py | devserver/utils/http.py | from django.conf import settings
from django.core.servers.basehttp import WSGIRequestHandler
from django.db import connection
from devserver.utils.time import ms_from_timedelta
from datetime import datetime
class SlimWSGIRequestHandler(WSGIRequestHandler):
"""
Hides all requests that originate from ```MEDIA_URL`` as well as any
request originating with a prefix included in ``DEVSERVER_IGNORED_PREFIXES``.
"""
def handle(self, *args, **kwargs):
self._start_request = datetime.now()
return WSGIRequestHandler.handle(self, *args, **kwargs)
def log_message(self, format, *args):
duration = datetime.now() - self._start_request
env = self.get_environ()
if settings.MEDIA_URL.startswith('http:'):
if ('http://%s%s' % (env['HTTP_HOST'], self.path)).startswith(settings.MEDIA_URL):
return
# if self.path.startswith(settings.MEDIA_URL):
# return
for path in getattr(settings, 'DEVSERVER_IGNORED_PREFIXES', []):
if self.path.startswith(path):
return
format += " (time: %.2fs; sql: %dms (%dq))"
args = list(args) + [
ms_from_timedelta(duration) / 1000,
sum(float(c.get('time', 0)) for c in connection.queries) * 1000,
len(connection.queries),
]
return WSGIRequestHandler.log_message(self, format, *args) | from django.conf import settings
from django.core.servers.basehttp import WSGIRequestHandler
from django.db import connection
from devserver.utils.time import ms_from_timedelta
from datetime import datetime
class SlimWSGIRequestHandler(WSGIRequestHandler):
"""
Hides all requests that originate from either ``STATIC_URL`` or ``MEDIA_URL``
as well as any request originating with a prefix included in
``DEVSERVER_IGNORED_PREFIXES``.
"""
def handle(self, *args, **kwargs):
self._start_request = datetime.now()
return WSGIRequestHandler.handle(self, *args, **kwargs)
def log_message(self, format, *args):
duration = datetime.now() - self._start_request
env = self.get_environ()
for url in (settings.STATIC_URL, settings.MEDIA_URL):
if self.path.startswith(url):
return
elif url.startswith('http:'):
if ('http://%s%s' % (env['HTTP_HOST'], self.path)).startswith(url):
return
for path in getattr(settings, 'DEVSERVER_IGNORED_PREFIXES', []):
if self.path.startswith(path):
return
format += " (time: %.2fs; sql: %dms (%dq))"
args = list(args) + [
ms_from_timedelta(duration) / 1000,
sum(float(c.get('time', 0)) for c in connection.queries) * 1000,
len(connection.queries),
]
return WSGIRequestHandler.log_message(self, format, *args) | Make sure that all requests for static files are correctly hidden from output | Make sure that all requests for static files are correctly hidden from output
| Python | bsd-3-clause | caffodian/django-devserver,madgeekfiend/django-devserver,jimmyye/django-devserver,takeshineshiro/django-devserver,pjdelport/django-devserver,bastianh/django-devserver,Stackdriver/django-devserver,dcramer/django-devserver,chriscauley/django-devserver,coagulant/django-devserver,mathspace/django-devserver | ---
+++
@@ -8,8 +8,9 @@
class SlimWSGIRequestHandler(WSGIRequestHandler):
"""
- Hides all requests that originate from ```MEDIA_URL`` as well as any
- request originating with a prefix included in ``DEVSERVER_IGNORED_PREFIXES``.
+ Hides all requests that originate from either ``STATIC_URL`` or ``MEDIA_URL``
+ as well as any request originating with a prefix included in
+ ``DEVSERVER_IGNORED_PREFIXES``.
"""
def handle(self, *args, **kwargs):
self._start_request = datetime.now()
@@ -20,12 +21,13 @@
env = self.get_environ()
- if settings.MEDIA_URL.startswith('http:'):
- if ('http://%s%s' % (env['HTTP_HOST'], self.path)).startswith(settings.MEDIA_URL):
+ for url in (settings.STATIC_URL, settings.MEDIA_URL):
+ if self.path.startswith(url):
return
-
- # if self.path.startswith(settings.MEDIA_URL):
- # return
+ elif url.startswith('http:'):
+ if ('http://%s%s' % (env['HTTP_HOST'], self.path)).startswith(url):
+ return
+
for path in getattr(settings, 'DEVSERVER_IGNORED_PREFIXES', []):
if self.path.startswith(path):
return |
9df0c21bcefdeda4ca65ee4126ed965a6d099416 | website/website/wagtail_hooks.py | website/website/wagtail_hooks.py | from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register, \
ThumbnailMixin
from website.models import Logo
class LogoAdmin(ThumbnailMixin, ModelAdmin):
model = Logo
menu_icon = 'picture'
menu_order = 1000
list_display = ('admin_thumb', 'category', 'link')
add_to_settings_menu = True
thumb_image_field_name = 'logo'
thumb_image_filter_spec = 'fill-128x128'
modeladmin_register(LogoAdmin)
| from wagtail.contrib.modeladmin.options import ModelAdmin,\
modeladmin_register, ThumbnailMixin
from website.models import Logo
class LogoAdmin(ThumbnailMixin, ModelAdmin):
model = Logo
menu_icon = 'picture'
menu_order = 1000
list_display = ('admin_thumb', 'category', 'link')
add_to_settings_menu = True
thumb_image_field_name = 'logo'
thumb_image_filter_spec = 'fill-128x128'
modeladmin_register(LogoAdmin)
| Fix line length on import statement | :green_heart: Fix line length on import statement
| Python | agpl-3.0 | Dekker1/moore,UTNkar/moore,UTNkar/moore,UTNkar/moore,Dekker1/moore,UTNkar/moore,Dekker1/moore,Dekker1/moore | ---
+++
@@ -1,5 +1,5 @@
-from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register, \
- ThumbnailMixin
+from wagtail.contrib.modeladmin.options import ModelAdmin,\
+ modeladmin_register, ThumbnailMixin
from website.models import Logo
|
f585a7cdf4ecbecfe240873a3b4b8e7d4376e69c | campus02/urls.py | campus02/urls.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.views.static import serve
urlpatterns = [
url(r'^', include('django.contrib.auth.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^web/', include('campus02.web.urls', namespace='web')),
url(r'^', include('campus02.base.urls', namespace='base')),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns.append(
url(
r'^__debug__/',
include(debug_toolbar.urls)
)
)
urlpatterns.append(
url(
r'^media/(?P<path>.*)$',
serve,
{
'document_root': settings.MEDIA_ROOT,
}
)
)
urlpatterns.append(
url(
r'^static/(?P<path>.*)$',
serve,
{
'document_root': settings.STATIC_ROOT,
}
),
)
| #!/usr/bin/python
# -*- coding: utf-8 -*-
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.views.static import serve
urlpatterns = [
url(r'^', include('django.contrib.auth.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^web/', include('campus02.web.urls', namespace='web')),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns.append(
url(
r'^__debug__/',
include(debug_toolbar.urls)
)
)
urlpatterns.append(
url(
r'^media/(?P<path>.*)$',
serve,
{
'document_root': settings.MEDIA_ROOT,
}
)
)
urlpatterns.append(
url(
r'^static/(?P<path>.*)$',
serve,
{
'document_root': settings.STATIC_ROOT,
}
),
)
urlpatterns.append(
url(r'^', include('campus02.base.urls', namespace='base'))
)
| Move fallback URL pattern to the end of the list so it gets matched last. | Move fallback URL pattern to the end of the list so it gets matched last.
| Python | mit | fladi/django-campus02,fladi/django-campus02 | ---
+++
@@ -10,7 +10,6 @@
url(r'^', include('django.contrib.auth.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^web/', include('campus02.web.urls', namespace='web')),
- url(r'^', include('campus02.base.urls', namespace='base')),
]
if settings.DEBUG:
@@ -39,3 +38,7 @@
}
),
)
+
+urlpatterns.append(
+ url(r'^', include('campus02.base.urls', namespace='base'))
+) |
2a08d3154992b5f0633d7cd2ca1bbfc7ecd63f69 | email_extras/__init__.py | email_extras/__init__.py |
from django.core.exceptions import ImproperlyConfigured
from email_extras.settings import USE_GNUPG
__version__ = "0.1.0"
if USE_GNUPG:
try:
import gnupg
except ImportError:
raise ImproperlyConfigured, "Could not import gnupg"
|
from email_extras.settings import USE_GNUPG
__version__ = "0.1.0"
if USE_GNUPG:
try:
import gnupg
except ImportError:
try:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured, "Could not import gnupg"
except ImportError:
pass
| Fix to allow version number to be imported without dependencies being installed. | Fix to allow version number to be imported without dependencies being installed.
| Python | bsd-2-clause | dreipol/django-email-extras,blag/django-email-extras,stephenmcd/django-email-extras,blag/django-email-extras,dreipol/django-email-extras,stephenmcd/django-email-extras | ---
+++
@@ -1,5 +1,3 @@
-
-from django.core.exceptions import ImproperlyConfigured
from email_extras.settings import USE_GNUPG
@@ -7,7 +5,13 @@
__version__ = "0.1.0"
if USE_GNUPG:
- try:
- import gnupg
- except ImportError:
- raise ImproperlyConfigured, "Could not import gnupg"
+ try:
+ import gnupg
+ except ImportError:
+ try:
+ from django.core.exceptions import ImproperlyConfigured
+ raise ImproperlyConfigured, "Could not import gnupg"
+ except ImportError:
+ pass
+
+ |
b39518482da1d3e064cdbc34490e4a9924f6d5f1 | quantecon/tests/test_ecdf.py | quantecon/tests/test_ecdf.py | """
Tests for ecdf.py
"""
import unittest
import numpy as np
from quantecon import ECDF
class TestECDF(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.obs = np.random.rand(40) # observations defining dist
cls.ecdf = ECDF(cls.obs)
def test_call_high(self):
"ecdf: x above all obs give 1.0"
# all of self.obs <= 1 so ecdf(1.1) should be 1
self.assertAlmostEqual(self.ecdf(1.1), 1.0)
def test_call_low(self):
"ecdf: x below all obs give 0.0"
# all of self.obs <= 1 so ecdf(1.1) should be 1
self.assertAlmostEqual(self.ecdf(-0.1), 0.0)
def test_ascending(self):
"ecdf: larger values should return F(x) at least as big"
x = np.random.rand()
F_1 = self.ecdf(x)
F_2 = self.ecdf(1.1 * x)
self.assertGreaterEqual(F_2, F_1)
| """
Tests for ecdf.py
"""
import unittest
import numpy as np
from quantecon import ECDF
class TestECDF(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.obs = np.random.rand(40) # observations defining dist
cls.ecdf = ECDF(cls.obs)
def test_call_high(self):
"ecdf: x above all obs give 1.0"
# all of self.obs <= 1 so ecdf(1.1) should be 1
self.assertAlmostEqual(self.ecdf(1.1), 1.0)
def test_call_low(self):
"ecdf: x below all obs give 0.0"
# all of self.obs <= 1 so ecdf(1.1) should be 1
self.assertAlmostEqual(self.ecdf(-0.1), 0.0)
def test_ascending(self):
"ecdf: larger values should return F(x) at least as big"
x = np.random.rand()
F_1 = self.ecdf(x)
F_2 = self.ecdf(1.1 * x)
self.assertGreaterEqual(F_2, F_1)
def test_vectorized(self):
"ecdf: testing vectorized __call__ method"
t = np.linspace(-1, 1, 100)
self.assertEqual(t.shape, self.ecdf(t).shape)
t = np.linspace(-1, 1, 100).reshape(2, 2, 25)
self.assertEqual(t.shape, self.ecdf(t).shape)
| Add a test for vectorized call | TST: Add a test for vectorized call
| Python | bsd-3-clause | oyamad/QuantEcon.py,QuantEcon/QuantEcon.py,oyamad/QuantEcon.py,QuantEcon/QuantEcon.py | ---
+++
@@ -30,3 +30,10 @@
F_1 = self.ecdf(x)
F_2 = self.ecdf(1.1 * x)
self.assertGreaterEqual(F_2, F_1)
+
+ def test_vectorized(self):
+ "ecdf: testing vectorized __call__ method"
+ t = np.linspace(-1, 1, 100)
+ self.assertEqual(t.shape, self.ecdf(t).shape)
+ t = np.linspace(-1, 1, 100).reshape(2, 2, 25)
+ self.assertEqual(t.shape, self.ecdf(t).shape) |
8d56c42dd3a721a477fa1333c1d979f4002e7cc1 | labonneboite/importer/conf/lbbdev.py | labonneboite/importer/conf/lbbdev.py | import os
# --- importer input directory of DPAE and ETABLISSEMENT exports
INPUT_SOURCE_FOLDER = '/srv/lbb/data'
# --- job 1/8 & 2/8 : check_etablissements & extract_etablissements
JENKINS_ETAB_PROPERTIES_FILENAME = os.path.join(os.environ["WORKSPACE"], "properties.jenkins")
MINIMUM_OFFICES_TO_BE_EXTRACTED_PER_DEPARTEMENT = 10000
# --- job 3/8 & 4/8 : check_dpae & extract_dpae
JENKINS_DPAE_PROPERTIES_FILENAME = os.path.join(os.environ["WORKSPACE"], "properties_dpae.jenkins")
MAXIMUM_ZIPCODE_ERRORS = 100
MAXIMUM_INVALID_ROWS = 100
# --- job 5/8 : compute_scores
SCORE_COEFFICIENT_OF_VARIATION_MAX = 2.0
RMSE_MAX = 1500 # On 2017.03.15 departement 52 reached RMSE=1141
HIGH_SCORE_COMPANIES_DIFF_MAX = 70
# --- job 6/8 : validate_scores
MINIMUM_OFFICES_PER_DEPARTEMENT_FOR_DPAE = 500
MINIMUM_OFFICES_PER_DEPARTEMENT_FOR_ALTERNANCE = 0
# --- job 8/8 : populate_flags
BACKUP_OUTPUT_FOLDER = '/srv/lbb/backups/outputs'
BACKUP_FOLDER = '/srv/lbb/backups'
| import os
# --- importer input directory of DPAE and ETABLISSEMENT exports
INPUT_SOURCE_FOLDER = '/srv/lbb/data'
# --- job 1/8 & 2/8 : check_etablissements & extract_etablissements
JENKINS_ETAB_PROPERTIES_FILENAME = os.path.join(os.environ["WORKSPACE"], "properties.jenkins")
MINIMUM_OFFICES_TO_BE_EXTRACTED_PER_DEPARTEMENT = 10000
# --- job 3/8 & 4/8 : check_dpae & extract_dpae
JENKINS_DPAE_PROPERTIES_FILENAME = os.path.join(os.environ["WORKSPACE"], "properties_dpae.jenkins")
MAXIMUM_ZIPCODE_ERRORS = 100
MAXIMUM_INVALID_ROWS = 100
# --- job 5/8 : compute_scores
SCORE_COEFFICIENT_OF_VARIATION_MAX = 2.0
RMSE_MAX = 1500 # On 2017.03.15 departement 52 reached RMSE=1141
HIGH_SCORE_COMPANIES_DIFF_MAX = 70
# --- job 6/8 : validate_scores
MINIMUM_OFFICES_PER_DEPARTEMENT_FOR_DPAE = 500
MINIMUM_OFFICES_PER_DEPARTEMENT_FOR_ALTERNANCE = 0
# --- job 8/8 : populate_flags
| Simplify importer paths after dockerization | Simplify importer paths after dockerization
| Python | agpl-3.0 | StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite | ---
+++
@@ -22,5 +22,3 @@
MINIMUM_OFFICES_PER_DEPARTEMENT_FOR_ALTERNANCE = 0
# --- job 8/8 : populate_flags
-BACKUP_OUTPUT_FOLDER = '/srv/lbb/backups/outputs'
-BACKUP_FOLDER = '/srv/lbb/backups' |
f1c270f2145cf1f48a0207696cb4f6e9592af357 | NTHU_Course/settings/testing_sqlite.py | NTHU_Course/settings/testing_sqlite.py | '''
A configuration for testing in travis CI with sqlite3
'''
from .default import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
# https://docs.djangoproject.com/en/1.10/topics/testing/overview/#the-test-database
# django uses in memory database for testing
'NAME': 'test_sqlite'
}
}
| '''
A configuration for testing in travis CI with sqlite3
'''
from .default import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
# https://docs.djangoproject.com/en/1.10/topics/testing/overview/#the-test-database
# django uses in memory database for testing
'NAME': ':memory:'
}
}
| Correct db `NAME`, use in-memory database for testing | Correct db `NAME`, use in-memory database for testing
| Python | mit | henryyang42/NTHU_Course,henryyang42/NTHU_Course,henryyang42/NTHU_Course,henryyang42/NTHU_Course | ---
+++
@@ -9,6 +9,6 @@
'ENGINE': 'django.db.backends.sqlite3',
# https://docs.djangoproject.com/en/1.10/topics/testing/overview/#the-test-database
# django uses in memory database for testing
- 'NAME': 'test_sqlite'
+ 'NAME': ':memory:'
}
} |
c5b00edd9b8acbe594e43ecce093cd1c695b8b01 | getalltextfromuser.py | getalltextfromuser.py | #!/usr/bin/env python3
"""
A program to extract all text sent by a particular user from a Telegram chat log which is in json form
"""
import argparse
from json import loads
def main():
parser = argparse.ArgumentParser(
description="Extract raw text sent by a user from a json telegram chat log")
parser.add_argument(
'filepath', help='the json file to analyse')
parser.add_argument(
'username', help='the username of the person whose text you want')
args=parser.parse_args()
filepath = args.filepath
username = args.username
with open(filepath, 'r') as jsonfile:
events = (loads(line) for line in jsonfile)
for event in events:
#check the event is the sort we're looking for
if "from" in event and "text" in event:
if "username" in event["from"]:
#do i need "from" here?
if event["from"]["username"] == username:
print(event["text"])
if __name__ == "__main__":
main()
| #!/usr/bin/env python3
"""
A program to extract all text sent by a particular user from a Telegram chat log which is in json form
"""
import argparse
from json import loads
def main():
parser = argparse.ArgumentParser(
description="Extract raw text sent by a user from a json telegram chat log")
parser.add_argument(
'filepath', help='the json file to analyse')
parser.add_argument(
'username', help='the username of the person whose text you want')
args=parser.parse_args()
filepath = args.filepath
username = args.username
user_id = ""
#first, get the ID of the user with that username.
with open(filepath, 'r') as jsonfile:
events = (loads(line) for line in jsonfile)
for event in events:
#check the event is the sort we're looking for
if "from" in event and "text" in event:
if "username" in event["from"]:
#do i need "from" here?
if event["from"]["username"] == username:
#print(event["text"])
print(event['from']['id'])
user_id = event['from']['id']
break
if user_id == "":
print("user not found")
exit()
with open(filepath, 'r') as jsonfile:
events = (loads(line) for line in jsonfile)
for event in events:
#check the event is the sort we're looking for
if "from" in event and "text" in event:
if user_id == event["from"]["id"]:
print(event["text"])
if __name__ == "__main__":
main()
| Use user ID instead of username to get messages even with username changes | Use user ID instead of username to get messages even with username changes
| Python | mit | expectocode/telegram-analysis,expectocode/telegramAnalysis | ---
+++
@@ -18,6 +18,9 @@
filepath = args.filepath
username = args.username
+ user_id = ""
+
+ #first, get the ID of the user with that username.
with open(filepath, 'r') as jsonfile:
events = (loads(line) for line in jsonfile)
for event in events:
@@ -26,7 +29,21 @@
if "username" in event["from"]:
#do i need "from" here?
if event["from"]["username"] == username:
- print(event["text"])
+ #print(event["text"])
+ print(event['from']['id'])
+ user_id = event['from']['id']
+ break
+ if user_id == "":
+ print("user not found")
+ exit()
+
+ with open(filepath, 'r') as jsonfile:
+ events = (loads(line) for line in jsonfile)
+ for event in events:
+ #check the event is the sort we're looking for
+ if "from" in event and "text" in event:
+ if user_id == event["from"]["id"]:
+ print(event["text"])
if __name__ == "__main__":
main() |
48b227f0019fb28a5b96874f62662fee79998fe5 | go/dashboard/views.py | go/dashboard/views.py | from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from go.dashboard import client
@login_required
@csrf_exempt
@require_http_methods(['GET'])
def diamondash_api_proxy(request):
"""
Proxies client snapshot requests to diamondash.
NOTE: This proxy is a fallback for dev purposes only. A more sensible
proxying solution should be used in production (eg. haproxy).
"""
api = client.get_diamondash_api()
_, url = request.path.split('/diamondash/api', 1)
response = api.raw_request(request.method, url, content=request.body)
return HttpResponse(
response['content'],
status=response['code'],
content_type='application/json')
| from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from go.dashboard import client
@login_required
@csrf_exempt
@require_http_methods(['GET'])
def diamondash_api_proxy(request):
"""
Proxies client snapshot requests to diamondash.
NOTE: This proxy is a fallback for dev purposes only. A more sensible
proxying solution should be used in production (eg. haproxy).
"""
api = client.get_diamondash_api()
_, url = request.path.split('/diamondash/api', 1)
response = api.raw_request(request.method, url, content=request.body)
# TODO for the case of snapshot requests, ensure the widgets requested are
# allowed for the given account
return HttpResponse(
response['content'],
status=response['code'],
content_type='application/json')
| Add a TODO for diamondash metric snapshot request auth in diamondash proxy view | Add a TODO for diamondash metric snapshot request auth in diamondash proxy view
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | ---
+++
@@ -20,6 +20,9 @@
_, url = request.path.split('/diamondash/api', 1)
response = api.raw_request(request.method, url, content=request.body)
+ # TODO for the case of snapshot requests, ensure the widgets requested are
+ # allowed for the given account
+
return HttpResponse(
response['content'],
status=response['code'], |
82bc502cf7bb64236feba6e140d98bb9e555f4ca | tests/backport_assert_raises.py | tests/backport_assert_raises.py | from __future__ import unicode_literals
"""
Patch courtesy of:
https://marmida.com/blog/index.php/2012/08/08/monkey-patching-assert_raises/
"""
# code for monkey-patching
import nose.tools
# let's fix nose.tools.assert_raises (which is really unittest.assertRaises)
# so that it always supports context management
# in order for these changes to be available to other modules, you'll need
# to guarantee this module is imported by your fixture before either nose or
# unittest are imported
try:
nose.tools.assert_raises(Exception)
except TypeError:
# this version of assert_raises doesn't support the 1-arg version
class AssertRaisesContext(object):
def __init__(self, expected):
self.expected = expected
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, tb):
self.exception = exc_val
nose.tools.assert_equal(exc_type, self.expected)
# if you get to this line, the last assertion must have passed
# suppress the propagation of this exception
return True
def assert_raises_context(exc_type):
return AssertRaisesContext(exc_type)
nose.tools.assert_raises = assert_raises_context
| from __future__ import unicode_literals
"""
Patch courtesy of:
https://marmida.com/blog/index.php/2012/08/08/monkey-patching-assert_raises/
"""
# code for monkey-patching
import nose.tools
# let's fix nose.tools.assert_raises (which is really unittest.assertRaises)
# so that it always supports context management
# in order for these changes to be available to other modules, you'll need
# to guarantee this module is imported by your fixture before either nose or
# unittest are imported
try:
nose.tools.assert_raises(Exception)
except TypeError:
# this version of assert_raises doesn't support the 1-arg version
class AssertRaisesContext(object):
def __init__(self, expected):
self.expected = expected
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, tb):
self.exception = exc_val
if issubclass(exc_type, self.expected):
return True
nose.tools.assert_equal(exc_type, self.expected)
# if you get to this line, the last assertion must have passed
# suppress the propagation of this exception
return True
def assert_raises_context(exc_type):
return AssertRaisesContext(exc_type)
nose.tools.assert_raises = assert_raises_context
| Fix assert_raises for catching parents of exceptions. | Fix assert_raises for catching parents of exceptions.
| Python | apache-2.0 | rocky4570/moto,ZuluPro/moto,Affirm/moto,Affirm/moto,kefo/moto,botify-labs/moto,okomestudio/moto,spulec/moto,Affirm/moto,dbfr3qs/moto,okomestudio/moto,kefo/moto,heddle317/moto,whummer/moto,2rs2ts/moto,Brett55/moto,dbfr3qs/moto,ZuluPro/moto,kefo/moto,william-richard/moto,spulec/moto,spulec/moto,ZuluPro/moto,gjtempleton/moto,2rs2ts/moto,spulec/moto,william-richard/moto,Brett55/moto,okomestudio/moto,Affirm/moto,gjtempleton/moto,okomestudio/moto,Brett55/moto,dbfr3qs/moto,rocky4570/moto,Affirm/moto,heddle317/moto,spulec/moto,rocky4570/moto,2rs2ts/moto,spulec/moto,william-richard/moto,botify-labs/moto,kefo/moto,Affirm/moto,Brett55/moto,gjtempleton/moto,rocky4570/moto,ZuluPro/moto,rocky4570/moto,whummer/moto,okomestudio/moto,whummer/moto,heddle317/moto,2rs2ts/moto,whummer/moto,botify-labs/moto,2rs2ts/moto,heddle317/moto,ZuluPro/moto,Brett55/moto,gjtempleton/moto,whummer/moto,william-richard/moto,rocky4570/moto,gjtempleton/moto,dbfr3qs/moto,kefo/moto,botify-labs/moto,Brett55/moto,william-richard/moto,whummer/moto,okomestudio/moto,ZuluPro/moto,heddle317/moto,dbfr3qs/moto,william-richard/moto,botify-labs/moto,silveregg/moto,dbfr3qs/moto,botify-labs/moto | ---
+++
@@ -27,6 +27,8 @@
def __exit__(self, exc_type, exc_val, tb):
self.exception = exc_val
+ if issubclass(exc_type, self.expected):
+ return True
nose.tools.assert_equal(exc_type, self.expected)
# if you get to this line, the last assertion must have passed
# suppress the propagation of this exception |
8998d0f617791f95b1ed6b4a1fffa0f71752b801 | pybo/bayesopt/inits.py | pybo/bayesopt/inits.py | """
Implementation of methods for sampling initial points.
"""
# future imports
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
# global imports
import numpy as np
# local imports
from ..utils import ldsample
# exported symbols
__all__ = ['init_middle', 'init_uniform', 'init_latin', 'init_sobol']
def init_middle(bounds):
return np.mean(bounds, axis=1)[None, :]
def init_uniform(bounds, rng=None):
n = 3*len(bounds)
X = ldsample.random(bounds, n, rng)
return X
def init_latin(bounds, rng=None):
n = 3*len(bounds)
X = ldsample.latin(bounds, n, rng)
return X
def init_sobol(bounds, rng=None):
n = 3*len(bounds)
X = ldsample.sobol(bounds, n, rng)
return X
| """
Implementation of methods for sampling initial points.
"""
# future imports
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
# global imports
import numpy as np
# local imports
from ..utils import ldsample
# exported symbols
__all__ = ['init_middle', 'init_uniform', 'init_latin', 'init_sobol']
def init_middle(bounds):
"""
Initialize using a single query in the middle of the space.
"""
return np.mean(bounds, axis=1)[None, :]
def init_uniform(bounds, n=None, rng=None):
"""
Initialize using `n` uniformly distributed query points. If `n` is `None`
then use 3D points where D is the dimensionality of the input space.
"""
n = 3*len(bounds) if (n is None) else n
X = ldsample.random(bounds, n, rng)
return X
def init_latin(bounds, n=None, rng=None):
"""
Initialize using a Latin hypercube design of size `n`. If `n` is `None`
then use 3D points where D is the dimensionality of the input space.
"""
n = 3*len(bounds) if (n is None) else n
X = ldsample.latin(bounds, n, rng)
return X
def init_sobol(bounds, n=None, rng=None):
"""
Initialize using a Sobol sequence of length `n`. If `n` is `None` then use
3D points where D is the dimensionality of the input space.
"""
n = 3*len(bounds) if (n is None) else n
X = ldsample.sobol(bounds, n, rng)
return X
| Update docs/params for initialization methods. | Update docs/params for initialization methods.
| Python | bsd-2-clause | mwhoffman/pybo,jhartford/pybo | ---
+++
@@ -18,22 +18,37 @@
def init_middle(bounds):
+ """
+ Initialize using a single query in the middle of the space.
+ """
return np.mean(bounds, axis=1)[None, :]
-def init_uniform(bounds, rng=None):
- n = 3*len(bounds)
+def init_uniform(bounds, n=None, rng=None):
+ """
+ Initialize using `n` uniformly distributed query points. If `n` is `None`
+ then use 3D points where D is the dimensionality of the input space.
+ """
+ n = 3*len(bounds) if (n is None) else n
X = ldsample.random(bounds, n, rng)
return X
-def init_latin(bounds, rng=None):
- n = 3*len(bounds)
+def init_latin(bounds, n=None, rng=None):
+ """
+ Initialize using a Latin hypercube design of size `n`. If `n` is `None`
+ then use 3D points where D is the dimensionality of the input space.
+ """
+ n = 3*len(bounds) if (n is None) else n
X = ldsample.latin(bounds, n, rng)
return X
-def init_sobol(bounds, rng=None):
- n = 3*len(bounds)
+def init_sobol(bounds, n=None, rng=None):
+ """
+ Initialize using a Sobol sequence of length `n`. If `n` is `None` then use
+ 3D points where D is the dimensionality of the input space.
+ """
+ n = 3*len(bounds) if (n is None) else n
X = ldsample.sobol(bounds, n, rng)
return X |
9729c3aecccfa8130db7b5942c423c0807726f81 | python/gbdt/_forest.py | python/gbdt/_forest.py | from libgbdt import Forest as _Forest
class Forest:
def __init__(self, forest):
if type(forest) is str or type(forest) is unicode:
self._forest = _Forest(forest)
elif type(forest) is _Forest:
self._forest = forest
else:
raise TypeError, 'Unsupported forest type: {0}'.format(type(forest))
def predict(self, data_store):
"""Computes prediction scores for data_store."""
return self._forest.predict(data_store._data_store)
def feature_importance(self):
"""Outputs list of feature importances in descending order."""
return self._forest.feature_importance()
def __str__(self):
return self._forest.as_json()
| from libgbdt import Forest as _Forest
class Forest:
def __init__(self, forest):
if type(forest) is str or type(forest) is unicode:
self._forest = _Forest(forest)
elif type(forest) is _Forest:
self._forest = forest
else:
raise TypeError, 'Unsupported forest type: {0}'.format(type(forest))
def predict(self, data_store):
"""Computes prediction scores for data_store."""
return self._forest.predict(data_store._data_store)
def feature_importance(self):
"""Outputs list of feature importances in descending order."""
return self._forest.feature_importance()
def feature_importance_bar_chart(self, color='blue'):
try:
from matplotlib import pyplot as plt
import numpy
except ImportError:
raise ImportError('Please install matplotlib and numpy.')
fimps = self.feature_importance()
importances = [v for _, v in fimps]
features = [f for f,_ in fimps]
ind = -numpy.arange(len(fimps))
_, ax = plt.subplots()
plt.barh(ind, importances, align='center', color=color)
ax.set_yticks(ind)
ax.set_yticklabels(features)
ax.set_xlabel('Feature importance')
def __str__(self):
return self._forest.as_json()
| Add feature importance bar chart. | Add feature importance bar chart.
| Python | apache-2.0 | yarny/gbdt,yarny/gbdt,yarny/gbdt,yarny/gbdt | ---
+++
@@ -17,5 +17,23 @@
"""Outputs list of feature importances in descending order."""
return self._forest.feature_importance()
+ def feature_importance_bar_chart(self, color='blue'):
+ try:
+ from matplotlib import pyplot as plt
+ import numpy
+ except ImportError:
+ raise ImportError('Please install matplotlib and numpy.')
+
+ fimps = self.feature_importance()
+ importances = [v for _, v in fimps]
+ features = [f for f,_ in fimps]
+ ind = -numpy.arange(len(fimps))
+
+ _, ax = plt.subplots()
+ plt.barh(ind, importances, align='center', color=color)
+ ax.set_yticks(ind)
+ ax.set_yticklabels(features)
+ ax.set_xlabel('Feature importance')
+
def __str__(self):
return self._forest.as_json() |
872a96b52061bd9ab3a3178aacf3e3d0be2cc498 | nap/dataviews/fields.py | nap/dataviews/fields.py |
from django.db.models.fields import NOT_PROVIDED
from nap.utils import digattr
class field(property):
'''A base class to compare against.'''
def __get__(self, instance, cls=None):
if instance is None:
return self
return self.fget(instance._obj)
def __set__(self, instance, value):
self.fset(instance._obj, value)
class Field(field):
'''
class V(DataView):
foo = Field('bar', default=1)
'''
def __init__(self, name, default=NOT_PROVIDED, filters=None):
self.name = name
self.default = default
self.filters = filters or []
def __get__(self, instance, cls=None):
if instance is None:
return self
value = getattr(instance._obj, self.name, self.default)
for filt in self.filters:
value = filt.from_python(value)
return value
def __set__(self, instance, value):
for filt in self.filters[::-1]:
value = filt.to_python(value)
setattr(instance._obj, self.name, value)
class DigField(Field):
def __get__(self, instance, cls=None):
if instance is None:
return self
return digattr(instance._obj, self.name, self.default)
def __set__(self, instance):
raise NotImplementedError
|
from django.db.models.fields import NOT_PROVIDED
from django.forms import ValidationError
from nap.utils import digattr
class field(property):
'''A base class to compare against.'''
def __get__(self, instance, cls=None):
if instance is None:
return self
return self.fget(instance._obj)
def __set__(self, instance, value):
self.fset(instance._obj, value)
class Field(field):
'''
class V(DataView):
foo = Field('bar', default=1)
'''
def __init__(self, name, default=NOT_PROVIDED, filters=None):
self.name = name
self.default = default
self.filters = filters or []
def __get__(self, instance, cls=None):
if instance is None:
return self
value = getattr(instance._obj, self.name, self.default)
for filt in self.filters:
try:
value = filt.from_python(value)
except (TypeError, ValueError):
raise ValidationError('Invalid value')
return value
def __set__(self, instance, value):
for filt in self.filters[::-1]:
value = filt.to_python(value)
setattr(instance._obj, self.name, value)
class DigField(Field):
def __get__(self, instance, cls=None):
if instance is None:
return self
return digattr(instance._obj, self.name, self.default)
def __set__(self, instance):
raise NotImplementedError
| Make field filter errors ValidationErrors | Make field filter errors ValidationErrors
| Python | bsd-3-clause | limbera/django-nap,MarkusH/django-nap | ---
+++
@@ -1,5 +1,6 @@
from django.db.models.fields import NOT_PROVIDED
+from django.forms import ValidationError
from nap.utils import digattr
@@ -30,7 +31,10 @@
return self
value = getattr(instance._obj, self.name, self.default)
for filt in self.filters:
- value = filt.from_python(value)
+ try:
+ value = filt.from_python(value)
+ except (TypeError, ValueError):
+ raise ValidationError('Invalid value')
return value
def __set__(self, instance, value): |
c170765132d6f24b08a4e40274df589813cebf85 | neutron/cmd/__init__.py | neutron/cmd/__init__.py | # All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_reports import guru_meditation_report as gmr
from neutron import version
_version_string = version.version_info.release_string()
gmr.TextGuruMeditation.setup_autorun(version=_version_string)
| # All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging as sys_logging
from oslo_reports import guru_meditation_report as gmr
from neutron import version
# During the call to gmr.TextGuruMeditation.setup_autorun(), Guru Meditation
# Report tries to start logging. Set a handler here to accommodate this.
logger = sys_logging.getLogger(None)
if not logger.handlers:
logger.addHandler(sys_logging.StreamHandler())
_version_string = version.version_info.release_string()
gmr.TextGuruMeditation.setup_autorun(version=_version_string)
| Fix logging error for Guru Meditation Report | Fix logging error for Guru Meditation Report
Currently, invoking any of the commands under neutron/cmd will trigger a
"No handlers could be found" error for Guru Meditation Report. This is
interupting the notify.sh script that is called by dibbler-client during the
IPv6 Prefix Delegation workflow.
This patch adds a logging handler to __init__.py to prevent the error.
Without the error message being thrown, neutron-pd-notify is once again
able to complete successfully when called by dibbler-client.
Change-Id: Iac3162f6b7e968c2f11fd8ef2a6e275242fb21ff
Closes-Bug: 1532053
| Python | apache-2.0 | mahak/neutron,klmitch/neutron,openstack/neutron,openstack/neutron,huntxu/neutron,openstack/neutron,noironetworks/neutron,wolverineav/neutron,mahak/neutron,wolverineav/neutron,bigswitch/neutron,cloudbase/neutron,dims/neutron,MaximNevrov/neutron,klmitch/neutron,eayunstack/neutron,sebrandon1/neutron,noironetworks/neutron,bigswitch/neutron,MaximNevrov/neutron,igor-toga/local-snat,sebrandon1/neutron,mahak/neutron,cloudbase/neutron,huntxu/neutron,eayunstack/neutron,dims/neutron,igor-toga/local-snat | ---
+++
@@ -12,9 +12,17 @@
# License for the specific language governing permissions and limitations
# under the License.
+import logging as sys_logging
+
from oslo_reports import guru_meditation_report as gmr
from neutron import version
+# During the call to gmr.TextGuruMeditation.setup_autorun(), Guru Meditation
+# Report tries to start logging. Set a handler here to accommodate this.
+logger = sys_logging.getLogger(None)
+if not logger.handlers:
+ logger.addHandler(sys_logging.StreamHandler())
+
_version_string = version.version_info.release_string()
gmr.TextGuruMeditation.setup_autorun(version=_version_string) |
170dce0afe013dee6721237219b9dfa5f2813780 | falafel/__init__.py | falafel/__init__.py | import os
from .core import LogFileOutput, Mapper, IniConfigFile, LegacyItemAccess # noqa: F401
from .core.plugins import mapper, reducer, make_response, make_metadata # noqa: F401
from .mappers import get_active_lines # noqa: F401
from .util import defaults, parse_table # noqa: F401
__here__ = os.path.dirname(os.path.abspath(__file__))
package_info = {k: None for k in ["RELEASE", "COMMIT", "VERSION", "NAME"]}
for name in package_info:
with open(os.path.join(__here__, name)) as f:
package_info[name] = f.read().strip()
def get_nvr():
return "{0}-{1}-{2}".format(package_info["NAME"],
package_info["VERSION"],
package_info["RELEASE"])
RULES_STATUS = {}
"""
Mapping of dictionaries containing nvr and commitid for each rule repo included
in this instance
{"rule_repo_1": {"version": nvr(), "commit": sha1}}
"""
def add_status(name, nvr, commit):
"""
Rule repositories should call this method in their package __init__ to
register their version information.
"""
RULES_STATUS[name] = {"version": nvr, "commit": commit}
| import os
from .core import LogFileOutput, Mapper, IniConfigFile, LegacyItemAccess # noqa: F401
from .core import FileListing # noqa: F401
from .core.plugins import mapper, reducer, make_response, make_metadata # noqa: F401
from .mappers import get_active_lines # noqa: F401
from .util import defaults, parse_table # noqa: F401
__here__ = os.path.dirname(os.path.abspath(__file__))
package_info = {k: None for k in ["RELEASE", "COMMIT", "VERSION", "NAME"]}
for name in package_info:
with open(os.path.join(__here__, name)) as f:
package_info[name] = f.read().strip()
def get_nvr():
return "{0}-{1}-{2}".format(package_info["NAME"],
package_info["VERSION"],
package_info["RELEASE"])
RULES_STATUS = {}
"""
Mapping of dictionaries containing nvr and commitid for each rule repo included
in this instance
{"rule_repo_1": {"version": nvr(), "commit": sha1}}
"""
def add_status(name, nvr, commit):
"""
Rule repositories should call this method in their package __init__ to
register their version information.
"""
RULES_STATUS[name] = {"version": nvr, "commit": commit}
| Add FileListing to objects we export | Add FileListing to objects we export
| Python | apache-2.0 | RedHatInsights/insights-core,RedHatInsights/insights-core | ---
+++
@@ -1,5 +1,6 @@
import os
from .core import LogFileOutput, Mapper, IniConfigFile, LegacyItemAccess # noqa: F401
+from .core import FileListing # noqa: F401
from .core.plugins import mapper, reducer, make_response, make_metadata # noqa: F401
from .mappers import get_active_lines # noqa: F401
from .util import defaults, parse_table # noqa: F401 |
aa3fc2e32d5b16ff30ab6f288b1a5554c4add374 | luigi/tests/rnacentral/utils_test.py | luigi/tests/rnacentral/utils_test.py | # -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from rnacentral.utils import upi_ranges
from tasks.config import db
def test_can_get_range_of_all_upis():
ranges = list(upi_ranges(db(), 100000))
assert len(ranges) == 133
def test_can_get_correct_upi_ranges():
ranges = list(upi_ranges(db(), 100000))
assert ranges[0:2] == [
(1, 100001),
(100001, 200001),
]
assert ranges[-1] == (13100001, 13167087L)
| # -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from rnacentral.utils import upi_ranges
from tasks.config import db
def test_can_get_range_of_all_upis():
ranges = list(upi_ranges(db(), 100000))
assert len(ranges) == 136
def test_can_get_correct_upi_ranges():
ranges = list(upi_ranges(db(), 100000))
assert ranges[0:2] == [
(1, 100001),
(100001, 200001),
]
assert ranges[-1] == (13400001, 13458282L)
| Update because of new number of sequences | Update because of new number of sequences
We should have an isolated database to deal with this.
| Python | apache-2.0 | RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline | ---
+++
@@ -19,7 +19,7 @@
def test_can_get_range_of_all_upis():
ranges = list(upi_ranges(db(), 100000))
- assert len(ranges) == 133
+ assert len(ranges) == 136
def test_can_get_correct_upi_ranges():
@@ -28,4 +28,4 @@
(1, 100001),
(100001, 200001),
]
- assert ranges[-1] == (13100001, 13167087L)
+ assert ranges[-1] == (13400001, 13458282L) |
cc184c3e4a911bab38ec5feb62a3fbef3c81ff08 | main/management/commands/poll_rss.py | main/management/commands/poll_rss.py |
from datetime import datetime
from time import mktime
from django.core.management.base import BaseCommand
from django.utils.timezone import get_default_timezone, make_aware
from feedparser import parse
from ...models import Link
class Command(BaseCommand):
def handle(self, *urls, **options):
for url in urls:
for entry in parse(url).entries:
link = self.entry_to_link_dict(entry)
try:
Link.objects.get(link=link["link"])
except Link.DoesNotExist:
Link.objects.create(**link)
def entry_to_link_dict(self, entry):
link = {"title": entry.title, "user_id": 1}
try:
link["link"] = entry.summary.split('href="')[2].split('"')[0]
except IndexError:
link["link"] = entry.link
try:
publish_date = entry.published_parsed
except AttributeError:
pass
else:
publish_date = datetime.fromtimestamp(mktime(publish_date))
publish_date = make_aware(publish_date, get_default_timezone())
link["publish_date"] = publish_date
return link
|
from datetime import datetime
from time import mktime
from django.core.management.base import BaseCommand
from django.utils.timezone import get_default_timezone, make_aware
from feedparser import parse
from ...models import Link
class Command(BaseCommand):
def handle(self, *urls, **options):
for url in urls:
for entry in parse(url).entries:
link = self.entry_to_link_dict(entry)
try:
Link.objects.get(link=link["link"])
except Link.DoesNotExist:
Link.objects.create(**link)
def entry_to_link_dict(self, entry):
link = {"title": entry.title, "user_id": 1, "gen_description": False}
try:
link["link"] = entry.summary.split('href="')[2].split('"')[0]
except IndexError:
link["link"] = entry.link
try:
publish_date = entry.published_parsed
except AttributeError:
pass
else:
publish_date = datetime.fromtimestamp(mktime(publish_date))
publish_date = make_aware(publish_date, get_default_timezone())
link["publish_date"] = publish_date
return link
| Set correct gen_description in rss importer. | Set correct gen_description in rss importer.
| Python | bsd-2-clause | abendig/drum,abendig/drum,yodermk/drum,renyi/drum,baturay/ne-istiyoruz,stephenmcd/drum,yodermk/drum,skybluejamie/wikipeace,skybluejamie/wikipeace,renyi/drum,tsybulevskij/drum,sing1ee/drum,tsybulevskij/drum,baturay/ne-istiyoruz,stephenmcd/drum,renyi/drum,yodermk/drum,j00bar/drum,j00bar/drum,sing1ee/drum,j00bar/drum,tsybulevskij/drum,abendig/drum,sing1ee/drum | ---
+++
@@ -21,7 +21,7 @@
Link.objects.create(**link)
def entry_to_link_dict(self, entry):
- link = {"title": entry.title, "user_id": 1}
+ link = {"title": entry.title, "user_id": 1, "gen_description": False}
try:
link["link"] = entry.summary.split('href="')[2].split('"')[0]
except IndexError: |
b02e2fb19224edebf28ceddbbe4b41ab9140b5d0 | inthe_am/taskmanager/admin.py | inthe_am/taskmanager/admin.py | from django.contrib import admin
from .models import TaskStore, TaskStoreActivityLog, UserMetadata
class TaskStoreAdmin(admin.ModelAdmin):
search_fields = ('user__username', 'local_path', 'taskrc_extras', )
list_display = ('user', 'local_path', 'configured', )
list_filter = ('configured', )
admin.site.register(TaskStore, TaskStoreAdmin)
class TaskStoreActivityLogAdmin(admin.ModelAdmin):
search_fields = ('store__user__username', 'message', )
list_display = (
'username', 'last_seen', 'created', 'error', 'message', 'count'
)
date_hierarchy = 'last_seen'
list_filter = ('created', 'last_seen', )
list_select_related = True
def username(self, obj):
return obj.store.user.username
username.short_description = 'Username'
admin.site.register(TaskStoreActivityLog, TaskStoreActivityLogAdmin)
class UserMetadataAdmin(admin.ModelAdmin):
search_fields = ('user__username', )
list_display = ('user', 'tos_version', 'tos_accepted', )
list_filter = ('tos_version', )
admin.site.register(UserMetadata, UserMetadataAdmin)
| from django.contrib import admin
from .models import TaskStore, TaskStoreActivityLog, UserMetadata
class TaskStoreAdmin(admin.ModelAdmin):
search_fields = ('user__username', 'local_path', 'taskrc_extras', )
list_display = ('user', 'local_path', 'configured', )
list_filter = ('configured', )
admin.site.register(TaskStore, TaskStoreAdmin)
class TaskStoreActivityLogAdmin(admin.ModelAdmin):
search_fields = ('store__user__username', 'message', )
list_display = (
'username', 'last_seen', 'created', 'error', 'message', 'count'
)
date_hierarchy = 'last_seen'
list_filter = ('created', 'last_seen', )
list_select_related = True
ordering = ('-last_seen', )
def username(self, obj):
return obj.store.user.username
username.short_description = 'Username'
admin.site.register(TaskStoreActivityLog, TaskStoreActivityLogAdmin)
class UserMetadataAdmin(admin.ModelAdmin):
search_fields = ('user__username', )
list_display = ('user', 'tos_version', 'tos_accepted', )
list_filter = ('tos_version', )
admin.site.register(UserMetadata, UserMetadataAdmin)
| Order by last seen, descending. | Order by last seen, descending.
| Python | agpl-3.0 | coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am | ---
+++
@@ -20,6 +20,7 @@
date_hierarchy = 'last_seen'
list_filter = ('created', 'last_seen', )
list_select_related = True
+ ordering = ('-last_seen', )
def username(self, obj):
return obj.store.user.username |
29521ac7b540c2f255b163f9139453103b76b38f | jsonsempai.py | jsonsempai.py | import imp
import json
import os
import sys
class Dot(dict):
def __init__(self, d):
super(dict, self).__init__()
for k, v in d.iteritems():
if isinstance(v, dict):
self[k] = Dot(v)
else:
self[k] = v
def __getattr__(self, attr):
return self.get(attr)
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
class SempaiLoader(object):
def find_module(self, name, path=None):
for d in sys.path:
self.json_path = os.path.join(d, '{}.json'.format(name))
if os.path.isfile(self.json_path):
print self.json_path
return self
return None
def load_module(self, name):
mod = imp.new_module(name)
mod.__file__ = self.json_path
mod.__loader__ = self
try:
with open(self.json_path) as f:
d = json.load(f)
except:
raise ImportError(
'Couldn\'t load json from"{}".'.format(self.json_path))
mod.__dict__.update(d)
for k, i in mod.__dict__.items():
if isinstance(i, dict):
mod.__dict__[k] = Dot(i)
return mod
sys.meta_path.append(SempaiLoader())
| import imp
import json
import os
import sys
class Dot(dict):
def __init__(self, d):
super(dict, self).__init__()
for k, v in d.iteritems():
if isinstance(v, dict):
self[k] = Dot(v)
else:
self[k] = v
def __getattr__(self, attr):
return self.get(attr)
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
class SempaiLoader(object):
def find_module(self, name, path=None):
for d in sys.path:
self.json_path = os.path.join(d, '{}.json'.format(name))
if os.path.isfile(self.json_path):
print self.json_path
return self
return None
def load_module(self, name):
mod = imp.new_module(name)
mod.__file__ = self.json_path
mod.__loader__ = self
try:
with open(self.json_path) as f:
d = json.load(f)
except ValueError:
raise ImportError(
'"{}" does not contain valid json.'.format(self.json_path))
except:
raise ImportError(
'Could not open "{}".'.format(self.json_path))
mod.__dict__.update(d)
for k, i in mod.__dict__.items():
if isinstance(i, dict):
mod.__dict__[k] = Dot(i)
return mod
sys.meta_path.append(SempaiLoader())
| Add better exception handling on invalid json | Add better exception handling on invalid json
| Python | mit | kragniz/json-sempai | ---
+++
@@ -40,9 +40,12 @@
try:
with open(self.json_path) as f:
d = json.load(f)
+ except ValueError:
+ raise ImportError(
+ '"{}" does not contain valid json.'.format(self.json_path))
except:
raise ImportError(
- 'Couldn\'t load json from"{}".'.format(self.json_path))
+ 'Could not open "{}".'.format(self.json_path))
mod.__dict__.update(d)
for k, i in mod.__dict__.items(): |
f4275a930410e71cd3b505c8be279d5e9ca8c92e | mozillians/graphql_profiles/views.py | mozillians/graphql_profiles/views.py | from django.http import Http404
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
import waffle
from csp.decorators import csp_exempt
from graphene_django.views import GraphQLView
class MozilliansGraphQLView(GraphQLView):
"""Class Based View to handle GraphQL requests."""
@method_decorator(csrf_exempt)
@method_decorator(csp_exempt)
def dispatch(self, *args, **kwargs):
"""Override dispatch method to allow the use of multiple decorators."""
if not waffle.flag_is_active(self.request, 'enable_graphql'):
raise Http404()
return super(MozilliansGraphQLView, self).dispatch(*args, **kwargs)
| from django.conf import settings
from django.http import Http404
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from csp.decorators import csp_exempt
from graphene_django.views import GraphQLView
class MozilliansGraphQLView(GraphQLView):
"""Class Based View to handle GraphQL requests."""
@method_decorator(csrf_exempt)
@method_decorator(csp_exempt)
def dispatch(self, *args, **kwargs):
"""Override dispatch method to allow the use of multiple decorators."""
if not settings.DINO_PARK_ACTIVE:
raise Http404()
return super(MozilliansGraphQLView, self).dispatch(*args, **kwargs)
| Use the same setting for DinoPark. | Use the same setting for DinoPark.
| Python | bsd-3-clause | mozilla/mozillians,mozilla/mozillians,akatsoulas/mozillians,mozilla/mozillians,akatsoulas/mozillians,mozilla/mozillians,akatsoulas/mozillians,akatsoulas/mozillians | ---
+++
@@ -1,8 +1,8 @@
+from django.conf import settings
from django.http import Http404
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
-import waffle
from csp.decorators import csp_exempt
from graphene_django.views import GraphQLView
@@ -15,7 +15,7 @@
def dispatch(self, *args, **kwargs):
"""Override dispatch method to allow the use of multiple decorators."""
- if not waffle.flag_is_active(self.request, 'enable_graphql'):
+ if not settings.DINO_PARK_ACTIVE:
raise Http404()
return super(MozilliansGraphQLView, self).dispatch(*args, **kwargs) |
7f3d76bdec3731ae50b9487556b1b2750cd3108e | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
import versioneer
setup(
name='iterm2-tools',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description='''iTerm2 tools.''',
author='Aaron Meurer',
author_email='asmeurer@gmail.com',
url='https://github.com/asmeurer/iterm2-tools',
packages=['iterm2_tools'],
package_data={'iterm2_tools.tests': ['aloha_cat.png']},
long_description="""
iterm2-tools
Some tools for working with iTerm2's proprietary escape codes.
For now, only includes iterm2_tools.images, which has functions for displaying
images inline.
License: MIT
""",
license="MIT",
classifiers=[
'Environment :: MacOS X',
'Operating System :: MacOS :: MacOS X',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 2',
],
)
| #!/usr/bin/env python
from distutils.core import setup
import versioneer
setup(
name='iterm2-tools',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description='''iTerm2 tools.''',
author='Aaron Meurer',
author_email='asmeurer@gmail.com',
url='https://github.com/asmeurer/iterm2-tools',
packages=[
'iterm2_tools',
'iterm2_tools.tests'
],
package_data={'iterm2_tools.tests': ['aloha_cat.png']},
long_description="""
iterm2-tools
Some tools for working with iTerm2's proprietary escape codes.
For now, only includes iterm2_tools.images, which has functions for displaying
images inline.
License: MIT
""",
license="MIT",
classifiers=[
'Environment :: MacOS X',
'Operating System :: MacOS :: MacOS X',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 2',
],
)
| Include the tests in the dist | Include the tests in the dist
| Python | mit | asmeurer/iterm2-tools | ---
+++
@@ -11,7 +11,10 @@
author='Aaron Meurer',
author_email='asmeurer@gmail.com',
url='https://github.com/asmeurer/iterm2-tools',
- packages=['iterm2_tools'],
+ packages=[
+ 'iterm2_tools',
+ 'iterm2_tools.tests'
+ ],
package_data={'iterm2_tools.tests': ['aloha_cat.png']},
long_description="""
iterm2-tools |
a2f121875e775cac9f7f5e07935f6e6756f30100 | setup.py | setup.py | #!/usr/bin/env python
# coding: utf-8
from distribute_setup import use_setuptools
use_setuptools()
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import sys
extra = {}
if sys.version_info >= (3,):
extra['use_2to3'] = True
setup(name='mockito',
version='0.3.0',
packages=['mockito', 'mockito_test', 'mockito_util'],
url='http://code.google.com/p/mockito/wiki/MockitoForPython',
download_url='http://bitbucket.org/szczepiq/mockito-python/downloads/',
maintainer='mockito maintainers',
maintainer_email='mockito-python@googlegroups.com',
license='MIT',
description='Spying framework',
long_description='Mockito is a spying framework based on Java library with the same name.',
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Software Development :: Testing',
'Programming Language :: Python :: 3'
],
test_loader = 'mockito_util.test:TestLoader',
test_suite = 'mockito_test',
**extra
)
| #!/usr/bin/env python
# coding: utf-8
from distribute_setup import use_setuptools
use_setuptools()
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import sys
extra = {}
if sys.version_info >= (3,):
extra['use_2to3'] = True
setup(name='mockito',
version='0.3.0',
packages=['mockito', 'mockito_test', 'mockito_util'],
url='http://code.google.com/p/mockito-python',
download_url='http://code.google.com/p/mockito-python/downloads/list',
maintainer='Mockito Maintainers',
maintainer_email='mockito-python@googlegroups.com',
license='MIT',
description='Spying framework',
long_description='Mockito is a spying framework based on Java library with the same name.',
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Software Development :: Testing',
'Programming Language :: Python :: 3'
],
test_loader = 'mockito_util.test:TestLoader',
test_suite = 'mockito_test',
**extra
)
| Change download and documentation URLs. | Change download and documentation URLs.
| Python | mit | lwoydziak/mockito-python,kaste/mockito-python | ---
+++
@@ -17,9 +17,9 @@
setup(name='mockito',
version='0.3.0',
packages=['mockito', 'mockito_test', 'mockito_util'],
- url='http://code.google.com/p/mockito/wiki/MockitoForPython',
- download_url='http://bitbucket.org/szczepiq/mockito-python/downloads/',
- maintainer='mockito maintainers',
+ url='http://code.google.com/p/mockito-python',
+ download_url='http://code.google.com/p/mockito-python/downloads/list',
+ maintainer='Mockito Maintainers',
maintainer_email='mockito-python@googlegroups.com',
license='MIT',
description='Spying framework', |
da4dee483ff244e4e964282032a0813a85680cd2 | setup.py | setup.py | #!/usr/bin/env python
"""Setup script for PythonTemplateDemo."""
import setuptools
from demo import __project__, __version__
try:
README = open("README.rst").read()
CHANGELOG = open("CHANGELOG.rst").read()
except IOError:
LONG_DESCRIPTION = "Coming soon..."
else:
LONG_DESCRIPTION = README + '\n' + CHANGELOG
setuptools.setup(
name=__project__,
version=__version__,
description="A sample project templated from jacebrowning/template-python.",
url='https://github.com/jacebrowning/template-python-demo',
author='Jace Browning',
author_email='jacebrowning@gmail.com',
packages=setuptools.find_packages(),
entry_points={'console_scripts': []},
long_description=LONG_DESCRIPTION,
license='MIT',
classifiers=[
# TODO: update this list to match your application: https://pypi.python.org/pypi?%3Aaction=list_classifiers
'Development Status :: 1 - Planning',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
install_requires=open("requirements.txt").readlines(),
)
| #!/usr/bin/env python
"""Setup script for PythonTemplateDemo."""
import setuptools
from demo import __project__, __version__
try:
README = open("README.rst").read()
CHANGELOG = open("CHANGELOG.rst").read()
except IOError:
LONG_DESCRIPTION = NotImplemented
else:
LONG_DESCRIPTION = README + '\n' + CHANGELOG
setuptools.setup(
name=__project__,
version=__version__,
description="A sample project templated from jacebrowning/template-python.",
url='https://github.com/jacebrowning/template-python-demo',
author='Jace Browning',
author_email='jacebrowning@gmail.com',
packages=setuptools.find_packages(),
entry_points={'console_scripts': []},
long_description=LONG_DESCRIPTION,
license='MIT',
classifiers=[
# TODO: update this list to match your application: https://pypi.python.org/pypi?%3Aaction=list_classifiers
'Development Status :: 1 - Planning',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
install_requires=open("requirements.txt").readlines(),
)
| Deploy Travis CI build 717 to GitHub | Deploy Travis CI build 717 to GitHub
| Python | mit | jacebrowning/template-python-demo | ---
+++
@@ -10,7 +10,7 @@
README = open("README.rst").read()
CHANGELOG = open("CHANGELOG.rst").read()
except IOError:
- LONG_DESCRIPTION = "Coming soon..."
+ LONG_DESCRIPTION = NotImplemented
else:
LONG_DESCRIPTION = README + '\n' + CHANGELOG
|
7a00ff49799afc50da74a748d07c52fef57ebc84 | setup.py | setup.py | import tungsten
from distutils.core import setup
setup(
name='Tungsten',
version=tungsten.__version__,
author='Seena Burns',
packages={'tungsten': 'tungsten'},
license=open('LICENSE.txt').read(),
description='Wolfram Alpha API built for Python.',
long_description=open('README.md').read(),
install_requires=[
"requests",
],
classifiers=(
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7'
),
)
| import tungsten
from distutils.core import setup
setup(
name='Tungsten',
version=tungsten.__version__,
author='Seena Burns',
author_email='hello@ethanbird.com',
url='https://github.com/seenaburns/Tungsten',
packages={'tungsten': 'tungsten'},
license=open('LICENSE.txt').read(),
description='Wolfram Alpha API built for Python.',
long_description=open('README.md').read(),
install_requires=[
"requests",
],
classifiers=(
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7'
),
)
| Add url / author email for PyPI regs | Add url / author email for PyPI regs
| Python | bsd-3-clause | seenaburns/Tungsten | ---
+++
@@ -5,6 +5,8 @@
name='Tungsten',
version=tungsten.__version__,
author='Seena Burns',
+ author_email='hello@ethanbird.com',
+ url='https://github.com/seenaburns/Tungsten',
packages={'tungsten': 'tungsten'},
license=open('LICENSE.txt').read(),
description='Wolfram Alpha API built for Python.', |
e6ae57355530376a1253bc73e10a188743784161 | setup.py | setup.py | import os
from setuptools import setup
setup(
name='etl-framework',
version='0.1',
url="https://github.com/pantheon-systems/etl-framework@master",
description='Etl Framework',
long_description='',
author='Michael Liu',
author_email='michael.liu@getpantheon.com',
#license='BSD',
keywords='framework etl'.split(),
platforms='any',
include_package_data=False
#test_suite='test_dashvisor.run_tests.run_all',
)
| from setuptools import setup
setup(
name='etl-framework',
version='0.1',
url="https://github.com/pantheon-systems/etl-framework@master",
description='Etl Framework',
long_description='',
author='Michael Liu',
author_email='michael.liu@getpantheon.com',
#license='BSD',
keywords='framework etl'.split(),
platforms='any',
include_package_data=False
#test_suite='test_dashvisor.run_tests.run_all',
)
| Make test folders and fix pylint errors | Make test folders and fix pylint errors
| Python | mit | pantheon-systems/etl-framework | ---
+++
@@ -1,4 +1,3 @@
-import os
from setuptools import setup
|
dfcac1268a46a879cb1c387fa8b33f450860038c | setup.py | setup.py | import os
import sys
import setuptools
if sys.version_info[0] < 3:
from codecs import open
def local_file(name):
return os.path.relpath(os.path.join(os.path.dirname(__file__), name))
README = local_file("README.rst")
with open(local_file("src/stratis_cli/_version.py")) as o:
exec(o.read())
setuptools.setup(
name='stratis-cli',
version=__version__,
author='Anne Mulhern',
author_email='amulhern@redhat.com',
description='prototype stratis cli',
long_description=open(README, encoding='utf-8').read(),
platforms=['Linux'],
license='GPL 2+',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries',
],
install_requires = [
'dbus-python'
],
package_dir={"": "src"},
packages=setuptools.find_packages("src"),
)
| import os
import sys
import setuptools
if sys.version_info[0] < 3:
from codecs import open
def local_file(name):
return os.path.relpath(os.path.join(os.path.dirname(__file__), name))
README = local_file("README.rst")
with open(local_file("src/stratis_cli/_version.py")) as o:
exec(o.read())
setuptools.setup(
name='stratis-cli',
version=__version__,
author='Anne Mulhern',
author_email='amulhern@redhat.com',
description='prototype stratis cli',
long_description=open(README, encoding='utf-8').read(),
platforms=['Linux'],
license='GPL 2+',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Libraries',
],
install_requires = [
'dbus-python'
],
package_dir={"": "src"},
packages=setuptools.find_packages("src"),
scripts=['bin/stratis']
)
| Make stratis an installable script. | Make stratis an installable script.
Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com>
| Python | apache-2.0 | stratis-storage/stratis-cli,stratis-storage/stratis-cli | ---
+++
@@ -37,4 +37,5 @@
],
package_dir={"": "src"},
packages=setuptools.find_packages("src"),
+ scripts=['bin/stratis']
) |
61697dba563a6f89d58ce7e2e7a182113c3f692c | setup.py | setup.py | from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
zip_safe=False,
install_requires=[
'aiofiles',
'aiohttp',
'boto3',
'beautifulsoup4>=4.4',
'lxml>=3.6',
'pandas>=0.18',
'tqdm'
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox.chamber_of_deputies', 'serenata_toolbox.datasets'],
url=REPO_URL,
version='9.0.3'
)
| from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
zip_safe=False,
install_requires=[
'aiofiles',
'aiohttp',
'boto3',
'beautifulsoup4>=4.4',
'lxml>=3.6',
'pandas>=0.18',
'tqdm'
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox.chamber_of_deputies', 'serenata_toolbox.datasets'],
url=REPO_URL,
version='9.0.4'
)
| Fix bump version to federal senate script | Fix bump version to federal senate script
| Python | mit | datasciencebr/serenata-toolbox | ---
+++
@@ -29,5 +29,5 @@
name='serenata-toolbox',
packages=['serenata_toolbox.chamber_of_deputies', 'serenata_toolbox.datasets'],
url=REPO_URL,
- version='9.0.3'
+ version='9.0.4'
) |
dfac0fe079f1f4f9d789632702b5750d706aa832 | setup.py | setup.py | from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
setup(
name='cygroonga',
version='0.1.0',
ext_modules=cythonize([
Extension("cygroonga", ["cygroonga.pyx"],
libraries=["groonga"])
]),
install_requires=[
'cython',
],
)
| from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
setup(
name='cygroonga',
version='0.1.0',
ext_modules=cythonize([
Extension("cygroonga", ["cygroonga.pyx"],
libraries=["groonga"])
]),
install_requires=[
'Cython',
],
)
| Change cython to Cython in install_requires | Change cython to Cython in install_requires
| Python | apache-2.0 | hnakamur/cygroonga | ---
+++
@@ -10,6 +10,6 @@
libraries=["groonga"])
]),
install_requires=[
- 'cython',
+ 'Cython',
],
) |
f18a180d0e3ac07412d814e326b3875c7468afc8 | setup.py | setup.py | from setuptools import setup, find_packages
long_description = (open('README.rst').read() +
open('CHANGES.rst').read() +
open('TODO.rst').read())
setup(
name='django-model-utils',
version='1.3.1.post1',
description='Django model mixins and utilities',
long_description=long_description,
author='Carl Meyer',
author_email='carl@oddbird.net',
url='https://github.com/carljm/django-model-utils/',
packages=find_packages(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
zip_safe=False,
tests_require=["Django>=1.2"],
test_suite='runtests.runtests'
)
| from setuptools import setup, find_packages
long_description = (open('README.rst').read() +
open('CHANGES.rst').read() +
open('TODO.rst').read())
setup(
name='django-model-utils',
version='1.3.1.post1',
description='Django model mixins and utilities',
long_description=long_description,
author='Carl Meyer',
author_email='carl@oddbird.net',
url='https://github.com/carljm/django-model-utils/',
packages=find_packages(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Framework :: Django',
],
zip_safe=False,
tests_require=["Django>=1.2"],
test_suite='runtests.runtests'
)
| Add supported Python versions to classifier troves | Add supported Python versions to classifier troves
| Python | bsd-3-clause | kezabelle/django-model-utils,patrys/django-model-utils,timmygee/django-model-utils,timmygee/django-model-utils,carljm/django-model-utils,patrys/django-model-utils,carljm/django-model-utils,kezabelle/django-model-utils,nemesisdesign/django-model-utils,yeago/django-model-utils,yeago/django-model-utils,nemesisdesign/django-model-utils | ---
+++
@@ -22,6 +22,11 @@
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
+ 'Programming Language :: Python :: 2.6',
+ 'Programming Language :: Python :: 2.7',
+ 'Programming Language :: Python :: 3',
+ 'Programming Language :: Python :: 3.2',
+ 'Programming Language :: Python :: 3.3',
'Framework :: Django',
],
zip_safe=False, |
af599f0168096fa594773d3fac049869c31f8ecc | setup.py | setup.py | from setuptools import setup
import jasinja, sys
requires = ['Jinja2']
if sys.version_info < (2, 6):
requirements += ['simplejson']
setup(
name='jasinja',
version=jasinja.__version__,
url='http://bitbucket.org/djc/jasinja',
license='BSD',
author='Dirkjan Ochtman',
author_email='dirkjan@ochtman.nl',
description='A JavaScript code generator for Jinja templates',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
],
packages=['jasinja', 'jasinja.tests'],
package_data={
'jasinja': ['*.js']
},
install_requires=requires,
test_suite='jasinja.tests.run.suite',
entry_points={
'console_scripts': ['jasinja-compile = jasinja.compile:main'],
},
)
| from setuptools import setup
import jasinja, sys
requires = ['Jinja2']
if sys.version_info < (2, 6):
requires += ['simplejson']
setup(
name='jasinja',
version=jasinja.__version__,
url='http://bitbucket.org/djc/jasinja',
license='BSD',
author='Dirkjan Ochtman',
author_email='dirkjan@ochtman.nl',
description='A JavaScript code generator for Jinja templates',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
],
packages=['jasinja', 'jasinja.tests'],
package_data={
'jasinja': ['*.js']
},
install_requires=requires,
test_suite='jasinja.tests.run.suite',
entry_points={
'console_scripts': ['jasinja-compile = jasinja.compile:main'],
},
)
| Fix stupid typo in requirements specification. | Fix stupid typo in requirements specification.
| Python | bsd-3-clause | djc/jasinja,djc/jasinja | ---
+++
@@ -3,7 +3,7 @@
requires = ['Jinja2']
if sys.version_info < (2, 6):
- requirements += ['simplejson']
+ requires += ['simplejson']
setup(
name='jasinja', |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.