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 |
|---|---|---|---|---|---|---|---|---|---|---|
f4c8462d1197fe657c9556515bde6eafeabce5ca | downstream_node/config/config.py | downstream_node/config/config.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
# Flask
SECRET_KEY = os.urandom(32)
# SQLAlchemy (DB)
SQLALCHEMY_DATABASE_URI = 'mysql://localhost/downstream'
# Heartbeat
HEARTBEAT_SECRET = (
r'6\x1eg\xd4\x19\xde\xad\xc1x\x00+\xc9\x04~_`%\x'
r'f0\x7fF\xd9\x0b=\x91J\xe5\x0b\xeb\xc1D\xcd\x8d'
)
FILES_PATH = '/opt/files'
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
# Flask
SECRET_KEY = os.urandom(32)
# SQLAlchemy (DB)
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://localhost/downstream'
# Heartbeat
HEARTBEAT_SECRET = (
r'6\x1eg\xd4\x19\xde\xad\xc1x\x00+\xc9\x04~_`%\x'
r'f0\x7fF\xd9\x0b=\x91J\xe5\x0b\xeb\xc1D\xcd\x8d'
)
FILES_PATH = '/opt/files'
| Fix mysql connect string to be pymysql compatible | Fix mysql connect string to be pymysql compatible
| Python | mit | Storj/downstream-node,Storj/downstream-node | ---
+++
@@ -7,7 +7,7 @@
SECRET_KEY = os.urandom(32)
# SQLAlchemy (DB)
-SQLALCHEMY_DATABASE_URI = 'mysql://localhost/downstream'
+SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://localhost/downstream'
# Heartbeat
HEARTBEAT_SECRET = ( |
dd3cc71bb09ab2fb265b3f4bdda69cb1880842c6 | tests/utils_test.py | tests/utils_test.py | import unittest
from zttf.utils import fixed_version, binary_search_parameters
class TestUtils(unittest.TestCase):
def test_fixed_version(self):
cases = [
(0x00005000, 0.5),
(0x00010000, 1.0),
(0x00035000, 3.5),
(0x00105000, 10.5)
]
for case in cases:
self.assertEqual(fixed_version(case[0]), case[1])
def test_binary_parameters(self):
cases = {
39: (32, 5),
10: (8, 3),
19: (16, 4)
}
for n, result in cases.items():
self.assertEqual(binary_search_parameters(n), result)
| import unittest
import struct
from zttf.utils import fixed_version, binary_search_parameters, ttf_checksum
class TestUtils(unittest.TestCase):
def test_fixed_version(self):
cases = [
(0x00005000, 0.5),
(0x00010000, 1.0),
(0x00035000, 3.5),
(0x00105000, 10.5)
]
for case in cases:
self.assertEqual(fixed_version(case[0]), case[1])
def test_binary_parameters(self):
cases = {
39: (32, 5),
10: (8, 3),
19: (16, 4)
}
for n, result in cases.items():
self.assertEqual(binary_search_parameters(n), result)
def test_checksum(self):
data = struct.pack(">12I", *range(0, 12))
self.assertEqual(len(data), 48)
self.assertEqual(ttf_checksum(data), 66)
self.assertEqual(ttf_checksum(struct.pack(">12I", *range(1000, 13000, 1000))), 78000)
self.assertEqual(ttf_checksum(struct.pack(">512I", *range(1024, 1024 * 2048, 4096))), 0x1FF80000) | Add a simple test for the checksum routine. | Add a simple test for the checksum routine.
| Python | apache-2.0 | zathras777/zttf | ---
+++
@@ -1,6 +1,7 @@
import unittest
+import struct
-from zttf.utils import fixed_version, binary_search_parameters
+from zttf.utils import fixed_version, binary_search_parameters, ttf_checksum
class TestUtils(unittest.TestCase):
@@ -22,3 +23,10 @@
}
for n, result in cases.items():
self.assertEqual(binary_search_parameters(n), result)
+
+ def test_checksum(self):
+ data = struct.pack(">12I", *range(0, 12))
+ self.assertEqual(len(data), 48)
+ self.assertEqual(ttf_checksum(data), 66)
+ self.assertEqual(ttf_checksum(struct.pack(">12I", *range(1000, 13000, 1000))), 78000)
+ self.assertEqual(ttf_checksum(struct.pack(">512I", *range(1024, 1024 * 2048, 4096))), 0x1FF80000) |
473aee0eda226acc6ae959a3ef39656dce6031b5 | akanda/horizon/routers/views.py | akanda/horizon/routers/views.py | from django.utils.translation import ugettext_lazy as _ # noqa
from horizon import exceptions
from openstack_dashboard import api
def get_interfaces_data(self):
try:
router_id = self.kwargs['router_id']
ports = api.neutron.port_list(self.request,
router_id=router_id)
except Exception:
ports = []
msg = _(
'Port list can not be retrieved for router ID %s' %
self.kwargs.get('router_id')
)
exceptions.handle(self.request, msg)
for p in ports:
p.set_id_as_name_if_empty()
return ports
| from django.utils.translation import ugettext_lazy as _ # noqa
from horizon import exceptions
from openstack_dashboard import api
def get_interfaces_data(self):
try:
router_id = self.kwargs['router_id']
router = api.quantum.router_get(self.request, router_id)
ports = [api.quantum.Port(p) for p in router.ports]
except Exception:
ports = []
msg = _(
'Port list can not be retrieved for router ID %s' %
self.kwargs.get('router_id')
)
exceptions.handle(self.request, msg)
for p in ports:
p.set_id_as_name_if_empty()
return ports
| Fix router's interface listing view | Fix router's interface listing view
To get all the ports for a router Horizon uses port_list
filtering by the device_id value which in vanilla openstack
is the quantum router_id, but we use the akanda_id as value for
that field so the listing doesn't work for us. Lets replace the
port_list call with router_get.
Change-Id: Ibaabb11b2afa97aa2445776842afbdd5c6c2563d
Signed-off-by: Rosario Di Somma <73b2fe5f91895aea2b4d0e8942a5edf9f18fa897@dreamhost.com>
| Python | apache-2.0 | dreamhost/akanda-horizon,dreamhost/akanda-horizon | ---
+++
@@ -7,8 +7,8 @@
def get_interfaces_data(self):
try:
router_id = self.kwargs['router_id']
- ports = api.neutron.port_list(self.request,
- router_id=router_id)
+ router = api.quantum.router_get(self.request, router_id)
+ ports = [api.quantum.Port(p) for p in router.ports]
except Exception:
ports = []
msg = _( |
22aaf754eb04e9f345c55f73ffb0f549d83c68df | apps/explorer/tests/test_templatetags.py | apps/explorer/tests/test_templatetags.py | from django.test import TestCase
from ..templatetags import explorer
class HighlightTestCase(TestCase):
def test_highlight_returns_text_when_empty_word(self):
expected = 'foo bar baz'
assert explorer.highlight('foo bar baz', '') == expected
def test_highlight(self):
expected = '<span class="highlight">foo</span> bar baz'
assert explorer.highlight('foo bar baz', 'foo') == expected
def test_highlight_matches_all_occurences(self):
expected = (
'<span class="highlight">foo</span> bar baz'
' nope <span class="highlight">foo</span> bar baz'
)
assert explorer.highlight(
'foo bar baz nope foo bar baz',
'foo'
) == expected
def test_highlight_matches_part_of_words(self):
expected = 'l<span class="highlight">ooo</span>oong word'
assert explorer.highlight('looooong word', 'ooo') == expected
| from django.test import TestCase
from ..templatetags import explorer
class HighlightTestCase(TestCase):
def test_highlight_returns_text_when_empty_word(self):
expected = 'foo bar baz'
assert explorer.highlight('foo bar baz', '') == expected
def test_highlight(self):
expected = '<span class="highlight">foo</span> bar baz'
assert explorer.highlight('foo bar baz', 'foo') == expected
def test_highlight_matches_all_occurences(self):
expected = (
'<span class="highlight">foo</span> bar baz'
' nope <span class="highlight">foo</span> bar baz'
)
assert explorer.highlight(
'foo bar baz nope foo bar baz',
'foo'
) == expected
def test_highlight_matches_part_of_words(self):
expected = 'l<span class="highlight">ooo</span>oong word'
assert explorer.highlight('looooong word', 'ooo') == expected
class ConcatTestCase(TestCase):
def test_concat(self):
expected = 'foo-bar'
assert explorer.concat('foo-', 'bar') == expected
| Add test for concat template tag | Add test for concat template tag
| Python | bsd-3-clause | Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel | ---
+++
@@ -30,3 +30,11 @@
expected = 'l<span class="highlight">ooo</span>oong word'
assert explorer.highlight('looooong word', 'ooo') == expected
+
+
+class ConcatTestCase(TestCase):
+
+ def test_concat(self):
+
+ expected = 'foo-bar'
+ assert explorer.concat('foo-', 'bar') == expected |
f52c8cc3938567a24ac6ea0a807654aa73caa871 | pages/views.py | pages/views.py | from pages.models import Page, Language, Content
from pages.utils import auto_render
from django.contrib.admin.views.decorators import staff_member_required
from django import forms
from django.http import Http404
import settings
@auto_render
def details(request, page_id=None):
template = None
lang = Language.get_from_request(request)
pages = Page.objects.filter(parent__isnull=True).order_by("tree_id")
if len(pages) > 0:
if page_id:
try:
current_page = Page.objects.get(id=int(page_id), status=1)
except Page.DoesNotExist:
raise Http404
else:
# get the first root page
current_page = pages[0]
template = current_page.get_template()
else:
template = settings.DEFAULT_PAGE_TEMPLATE
return template, locals()
| from pages.models import Page, Language, Content
from pages.utils import auto_render
from django.contrib.admin.views.decorators import staff_member_required
from django import forms
from django.http import Http404
import settings
@auto_render
def details(request, page_id=None):
template = None
lang = Language.get_from_request(request)
pages = Page.objects.filter(parent__isnull=True).order_by("tree_id")
if len(pages) > 0:
if page_id:
try:
current_page = Page.objects.get(id=int(page_id), status=1)
except Page.DoesNotExist:
raise Http404
else:
# get the first root page
current_page = pages[0]
template = current_page.get_template()
else:
current_page = None
template = settings.DEFAULT_PAGE_TEMPLATE
return template, locals()
| Fix a bug with an empty database | Fix a bug with an empty database
git-svn-id: 54fea250f97f2a4e12c6f7a610b8f07cb4c107b4@138 439a9e5f-3f3e-0410-bc46-71226ad0111b
| Python | bsd-3-clause | pombredanne/django-page-cms-1,oliciv/django-page-cms,akaihola/django-page-cms,pombredanne/django-page-cms-1,akaihola/django-page-cms,remik/django-page-cms,pombredanne/django-page-cms-1,batiste/django-page-cms,oliciv/django-page-cms,remik/django-page-cms,batiste/django-page-cms,oliciv/django-page-cms,batiste/django-page-cms,remik/django-page-cms,remik/django-page-cms,akaihola/django-page-cms | ---
+++
@@ -21,6 +21,7 @@
current_page = pages[0]
template = current_page.get_template()
else:
+ current_page = None
template = settings.DEFAULT_PAGE_TEMPLATE
return template, locals() |
265ed91b7e7f204926e7c5f9d2fbe76f447f7955 | gitfs/views/read_only.py | gitfs/views/read_only.py | import os
from errno import EROFS
from fuse import FuseOSError
from gitfs import FuseMethodNotImplemented
from .view import View
class ReadOnlyView(View):
def getxattr(self, path, fh):
raise FuseMethodNotImplemented
def open(self, path, flags):
return 0
def create(self, path, fh):
raise FuseOSError(EROFS)
def write(self, path, fh):
raise FuseOSError(EROFS)
def opendir(self, path):
return 0
def releasedir(self, path, fi):
return 0
def flush(self, path, fh):
return 0
def release(self, path, fh):
return 0
def access(self, path, amode):
return 0
def mkdir(self, path, mode):
raise FuseOSError(EROFS)
def utimens(self, path, times=None):
raise FuseOSError(EROFS)
def chown(self, path, uid, gid):
raise FuseOSError(EROFS)
| import os
from errno import EROFS
from fuse import FuseOSError
from gitfs import FuseMethodNotImplemented
from .view import View
class ReadOnlyView(View):
def getxattr(self, path, fh):
raise FuseMethodNotImplemented
def open(self, path, flags):
return 0
def create(self, path, fh):
raise FuseOSError(EROFS)
def write(self, path, fh):
raise FuseOSError(EROFS)
def opendir(self, path):
return 0
def releasedir(self, path, fi):
return 0
def flush(self, path, fh):
return 0
def release(self, path, fh):
return 0
def access(self, path, amode):
return 0
def mkdir(self, path, mode):
raise FuseOSError(EROFS)
def utimens(self, path, times=None):
raise FuseOSError(EROFS)
def chown(self, path, uid, gid):
raise FuseOSError(EROFS)
def chmod(self, path, mode):
raise FuseOSError(EROFS)
| Raise read-only filesystem when the user wants to chmod in /history. | Raise read-only filesystem when the user wants to chmod in /history.
| Python | apache-2.0 | PressLabs/gitfs,bussiere/gitfs,rowhit/gitfs,ksmaheshkumar/gitfs,PressLabs/gitfs | ---
+++
@@ -44,3 +44,6 @@
def chown(self, path, uid, gid):
raise FuseOSError(EROFS)
+
+ def chmod(self, path, mode):
+ raise FuseOSError(EROFS) |
bbc6ce8225cf54e56331ec75fa2de007d02162af | src/_thread/__init__.py | src/_thread/__init__.py | from __future__ import absolute_import
import sys
__future_module__ = True
if sys.version_info[0] < 3:
from dummy_thread import *
else:
raise ImportError('This package should not be accessible on Python 3. '
'Either you are trying to run from the python-future src folder '
'or your installation of python-future is corrupted.')
| from __future__ import absolute_import
import sys
__future_module__ = True
if sys.version_info[0] < 3:
try:
from thread import *
except ImportError:
from dummy_thread import *
else:
raise ImportError('This package should not be accessible on Python 3. '
'Either you are trying to run from the python-future src folder '
'or your installation of python-future is corrupted.')
| Fix bug where dummy_thread was always imported | Fix bug where dummy_thread was always imported
The code always import the dummy_thread module even on platforms where the real thread module is available. This caused bugs in other packages that use this import style:
try:
from _thread import interrupt_main # Py 3
except ImportError:
from thread import interrupt_main # Py 2
See https://github.com/ipython/ipython/pull/7079 | Python | mit | QuLogic/python-future,QuLogic/python-future,PythonCharmers/python-future,michaelpacer/python-future,michaelpacer/python-future,PythonCharmers/python-future | ---
+++
@@ -3,7 +3,10 @@
__future_module__ = True
if sys.version_info[0] < 3:
- from dummy_thread import *
+ try:
+ from thread import *
+ except ImportError:
+ from dummy_thread import *
else:
raise ImportError('This package should not be accessible on Python 3. '
'Either you are trying to run from the python-future src folder ' |
4f7382303d56871b2b174e291b47b238777f5d32 | yubico/yubico_exceptions.py | yubico/yubico_exceptions.py | __all___ = [
'YubicoError',
'StatusCodeError',
'InvalidClientIdError',
'InvalidValidationResponse',
'SignatureVerificationError'
]
class YubicoError(Exception):
""" Base class for Yubico related exceptions. """
pass
class StatusCodeError(YubicoError):
def __init__(self, status_code):
self.status_code = status_code
def __str__(self):
return ('Yubico server returned the following status code: %s' %
(self.status_code))
class InvalidClientIdError(YubicoError):
def __init__(self, client_id):
self.client_id = client_id
def __str__(self):
return 'The client with ID %s does not exist' % (self.client_id)
class InvalidValidationResponse(YubicoError):
def __init__(self, reason, response, parameters=None):
self.reason = reason
self.response = response
self.parameters = parameters
def __str__(self):
return self.reason
class SignatureVerificationError(YubicoError):
def __init__(self, generated_signature, response_signature):
self.generated_signature = generated_signature
self.response_signature = response_signature
def __str__(self):
return repr('Server response message signature verification failed' +
'(expected %s, got %s)' % (self.generated_signature,
self.response_signature))
| __all___ = [
'YubicoError',
'StatusCodeError',
'InvalidClientIdError',
'InvalidValidationResponse',
'SignatureVerificationError'
]
class YubicoError(Exception):
""" Base class for Yubico related exceptions. """
pass
class StatusCodeError(YubicoError):
def __init__(self, status_code):
self.status_code = status_code
def __str__(self):
return ('Yubico server returned the following status code: %s' %
(self.status_code))
class InvalidClientIdError(YubicoError):
def __init__(self, client_id):
self.client_id = client_id
def __str__(self):
return 'The client with ID %s does not exist' % (self.client_id)
class InvalidValidationResponse(YubicoError):
def __init__(self, reason, response, parameters=None):
self.reason = reason
self.response = response
self.parameters = parameters
self.message = self.reason
def __str__(self):
return self.reason
class SignatureVerificationError(YubicoError):
def __init__(self, generated_signature, response_signature):
self.generated_signature = generated_signature
self.response_signature = response_signature
def __str__(self):
return repr('Server response message signature verification failed' +
'(expected %s, got %s)' % (self.generated_signature,
self.response_signature))
| Set message attribute on InvalidValidationResponse error class. | Set message attribute on InvalidValidationResponse error class.
| Python | bsd-3-clause | Kami/python-yubico-client | ---
+++
@@ -34,6 +34,7 @@
self.reason = reason
self.response = response
self.parameters = parameters
+ self.message = self.reason
def __str__(self):
return self.reason |
b6027aceae21769c2f3dc7baccd5960e83ed9a90 | heufybot/connection.py | heufybot/connection.py | from twisted.words.protocols import irc
class HeufyBotConnection(irc.IRC):
def __init__(self, protocol):
self.protocol = protocol
self.nickname = "PyHeufyBot" #TODO This will be set by a configuration at some point
self.ident = "PyHeufyBot" #TODO This will be set by a configuration at some point
self.gecos = "PyHeufyBot IRC Bot" #TODO This will be set by a configuration at some point
def connectionMade(self):
self.sendMessage("NICK", "PyHeufyBot")
self.sendMessage("USER", "PyHeufyBot", "0", "0", ":PyHeufyBot Bot")
print "OK"
def connectionLost(self, reason=""):
print reason
def dataReceived(self, data):
print data | from twisted.words.protocols import irc
class HeufyBotConnection(irc.IRC):
def __init__(self, protocol):
self.protocol = protocol
self.nickname = "PyHeufyBot" #TODO This will be set by a configuration at some point
self.ident = "PyHeufyBot" #TODO This will be set by a configuration at some point
self.gecos = "PyHeufyBot IRC Bot" #TODO This will be set by a configuration at some point
def connectionMade(self):
self.cmdNICK(self.nickname)
self.cmdUSER(self.ident, self.gecos)
def connectionLost(self, reason=""):
print reason
def dataReceived(self, data):
print data
def sendMessage(self, command, *parameter_list, **prefix):
print command, " ".join(parameter_list)
irc.IRC.sendMessage(self, command, *parameter_list, **prefix)
def cmdNICK(self, nickname):
self.sendMessage("NICK", nickname)
def cmdUSER(self, ident, gecos):
# RFC2812 allows usermodes to be set, but this isn't implemented much in IRCds at all.
# Pass 0 for usermodes instead.
self.sendMessage("USER", ident, "0", "*", ":{}".format(gecos)) | Add functions for NICK and USER sending. Override sendMessage for debugging. | Add functions for NICK and USER sending. Override sendMessage for debugging.
| Python | mit | Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot | ---
+++
@@ -9,12 +9,23 @@
self.gecos = "PyHeufyBot IRC Bot" #TODO This will be set by a configuration at some point
def connectionMade(self):
- self.sendMessage("NICK", "PyHeufyBot")
- self.sendMessage("USER", "PyHeufyBot", "0", "0", ":PyHeufyBot Bot")
- print "OK"
+ self.cmdNICK(self.nickname)
+ self.cmdUSER(self.ident, self.gecos)
def connectionLost(self, reason=""):
print reason
def dataReceived(self, data):
print data
+
+ def sendMessage(self, command, *parameter_list, **prefix):
+ print command, " ".join(parameter_list)
+ irc.IRC.sendMessage(self, command, *parameter_list, **prefix)
+
+ def cmdNICK(self, nickname):
+ self.sendMessage("NICK", nickname)
+
+ def cmdUSER(self, ident, gecos):
+ # RFC2812 allows usermodes to be set, but this isn't implemented much in IRCds at all.
+ # Pass 0 for usermodes instead.
+ self.sendMessage("USER", ident, "0", "*", ":{}".format(gecos)) |
16c68198d353735343321b7b9558370247ad1b5e | banana/maya/extensions/OpenMaya/MFileIO.py | banana/maya/extensions/OpenMaya/MFileIO.py | """
banana.maya.MFileIO
~~~~~~~~~~~~~~~~~~~
Monkey patching of the `~maya.OpenMaya.MFileIO` class.
:copyright: Copyright 2014 by Christopher Crouzet.
:license: MIT, see LICENSE for details.
"""
import gorilla
from maya import OpenMaya
@gorilla.patch(OpenMaya)
class MFileIO(object):
@classmethod
def bnn_importFile(cls, fileName, type='', preserveReferences=False,
nameSpace='', ignoreVersion=False):
"""Import a file into the current Maya session.
Parameters
----------
fileName : str
File name to import.
type : str, optional
Type of the file to import.
preserveReferences : bool, optional
True if the references needs to be preserved.
nameSpace : str, optional
Namespace to use when importing the objects.
ignoreVersion : bool, optional
True to ignore the version.
Returns
-------
list of maya.OpenMaya.MDagPath
The top level transforms imported.
"""
if not type:
type = None
if not nameSpace:
nameSpace = None
topLevelDagPaths = list(OpenMaya.bnn_MItDagHierarchy())
OpenMaya.MFileIO.importFile(fileName, type, preserveReferences,
nameSpace, ignoreVersion)
return [dagPath for dagPath in OpenMaya.bnn_MItDagHierarchy()
if not dagPath in topLevelDagPaths]
| """
banana.maya.MFileIO
~~~~~~~~~~~~~~~~~~~
Monkey patching of the `~maya.OpenMaya.MFileIO` class.
:copyright: Copyright 2014 by Christopher Crouzet.
:license: MIT, see LICENSE for details.
"""
import gorilla
from maya import OpenMaya
@gorilla.patch(OpenMaya)
class MFileIO(object):
@classmethod
def bnn_importFile(cls, fileName, type='', preserveReferences=False,
nameSpace='', ignoreVersion=False):
"""Import a file into the current Maya session.
Parameters
----------
fileName : str
File name to import.
type : str, optional
Type of the file to import.
preserveReferences : bool, optional
True if the references needs to be preserved.
nameSpace : str, optional
Namespace to use when importing the objects.
ignoreVersion : bool, optional
True to ignore the version.
Returns
-------
list of maya.OpenMaya.MDagPath
The top level transforms imported.
"""
if not type:
type = None
if not nameSpace:
nameSpace = None
topLevelDagPaths = set(OpenMaya.bnn_MItDagHierarchy())
OpenMaya.MFileIO.importFile(fileName, type, preserveReferences,
nameSpace, ignoreVersion)
return [dagPath for dagPath in OpenMaya.bnn_MItDagHierarchy()
if not dagPath in topLevelDagPaths]
| Replace the use of the list for a set to emphasize the semantics. | Replace the use of the list for a set to emphasize the semantics.
| Python | mit | christophercrouzet/banana.maya,christophercrouzet/bana | ---
+++
@@ -44,7 +44,7 @@
if not nameSpace:
nameSpace = None
- topLevelDagPaths = list(OpenMaya.bnn_MItDagHierarchy())
+ topLevelDagPaths = set(OpenMaya.bnn_MItDagHierarchy())
OpenMaya.MFileIO.importFile(fileName, type, preserveReferences,
nameSpace, ignoreVersion)
return [dagPath for dagPath in OpenMaya.bnn_MItDagHierarchy() |
cbbfa328f3f5998c2d3bc78315f9ecfc3fee9aad | pirx/checks.py | pirx/checks.py | #!/usr/bin/env python
import socket
import sys
def host(name):
"""Check if host name is equal to the given name"""
return socket.gethostname() == name
def arg(name, expected_value=None):
"""
Check if command-line argument with a given name was passed and if it has
the expected value.
"""
args = [
arg.split('=') for arg in sys.argv[1:] if '=' in arg else (arg, None)
]
for arg_name, arg_value in args:
if arg_name.lstrip('--') == name:
return arg_value == expected_value
return False
| #!/usr/bin/env python
import socket
import sys
def host(name):
"""Check if host name is equal to the given name"""
return socket.gethostname() == name
def arg(name, expected_value=None):
"""
Check if command-line argument with a given name was passed and if it has
the expected value.
"""
args = [
arg.split('=') if '=' in arg else (arg, None) for arg in sys.argv[1:]
]
for arg_name, arg_value in args:
if arg_name.lstrip('--') == name:
return arg_value == expected_value
return False
| Fix for-if in "arg" function | Fix for-if in "arg" function
| Python | mit | piotrekw/pirx | ---
+++
@@ -13,7 +13,7 @@
the expected value.
"""
args = [
- arg.split('=') for arg in sys.argv[1:] if '=' in arg else (arg, None)
+ arg.split('=') if '=' in arg else (arg, None) for arg in sys.argv[1:]
]
for arg_name, arg_value in args:
if arg_name.lstrip('--') == name: |
12d55dbd223d32b4be77dde8d3342517e617a48f | migmig/log.py | migmig/log.py | # migmig logger module
import logging
import sys
console = True
class logger():
def __init__(self):
logging.basicConfig(level=logging.DEBUG, filename='test/mylog.txt', format='%(name)s \t%(message)s')
self.handlers = []
if console:
self.handlers.append(logging.StreamHandler(sys.stdout))
def get_logger(self, mod_name):
return logging.getLogger(mod_name)
def h(self):
self.root_logger.addHandler(self.handlers[0])
| # migmig logger module
import logging
import sys
class logger():
def __init__(self, verbose, console = None):
'''
Python doc :
https://docs.python.org/2/library/logging.html#logrecord-attributes
Levels:
0: NOTSET - 0
1: DEBUG - 10
2: INFO - 20
3: WARNING - 30
4: ERROR - 40
5: CRITICAL - 50
'''
levels = {
4: logging.DEBUG,
3: logging.INFO,
2: logging.WARNING,
1: logging.ERROR,
0: logging.WARNING
}
if verbose in levels:
# Note: if user doesnt specify the verbose level, default will be zero (0:Warning)
level = levels[verbose]
else:
# log details is not important.
level = levels[1]
FORMAT = '%(module)s(%(name)s)-%(asctime)s \t%(message)s'
LOG_PATH = 'test/migmig.log'
logging.basicConfig(level=level, filename=LOG_PATH, format=FORMAT)
self.root_logger = logging.getLogger()
if console:
'''
User wants logs on his console
'''
self.console_handler()
def get_logger(self, logger_name=None):
return logging.getLogger(logger_name)
def console_handler(self):
hdlr = logging.StreamHandler(sys.stdout)
# the logging format of console
FORMAT = '[%(module)s]: %(message)s'
fo = logging.Formatter(FORMAT)
hdlr.setFormatter(fo)
self.root_logger.addHandler(hdlr)
| Improve the Log module, add console handler | Improve the Log module, add console handler
This commit will improve the logging levels, user now can set the
verbose level by typing "-v" option.
if user wants the logs into the console, he should type "--console" option.
| Python | agpl-3.0 | dotamin/migmig | ---
+++
@@ -3,19 +3,61 @@
import logging
import sys
-console = True
class logger():
- def __init__(self):
- logging.basicConfig(level=logging.DEBUG, filename='test/mylog.txt', format='%(name)s \t%(message)s')
- self.handlers = []
+ def __init__(self, verbose, console = None):
+ '''
+ Python doc :
+ https://docs.python.org/2/library/logging.html#logrecord-attributes
+
+ Levels:
+ 0: NOTSET - 0
+ 1: DEBUG - 10
+ 2: INFO - 20
+ 3: WARNING - 30
+ 4: ERROR - 40
+ 5: CRITICAL - 50
+ '''
+ levels = {
+ 4: logging.DEBUG,
+ 3: logging.INFO,
+ 2: logging.WARNING,
+ 1: logging.ERROR,
+ 0: logging.WARNING
+ }
+ if verbose in levels:
+ # Note: if user doesnt specify the verbose level, default will be zero (0:Warning)
+ level = levels[verbose]
+ else:
+ # log details is not important.
+ level = levels[1]
+
+
+ FORMAT = '%(module)s(%(name)s)-%(asctime)s \t%(message)s'
+ LOG_PATH = 'test/migmig.log'
+
+ logging.basicConfig(level=level, filename=LOG_PATH, format=FORMAT)
+ self.root_logger = logging.getLogger()
+
if console:
- self.handlers.append(logging.StreamHandler(sys.stdout))
+ '''
+ User wants logs on his console
+ '''
+ self.console_handler()
- def get_logger(self, mod_name):
- return logging.getLogger(mod_name)
- def h(self):
- self.root_logger.addHandler(self.handlers[0])
+ def get_logger(self, logger_name=None):
+ return logging.getLogger(logger_name)
+
+ def console_handler(self):
+ hdlr = logging.StreamHandler(sys.stdout)
+
+ # the logging format of console
+ FORMAT = '[%(module)s]: %(message)s'
+
+ fo = logging.Formatter(FORMAT)
+ hdlr.setFormatter(fo)
+ self.root_logger.addHandler(hdlr)
+ |
9e17cda40ddefaa5c2b905b3ffdfadf485461eaa | plugin/main.py | plugin/main.py | #!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Change directory to deploy path
deploy_path = payload["workspace"]["path"]
os.chdir(deploy_path)
# Optional fields
compose_file = vargs.get('compose_file', 'docker-compose.yml')
stack = vargs.get('stack', payload['repo']['name'])
services = vargs.get('services', '')
# Set Required fields for rancher-compose to work
# Should raise an error if they are not declared
os.environ["RANCHER_URL"] = vargs['url']
os.environ["RANCHER_ACCESS_KEY"] = vargs['access_key']
os.environ["RANCHER_SECRET_KEY"] = vargs['secret_key']
try:
rc_args = [
"rancher-compose", "-f", compose_file, "-p", stack, "up", services,
]
subprocess.check_call(rc_args)
finally:
# Unset environmental variables, no point in them hanging about
del os.environ['RANCHER_URL']
del os.environ['RANCHER_ACCESS_KEY']
del os.environ['RANCHER_SECRET_KEY']
if __name__ == "__main__":
main()
| #!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Change directory to deploy path
deploy_path = payload["workspace"]["path"]
os.chdir(deploy_path)
# Optional fields
compose_file = vargs.get('compose_file', 'docker-compose.yml')
stack = vargs.get('stack', payload['repo']['name'])
services = vargs.get('services', '')
# Set Required fields for rancher-compose to work
# Should raise an error if they are not declared
os.environ["RANCHER_URL"] = vargs['url']
os.environ["RANCHER_ACCESS_KEY"] = vargs['access_key']
os.environ["RANCHER_SECRET_KEY"] = vargs['secret_key']
try:
rc_args = [
"rancher-compose", "-f", compose_file, "-p", stack, "up"
]
if services:
rc_args.append(services)
subprocess.check_call(rc_args)
finally:
# Unset environmental variables, no point in them hanging about
del os.environ['RANCHER_URL']
del os.environ['RANCHER_ACCESS_KEY']
del os.environ['RANCHER_SECRET_KEY']
if __name__ == "__main__":
main()
| Append services string only if not blank | Append services string only if not blank
| Python | apache-2.0 | dangerfarms/drone-rancher | ---
+++
@@ -30,8 +30,10 @@
try:
rc_args = [
- "rancher-compose", "-f", compose_file, "-p", stack, "up", services,
+ "rancher-compose", "-f", compose_file, "-p", stack, "up"
]
+ if services:
+ rc_args.append(services)
subprocess.check_call(rc_args)
finally:
# Unset environmental variables, no point in them hanging about |
5055e3b911afe52f70f60915254d27bfc0c2b645 | application/navigation/views.py | application/navigation/views.py | from flask import Markup
from flask import render_template
from application.page.models import Page
def find_subpages(pages, parent):
subpages = []
for page in pages:
prefix = '/'.join(page.path.split('/')[:-1])
if prefix == parent.path:
subpages.append(page)
return subpages
def view_bar(current_page=''):
pages = Page.get_all_pages()
all_pages = []
print pages
for page in pages:
if not '/' in page.path:
all_pages.append({'main': page,
'subpages': find_subpages(pages, page)})
return Markup(render_template('navigation/view_bar.htm', pages=all_pages, current_page=current_page))
| from flask import Markup
from flask import render_template
from application.page.models import Page
def find_subpages(pages, parent):
subpages = []
for page in pages:
prefix = '/'.join(page.path.split('/')[:-1])
if prefix == parent.path:
subpages.append(page)
return subpages
def view_bar(current_page=''):
pages = Page.get_all_pages()
all_pages = []
for page in pages:
if not '/' in page.path:
all_pages.append({'main': page,
'subpages': find_subpages(pages, page)})
return Markup(render_template('navigation/view_bar.htm', pages=all_pages, current_page=current_page))
| Remove print statement so Stephan won't be annoyed anymore | Remove print statement so Stephan won't be annoyed anymore
| Python | mit | viaict/viaduct,viaict/viaduct,viaict/viaduct,viaict/viaduct,viaict/viaduct | ---
+++
@@ -16,7 +16,6 @@
def view_bar(current_page=''):
pages = Page.get_all_pages()
all_pages = []
- print pages
for page in pages:
if not '/' in page.path: |
2fb3a72885d279f7a79e10f00d71991144748f1c | haas/plugins/base_plugin.py | haas/plugins/base_plugin.py | from haas.utils import uncamelcase
from .i_plugin import IPlugin
class BasePlugin(IPlugin):
name = None
enabled = False
enabling_option = None
def __init__(self, name=None):
if name is None:
name = uncamelcase(type(self).__name__, sep='-')
self.name = name
self.enabling_option = 'with_{0}'.format(name.replace('-', '_'))
def add_parser_arguments(self, parser):
parser.add_argument('--with-{0}'.format(self.name),
action='store_true',
dest=self.enabling_option)
def configure(self, args):
if getattr(args, self.enabling_option, False):
self.enabled = True
| from haas.utils import uncamelcase
from .i_plugin import IPlugin
class BasePlugin(IPlugin):
name = None
enabled = False
enabling_option = None
def __init__(self, name=None):
if name is None:
name = uncamelcase(type(self).__name__, sep='-')
self.name = name
self.enabling_option = 'with_{0}'.format(name.replace('-', '_'))
def add_parser_arguments(self, parser):
parser.add_argument('--with-{0}'.format(self.name),
action='store_true',
help='Enable the {0} plugin'.format(self.name),
dest=self.enabling_option)
def configure(self, args):
if getattr(args, self.enabling_option, False):
self.enabled = True
| Add help text for plugin enable option | Add help text for plugin enable option
| Python | bsd-3-clause | sjagoe/haas,scalative/haas,sjagoe/haas,itziakos/haas,scalative/haas,itziakos/haas | ---
+++
@@ -17,6 +17,7 @@
def add_parser_arguments(self, parser):
parser.add_argument('--with-{0}'.format(self.name),
action='store_true',
+ help='Enable the {0} plugin'.format(self.name),
dest=self.enabling_option)
def configure(self, args): |
9fc92a176fbc9425229d02a032d3494566139e6a | tests/Physics/TestNTC.py | tests/Physics/TestNTC.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from numpy.testing import assert_approx_equal, assert_allclose, assert_array_less
from nose.tools import raises, assert_true, assert_equal
from UliEngineering.Physics.NTC import *
from UliEngineering.Exceptions import *
import functools
import numpy as np
class TestNTC(object):
def test_ntc_resistance(self):
# Values arbitrarily from Murata NCP15WB473D03RC
assert_approx_equal(ntc_resistance("47k", "4050K", "25°C"), 47000)
assert_approx_equal(ntc_resistance("47k", "4050K", "0°C"), 162942.79)
assert_approx_equal(ntc_resistance("47k", "4050K", "5°C"), 124819.66)
assert_approx_equal(ntc_resistance("47k", "4050K", "60°C"), 11280.407)
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from numpy.testing import assert_approx_equal, assert_allclose, assert_array_less
from nose.tools import raises, assert_true, assert_equal
from UliEngineering.Physics.NTC import *
from UliEngineering.Exceptions import *
import functools
import numpy as np
class TestNTC(object):
def test_ntc_resistance(self):
# Values arbitrarily from Murata NCP15WB473D03RC
assert_approx_equal(ntc_resistance("47k", "4050K", "25°C"), 47000)
assert_approx_equal(ntc_resistance("47k", "4050K", "0°C"), 162942.79)
assert_approx_equal(ntc_resistance("47k", "4050K", "-18°C"), 463773.791)
assert_approx_equal(ntc_resistance("47k", "4050K", "5°C"), 124819.66)
assert_approx_equal(ntc_resistance("47k", "4050K", "60°C"), 11280.407)
| Add more NTC unit tests | Add more NTC unit tests
| Python | apache-2.0 | ulikoehler/UliEngineering | ---
+++
@@ -12,5 +12,6 @@
# Values arbitrarily from Murata NCP15WB473D03RC
assert_approx_equal(ntc_resistance("47k", "4050K", "25°C"), 47000)
assert_approx_equal(ntc_resistance("47k", "4050K", "0°C"), 162942.79)
+ assert_approx_equal(ntc_resistance("47k", "4050K", "-18°C"), 463773.791)
assert_approx_equal(ntc_resistance("47k", "4050K", "5°C"), 124819.66)
assert_approx_equal(ntc_resistance("47k", "4050K", "60°C"), 11280.407) |
cd959b5216a0bc1cdc89c963022f312d0ea65e8a | bluebottle/projects/urls/api.py | bluebottle/projects/urls/api.py | from bluebottle.projects.views import ProjectMediaDetail, ProjectSupportDetail
from ..views import (
ManageProjectBudgetLineDetail, ManageProjectBudgetLineList,
ManageProjectDocumentList, ManageProjectDocumentDetail)
from django.conf.urls import patterns, url
urlpatterns = patterns(
'',
url(r'^media/(?P<slug>[\w-]+)/$',
ProjectMediaDetail.as_view(),
name='project-media-detail'),
url(r'^support/(?P<slug>[\w-]+)/$',
ProjectSupportDetail.as_view(),
name='project-supporters-detail'),
url(r'^budgetlines/$',
ManageProjectBudgetLineList.as_view(),
name='project-budgetline-list'),
url(r'^budgetlines/(?P<pk>\d+)$',
ManageProjectBudgetLineDetail.as_view(),
name='project-budgetline-detail'),
url(r'^documents/manage/$',
ManageProjectDocumentList.as_view(),
name='manage-project-document-list'),
url(r'^documents/manage/(?P<pk>\d+)$',
ManageProjectDocumentDetail.as_view(),
name='manage-project-document-detail'),
)
| from bluebottle.projects.views import ProjectMediaDetail, ProjectSupportDetail
from ..views import (
ManageProjectBudgetLineDetail, ManageProjectBudgetLineList,
ManageProjectDocumentList, ManageProjectDocumentDetail)
from django.conf.urls import patterns, url
urlpatterns = patterns(
'',
url(r'^media/(?P<slug>[\w-]+)$',
ProjectMediaDetail.as_view(),
name='project-media-detail'),
url(r'^support/(?P<slug>[\w-]+)$',
ProjectSupportDetail.as_view(),
name='project-supporters-detail'),
url(r'^budgetlines/$',
ManageProjectBudgetLineList.as_view(),
name='project-budgetline-list'),
url(r'^budgetlines/(?P<pk>\d+)$',
ManageProjectBudgetLineDetail.as_view(),
name='project-budgetline-detail'),
url(r'^documents/manage/$',
ManageProjectDocumentList.as_view(),
name='manage-project-document-list'),
url(r'^documents/manage/(?P<pk>\d+)$',
ManageProjectDocumentDetail.as_view(),
name='manage-project-document-detail'),
)
| Use urls without a slash in project/media project/support | Use urls without a slash in project/media project/support
BB-7765 #resolve
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | ---
+++
@@ -8,10 +8,10 @@
urlpatterns = patterns(
'',
- url(r'^media/(?P<slug>[\w-]+)/$',
+ url(r'^media/(?P<slug>[\w-]+)$',
ProjectMediaDetail.as_view(),
name='project-media-detail'),
- url(r'^support/(?P<slug>[\w-]+)/$',
+ url(r'^support/(?P<slug>[\w-]+)$',
ProjectSupportDetail.as_view(),
name='project-supporters-detail'),
|
4b9789350a01fee5c341ac8a5612c7dae123fddd | tests/test_boto_store.py | tests/test_boto_store.py | #!/usr/bin/env python
import pytest
boto = pytest.importorskip('boto')
from simplekv.net.botostore import BotoStore
from basic_store import BasicStore
from url_store import UrlStore
from bucket_manager import boto_credentials, boto_bucket
@pytest.fixture(params=boto_credentials,
ids=[c['access_key'] for c in boto_credentials])
def credentials(request):
return request.param
@pytest.yield_fixture()
def bucket(credentials):
with boto_bucket(**credentials) as bucket:
yield bucket
class TestBotoStorage(BasicStore, UrlStore):
@pytest.fixture(params=['', '/test-prefix'])
def prefix(self, request):
return request.param
@pytest.fixture
def store(self, bucket, prefix):
return BotoStore(bucket, prefix)
| #!/usr/bin/env python
import os
from tempdir import TempDir
import pytest
boto = pytest.importorskip('boto')
from simplekv.net.botostore import BotoStore
from basic_store import BasicStore
from url_store import UrlStore
from bucket_manager import boto_credentials, boto_bucket
@pytest.fixture(params=boto_credentials,
ids=[c['access_key'] for c in boto_credentials])
def credentials(request):
return request.param
@pytest.yield_fixture()
def bucket(credentials):
with boto_bucket(**credentials) as bucket:
yield bucket
class TestBotoStorage(BasicStore, UrlStore):
@pytest.fixture(params=['', '/test-prefix'])
def prefix(self, request):
return request.param
@pytest.fixture
def store(self, bucket, prefix):
return BotoStore(bucket, prefix)
def test_get_filename_nonexistant(self, store):
# NOTE: boto misbehaves here and tries to erase the target file
# the parent tests use /dev/null, which you really should not try
# to os.remove!
with TempDir() as tmpdir:
with pytest.raises(KeyError):
store.get_file('nonexistantkey', os.path.join(tmpdir, 'a'))
| Fix botos rudeness when handling nonexisting files. | Fix botos rudeness when handling nonexisting files.
| Python | mit | fmarczin/simplekv,karteek/simplekv,fmarczin/simplekv,mbr/simplekv,mbr/simplekv,karteek/simplekv | ---
+++
@@ -1,4 +1,7 @@
#!/usr/bin/env python
+
+import os
+from tempdir import TempDir
import pytest
@@ -30,3 +33,11 @@
@pytest.fixture
def store(self, bucket, prefix):
return BotoStore(bucket, prefix)
+
+ def test_get_filename_nonexistant(self, store):
+ # NOTE: boto misbehaves here and tries to erase the target file
+ # the parent tests use /dev/null, which you really should not try
+ # to os.remove!
+ with TempDir() as tmpdir:
+ with pytest.raises(KeyError):
+ store.get_file('nonexistantkey', os.path.join(tmpdir, 'a')) |
acf9e2d1f879758412154fe8008371b387f4d2bc | namegen/name.py | namegen/name.py |
import random
__metaclass__ = type
class Generator:
def __init__(self, data):
if isinstance(data, str):
data = data.split('\n')
self.clusters = []
for item in data:
if item.find(' ') < 0:
item += ' '
name, info = item.split(' ', 2)
for i in range(len(name) - 1):
self.clusters.append((name[i:i+2], info))
def generate(self, length=5):
length -= 2 # Account for initial cluster and cluster length of 2
valid = False
while not valid:
valid = True
clusters = [random.choice(self.clusters)[0]]
for i in range(length):
random.shuffle(self.clusters)
valid = False
for c in self.clusters:
if c[0][0] == clusters[-1][1]:
valid = True
clusters.append(c[0])
break
if not valid:
break
if clusters[-2] == clusters[-1]:
# Don't allow triple letters
valid = False
break
return clusters[0][0] + ''.join([c[1] for c in clusters])
|
import random
__metaclass__ = type
class Generator:
def __init__(self, data):
if isinstance(data, str):
data = data.split('\n')
self.clusters = []
for item in data:
if item.find(' ') < 0:
item += ' '
name, info = item.split(' ', 2)
for i in range(len(name) - 2):
self.clusters.append((name[i:i+3], info))
def generate(self, length=5):
length -= 3 # Account for initial cluster and cluster length of 3
valid = False
while not valid:
valid = True
clusters = [random.choice(self.clusters)[0]]
for i in range(length):
random.shuffle(self.clusters)
valid = False
for c in self.clusters:
if c[0][0] == clusters[-1][2]:
valid = True
clusters.append(c[0])
break
if not valid:
break
if clusters[-2] == clusters[-1]:
# Don't allow triple letters
valid = False
break
return (clusters[0][0] + ''.join([c[1:] for c in clusters]))[:length+3]
| Use cluster length of 3 | Use cluster length of 3
| Python | mit | lethosor/py-namegen | ---
+++
@@ -12,11 +12,11 @@
if item.find(' ') < 0:
item += ' '
name, info = item.split(' ', 2)
- for i in range(len(name) - 1):
- self.clusters.append((name[i:i+2], info))
+ for i in range(len(name) - 2):
+ self.clusters.append((name[i:i+3], info))
def generate(self, length=5):
- length -= 2 # Account for initial cluster and cluster length of 2
+ length -= 3 # Account for initial cluster and cluster length of 3
valid = False
while not valid:
valid = True
@@ -25,7 +25,7 @@
random.shuffle(self.clusters)
valid = False
for c in self.clusters:
- if c[0][0] == clusters[-1][1]:
+ if c[0][0] == clusters[-1][2]:
valid = True
clusters.append(c[0])
break
@@ -35,7 +35,7 @@
# Don't allow triple letters
valid = False
break
- return clusters[0][0] + ''.join([c[1] for c in clusters])
+ return (clusters[0][0] + ''.join([c[1:] for c in clusters]))[:length+3]
|
ff35b4353fbb47c602d3561c5e6e84201355df14 | Cryptor.py | Cryptor.py | from Crypto.Cipher import AES
class Cryptor(object):
def __init__(self, key, iv):
#self.aes = AES.new(key, mode=AES.MODE_CBC, IV=iv) # This resembles stuff from shairtunes
self.aes = AES.new(key, mode=AES.MODE_ECB, IV=iv) # I found this in airtunesd
self.inbuf = ""
self.outbuf = ""
self.lastLen = 0
def decrypt(self, data):
self.inbuf += data
blocksEnd = len(self.inbuf)
blocksEnd -= blocksEnd % AES.block_size
self.outbuf += self.aes.decrypt(self.inbuf[:blocksEnd])
self.inbuf = self.inbuf[blocksEnd:]
res = self.outbuf[:self.lastLen]
self.outbuf = self.outbuf[self.lastLen:]
self.lastLen = len(data)
return res
class EchoCryptor(object):
def decrypt(self, data):
return data
| from Crypto.Cipher import AES
import Crypto.Util.Counter
class Cryptor(AES.AESCipher):
def __init__(self, key, iv):
self.counter = Crypto.Util.Counter.new(128, initial_value=long(iv.encode("hex"), 16))
AES.AESCipher.__init__(self, key, mode=AES.MODE_CTR, counter=self.counter)
class EchoCryptor(object):
def decrypt(self, data):
return data
| Use CTR as encrypton mode. Works with iOS6. | Use CTR as encrypton mode. Works with iOS6.
| Python | bsd-2-clause | tzwenn/PyOpenAirMirror,tzwenn/PyOpenAirMirror | ---
+++
@@ -1,27 +1,11 @@
from Crypto.Cipher import AES
+import Crypto.Util.Counter
-class Cryptor(object):
+class Cryptor(AES.AESCipher):
def __init__(self, key, iv):
- #self.aes = AES.new(key, mode=AES.MODE_CBC, IV=iv) # This resembles stuff from shairtunes
- self.aes = AES.new(key, mode=AES.MODE_ECB, IV=iv) # I found this in airtunesd
- self.inbuf = ""
- self.outbuf = ""
- self.lastLen = 0
-
- def decrypt(self, data):
- self.inbuf += data
- blocksEnd = len(self.inbuf)
- blocksEnd -= blocksEnd % AES.block_size
- self.outbuf += self.aes.decrypt(self.inbuf[:blocksEnd])
- self.inbuf = self.inbuf[blocksEnd:]
-
- res = self.outbuf[:self.lastLen]
- self.outbuf = self.outbuf[self.lastLen:]
-
- self.lastLen = len(data)
- return res
-
+ self.counter = Crypto.Util.Counter.new(128, initial_value=long(iv.encode("hex"), 16))
+ AES.AESCipher.__init__(self, key, mode=AES.MODE_CTR, counter=self.counter)
class EchoCryptor(object):
|
f9903bc92bf02eeaa18e1a2843d288e909b71c33 | social_core/tests/backends/test_asana.py | social_core/tests/backends/test_asana.py | import json
from .oauth import OAuth2Test
class AsanaOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.asana.AsanaOAuth2'
user_data_url = 'https://app.asana.com/api/1.0/users/me'
expected_username = 'erlich@bachmanity.com'
access_token_body = json.dumps({
'access_token': 'aviato',
'token_type': 'bearer'
})
user_data_body = json.dumps({
'id': 12345,
'name': 'Erlich Bachman',
'email': 'erlich@bachmanity.com',
'photo': None,
'workspaces': [
{
'id': 123456,
'name': 'Pied Piper'
}
]
})
def test_login(self):
self.do_login()
def test_partial_pipeline(self):
self.do_partial_pipeline()
| import json
from .oauth import OAuth2Test
class AsanaOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.asana.AsanaOAuth2'
user_data_url = 'https://app.asana.com/api/1.0/users/me'
expected_username = 'erlich@bachmanity.com'
access_token_body = json.dumps({
'access_token': 'aviato',
'token_type': 'bearer'
})
# https://asana.com/developers/api-reference/users
user_data_body = json.dumps({
'data': {
'id': 12345,
'name': 'Erlich Bachman',
'email': 'erlich@bachmanity.com',
'photo': None,
'workspaces': [
{
'id': 123456,
'name': 'Pied Piper'
}
]
}
})
def test_login(self):
self.do_login()
def test_partial_pipeline(self):
self.do_partial_pipeline()
| Correct mocked response from Asana API | Correct mocked response from Asana API
| Python | bsd-3-clause | tobias47n9e/social-core,python-social-auth/social-core,python-social-auth/social-core | ---
+++
@@ -11,17 +11,20 @@
'access_token': 'aviato',
'token_type': 'bearer'
})
+ # https://asana.com/developers/api-reference/users
user_data_body = json.dumps({
- 'id': 12345,
- 'name': 'Erlich Bachman',
- 'email': 'erlich@bachmanity.com',
- 'photo': None,
- 'workspaces': [
- {
- 'id': 123456,
- 'name': 'Pied Piper'
- }
- ]
+ 'data': {
+ 'id': 12345,
+ 'name': 'Erlich Bachman',
+ 'email': 'erlich@bachmanity.com',
+ 'photo': None,
+ 'workspaces': [
+ {
+ 'id': 123456,
+ 'name': 'Pied Piper'
+ }
+ ]
+ }
})
def test_login(self): |
05e86efadfd0a05bac660e2ce47a5502b5bbdddb | tempest/tests/fake_auth_provider.py | tempest/tests/fake_auth_provider.py | # Copyright 2014 Hewlett-Packard Development Company, L.P.
# 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.
class FakeAuthProvider(object):
def auth_request(self, method, url, headers=None, body=None, filters=None):
return url, headers, body
def get_token(self):
return "faketoken"
def base_url(self, filters, auth_data=None):
return "https://example.com"
| # Copyright 2014 Hewlett-Packard Development Company, L.P.
# 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.
class FakeAuthProvider(object):
def get_token(self):
return "faketoken"
def base_url(self, filters, auth_data=None):
return "https://example.com"
| Remove auth_request as no used | Remove auth_request as no used
Function auth_request() isn't be used, it can be removed for the
code clean.
Change-Id: I979b67e934c72f50dd62c75ac614f99f136cfeae
| Python | apache-2.0 | vedujoshi/tempest,Tesora/tesora-tempest,openstack/tempest,openstack/tempest,vedujoshi/tempest,masayukig/tempest,masayukig/tempest,Juniper/tempest,cisco-openstack/tempest,sebrandon1/tempest,sebrandon1/tempest,cisco-openstack/tempest,Tesora/tesora-tempest,Juniper/tempest | ---
+++
@@ -16,9 +16,6 @@
class FakeAuthProvider(object):
- def auth_request(self, method, url, headers=None, body=None, filters=None):
- return url, headers, body
-
def get_token(self):
return "faketoken"
|
51ab41fc42bf3cc79461733fbfac50667da63eed | sanitytest.py | sanitytest.py | #!/usr/bin/python
import libvirt
globals = dir(libvirt)
# Sanity test that the generator hasn't gone wrong
# Look for core classes
assert("virConnect" in globals)
assert("virDomain" in globals)
assert("virDomainSnapshot" in globals)
assert("virInterface" in globals)
assert("virNWFilter" in globals)
assert("virNodeDevice" in globals)
assert("virNetwork" in globals)
assert("virSecret" in globals)
assert("virStoragePool" in globals)
assert("virStorageVol" in globals)
assert("virStream" in globals)
assert("VIR_CONNECT_RO" in globals)
# Error related bits
assert("libvirtError" in globals)
assert("VIR_ERR_AUTH_FAILED" in globals)
assert("virGetLastError" in globals)
# Some misc methods
assert("virInitialize" in globals)
assert("virEventAddHandle" in globals)
assert("virEventRegisterDefaultImpl" in globals)
| #!/usr/bin/python
import libvirt
globals = dir(libvirt)
# Sanity test that the generator hasn't gone wrong
# Look for core classes
for clsname in ["virConnect",
"virDomain",
"virDomainSnapshot",
"virInterface",
"virNWFilter",
"virNodeDevice",
"virNetwork",
"virSecret",
"virStoragePool",
"virStorageVol",
"virStream",
]:
assert(clsname in globals)
assert(object in getattr(libvirt, clsname).__bases__)
# Constants
assert("VIR_CONNECT_RO" in globals)
# Error related bits
assert("libvirtError" in globals)
assert("VIR_ERR_AUTH_FAILED" in globals)
assert("virGetLastError" in globals)
# Some misc methods
assert("virInitialize" in globals)
assert("virEventAddHandle" in globals)
assert("virEventRegisterDefaultImpl" in globals)
| Check if classes are derived from object | Check if classes are derived from object
This makes sure we don't regress to old style classes
| Python | lgpl-2.1 | cardoe/libvirt-python,cardoe/libvirt-python,libvirt/libvirt-python,libvirt/libvirt-python,libvirt/libvirt-python,cardoe/libvirt-python | ---
+++
@@ -7,17 +7,22 @@
# Sanity test that the generator hasn't gone wrong
# Look for core classes
-assert("virConnect" in globals)
-assert("virDomain" in globals)
-assert("virDomainSnapshot" in globals)
-assert("virInterface" in globals)
-assert("virNWFilter" in globals)
-assert("virNodeDevice" in globals)
-assert("virNetwork" in globals)
-assert("virSecret" in globals)
-assert("virStoragePool" in globals)
-assert("virStorageVol" in globals)
-assert("virStream" in globals)
+for clsname in ["virConnect",
+ "virDomain",
+ "virDomainSnapshot",
+ "virInterface",
+ "virNWFilter",
+ "virNodeDevice",
+ "virNetwork",
+ "virSecret",
+ "virStoragePool",
+ "virStorageVol",
+ "virStream",
+ ]:
+ assert(clsname in globals)
+ assert(object in getattr(libvirt, clsname).__bases__)
+
+# Constants
assert("VIR_CONNECT_RO" in globals)
# Error related bits |
ebe21ef2014b9b6c6d77c1254a87546d5096642f | src/foremast/app/aws.py | src/foremast/app/aws.py | """AWS Spinnaker Application."""
from pprint import pformat
from foremast.app.base import BaseApp
from foremast.utils import wait_for_task
class SpinnakerApp(BaseApp):
"""Create AWS Spinnaker Application."""
def create(self):
"""Send a POST to spinnaker to create a new application with class variables.
Raises:
AssertionError: Application creation failed.
"""
self.appinfo['accounts'] = self.get_accounts()
self.log.debug('Pipeline Config\n%s', pformat(self.pipeline_config))
self.log.debug('App info:\n%s', pformat(self.appinfo))
jsondata = self.retrieve_template()
wait_for_task(jsondata)
self.log.info("Successfully created %s application", self.appname)
return
def delete(self):
"""Delete AWS Spinnaker Application."""
return False
def update(self):
"""Update AWS Spinnaker Application."""
return False
| """AWS Spinnaker Application."""
from pprint import pformat
from foremast.app import base
from foremast.utils import wait_for_task
class SpinnakerApp(base.BaseApp):
"""Create AWS Spinnaker Application."""
def create(self):
"""Send a POST to spinnaker to create a new application with class variables.
Raises:
AssertionError: Application creation failed.
"""
self.appinfo['accounts'] = self.get_accounts()
self.log.debug('Pipeline Config\n%s', pformat(self.pipeline_config))
self.log.debug('App info:\n%s', pformat(self.appinfo))
jsondata = self.retrieve_template()
wait_for_task(jsondata)
self.log.info("Successfully created %s application", self.appname)
return
def delete(self):
"""Delete AWS Spinnaker Application."""
return False
def update(self):
"""Update AWS Spinnaker Application."""
return False
| Use different import for better testing | fix: Use different import for better testing
| Python | apache-2.0 | gogoair/foremast,gogoair/foremast | ---
+++
@@ -1,10 +1,11 @@
"""AWS Spinnaker Application."""
from pprint import pformat
-from foremast.app.base import BaseApp
+
+from foremast.app import base
from foremast.utils import wait_for_task
-class SpinnakerApp(BaseApp):
+class SpinnakerApp(base.BaseApp):
"""Create AWS Spinnaker Application."""
def create(self): |
c8decb4f11059b58dd96442a4114f10cb95c7b35 | tv-script-generation/helper.py | tv-script-generation/helper.py | import os
import pickle
def load_data(path):
"""
Load Dataset from File
"""
input_file = os.path.join(path)
with open(input_file, "r") as f:
data = f.read()
return data
def preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables):
"""
Preprocess Text Data
"""
text = load_data(dataset_path)
token_dict = token_lookup()
for key, token in token_dict.items():
text = text.replace(key, ' {} '.format(token))
text = text.lower()
text = text.split()
vocab_to_int, int_to_vocab = create_lookup_tables(text)
int_text = [vocab_to_int[word] for word in text]
pickle.dump((int_text, vocab_to_int, int_to_vocab, token_dict), open('preprocess.p', 'wb'))
def load_preprocess():
"""
Load the Preprocessed Training data and return them in batches of <batch_size> or less
"""
return pickle.load(open('preprocess.p', mode='rb'))
def save_params(params):
"""
Save parameters to file
"""
pickle.dump(params, open('params.p', 'wb'))
def load_params():
"""
Load parameters from file
"""
return pickle.load(open('params.p', mode='rb'))
| import os
import pickle
def load_data(path):
"""
Load Dataset from File
"""
input_file = os.path.join(path)
with open(input_file, "r") as f:
data = f.read()
return data
def preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables):
"""
Preprocess Text Data
"""
text = load_data(dataset_path)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
token_dict = token_lookup()
for key, token in token_dict.items():
text = text.replace(key, ' {} '.format(token))
text = text.lower()
text = text.split()
vocab_to_int, int_to_vocab = create_lookup_tables(text)
int_text = [vocab_to_int[word] for word in text]
pickle.dump((int_text, vocab_to_int, int_to_vocab, token_dict), open('preprocess.p', 'wb'))
def load_preprocess():
"""
Load the Preprocessed Training data and return them in batches of <batch_size> or less
"""
return pickle.load(open('preprocess.p', mode='rb'))
def save_params(params):
"""
Save parameters to file
"""
pickle.dump(params, open('params.p', 'wb'))
def load_params():
"""
Load parameters from file
"""
return pickle.load(open('params.p', mode='rb'))
| Remove copyright notice during preprocessing | Remove copyright notice during preprocessing
| Python | mit | danresende/deep-learning,snegirigens/DLND,0x4a50/udacity-0x4a50-deep-learning-nanodegree,kitu2007/dl_class,seinberg/deep-learning,samirma/deep-learning,schaber/deep-learning,dataewan/deep-learning,michaelgat/Udacity_DL,Bismarrck/deep-learning,greg-ashby/deep-learning-nanodegree,cranium/deep-learning,thiagoqd/queirozdias-deep-learning,mastertrojan/Udacity,arthurtsang/deep-learning,oscarmore2/deep-learning-study,rahulkgup/deep-learning-foundation,ktmud/deep-learning,saravanakumar-periyasamy/deep-learning,nwhidden/ND101-Deep-Learning,elizabetht/deep-learning,Heerozh/deep-learning,yuanotes/deep-learning,chetnapriyadarshini/deep-learning,dxl0632/deeplearning_nd_udacity,ksooklall/deep_learning_foundation,rishizek/deep-learning,tkurfurst/deep-learning,haltux/deep-learning,adrianstaniec/deep-learning,voyageth/udacity-Deep_Learning_Foundations_Nanodegree,postBG/DL_project,stubz/deep-learning,kolaogun/deep-learning,xtr33me/deep-learning,atremblay/deep-learning,ClementPhil/deep-learning,adico-somoto/deep-learning,Bismarrck/deep-learning,quietcoolwu/deep-learning,gatmeh/Udacity-deep-learning,AlphaGit/deep-learning,khalido/deep-learning,jc091/deep-learning,azhurb/deep-learning,franciscodominguezmateos/DeepLearningNanoDegree,jc091/deep-learning,dewitt-li/deep-learning,xtr33me/deep-learning,elizabetht/deep-learning,guyk1971/deep-learning,voyageth/udacity-Deep_Learning_Foundations_Nanodegree,hfoffani/deep-learning,buncem/deep-learning,samirma/deep-learning,highb/deep-learning,sisnkemp/deep-learning,ktmud/deep-learning,tatsuya-ogawa/udacity-deep-learning,chetnapriyadarshini/deep-learning,ClementPhil/deep-learning,hvillanua/deep-learning,navaro1/deep-learning,javoweb/deep-learning,stubz/deep-learning,mdiaz236/DeepLearningFoundations,abhi1509/deep-learning,VenkatRepaka/deep-learning,angelmtenor/deep-learning,Jericho/deep-learning,hdchan/deep-learning,geilerloui/deep-learning,AndysDeepAbstractions/deep-learning,vvishwa/deep-learning,chusine/dlnd,oscarmore2/deep-learning-study,sisnkemp/deep-learning,raoyvn/deep-learning,luofan18/deep-learning,tamasjozsa/deep-learning,oscarmore2/deep-learning-study,kumi360/bike_sharing_prediction,gronnbeck/udacity-deep-learning,Agent007/deep-learning,ksooklall/deep_learning_foundation,brandoncgay/deep-learning,takahish/deep-learning,vinitsamel/udacitydeeplearning,strandbygaard/deep-learning,yuvrajsingh86/DeepLearning_Udacity,navaro1/deep-learning,scottquiring/Udacity_Deeplearning,theamazingfedex/ml-project-4,DestrinStorm/deep-learning,herruzojm/udacity-deep-learning,arturops/deep-learning,yuan-zong/deep-learning,dxl0632/deeplearning_nd_udacity,msanterre/deep_learning,greg-ashby/deep-learning-nanodegree,hvillanua/deep-learning,DataShrimp/deep-learning,DataShrimp/deep-learning,udacity/deep-learning,franciscodominguezmateos/DeepLearningNanoDegree,marko911/deep-learning,kimegitee/deep-learning,rahulkgup/deep-learning-foundation,ianhamilton117/deep-learning,JavascriptMick/deeplearning,azhurb/deep-learning,highb/deep-learning,sidazhang/udacity-dlnd,kazzz24/deep-learning,chusine/dlnd,Agent007/deep-learning,mkowoods/deep-learning,seinberg/deep-learning,nadvamir/deep-learning,thiagoqd/queirozdias-deep-learning,elenduuche/deep-learning,d-k-b/udacity-deep-learning,saravanakumar-periyasamy/deep-learning,johannesgiorgis/deep_learning,gururajl/deep-learning,raoyvn/deep-learning,strandbygaard/deep-learning,mikelseverson/Udacity-Deep_Learning-Nanodegree,rishizek/deep-learning,dewitt-li/deep-learning,llulai/deep-learning,kimegitee/deep-learning,luofan18/deep-learning,zizouvb/deeplearning,adico-somoto/deep-learning,gatmeh/Udacity-deep-learning,kvr777/deep-learning,AndysDeepAbstractions/deep-learning,heckmanc13/deep-learning,blua/deep-learning,efoley/deep-learning,kvr777/deep-learning,FiryZeplin/deep-learning,schaber/deep-learning,AndysDeepAbstractions/deep-learning,etendue/deep-learning,fnakashima/deep-learning,toddstrader/deep-learning,0x4a50/udacity-0x4a50-deep-learning-nanodegree,cranium/deep-learning,arthurtsang/deep-learning,scollins83/deep-learning,michaelgat/Udacity_DL,ysmazda/deep-learning,kumi360/bike_sharing_prediction,VenkatRepaka/deep-learning,guyk1971/deep-learning,tatsuya-ogawa/udacity-deep-learning,mikelseverson/Udacity-Deep_Learning-Nanodegree,dataewan/deep-learning,elenduuche/deep-learning,abhi1509/deep-learning,Riptawr/deep-learning,JasonNK/udacity-dlnd,josealber84/deep-learning,haltux/deep-learning,SlipknotTN/udacity-deeplearning-nanodegree,gronnbeck/udacity-deep-learning,retnuh/deep-learning,brandoncgay/deep-learning,angelmtenor/deep-learning,mdiaz236/DeepLearningFoundations,lukechen526/deep-learning,marko911/deep-learning,scottquiring/Udacity_Deeplearning,nwhidden/ND101-Deep-Learning,godfreyduke/deep-learning,yuan-zong/deep-learning,etendue/deep-learning,FishingOnATree/deep-learning,JasonNK/udacity-dlnd,AlphaGit/deep-learning,postBG/DL_project,rally12/deep-learning,throx66/deep-learning,godfreyduke/deep-learning,vinitsamel/udacitydeeplearning,Heerozh/deep-learning,rally12/deep-learning,arturops/deep-learning,harper/dlnd_thirdproject,georgebastille/deep-learning,flaviocordova/udacity_deep_learn_project,kiritisai/deep-learning-udacity,throx66/deep-learning,llulai/deep-learning,josealber84/deep-learning,herruzojm/udacity-deep-learning,sidazhang/udacity-dlnd,tamasjozsa/deep-learning,SlipknotTN/udacity-deeplearning-nanodegree,lukechen526/deep-learning,adrianstaniec/deep-learning,hfoffani/deep-learning,harper/dlnd_thirdproject,tkurfurst/deep-learning,jt6211/deep-learning,d-k-b/udacity-deep-learning,jc091/deep-learning,kazzz24/deep-learning,javoweb/deep-learning,retnuh/deep-learning,johannesgiorgis/deep_learning,ksooklall/deep_learning_foundation,theamazingfedex/ml-project-4,atremblay/deep-learning,zhuanxuhit/deep-learning,schaber/deep-learning,Riptawr/deep-learning,takahish/deep-learning | ---
+++
@@ -18,6 +18,9 @@
Preprocess Text Data
"""
text = load_data(dataset_path)
+
+ # Ignore notice, since we don't use it for analysing the data
+ text = text[81:]
token_dict = token_lookup()
for key, token in token_dict.items(): |
df0aa97de17be8b8b4d906bddf61272927009eb9 | web.py | web.py | import os
import requests
import json
from flask import Flask, jsonify, abort, make_response, request
FLICKR_BASE = "http://api.flickr.com/services/rest/"
app = Flask(__name__)
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port, debug=True)
| import os
import flickr
from flask import Flask, jsonify, abort, make_response, request
app = Flask(__name__)
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port, debug=True)
| Add the helper to the default | Add the helper to the default
| Python | mit | kyleconroy/quivr | ---
+++
@@ -1,9 +1,6 @@
import os
-import requests
-import json
+import flickr
from flask import Flask, jsonify, abort, make_response, request
-
-FLICKR_BASE = "http://api.flickr.com/services/rest/"
app = Flask(__name__)
|
4a95e49570a26f1295a2dad9d6d71ad9a887f1b1 | setup_data.py | setup_data.py | INFO = {
'name': 'Mayavi',
'version': '3.4.1',
'install_requires': [
'AppTools >= 3.4.1.dev',
'Traits >= 3.6.0.dev',
],
}
| INFO = {
'extras_require': {
'app' : [
'EnvisageCore >= 3.2.0.dev',
'EnvisagePlugins >= 3.2.0.dev',
'TraitsBackendWX >= 3.6.0.dev',
],
},
'name': 'Mayavi',
'version': '3.4.1',
'install_requires': [
'AppTools >= 3.4.1.dev',
'Traits >= 3.6.0.dev',
'TraitsGUI >= 3.6.0.dev',
],
}
| Add back the extra requires for the | MISC: Add back the extra requires for the [app]
| Python | bsd-3-clause | liulion/mayavi,dmsurti/mayavi,alexandreleroux/mayavi,alexandreleroux/mayavi,dmsurti/mayavi,liulion/mayavi | ---
+++
@@ -1,8 +1,16 @@
INFO = {
+ 'extras_require': {
+ 'app' : [
+ 'EnvisageCore >= 3.2.0.dev',
+ 'EnvisagePlugins >= 3.2.0.dev',
+ 'TraitsBackendWX >= 3.6.0.dev',
+ ],
+ },
'name': 'Mayavi',
'version': '3.4.1',
'install_requires': [
'AppTools >= 3.4.1.dev',
'Traits >= 3.6.0.dev',
+ 'TraitsGUI >= 3.6.0.dev',
],
} |
ac923a58ffa7c437985e68d98e7dd0e4e67df39c | shiva/http.py | shiva/http.py | from flask import current_app as app, Response
from flask.ext import restful
from shiva.decorators import allow_origins
class Resource(restful.Resource):
def __new__(cls, *args, **kwargs):
if app.config.get('CORS_ENABLED') is True:
# Applies to all inherited resources
cls.method_decorators = [allow_origins]
return super(Resource, cls).__new__(cls, *args, **kwargs)
# Without this the shiva.decorator.allow_origins method won't get called
# when issuing an OPTIONS request.
def options(self):
return JSONResponse()
class JSONResponse(Response):
"""
A subclass of flask.Response that sets the Content-Type header by default
to "application/json".
"""
def __init__(self, status=200, **kwargs):
params = {
'headers': [],
'mimetype': 'application/json',
'response': '',
'status': status,
}
params.update(kwargs)
super(JSONResponse, self).__init__(**params)
| from flask import current_app as app, Response
from flask.ext import restful
from shiva.decorators import allow_origins
class Resource(restful.Resource):
def __new__(cls, *args, **kwargs):
if app.config.get('CORS_ENABLED') is True:
# Applies to all inherited resources
cls.method_decorators = [allow_origins]
return super(Resource, cls).__new__(cls, *args, **kwargs)
# Without this the shiva.decorator.allow_origins method won't get called
# when issuing an OPTIONS request.
def options(self, *args, **kwargs):
return JSONResponse()
class JSONResponse(Response):
"""
A subclass of flask.Response that sets the Content-Type header by default
to "application/json".
"""
def __init__(self, status=200, **kwargs):
params = {
'headers': [],
'mimetype': 'application/json',
'response': '',
'status': status,
}
params.update(kwargs)
super(JSONResponse, self).__init__(**params)
| Fix for OPTIONS method to an instance | Fix for OPTIONS method to an instance
OPTIONS /track/1
TypeError: options() got an unexpected keyword argument 'track_id'
| Python | mit | tooxie/shiva-server,maurodelazeri/shiva-server,maurodelazeri/shiva-server,tooxie/shiva-server | ---
+++
@@ -14,7 +14,7 @@
# Without this the shiva.decorator.allow_origins method won't get called
# when issuing an OPTIONS request.
- def options(self):
+ def options(self, *args, **kwargs):
return JSONResponse()
|
41e0ea623baaff22ed5f436ad563edf52b762bcc | Main.py | Main.py | """Main Module of PDF Splitter"""
import argparse
import os
from PyPDF2 import PdfFileWriter
from Util import all_pdf_files_in_directory, split_on_condition, concat_pdf_pages
parser = \
argparse.ArgumentParser(
description='Split all the pages of multiple PDF files in a directory by document number'
)
parser.add_argument(
'directory',
metavar='PATH',
type=str,
help='path to a directory'
)
def width_greater_than_height(page):
box = page.mediaBox
return box.getWidth() > box.getHeight()
if __name__ == '__main__':
args = parser.parse_args()
all_pdf_files = all_pdf_files_in_directory(args.directory)
opened_files = map(lambda path: open(path, 'rb'), all_pdf_files)
all_pages = concat_pdf_pages(opened_files)
for idx, pages in enumerate(split_on_condition(all_pages, predicate=width_greater_than_height), start=1):
pdf_writer = PdfFileWriter()
map(pdf_writer.addPage, pages)
output_filename = '{0:05}.pdf'.format(idx)
with open(output_filename, 'wb') as output_file:
pdf_writer.write(output_file)
output_file.flush()
os.fsync(output_file.fileno())
map(lambda f: f.close, opened_files)
| """Main Module of PDF Splitter"""
import argparse
import os
from PyPDF2 import PdfFileWriter
from Util import all_pdf_files_in_directory, split_on_condition, concat_pdf_pages
parser = \
argparse.ArgumentParser(
description='Split all the pages of multiple PDF files in a directory by document number'
)
parser.add_argument(
'directory',
metavar='PATH',
type=str,
help='path to a directory'
)
def width_greater_than_height(page):
box = page.mediaBox
return box.getWidth() > box.getHeight()
if __name__ == '__main__':
args = parser.parse_args()
directory = args.directory
all_pdf_files = [os.path.join(directory, filename) for filename in all_pdf_files_in_directory(directory)]
opened_files = map(lambda path: open(path, 'rb'), all_pdf_files)
all_pages = concat_pdf_pages(opened_files)
for idx, pages in enumerate(split_on_condition(all_pages, predicate=width_greater_than_height), start=1):
pdf_writer = PdfFileWriter()
map(pdf_writer.addPage, pages)
output_filename = '{0:05}.pdf'.format(idx)
with open(output_filename, 'wb') as output_file:
pdf_writer.write(output_file)
output_file.flush()
os.fsync(output_file.fileno())
map(lambda f: f.close, opened_files)
| Fix bug where only PDF files in current directory can be found | Fix bug where only PDF files in current directory can be found
| Python | mit | shunghsiyu/pdf-processor | ---
+++
@@ -25,7 +25,8 @@
if __name__ == '__main__':
args = parser.parse_args()
- all_pdf_files = all_pdf_files_in_directory(args.directory)
+ directory = args.directory
+ all_pdf_files = [os.path.join(directory, filename) for filename in all_pdf_files_in_directory(directory)]
opened_files = map(lambda path: open(path, 'rb'), all_pdf_files)
all_pages = concat_pdf_pages(opened_files)
|
84741b8f6c7aec220b8644d92535e1a805c65b08 | run_example.py | run_example.py | import keras
from DatasetHandler.CreateDataset import *
from ModelHandler.CreateModel.functions_for_vgg16 import *
import time
#d = load_8376_resized_150x150(desired_number=10)
#d.statistics()
start = time.time()
print time.ctime()
main_vgg16(TMP_size_of_dataset=100, TMP_num_of_epochs=150, name_of_the_experiment = '-newWawe-1stRoundShouldCountBoth')
end = time.time()
print time.ctime()
print "### TOTAL TIME ", format(end - start, '.2f'), " sec." | import keras
from DatasetHandler.CreateDataset import *
from ModelHandler.CreateModel.functions_for_vgg16 import *
import time
import sys
# DEFAULT VALUES:
TMP_size_of_dataset=100
TMP_num_of_epochs=150
name_of_the_experiment = '-newWawe-1stRoundShouldCountBoth'
# python python_script.py var1 var2 var3
if len(sys.argv) > 3:
TMP_size_of_dataset = int(sys.argv[1]) # var1
TMP_num_of_epochs = int(sys.argv[2]) # var2
name_of_the_experiment = sys.argv[3] # var3
else:
print "Using default values. Please run as: python_script.py sizeOfDataset numOfEpochs nameOfExp"
print "[Setting] python_script.py", TMP_size_of_dataset, TMP_num_of_epochs, name_of_the_experiment
#d = load_8376_resized_150x150(desired_number=10)
#d.statistics()
start = time.time()
print time.ctime()
main_vgg16(TMP_size_of_dataset=100, TMP_num_of_epochs=150, name_of_the_experiment = '-newWawe-1stRoundShouldCountBoth')
end = time.time()
print time.ctime()
print "### TOTAL TIME ", format(end - start, '.2f'), " sec." | Add the support for custom setting given by bash script (run as "python_script.py sizeOfDataset numOfEpochs nameOfExp") | Add the support for custom setting given by bash script (run as "python_script.py sizeOfDataset numOfEpochs nameOfExp")
| Python | mit | previtus/MGR-Project-Code,previtus/MGR-Project-Code,previtus/MGR-Project-Code | ---
+++
@@ -2,6 +2,23 @@
from DatasetHandler.CreateDataset import *
from ModelHandler.CreateModel.functions_for_vgg16 import *
import time
+import sys
+
+# DEFAULT VALUES:
+TMP_size_of_dataset=100
+TMP_num_of_epochs=150
+name_of_the_experiment = '-newWawe-1stRoundShouldCountBoth'
+
+# python python_script.py var1 var2 var3
+if len(sys.argv) > 3:
+ TMP_size_of_dataset = int(sys.argv[1]) # var1
+ TMP_num_of_epochs = int(sys.argv[2]) # var2
+ name_of_the_experiment = sys.argv[3] # var3
+else:
+ print "Using default values. Please run as: python_script.py sizeOfDataset numOfEpochs nameOfExp"
+
+print "[Setting] python_script.py", TMP_size_of_dataset, TMP_num_of_epochs, name_of_the_experiment
+
#d = load_8376_resized_150x150(desired_number=10)
#d.statistics() |
d4580c01fc6adc078b382281a23022537c87940a | imager/imagerprofile/handlers.py | imager/imagerprofile/handlers.py | from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from imagerprofile.models import ImagerProfile
@receiver(post_save, sender=User)
def add_profile(sender, instance, **kwargs):
if kwargs['created']:
# try:
new_profile = ImagerProfile(user=instance)
new_profile.save()
# except:
# pass
| from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from imagerprofile.models import ImagerProfile
@receiver(post_save, sender=User)
def add_profile(sender, instance, **kwargs):
if kwargs['created']:
new_profile = ImagerProfile(user=instance)
new_profile.save()
| Remove commented out code that isn't needed | Remove commented out code that isn't needed
| Python | mit | nbeck90/django-imager,nbeck90/django-imager | ---
+++
@@ -7,8 +7,5 @@
@receiver(post_save, sender=User)
def add_profile(sender, instance, **kwargs):
if kwargs['created']:
- # try:
new_profile = ImagerProfile(user=instance)
new_profile.save()
- # except:
- # pass |
52d8ace9c944dda105dc95ab0baff4a41b4b48c3 | scripts/art.py | scripts/art.py | #!/usr/bin/env python
import sys
from pyfiglet import Figlet
from optparse import OptionParser
def draw_text(f, font, text):
f.setFont(font=font)
print f.renderText(text)
def main(args):
parser = OptionParser()
parser.add_option("-f", "--font", help="specify the font",
action="store", type="string", dest="font", default='clr8x8')
parser.add_option("-l", "--list", help="list available fonts",
action="store_true", dest="listfonts", default=False)
(options, args) = parser.parse_args()
print ""
f = Figlet()
if options.listfonts:
for font in f.getFonts():
print font
else:
draw_text(f, options.font, 'Thanks Levi & Andras')
draw_text(f, options.font, 'for the cards !!!')
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
| #!/usr/bin/env python
import sys
from pyfiglet import Figlet
from optparse import OptionParser
def draw_text(figlet, font, textlist):
figlet.setFont(font=font)
for t in textlist:
print figlet.renderText(t)
def list_fonts(figlet, count=10):
fonts = figlet.getFonts()
nrows = len(fonts)/count
if len(fonts) % count != 0:
nrows += 1
print "Available fonts in the system"
print
for start in range(0, nrows):
items = fonts[start*count:(start+1)*count]
for item in items:
print item + "\t",
print
def main(args):
usage = "Usage: %prog <options> <line 1> <line 2> ..."
parser = OptionParser(usage)
parser.add_option("-f", "--font", help="specify the font",
action="store", type="string", dest="font", default='clr8x8')
parser.add_option("-l", "--list", help="list available fonts",
action="store_true", dest="listfonts", default=False)
(options, args) = parser.parse_args()
print ""
f = Figlet()
if options.listfonts:
list_fonts(f)
else:
tlist = args
draw_text(f, options.font, tlist)
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
| Support for text input via args. | Support for text input via args.
1. better help message
2. support for input arguments
3. better defaults
4. columnar display of fonts
| Python | mit | shiva/asciiart | ---
+++
@@ -4,12 +4,28 @@
from pyfiglet import Figlet
from optparse import OptionParser
-def draw_text(f, font, text):
- f.setFont(font=font)
- print f.renderText(text)
+def draw_text(figlet, font, textlist):
+ figlet.setFont(font=font)
+ for t in textlist:
+ print figlet.renderText(t)
+def list_fonts(figlet, count=10):
+ fonts = figlet.getFonts()
+ nrows = len(fonts)/count
+ if len(fonts) % count != 0:
+ nrows += 1
+
+ print "Available fonts in the system"
+ print
+ for start in range(0, nrows):
+ items = fonts[start*count:(start+1)*count]
+ for item in items:
+ print item + "\t",
+ print
+
def main(args):
- parser = OptionParser()
+ usage = "Usage: %prog <options> <line 1> <line 2> ..."
+ parser = OptionParser(usage)
parser.add_option("-f", "--font", help="specify the font",
action="store", type="string", dest="font", default='clr8x8')
parser.add_option("-l", "--list", help="list available fonts",
@@ -21,11 +37,10 @@
f = Figlet()
if options.listfonts:
- for font in f.getFonts():
- print font
+ list_fonts(f)
else:
- draw_text(f, options.font, 'Thanks Levi & Andras')
- draw_text(f, options.font, 'for the cards !!!')
+ tlist = args
+ draw_text(f, options.font, tlist)
if __name__ == "__main__":
sys.exit(main(sys.argv[1:])) |
a7d8d2f95acbf801c0cc8b0f2a8cc008f6cb34c0 | rouver/types.py | rouver/types.py | from __future__ import annotations
from collections.abc import Iterable, Mapping
from typing import Any, Callable, Dict, Tuple
from typing_extensions import TypeAlias
from werkzeug.wrappers import Request
# (name, value)
Header: TypeAlias = Tuple[str, str]
WSGIEnvironment: TypeAlias = Dict[str, Any]
# (body) -> None
StartResponseReturnType: TypeAlias = Callable[[bytes], object]
# (status: str, headers: List[Headers], exc_info) -> response
StartResponse: TypeAlias = Callable[..., StartResponseReturnType]
WSGIResponse: TypeAlias = Iterable[bytes]
WSGIApplication: TypeAlias = Callable[
[WSGIEnvironment, StartResponse], WSGIResponse
]
# (method, path, callback)
RouteDescription: TypeAlias = Tuple[str, str, WSGIApplication]
# (request, previous_args, path_part) -> result
RouteTemplateHandler: TypeAlias = Callable[
[Request, Tuple[Any, ...], str], Any
]
BadArgumentsDict: TypeAlias = Mapping[str, str]
| from __future__ import annotations
from typing import Any, Callable, Dict, Iterable, Mapping, Tuple
from typing_extensions import TypeAlias
from werkzeug.wrappers import Request
# (name, value)
Header: TypeAlias = Tuple[str, str]
WSGIEnvironment: TypeAlias = Dict[str, Any]
# (body) -> None
StartResponseReturnType: TypeAlias = Callable[[bytes], object]
# (status: str, headers: List[Headers], exc_info) -> response
StartResponse: TypeAlias = Callable[..., StartResponseReturnType]
WSGIResponse: TypeAlias = Iterable[bytes]
WSGIApplication: TypeAlias = Callable[
[WSGIEnvironment, StartResponse], WSGIResponse
]
# (method, path, callback)
RouteDescription: TypeAlias = Tuple[str, str, WSGIApplication]
# (request, previous_args, path_part) -> result
RouteTemplateHandler: TypeAlias = Callable[
[Request, Tuple[Any, ...], str], Any
]
BadArgumentsDict: TypeAlias = Mapping[str, str]
| Fix imports on Python <= 3.8 | Fix imports on Python <= 3.8
| Python | mit | srittau/rouver | ---
+++
@@ -1,7 +1,6 @@
from __future__ import annotations
-from collections.abc import Iterable, Mapping
-from typing import Any, Callable, Dict, Tuple
+from typing import Any, Callable, Dict, Iterable, Mapping, Tuple
from typing_extensions import TypeAlias
from werkzeug.wrappers import Request |
5b87029e229fa3dcf0e81231899c36bd52a7616c | numpy/core/__init__.py | numpy/core/__init__.py |
from info import __doc__
from numpy.version import version as __version__
import multiarray
import umath
import numerictypes as nt
multiarray.set_typeDict(nt.sctypeDict)
import _sort
from numeric import *
from fromnumeric import *
from defmatrix import *
import ma
import defchararray as char
import records as rec
from records import *
from memmap import *
from defchararray import *
import scalarmath
del nt
from fromnumeric import amax as max, amin as min, \
round_ as round
from numeric import absolute as abs
__all__ = ['char','rec','memmap','ma']
__all__ += numeric.__all__
__all__ += fromnumeric.__all__
__all__ += defmatrix.__all__
__all__ += rec.__all__
__all__ += char.__all__
def test(level=1, verbosity=1):
from numpy.testing import NumpyTest
return NumpyTest().test(level, verbosity)
|
from info import __doc__
from numpy.version import version as __version__
import multiarray
import umath
import _internal # for freeze programs
import numerictypes as nt
multiarray.set_typeDict(nt.sctypeDict)
import _sort
from numeric import *
from fromnumeric import *
from defmatrix import *
import ma
import defchararray as char
import records as rec
from records import *
from memmap import *
from defchararray import *
import scalarmath
del nt
from fromnumeric import amax as max, amin as min, \
round_ as round
from numeric import absolute as abs
__all__ = ['char','rec','memmap','ma']
__all__ += numeric.__all__
__all__ += fromnumeric.__all__
__all__ += defmatrix.__all__
__all__ += rec.__all__
__all__ += char.__all__
def test(level=1, verbosity=1):
from numpy.testing import NumpyTest
return NumpyTest().test(level, verbosity)
| Add an dummy import statement so that freeze programs pick up _internal.p | Add an dummy import statement so that freeze programs pick up _internal.p
| Python | bsd-3-clause | dato-code/numpy,jorisvandenbossche/numpy,mathdd/numpy,stefanv/numpy,sinhrks/numpy,stuarteberg/numpy,rajathkumarmp/numpy,madphysicist/numpy,skwbc/numpy,rudimeier/numpy,abalkin/numpy,brandon-rhodes/numpy,Linkid/numpy,shoyer/numpy,pizzathief/numpy,rherault-insa/numpy,pbrod/numpy,mingwpy/numpy,MaPePeR/numpy,argriffing/numpy,hainm/numpy,empeeu/numpy,embray/numpy,CMartelLML/numpy,drasmuss/numpy,ahaldane/numpy,empeeu/numpy,jakirkham/numpy,sonnyhu/numpy,jakirkham/numpy,bertrand-l/numpy,BMJHayward/numpy,dato-code/numpy,gfyoung/numpy,dimasad/numpy,mindw/numpy,GaZ3ll3/numpy,has2k1/numpy,ajdawson/numpy,tynn/numpy,charris/numpy,Srisai85/numpy,ddasilva/numpy,BMJHayward/numpy,leifdenby/numpy,NextThought/pypy-numpy,Anwesh43/numpy,rhythmsosad/numpy,abalkin/numpy,dwillmer/numpy,tdsmith/numpy,has2k1/numpy,mingwpy/numpy,chatcannon/numpy,MSeifert04/numpy,SunghanKim/numpy,dwf/numpy,dimasad/numpy,pizzathief/numpy,has2k1/numpy,ChristopherHogan/numpy,chatcannon/numpy,astrofrog/numpy,numpy/numpy-refactor,MSeifert04/numpy,dwf/numpy,trankmichael/numpy,KaelChen/numpy,joferkington/numpy,trankmichael/numpy,BabeNovelty/numpy,GrimDerp/numpy,solarjoe/numpy,utke1/numpy,GrimDerp/numpy,njase/numpy,dch312/numpy,ewmoore/numpy,cjermain/numpy,bringingheavendown/numpy,musically-ut/numpy,nbeaver/numpy,skymanaditya1/numpy,ekalosak/numpy,rgommers/numpy,gmcastil/numpy,njase/numpy,rajathkumarmp/numpy,simongibbons/numpy,embray/numpy,felipebetancur/numpy,argriffing/numpy,mingwpy/numpy,jschueller/numpy,ahaldane/numpy,dch312/numpy,dwf/numpy,ESSS/numpy,MaPePeR/numpy,WarrenWeckesser/numpy,gfyoung/numpy,maniteja123/numpy,stuarteberg/numpy,ssanderson/numpy,solarjoe/numpy,SiccarPoint/numpy,mathdd/numpy,BabeNovelty/numpy,WillieMaddox/numpy,trankmichael/numpy,charris/numpy,ChristopherHogan/numpy,pdebuyl/numpy,ekalosak/numpy,MichaelAquilina/numpy,ewmoore/numpy,Dapid/numpy,ChanderG/numpy,musically-ut/numpy,pizzathief/numpy,mattip/numpy,anntzer/numpy,sinhrks/numpy,tdsmith/numpy,madphysicist/numpy,brandon-rhodes/numpy,mortada/numpy,Yusa95/numpy,Srisai85/numpy,naritta/numpy,SunghanKim/numpy,ChristopherHogan/numpy,endolith/numpy,ahaldane/numpy,ogrisel/numpy,nguyentu1602/numpy,ChristopherHogan/numpy,rhythmsosad/numpy,larsmans/numpy,SunghanKim/numpy,cjermain/numpy,rudimeier/numpy,empeeu/numpy,ssanderson/numpy,larsmans/numpy,jonathanunderwood/numpy,numpy/numpy-refactor,mortada/numpy,GrimDerp/numpy,tynn/numpy,dimasad/numpy,MichaelAquilina/numpy,shoyer/numpy,tynn/numpy,seberg/numpy,nbeaver/numpy,pdebuyl/numpy,bmorris3/numpy,gmcastil/numpy,MaPePeR/numpy,AustereCuriosity/numpy,ewmoore/numpy,mhvk/numpy,solarjoe/numpy,jorisvandenbossche/numpy,Yusa95/numpy,jorisvandenbossche/numpy,dch312/numpy,sigma-random/numpy,WarrenWeckesser/numpy,gmcastil/numpy,ESSS/numpy,rgommers/numpy,andsor/numpy,jorisvandenbossche/numpy,dwf/numpy,NextThought/pypy-numpy,shoyer/numpy,jankoslavic/numpy,WarrenWeckesser/numpy,embray/numpy,BMJHayward/numpy,ewmoore/numpy,chatcannon/numpy,Linkid/numpy,ogrisel/numpy,KaelChen/numpy,MSeifert04/numpy,madphysicist/numpy,mindw/numpy,KaelChen/numpy,yiakwy/numpy,rgommers/numpy,groutr/numpy,pizzathief/numpy,pbrod/numpy,kiwifb/numpy,tdsmith/numpy,immerrr/numpy,Dapid/numpy,bertrand-l/numpy,behzadnouri/numpy,sigma-random/numpy,groutr/numpy,GaZ3ll3/numpy,maniteja123/numpy,KaelChen/numpy,Eric89GXL/numpy,Dapid/numpy,endolith/numpy,pelson/numpy,embray/numpy,mhvk/numpy,SiccarPoint/numpy,simongibbons/numpy,grlee77/numpy,b-carter/numpy,CMartelLML/numpy,GaZ3ll3/numpy,moreati/numpy,ddasilva/numpy,BabeNovelty/numpy,mhvk/numpy,anntzer/numpy,dimasad/numpy,matthew-brett/numpy,Yusa95/numpy,pdebuyl/numpy,matthew-brett/numpy,matthew-brett/numpy,sigma-random/numpy,moreati/numpy,simongibbons/numpy,gfyoung/numpy,ogrisel/numpy,hainm/numpy,rudimeier/numpy,behzadnouri/numpy,charris/numpy,tacaswell/numpy,kirillzhuravlev/numpy,ChanderG/numpy,brandon-rhodes/numpy,githubmlai/numpy,naritta/numpy,skymanaditya1/numpy,argriffing/numpy,githubmlai/numpy,BMJHayward/numpy,kirillzhuravlev/numpy,githubmlai/numpy,chiffa/numpy,nguyentu1602/numpy,skwbc/numpy,nbeaver/numpy,abalkin/numpy,matthew-brett/numpy,astrofrog/numpy,ContinuumIO/numpy,mindw/numpy,joferkington/numpy,rmcgibbo/numpy,mindw/numpy,chiffa/numpy,matthew-brett/numpy,nguyentu1602/numpy,bmorris3/numpy,andsor/numpy,bmorris3/numpy,bringingheavendown/numpy,pyparallel/numpy,cjermain/numpy,felipebetancur/numpy,yiakwy/numpy,sonnyhu/numpy,drasmuss/numpy,musically-ut/numpy,mattip/numpy,bringingheavendown/numpy,rmcgibbo/numpy,trankmichael/numpy,endolith/numpy,numpy/numpy,stuarteberg/numpy,cowlicks/numpy,dwillmer/numpy,b-carter/numpy,astrofrog/numpy,mortada/numpy,rhythmsosad/numpy,ViralLeadership/numpy,ChanderG/numpy,Srisai85/numpy,skwbc/numpy,jankoslavic/numpy,CMartelLML/numpy,njase/numpy,dwillmer/numpy,pyparallel/numpy,cjermain/numpy,pyparallel/numpy,grlee77/numpy,jonathanunderwood/numpy,mattip/numpy,jankoslavic/numpy,WarrenWeckesser/numpy,GaZ3ll3/numpy,ChanderG/numpy,leifdenby/numpy,rherault-insa/numpy,AustereCuriosity/numpy,seberg/numpy,ogrisel/numpy,ajdawson/numpy,jschueller/numpy,madphysicist/numpy,numpy/numpy-refactor,bertrand-l/numpy,stuarteberg/numpy,shoyer/numpy,cowlicks/numpy,sinhrks/numpy,immerrr/numpy,pelson/numpy,rgommers/numpy,drasmuss/numpy,mathdd/numpy,kiwifb/numpy,shoyer/numpy,musically-ut/numpy,ContinuumIO/numpy,utke1/numpy,simongibbons/numpy,tdsmith/numpy,pelson/numpy,Yusa95/numpy,immerrr/numpy,seberg/numpy,mwiebe/numpy,hainm/numpy,astrofrog/numpy,Srisai85/numpy,MichaelAquilina/numpy,kirillzhuravlev/numpy,rhythmsosad/numpy,numpy/numpy,WarrenWeckesser/numpy,numpy/numpy-refactor,moreati/numpy,cowlicks/numpy,MSeifert04/numpy,stefanv/numpy,anntzer/numpy,jakirkham/numpy,tacaswell/numpy,ContinuumIO/numpy,dato-code/numpy,rherault-insa/numpy,githubmlai/numpy,yiakwy/numpy,kirillzhuravlev/numpy,ajdawson/numpy,jankoslavic/numpy,embray/numpy,pelson/numpy,pbrod/numpy,skymanaditya1/numpy,rmcgibbo/numpy,tacaswell/numpy,NextThought/pypy-numpy,bmorris3/numpy,Anwesh43/numpy,cowlicks/numpy,seberg/numpy,immerrr/numpy,Anwesh43/numpy,b-carter/numpy,Eric89GXL/numpy,madphysicist/numpy,andsor/numpy,ViralLeadership/numpy,kiwifb/numpy,mingwpy/numpy,anntzer/numpy,chiffa/numpy,AustereCuriosity/numpy,sinhrks/numpy,numpy/numpy,WillieMaddox/numpy,pelson/numpy,yiakwy/numpy,skymanaditya1/numpy,Eric89GXL/numpy,MSeifert04/numpy,ogrisel/numpy,ddasilva/numpy,rajathkumarmp/numpy,endolith/numpy,mwiebe/numpy,ekalosak/numpy,grlee77/numpy,simongibbons/numpy,utke1/numpy,sigma-random/numpy,WillieMaddox/numpy,stefanv/numpy,SunghanKim/numpy,jonathanunderwood/numpy,sonnyhu/numpy,Anwesh43/numpy,stefanv/numpy,rajathkumarmp/numpy,has2k1/numpy,groutr/numpy,ssanderson/numpy,empeeu/numpy,felipebetancur/numpy,nguyentu1602/numpy,dwillmer/numpy,jakirkham/numpy,joferkington/numpy,mhvk/numpy,ViralLeadership/numpy,Linkid/numpy,GrimDerp/numpy,Eric89GXL/numpy,dch312/numpy,astrofrog/numpy,grlee77/numpy,mortada/numpy,jschueller/numpy,BabeNovelty/numpy,ahaldane/numpy,hainm/numpy,Linkid/numpy,dwf/numpy,pbrod/numpy,numpy/numpy,brandon-rhodes/numpy,ahaldane/numpy,mhvk/numpy,dato-code/numpy,naritta/numpy,NextThought/pypy-numpy,ekalosak/numpy,CMartelLML/numpy,SiccarPoint/numpy,andsor/numpy,leifdenby/numpy,SiccarPoint/numpy,ESSS/numpy,jakirkham/numpy,pbrod/numpy,sonnyhu/numpy,stefanv/numpy,jorisvandenbossche/numpy,mwiebe/numpy,charris/numpy,MichaelAquilina/numpy,pdebuyl/numpy,larsmans/numpy,mathdd/numpy,maniteja123/numpy,pizzathief/numpy,numpy/numpy-refactor,larsmans/numpy,MaPePeR/numpy,grlee77/numpy,rmcgibbo/numpy,mattip/numpy,ajdawson/numpy,rudimeier/numpy,felipebetancur/numpy,behzadnouri/numpy,joferkington/numpy,ewmoore/numpy,naritta/numpy,jschueller/numpy | ---
+++
@@ -4,6 +4,7 @@
import multiarray
import umath
+import _internal # for freeze programs
import numerictypes as nt
multiarray.set_typeDict(nt.sctypeDict)
import _sort |
389fd283c0e05a7c3ccdc871b2423a1d0f3b2280 | stack/cluster.py | stack/cluster.py | from troposphere import (
Parameter,
Ref,
)
from troposphere.ecs import (
Cluster,
)
from .template import template
container_instance_type = Ref(template.add_parameter(Parameter(
"ContainerInstanceType",
Description="The container instance type",
Type="String",
Default="t2.micro",
AllowedValues=["t2.micro", "t2.small", "t2.medium"]
)))
# ECS cluster
cluster = Cluster(
"Cluster",
template=template,
)
| from troposphere import (
Parameter,
Ref,
)
from troposphere.ecs import (
Cluster,
)
from .template import template
container_instance_type = Ref(template.add_parameter(Parameter(
"ContainerInstanceType",
Description="The container instance type",
Type="String",
Default="t2.micro",
AllowedValues=["t2.micro", "t2.small", "t2.medium"]
)))
template.add_mapping("ECSRegionMap", {
"eu-west-1": {"AMI": "ami-4e6ffe3d"},
"us-east-1": {"AMI": "ami-8f7687e2"},
"us-west-2": {"AMI": "ami-84b44de4"},
})
# ECS cluster
cluster = Cluster(
"Cluster",
template=template,
)
| Add a `ECS` ami ids as a region mapping | Add a `ECS` ami ids as a region mapping
| Python | mit | tobiasmcnulty/aws-container-basics,caktus/aws-web-stacks | ---
+++
@@ -19,6 +19,13 @@
)))
+template.add_mapping("ECSRegionMap", {
+ "eu-west-1": {"AMI": "ami-4e6ffe3d"},
+ "us-east-1": {"AMI": "ami-8f7687e2"},
+ "us-west-2": {"AMI": "ami-84b44de4"},
+})
+
+
# ECS cluster
cluster = Cluster(
"Cluster", |
56300ddbac1a47f9b2c9f7946c8810e55e19bb07 | Code/Native/update_module_builder.py | Code/Native/update_module_builder.py | """
This script downloads and updates the module builder.
"""
# Dont checkout all files
IGNORE_FILES = [
"__init__.py",
".gitignore",
"LICENSE",
"README.md",
"config.ini",
"Source/config_module.cpp",
"Source/config_module.h",
"Source/ExampleClass.cpp",
"Source/ExampleClass.h",
"Source/ExampleClass.I",
]
import sys
import os
sys.path.insert(0, "../../")
from Code.Util.SubmoduleDownloader import SubmoduleDownloader
if __name__ == "__main__":
curr_dir = os.path.dirname(os.path.realpath(__file__))
SubmoduleDownloader.download_submodule("tobspr", "P3DModuleBuilder", curr_dir, IGNORE_FILES)
| """
This script downloads and updates the module builder.
"""
# Dont checkout all files
IGNORE_FILES = [
"__init__.py",
".gitignore",
"LICENSE",
"README.md",
"config.ini",
"Source/config_module.cpp",
"Source/config_module.h",
"Source/ExampleClass.cpp",
"Source/ExampleClass.h",
"Source/ExampleClass.I",
]
import sys
import os
sys.path.insert(0, "../../")
from Code.Util.SubmoduleDownloader import SubmoduleDownloader
if __name__ == "__main__":
curr_dir = os.path.dirname(os.path.realpath(__file__))
SubmoduleDownloader.download_submodule("tobspr", "P3DModuleBuilder", curr_dir, IGNORE_FILES)
# Make the init file at the Scripts directory
with open(os.path.join(curr_dir, "Scripts/__init__.py"), "w") as handle:
pass
| Fix missing __init__ in native directory | Fix missing __init__ in native directory
| Python | mit | eswartz/RenderPipeline,eswartz/RenderPipeline,eswartz/RenderPipeline | ---
+++
@@ -27,3 +27,7 @@
if __name__ == "__main__":
curr_dir = os.path.dirname(os.path.realpath(__file__))
SubmoduleDownloader.download_submodule("tobspr", "P3DModuleBuilder", curr_dir, IGNORE_FILES)
+
+ # Make the init file at the Scripts directory
+ with open(os.path.join(curr_dir, "Scripts/__init__.py"), "w") as handle:
+ pass |
716f6d2f8ed4e2845746bcb803092806dd8f50b7 | tx_salaries/utils/transformers/mixins.py | tx_salaries/utils/transformers/mixins.py | class OrganizationMixin(object):
"""
Adds a generic ``organization`` property to the class
This requires that the class mixing it in adds an
``ORGANIZATION_NAME`` property of the main level agency or
department.
"""
@property
def organization(self):
return {
'name': self.ORGANIZATION_NAME,
'children': [{
'name': unicode(self.department),
}],
}
| class OrganizationMixin(object):
"""
Adds a generic ``organization`` property to the class
This requires that the class mixing it in adds an
``ORGANIZATION_NAME`` property of the main level agency or
department and needs a ``department`` property.
"""
@property
def organization(self):
return {
'name': self.ORGANIZATION_NAME,
'children': [{
'name': unicode(self.department),
}],
}
| Tweak the wording just a bit | Tweak the wording just a bit
| Python | apache-2.0 | texastribune/tx_salaries,texastribune/tx_salaries | ---
+++
@@ -4,7 +4,7 @@
This requires that the class mixing it in adds an
``ORGANIZATION_NAME`` property of the main level agency or
- department.
+ department and needs a ``department`` property.
"""
@property
def organization(self): |
83361d2e5cd1cbada31da7350c653133ae9a185f | typhon/spareice/collocations/__init__.py | typhon/spareice/collocations/__init__.py | """
This module contains classes to find collocations between datasets. They are
inspired by the implemented CollocatedDataset classes in atmlab written by
Gerrit Holl.
TODO: I would like to have this package as typhon.collocations.
Created by John Mrziglod, June 2017
"""
from .common import * # noqa
__all__ = [
"CollocatedDataset",
"NotCollapsedError",
] | Divide collocations package into submodules | Divide collocations package into submodules
| Python | mit | atmtools/typhon,atmtools/typhon | ---
+++
@@ -0,0 +1,16 @@
+"""
+This module contains classes to find collocations between datasets. They are
+inspired by the implemented CollocatedDataset classes in atmlab written by
+Gerrit Holl.
+
+TODO: I would like to have this package as typhon.collocations.
+
+Created by John Mrziglod, June 2017
+"""
+
+from .common import * # noqa
+
+__all__ = [
+ "CollocatedDataset",
+ "NotCollapsedError",
+] | |
7b4b5bc95f0a498ab83422192410f9213bfdb251 | praw/models/listing/mixins/submission.py | praw/models/listing/mixins/submission.py | """Provide the SubmissionListingMixin class."""
from ....const import API_PATH
from ..generator import ListingGenerator
from .base import BaseListingMixin
from .gilded import GildedListingMixin
class SubmissionListingMixin(BaseListingMixin, GildedListingMixin):
"""Adds additional methods pertaining to Submission instances."""
def duplicates(self, **generator_kwargs):
"""Return a ListingGenerator for the submission's duplicates.
Additional keyword arguments are passed in the initialization of
:class:`.ListingGenerator`.
"""
url = API_PATH['duplicates'].format(submission_id=self.id)
return ListingGenerator(self._reddit, url, **generator_kwargs)
| """Provide the SubmissionListingMixin class."""
from ....const import API_PATH
from ..generator import ListingGenerator
from .gilded import GildedListingMixin
class SubmissionListingMixin(GildedListingMixin):
"""Adds additional methods pertaining to Submission instances."""
def duplicates(self, **generator_kwargs):
"""Return a ListingGenerator for the submission's duplicates.
Additional keyword arguments are passed in the initialization of
:class:`.ListingGenerator`.
"""
url = API_PATH['duplicates'].format(submission_id=self.id)
return ListingGenerator(self._reddit, url, **generator_kwargs)
| Remove BaseListingMixin as superclass for SubmissionListingMixin | Remove BaseListingMixin as superclass for SubmissionListingMixin
| Python | bsd-2-clause | darthkedrik/praw,leviroth/praw,praw-dev/praw,gschizas/praw,13steinj/praw,nmtake/praw,13steinj/praw,gschizas/praw,nmtake/praw,praw-dev/praw,darthkedrik/praw,leviroth/praw | ---
+++
@@ -1,11 +1,10 @@
"""Provide the SubmissionListingMixin class."""
from ....const import API_PATH
from ..generator import ListingGenerator
-from .base import BaseListingMixin
from .gilded import GildedListingMixin
-class SubmissionListingMixin(BaseListingMixin, GildedListingMixin):
+class SubmissionListingMixin(GildedListingMixin):
"""Adds additional methods pertaining to Submission instances."""
def duplicates(self, **generator_kwargs): |
27360cf049446c5a619b7280dbdd7c3f49c45ad8 | app/questionnaire_state/answer.py | app/questionnaire_state/answer.py | from app.questionnaire_state.item import Item
class Answer(Item):
def __init__(self, id):
super().__init__(id=id)
# typed value
self.value = None
# actual user input
self.input = None
def update_state(self, user_input, schema_item):
if self.id in user_input.keys():
self.input = user_input[self.id]
if schema_item:
try:
# Do we have the item or it's containing block?
if schema_item.id != self.id:
schema_item = schema_item.questionnaire.get_item_by_id(self.id)
# Mandatory check
if self.input:
self.value = schema_item.get_typed_value(user_input)
self.is_valid = True
elif schema_item.mandatory:
self.errors = []
self.errors.append(schema_item.questionnaire.get_error_message('MANDATORY', schema_item.id))
self.is_valid = False
except Exception as e:
self.value = None
# @TODO: Need to look again at this interface when we come to warnings
self.errors = []
self.errors.append(schema_item.questionnaire.get_error_message(str(e), schema_item.id))
self.is_valid = False
def get_answers(self):
return [self]
| from app.questionnaire_state.item import Item
class Answer(Item):
def __init__(self, id):
super().__init__(id=id)
# typed value
self.value = None
# actual user input
self.input = None
def update_state(self, user_input, schema_item):
if self.id in user_input.keys():
self.input = user_input[self.id]
if schema_item:
try:
# Do we have the item or it's containing block?
if schema_item.id != self.id:
schema_item = schema_item.questionnaire.get_item_by_id(self.id)
# Mandatory check
if self.input:
self.value = schema_item.get_typed_value(user_input)
self.is_valid = True
self.errors = None
self.warnings = None
elif schema_item.mandatory:
self.errors = []
self.errors.append(schema_item.questionnaire.get_error_message('MANDATORY', schema_item.id))
self.is_valid = False
except Exception as e:
self.value = None
# @TODO: Need to look again at this interface when we come to warnings
self.errors = []
self.errors.append(schema_item.questionnaire.get_error_message(str(e), schema_item.id))
self.is_valid = False
def get_answers(self):
return [self]
| Clear warnings and errors when type checking passes | Clear warnings and errors when type checking passes
| Python | mit | ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner | ---
+++
@@ -22,6 +22,8 @@
if self.input:
self.value = schema_item.get_typed_value(user_input)
self.is_valid = True
+ self.errors = None
+ self.warnings = None
elif schema_item.mandatory:
self.errors = []
self.errors.append(schema_item.questionnaire.get_error_message('MANDATORY', schema_item.id)) |
af0f80d2385001b52560cb0ec9d31e85c4a891bf | mopidy/frontends/mpd/__init__.py | mopidy/frontends/mpd/__init__.py | import logging
from mopidy.frontends.base import BaseFrontend
from mopidy.frontends.mpd.dispatcher import MpdDispatcher
from mopidy.frontends.mpd.thread import MpdThread
from mopidy.utils.process import unpickle_connection
logger = logging.getLogger('mopidy.frontends.mpd')
class MpdFrontend(BaseFrontend):
"""
The MPD frontend.
**Settings:**
- :attr:`mopidy.settings.MPD_SERVER_HOSTNAME`
- :attr:`mopidy.settings.MPD_SERVER_PORT`
"""
def __init__(self, *args, **kwargs):
super(MpdFrontend, self).__init__(*args, **kwargs)
self.thread = None
self.dispatcher = MpdDispatcher(self.backend)
def start(self):
"""Starts the MPD server."""
self.thread = MpdThread(self.core_queue)
self.thread.start()
def destroy(self):
"""Destroys the MPD server."""
self.thread.destroy()
def process_message(self, message):
"""
Processes messages with the MPD frontend as destination.
:param message: the message
:type message: dict
"""
assert message['to'] == 'frontend', \
u'Message recipient must be "frontend".'
if message['command'] == 'mpd_request':
response = self.dispatcher.handle_request(message['request'])
connection = unpickle_connection(message['reply_to'])
connection.send(response)
else:
pass # Ignore messages for other frontends
| import logging
from mopidy.frontends.base import BaseFrontend
from mopidy.frontends.mpd.dispatcher import MpdDispatcher
from mopidy.frontends.mpd.thread import MpdThread
from mopidy.utils.process import unpickle_connection
logger = logging.getLogger('mopidy.frontends.mpd')
class MpdFrontend(BaseFrontend):
"""
The MPD frontend.
**Settings:**
- :attr:`mopidy.settings.MPD_SERVER_HOSTNAME`
- :attr:`mopidy.settings.MPD_SERVER_PASSWORD`
- :attr:`mopidy.settings.MPD_SERVER_PORT`
"""
def __init__(self, *args, **kwargs):
super(MpdFrontend, self).__init__(*args, **kwargs)
self.thread = None
self.dispatcher = MpdDispatcher(self.backend)
def start(self):
"""Starts the MPD server."""
self.thread = MpdThread(self.core_queue)
self.thread.start()
def destroy(self):
"""Destroys the MPD server."""
self.thread.destroy()
def process_message(self, message):
"""
Processes messages with the MPD frontend as destination.
:param message: the message
:type message: dict
"""
assert message['to'] == 'frontend', \
u'Message recipient must be "frontend".'
if message['command'] == 'mpd_request':
response = self.dispatcher.handle_request(message['request'])
connection = unpickle_connection(message['reply_to'])
connection.send(response)
else:
pass # Ignore messages for other frontends
| Add MPD_SERVER_PASSWORD to list of relevant frontend settings | Add MPD_SERVER_PASSWORD to list of relevant frontend settings
| Python | apache-2.0 | ali/mopidy,quartz55/mopidy,priestd09/mopidy,rawdlite/mopidy,quartz55/mopidy,vrs01/mopidy,mokieyue/mopidy,mopidy/mopidy,jcass77/mopidy,pacificIT/mopidy,bencevans/mopidy,ali/mopidy,hkariti/mopidy,bencevans/mopidy,pacificIT/mopidy,kingosticks/mopidy,jcass77/mopidy,quartz55/mopidy,jodal/mopidy,glogiotatidis/mopidy,diandiankan/mopidy,rawdlite/mopidy,glogiotatidis/mopidy,swak/mopidy,jcass77/mopidy,abarisain/mopidy,liamw9534/mopidy,jmarsik/mopidy,rawdlite/mopidy,diandiankan/mopidy,kingosticks/mopidy,vrs01/mopidy,dbrgn/mopidy,bacontext/mopidy,pacificIT/mopidy,woutervanwijk/mopidy,tkem/mopidy,bacontext/mopidy,mokieyue/mopidy,bacontext/mopidy,tkem/mopidy,kingosticks/mopidy,swak/mopidy,SuperStarPL/mopidy,bencevans/mopidy,SuperStarPL/mopidy,priestd09/mopidy,jmarsik/mopidy,dbrgn/mopidy,liamw9534/mopidy,abarisain/mopidy,mokieyue/mopidy,dbrgn/mopidy,adamcik/mopidy,ZenithDK/mopidy,jodal/mopidy,ZenithDK/mopidy,ali/mopidy,bencevans/mopidy,ZenithDK/mopidy,jodal/mopidy,hkariti/mopidy,dbrgn/mopidy,vrs01/mopidy,glogiotatidis/mopidy,swak/mopidy,mopidy/mopidy,mopidy/mopidy,hkariti/mopidy,pacificIT/mopidy,swak/mopidy,adamcik/mopidy,glogiotatidis/mopidy,diandiankan/mopidy,vrs01/mopidy,diandiankan/mopidy,jmarsik/mopidy,SuperStarPL/mopidy,ali/mopidy,bacontext/mopidy,woutervanwijk/mopidy,mokieyue/mopidy,rawdlite/mopidy,quartz55/mopidy,ZenithDK/mopidy,tkem/mopidy,tkem/mopidy,SuperStarPL/mopidy,adamcik/mopidy,hkariti/mopidy,priestd09/mopidy,jmarsik/mopidy | ---
+++
@@ -14,6 +14,7 @@
**Settings:**
- :attr:`mopidy.settings.MPD_SERVER_HOSTNAME`
+ - :attr:`mopidy.settings.MPD_SERVER_PASSWORD`
- :attr:`mopidy.settings.MPD_SERVER_PORT`
"""
|
a7bea68d4e904a27c53d08d37093ac5ed2c033f0 | utilities/StartPages.py | utilities/StartPages.py | #--coding:utf-8--
#StartPage.py
#Create/Edit file:'../cfg/StartPage.json'
import os
import re
import sys
import json
from __common__code__ import CreateFile
from __tmpl__ import Prompt
class PromptClass(Prompt.ErrPrompt):
def InitInput(self):
print ("Please input URL(s), use EOF to finish. \n(CTRL+D. if not work for Windows, try CTRL+Z)")
def main():
prompt = PromptClass()
cfgfile = CreateFile('StartPage.json', 'cfg', TransferredMeaning = True, Prompt = True)
URL = []
IllegalChars = r"[^ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\-\.\_\~\:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=]"
try:
prompt.InitInput()
while True:
tmp = raw_input()
if re.search(IllegalChars, tmp):
prompt.IllegalURL()
URL.append(tmp)
except EOFError:
prompt.Exit()
json.dump(URL, cfgfile)
cfgfile.close()
return
if __name__ == '__main__':
main()
else:
raise EnvironmentError("Please do not import this script as a module!")
| #--coding:utf-8--
#StartPage.py
#Create/Edit file:'../cfg/StartPage.json'
import re
import sys
import json
from __common__code__ import CreateFile
from __tmpl__ import Prompt
class PromptClass(Prompt.ErrPrompt):
def InitInput(self):
print ("Please input URL(s), use EOF to finish. \n(CTRL+D. if not work for Windows, try CTRL+Z)")
def main():
prompt = PromptClass()
cfgfile = CreateFile('StartPage.json', 'cfg', TransferredMeaning = True, Prompt = True)
if not cfgfile:
prompt.Exit()
sys.exit(False)
URL = []
IllegalChars = r"[^ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\-\.\_\~\:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=]"
try:
prompt.InitInput()
while True:
tmp = raw_input()
if re.search(IllegalChars, tmp):
prompt.IllegalURL()
URL.append(tmp)
except EOFError:
prompt.Exit()
json.dump(URL, cfgfile)
cfgfile.close()
return
if __name__ == '__main__':
main()
else:
raise EnvironmentError("Please do not import this script as a module!")
| Fix bug: continue running when fail to open file | Fix bug: continue running when fail to open file
| Python | mit | nday-dev/Spider-Framework | ---
+++
@@ -1,7 +1,6 @@
#--coding:utf-8--
#StartPage.py
#Create/Edit file:'../cfg/StartPage.json'
-import os
import re
import sys
import json
@@ -15,6 +14,9 @@
def main():
prompt = PromptClass()
cfgfile = CreateFile('StartPage.json', 'cfg', TransferredMeaning = True, Prompt = True)
+ if not cfgfile:
+ prompt.Exit()
+ sys.exit(False)
URL = []
IllegalChars = r"[^ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\-\.\_\~\:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=]"
try: |
c136ee96237a05cb717c777dd33b9a3dff9b0015 | test/test_py3.py | test/test_py3.py | import pytest
from in_place import InPlace
from test_in_place_util import UNICODE, pylistdir
def test_py3_textstr(tmpdir):
""" Assert that `InPlace` works with text strings in Python 3 """
assert pylistdir(tmpdir) == []
p = tmpdir.join("file.txt")
p.write_text(UNICODE, 'utf-8')
with InPlace(str(p)) as fp:
txt = fp.read()
assert isinstance(txt, str)
assert txt == UNICODE
print(UNICODE, file=fp)
assert pylistdir(tmpdir) == ['file.txt']
assert p.read_text('utf-8') == UNICODE + '\n'
def test_py3_not_bytestr(tmpdir):
""" Assert that `InPlace` does not work with byte strings in Python 3 """
assert pylistdir(tmpdir) == []
p = tmpdir.join("file.txt")
p.write_text(UNICODE, 'utf-8')
with InPlace(str(p)) as fp:
txt = fp.read()
assert isinstance(txt, str)
assert txt == UNICODE
txt = txt.encode('utf-8')
with pytest.raises(TypeError):
# `print()` would stringify `txt` to `b'...'`, which is not what we
# want.
fp.write(txt)
| import locale
import pytest
from in_place import InPlace
from test_in_place_util import UNICODE, pylistdir
def test_py3_textstr(tmpdir):
""" Assert that `InPlace` works with text strings in Python 3 """
assert pylistdir(tmpdir) == []
p = tmpdir.join("file.txt")
p.write_text(UNICODE, locale.getpreferredencoding())
with InPlace(str(p)) as fp:
txt = fp.read()
assert isinstance(txt, str)
assert txt == UNICODE
print(UNICODE, file=fp)
assert pylistdir(tmpdir) == ['file.txt']
assert p.read_text(locale.getpreferredencoding()) == UNICODE + '\n'
def test_py3_not_bytestr(tmpdir):
""" Assert that `InPlace` does not work with byte strings in Python 3 """
assert pylistdir(tmpdir) == []
p = tmpdir.join("file.txt")
p.write_text(UNICODE, locale.getpreferredencoding())
with InPlace(str(p)) as fp:
txt = fp.read()
assert isinstance(txt, str)
assert txt == UNICODE
txt = txt.encode('utf-8')
with pytest.raises(TypeError):
# `print()` would stringify `txt` to `b'...'`, which is not what we
# want.
fp.write(txt)
| Handle different default encoding on Windows in tests | Handle different default encoding on Windows in tests
| Python | mit | jwodder/inplace | ---
+++
@@ -1,3 +1,4 @@
+import locale
import pytest
from in_place import InPlace
from test_in_place_util import UNICODE, pylistdir
@@ -6,20 +7,20 @@
""" Assert that `InPlace` works with text strings in Python 3 """
assert pylistdir(tmpdir) == []
p = tmpdir.join("file.txt")
- p.write_text(UNICODE, 'utf-8')
+ p.write_text(UNICODE, locale.getpreferredencoding())
with InPlace(str(p)) as fp:
txt = fp.read()
assert isinstance(txt, str)
assert txt == UNICODE
print(UNICODE, file=fp)
assert pylistdir(tmpdir) == ['file.txt']
- assert p.read_text('utf-8') == UNICODE + '\n'
+ assert p.read_text(locale.getpreferredencoding()) == UNICODE + '\n'
def test_py3_not_bytestr(tmpdir):
""" Assert that `InPlace` does not work with byte strings in Python 3 """
assert pylistdir(tmpdir) == []
p = tmpdir.join("file.txt")
- p.write_text(UNICODE, 'utf-8')
+ p.write_text(UNICODE, locale.getpreferredencoding())
with InPlace(str(p)) as fp:
txt = fp.read()
assert isinstance(txt, str) |
f5ace7ea8badb2401190e4845fb0216c7a80891e | tests/testall.py | tests/testall.py | #!/usr/bin/env python
import unittest, os, sys
try:
import coverage
coverage.erase()
coverage.start()
except ImportError:
coverage = None
my_dir = os.path.dirname(sys.argv[0])
if not my_dir:
my_dir = os.getcwd()
sys.argv.append('-v')
suite_names = [f[:-3] for f in os.listdir(my_dir)
if f.startswith('test') and f.endswith('.py')]
suite_names.remove('testall')
suite_names.sort()
alltests = unittest.TestSuite()
for name in suite_names:
m = __import__(name, globals(), locals(), [])
alltests.addTest(m.suite)
a = unittest.TextTestRunner(verbosity=2).run(alltests)
if coverage:
coverage.stop()
else:
print "Coverage module not found. Skipping coverage report."
print "\nResult", a
if not a.wasSuccessful():
sys.exit(1)
if coverage:
all_sources = []
def incl(d):
for x in os.listdir(d):
if x.endswith('.py'):
all_sources.append(os.path.join(d, x))
incl('..')
coverage.report(all_sources + ['../0publish'])
| #!/usr/bin/env python
import unittest, os, sys
try:
import coverage
coverage.erase()
coverage.start()
except ImportError:
coverage = None
my_dir = os.path.dirname(sys.argv[0])
if not my_dir:
my_dir = os.getcwd()
testLoader = unittest.TestLoader()
if len(sys.argv) > 1:
alltests = testLoader.loadTestsFromNames(sys.argv[1:])
else:
alltests = unittest.TestSuite()
suite_names = [f[:-3] for f in os.listdir(my_dir)
if f.startswith('test') and f.endswith('.py')]
suite_names.remove('testall')
suite_names.sort()
for name in suite_names:
m = __import__(name, globals(), locals(), [])
t = testLoader.loadTestsFromModule(m)
alltests.addTest(t)
a = unittest.TextTestRunner(verbosity=2).run(alltests)
if coverage:
coverage.stop()
else:
print "Coverage module not found. Skipping coverage report."
print "\nResult", a
if not a.wasSuccessful():
sys.exit(1)
if coverage:
all_sources = []
def incl(d):
for x in os.listdir(d):
if x.endswith('.py'):
all_sources.append(os.path.join(d, x))
incl('..')
coverage.report(all_sources + ['../0publish'])
| Allow specifying which unit-tests to run | Allow specifying which unit-tests to run
e.g. 0test ../0release.xml -- testrelease.TestRelease.testBinaryRelease
| Python | lgpl-2.1 | timbertson/0release,0install/0release,0install/0release,gfxmonk/0release | ---
+++
@@ -11,18 +11,22 @@
if not my_dir:
my_dir = os.getcwd()
-sys.argv.append('-v')
+testLoader = unittest.TestLoader()
-suite_names = [f[:-3] for f in os.listdir(my_dir)
- if f.startswith('test') and f.endswith('.py')]
-suite_names.remove('testall')
-suite_names.sort()
+if len(sys.argv) > 1:
+ alltests = testLoader.loadTestsFromNames(sys.argv[1:])
+else:
+ alltests = unittest.TestSuite()
-alltests = unittest.TestSuite()
+ suite_names = [f[:-3] for f in os.listdir(my_dir)
+ if f.startswith('test') and f.endswith('.py')]
+ suite_names.remove('testall')
+ suite_names.sort()
-for name in suite_names:
- m = __import__(name, globals(), locals(), [])
- alltests.addTest(m.suite)
+ for name in suite_names:
+ m = __import__(name, globals(), locals(), [])
+ t = testLoader.loadTestsFromModule(m)
+ alltests.addTest(t)
a = unittest.TextTestRunner(verbosity=2).run(alltests)
|
d190e4466a28714bf0e04869dc11a940526031b1 | fullcalendar/templatetags/fullcalendar.py | fullcalendar/templatetags/fullcalendar.py | from django import template
from fullcalendar.models import Occurrence
register = template.Library()
@register.inclusion_tag('events/agenda_tag.html')
def show_agenda(*args, **kwargs):
qs = Occurrence.objects.upcoming()
if 'limit' in kwargs:
qs.limit(int(kwargs['limit']))
return {
'occurrences': qs,
'all_sites': True,
}
@register.assignment_tag
def get_agenda(*args, **kwargs):
qs = Occurrence.site_related.upcoming()
if 'limit' in kwargs:
qs.limit(int(kwargs['limit']))
return qs
@register.inclusion_tag('events/agenda_tag.html')
def show_site_agenda(*args, **kwargs):
qs = Occurrence.site_related.upcoming()
if 'limit' in kwargs:
qs.limit(int(kwargs['limit']))
return {
'occurrences': qs
}
@register.assignment_tag
def get_site_agenda(*args, **kwargs):
qs = Occurrence.site_related.upcoming()
if 'limit' in kwargs:
qs.limit(int(kwargs['limit']))
return qs
| from django import template
from fullcalendar.models import Occurrence
register = template.Library()
@register.inclusion_tag('events/agenda_tag.html')
def show_agenda(*args, **kwargs):
qs = Occurrence.objects.upcoming()
if 'limit' in kwargs:
qs = qs[:int(kwargs['limit'])]
return {
'occurrences': qs,
'all_sites': True,
}
@register.assignment_tag
def get_agenda(*args, **kwargs):
qs = Occurrence.site_related.upcoming()
if 'limit' in kwargs:
return qs[:int(kwargs['limit'])]
return qs
@register.inclusion_tag('events/agenda_tag.html')
def show_site_agenda(*args, **kwargs):
qs = Occurrence.site_related.upcoming()
if 'limit' in kwargs:
qs = qs[:int(kwargs['limit'])]
return {
'occurrences': qs
}
@register.assignment_tag
def get_site_agenda(*args, **kwargs):
qs = Occurrence.site_related.upcoming()
if 'limit' in kwargs:
return qs[:int(kwargs['limit'])]
return qs
| Use the right way to limit queries | Use the right way to limit queries
| Python | mit | jonge-democraten/mezzanine-fullcalendar | ---
+++
@@ -9,7 +9,7 @@
qs = Occurrence.objects.upcoming()
if 'limit' in kwargs:
- qs.limit(int(kwargs['limit']))
+ qs = qs[:int(kwargs['limit'])]
return {
'occurrences': qs,
@@ -21,17 +21,16 @@
qs = Occurrence.site_related.upcoming()
if 'limit' in kwargs:
- qs.limit(int(kwargs['limit']))
+ return qs[:int(kwargs['limit'])]
return qs
-
@register.inclusion_tag('events/agenda_tag.html')
def show_site_agenda(*args, **kwargs):
qs = Occurrence.site_related.upcoming()
if 'limit' in kwargs:
- qs.limit(int(kwargs['limit']))
+ qs = qs[:int(kwargs['limit'])]
return {
'occurrences': qs
@@ -42,7 +41,7 @@
qs = Occurrence.site_related.upcoming()
if 'limit' in kwargs:
- qs.limit(int(kwargs['limit']))
+ return qs[:int(kwargs['limit'])]
return qs
|
3a70e339637285355e594f9bec15481eae631a63 | ibmcnx/config/j2ee/RoleBackup.py | ibmcnx/config/j2ee/RoleBackup.py | ######
# Create a backup of J2EE Security Roles
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
#
import sys
import os
import ibmcnx.functions
# Only load commands if not initialized directly (call from menu)
if __name__ == "__main__":
execfile("ibmcnx/loadCnxApps.py")
path = raw_input( "Please provide a path for your backup files: " )
ibmcnx.functions.checkBackupPath( path )
apps = AdminApp.list()
appsList = apps.splitlines()
for app in appsList:
filename = path + "/" + app + ".txt"
print "Backup of %(1)s security roles saved to %(2)s." % { "1" : app.upper(), "2": filename}
my_file = open( filename, 'w' )
my_file.write ( AdminApp.view( app, "-MapRolesToUsers" ) )
my_file.flush
my_file.close()
| ######
# Create a backup of J2EE Security Roles
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
#
import sys
import os
import ibmcnx.functions
path = raw_input( "Please provide a path for your backup files: " )
ibmcnx.functions.checkBackupPath( path )
apps = AdminApp.list()
appsList = apps.splitlines()
for app in appsList:
filename = path + "/" + app + ".txt"
print "Backup of %(1)s security roles saved to %(2)s." % { "1" : app.upper(), "2": filename}
my_file = open( filename, 'w' )
my_file.write ( AdminApp.view( app, "-MapRolesToUsers" ) )
my_file.flush
my_file.close()
| Test all scripts on Windows | 10: Test all scripts on Windows
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/10 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 | ---
+++
@@ -16,10 +16,6 @@
import os
import ibmcnx.functions
-# Only load commands if not initialized directly (call from menu)
-if __name__ == "__main__":
- execfile("ibmcnx/loadCnxApps.py")
-
path = raw_input( "Please provide a path for your backup files: " )
ibmcnx.functions.checkBackupPath( path )
|
8dcda9a9dd5c7f106d5544bb185fa348157495fb | blimp_boards/accounts/serializers.py | blimp_boards/accounts/serializers.py | from rest_framework import serializers
from ..utils.fields import DomainNameField
from .fields import SignupDomainsField
from .models import Account
class ValidateSignupDomainsSerializer(serializers.Serializer):
"""
Serializer that handles signup domains validation endpoint.
"""
signup_domains = SignupDomainsField()
class AccountSerializer(serializers.ModelSerializer):
"""
Serializer for Accounts.
"""
class Meta:
model = Account
fields = ('id', 'name', 'slug', 'disqus_shortname', 'logo_color',
'date_created', 'date_modified')
class CheckSignupDomainSerializer(serializers.Serializer):
"""
Serializer to get account that has signup domain setup.
"""
signup_domain = DomainNameField()
def validate_signup_domain(self, attrs, source):
signup_domain = attrs[source]
data = {}
try:
account = Account.objects.get(
allow_signup=True, email_domains__domain_name=signup_domain)
data = AccountSerializer(account).data
except Account.DoesNotExist:
pass
return data
| from rest_framework import serializers
from ..utils.fields import DomainNameField
from .fields import SignupDomainsField
from .models import Account
class ValidateSignupDomainsSerializer(serializers.Serializer):
"""
Serializer that handles signup domains validation endpoint.
"""
signup_domains = SignupDomainsField()
class AccountSerializer(serializers.ModelSerializer):
"""
Serializer for Accounts.
"""
class Meta:
model = Account
read_only_fields = ('logo_color', )
fields = ('id', 'name', 'slug', 'disqus_shortname', 'logo_color',
'date_created', 'date_modified')
class CheckSignupDomainSerializer(serializers.Serializer):
"""
Serializer to get account that has signup domain setup.
"""
signup_domain = DomainNameField()
def validate_signup_domain(self, attrs, source):
signup_domain = attrs[source]
data = {}
try:
account = Account.objects.get(
allow_signup=True, email_domains__domain_name=signup_domain)
data = AccountSerializer(account).data
except Account.DoesNotExist:
pass
return data
| Set Account logo_color to be read only | Set Account logo_color to be read only | Python | agpl-3.0 | jessamynsmith/boards-backend,jessamynsmith/boards-backend,GetBlimp/boards-backend | ---
+++
@@ -18,6 +18,7 @@
"""
class Meta:
model = Account
+ read_only_fields = ('logo_color', )
fields = ('id', 'name', 'slug', 'disqus_shortname', 'logo_color',
'date_created', 'date_modified')
|
243feb2fe194ad00f59c6ff22ac41989fe0978d1 | bots.sample/number-jokes/__init__.py | bots.sample/number-jokes/__init__.py | import random
from botfriend.bot import TextGeneratorBot
class ExampleBot(TextGeneratorBot):
def generate_text(self):
"""Tell a joke about numbers."""
num = random.randint(1,10)
arguments = dict(
num=num,
plus_1=num+1,
plus_3=num+3
)
setup = "Why is %(num)d afraid of %(plus_1)d? "
punchline = "Because %(plus_1)d ate %(plus_3)d!"
return (setup + punchline) % arguments
Bot = ExampleBot
| import random
from botfriend.bot import TextGeneratorBot
class NumberJokes(TextGeneratorBot):
def generate_text(self):
"""Tell a joke about numbers."""
num = random.randint(1,10)
arguments = dict(
num=num,
plus_1=num+1,
plus_3=num+3
)
setup = "Why is %(num)d afraid of %(plus_1)d? "
punchline = "Because %(plus_1)d ate %(plus_3)d!"
return (setup + punchline) % arguments
Bot = NumberJokes
| Change number-jokes to match the tutorial. | Change number-jokes to match the tutorial.
| Python | mit | leonardr/botfriend | ---
+++
@@ -1,7 +1,7 @@
import random
from botfriend.bot import TextGeneratorBot
-class ExampleBot(TextGeneratorBot):
+class NumberJokes(TextGeneratorBot):
def generate_text(self):
"""Tell a joke about numbers."""
@@ -15,4 +15,4 @@
punchline = "Because %(plus_1)d ate %(plus_3)d!"
return (setup + punchline) % arguments
-Bot = ExampleBot
+Bot = NumberJokes |
d01adfce91927c57258f1e13ed34e4e600e40048 | pipenv/pew/__main__.py | pipenv/pew/__main__.py | from pipenv.patched import pew
if __name__ == '__main__':
pew.pew.pew()
| from pipenv.patched import pew
import os
import sys
pipenv_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
pipenv_vendor = os.sep.join([pipenv_root, 'vendor'])
pipenv_patched = os.sep.join([pipenv_root, 'patched'])
if __name__ == '__main__':
sys.path.insert(0, pipenv_vendor)
sys.path.insert(0, pipenv_patched)
pew.pew.pew()
| Add vendor and patch directories to pew path | Add vendor and patch directories to pew path
- Fixes #1661
| Python | mit | kennethreitz/pipenv | ---
+++
@@ -1,4 +1,13 @@
from pipenv.patched import pew
+import os
+import sys
+
+pipenv_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+pipenv_vendor = os.sep.join([pipenv_root, 'vendor'])
+pipenv_patched = os.sep.join([pipenv_root, 'patched'])
+
if __name__ == '__main__':
+ sys.path.insert(0, pipenv_vendor)
+ sys.path.insert(0, pipenv_patched)
pew.pew.pew() |
4a0d781c64da4a0ad211e5fb211dc317a4e3f4c5 | data_structures/doubly_linked_list.py | data_structures/doubly_linked_list.py | class Node(object):
def __init__(self, val, prev=None, next_=None):
self.val = val
self.prev = prev
self.next = next_
def __repr__(self):
return '{val}'.format(val=self.val)
class DoublLinkedList(object):
def __init__(self, iterable=()):
self._current = None
self.head = None
self.tail = None
self.length = 0
for val in reversed(iterable):
self.insert(val)
def __repr__(self):
node = self.head
output = ''
for node in self:
output += '{!r}, '.format(node.val)
return '({})'.format(output.rstrip(' ,'))
def __len__(self):
return self.length
def __iter__(self):
if self.head is not None:
self._current = self.head
return self
def next(self):
pass
def size(self):
pass
def search(self, search):
pass
def remove(self, search):
pass
def insert(self, val):
pass
def append(self, val):
pass
def pop(self):
pass
def shift(self):
pass
def display(self):
''''''
return repr(self)
| Add structure and methods to double linked list. | Add structure and methods to double linked list.
| Python | mit | sjschmidt44/python_data_structures | ---
+++
@@ -0,0 +1,61 @@
+class Node(object):
+ def __init__(self, val, prev=None, next_=None):
+ self.val = val
+ self.prev = prev
+ self.next = next_
+
+ def __repr__(self):
+ return '{val}'.format(val=self.val)
+
+
+class DoublLinkedList(object):
+ def __init__(self, iterable=()):
+ self._current = None
+ self.head = None
+ self.tail = None
+ self.length = 0
+ for val in reversed(iterable):
+ self.insert(val)
+
+ def __repr__(self):
+ node = self.head
+ output = ''
+ for node in self:
+ output += '{!r}, '.format(node.val)
+ return '({})'.format(output.rstrip(' ,'))
+
+ def __len__(self):
+ return self.length
+
+ def __iter__(self):
+ if self.head is not None:
+ self._current = self.head
+ return self
+
+ def next(self):
+ pass
+
+ def size(self):
+ pass
+
+ def search(self, search):
+ pass
+
+ def remove(self, search):
+ pass
+
+ def insert(self, val):
+ pass
+
+ def append(self, val):
+ pass
+
+ def pop(self):
+ pass
+
+ def shift(self):
+ pass
+
+ def display(self):
+ ''''''
+ return repr(self) | |
8a61bd499e9a3cc538d7d83719c6d4231753925b | megalista_dataflow/uploaders/uploaders.py | megalista_dataflow/uploaders/uploaders.py | # Copyright 2022 Google LLC
#
# 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
#
# https://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 apache_beam as beam
from error.error_handling import ErrorHandler
from models.execution import Execution
class MegalistaUploader(beam.DoFn):
"""
General DoFn to be used as supper for DoFn uploaders.
Add error notification capabilities.
"""
def __init__(self, error_handler: ErrorHandler):
super().__init__()
self._error_handler = error_handler
def _add_error(self, execution: Execution, error_message: str):
self._error_handler.add_error(execution, error_message)
def teardown(self):
self._error_handler.notify_errors()
| # Copyright 2022 Google LLC
#
# 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
#
# https://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 apache_beam as beam
from error.error_handling import ErrorHandler
from models.execution import Execution
class MegalistaUploader(beam.DoFn):
"""
General DoFn to be used as supper for DoFn uploaders.
Add error notification capabilities.
"""
def __init__(self, error_handler: ErrorHandler):
super().__init__()
self._error_handler = error_handler
def _add_error(self, execution: Execution, error_message: str):
self._error_handler.add_error(execution, error_message)
def finish_bundle(self):
self._error_handler.notify_errors()
| Change the notifier to be sent on finish_bundle instead of teardown | Change the notifier to be sent on finish_bundle instead of teardown
Change-Id: I6b80b1d0431b0fe285a5b59e9a33199bf8bd3510
| Python | apache-2.0 | google/megalista,google/megalista | ---
+++
@@ -31,5 +31,5 @@
def _add_error(self, execution: Execution, error_message: str):
self._error_handler.add_error(execution, error_message)
- def teardown(self):
+ def finish_bundle(self):
self._error_handler.notify_errors() |
0c9582598d172585466f89434035cf3e3cafcf61 | frontends/etiquette_flask/etiquette_flask_launch.py | frontends/etiquette_flask/etiquette_flask_launch.py | import gevent.monkey
gevent.monkey.patch_all()
import logging
handler = logging.StreamHandler()
log_format = '{levelname}:etiquette.{module}.{funcName}: {message}'
handler.setFormatter(logging.Formatter(log_format, style='{'))
logging.getLogger().addHandler(handler)
import etiquette_flask
import gevent.pywsgi
import gevent.wsgi
import sys
import werkzeug.contrib.fixers
etiquette_flask.site.wsgi_app = werkzeug.contrib.fixers.ProxyFix(etiquette_flask.site.wsgi_app)
if len(sys.argv) == 2:
port = int(sys.argv[1])
else:
port = 5000
if port == 443:
http = gevent.pywsgi.WSGIServer(
listener=('0.0.0.0', port),
application=etiquette_flask.site,
keyfile='D:\\git\\etiquette\\frontends\\etiquette_flask\\https\\etiquette.key',
certfile='D:\\git\\etiquette\\frontends\\etiquette_flask\\https\\etiquette.crt',
)
else:
http = gevent.pywsgi.WSGIServer(
listener=('0.0.0.0', port),
application=etiquette_flask.site,
)
print('Starting server on port %d' % port)
http.serve_forever()
| import gevent.monkey
gevent.monkey.patch_all()
import logging
handler = logging.StreamHandler()
log_format = '{levelname}:etiquette.{module}.{funcName}: {message}'
handler.setFormatter(logging.Formatter(log_format, style='{'))
logging.getLogger().addHandler(handler)
import etiquette_flask
import gevent.pywsgi
import gevent.wsgi
import sys
import werkzeug.contrib.fixers
etiquette_flask.site.wsgi_app = werkzeug.contrib.fixers.ProxyFix(etiquette_flask.site.wsgi_app)
if len(sys.argv) >= 2:
port = int(sys.argv[1])
else:
port = 5000
use_https = (port == 443) or ('--https' in sys.argv)
if use_https:
http = gevent.pywsgi.WSGIServer(
listener=('0.0.0.0', port),
application=etiquette_flask.site,
keyfile='D:\\git\\etiquette\\frontends\\etiquette_flask\\https\\etiquette.key',
certfile='D:\\git\\etiquette\\frontends\\etiquette_flask\\https\\etiquette.crt',
)
else:
http = gevent.pywsgi.WSGIServer(
listener=('0.0.0.0', port),
application=etiquette_flask.site,
)
message = 'Starting server on port %d' % port
if use_https:
message += ' (https)'
print(message)
http.serve_forever()
| Add arg --https even for non-443. | Add arg --https even for non-443.
| Python | bsd-3-clause | voussoir/etiquette,voussoir/etiquette,voussoir/etiquette | ---
+++
@@ -17,12 +17,13 @@
etiquette_flask.site.wsgi_app = werkzeug.contrib.fixers.ProxyFix(etiquette_flask.site.wsgi_app)
-if len(sys.argv) == 2:
+if len(sys.argv) >= 2:
port = int(sys.argv[1])
else:
port = 5000
-if port == 443:
+use_https = (port == 443) or ('--https' in sys.argv)
+if use_https:
http = gevent.pywsgi.WSGIServer(
listener=('0.0.0.0', port),
application=etiquette_flask.site,
@@ -36,5 +37,8 @@
)
-print('Starting server on port %d' % port)
+message = 'Starting server on port %d' % port
+if use_https:
+ message += ' (https)'
+print(message)
http.serve_forever() |
ffb261023de0a2b918a0245c05f680e0c644d7f1 | caribou/antler/antler_settings.py | caribou/antler/antler_settings.py | from caribou.settings.setting_types import *
from caribou.i18n import _
AntlerSettings = SettingsTopGroup(
_("Antler Preferences"), "/org/gnome/antler/", "org.gnome.antler",
[SettingsGroup("antler", _("Antler"), [
SettingsGroup("appearance", _("Appearance"), [
StringSetting(
"keyboard_type", _("Keyboard Type"), "touch",
_("The keyboard geometry Caribou should use"),
_("The keyboard geometry determines the shape "
"and complexity of the keyboard, it could range from "
"a 'natural' look and feel good for composing simple "
"text, to a fullscale keyboard."),
# Translators: Keyboard type (similar to touch/tactile device)
allowed=[(('touch'), _('Touch')),
# Translators: Keyboard type (conventional keyboard)
(('fullscale'), _('Full scale')),
# Translators: Keyboard type (scanned grid by rows/columns)
(('scan'), _('Scan'))]),
BooleanSetting("use_system", _("Use System Theme"),
True, _("Use System Theme")),
FloatSetting("min_alpha", _("Minimum Alpha"),
0.2, _("Minimal opacity of keyboard"),
min=0.0, max=1.0),
FloatSetting("max_alpha", _("Maximum Alpha"),
1.0, _("Maximal opacity of keyboard"),
min=0.0, max=1.0),
IntegerSetting("max_distance", _("Maximum Distance"),
100, _("Maximum distance when keyboard is hidden"),
min=0, max=1024)
])
])
])
| from caribou.settings.setting_types import *
from caribou.i18n import _
AntlerSettings = SettingsTopGroup(
_("Antler Preferences"), "/org/gnome/antler/", "org.gnome.antler",
[SettingsGroup("antler", _("Antler"), [
SettingsGroup("appearance", _("Appearance"), [
StringSetting(
"keyboard_type", _("Keyboard Type"), "touch",
_("The keyboard geometry Caribou should use"),
_("The keyboard geometry determines the shape "
"and complexity of the keyboard, it could range from "
"a 'natural' look and feel good for composing simple "
"text, to a fullscale keyboard."),
# Translators: Keyboard type (similar to touch/tactile device)
allowed=[(('touch'), _('Touch')),
# Translators: Keyboard type (conventional keyboard)
(('fullscale'), _('Full scale')),
# Translators: Keyboard type (scanned grid by rows/columns)
(('scan'), _('Scan'))]),
BooleanSetting("use_system", _("Use System Theme"),
False, _("Use System Theme")),
FloatSetting("min_alpha", _("Minimum Alpha"),
0.2, _("Minimal opacity of keyboard"),
min=0.0, max=1.0),
FloatSetting("max_alpha", _("Maximum Alpha"),
1.0, _("Maximal opacity of keyboard"),
min=0.0, max=1.0),
IntegerSetting("max_distance", _("Maximum Distance"),
100, _("Maximum distance when keyboard is hidden"),
min=0, max=1024)
])
])
])
| Use custom theme by default. | antler: Use custom theme by default.
| Python | lgpl-2.1 | GNOME/caribou,GNOME/caribou,GNOME/caribou | ---
+++
@@ -19,7 +19,7 @@
# Translators: Keyboard type (scanned grid by rows/columns)
(('scan'), _('Scan'))]),
BooleanSetting("use_system", _("Use System Theme"),
- True, _("Use System Theme")),
+ False, _("Use System Theme")),
FloatSetting("min_alpha", _("Minimum Alpha"),
0.2, _("Minimal opacity of keyboard"),
min=0.0, max=1.0), |
d75d26bc51ed35eec362660e29bda58a91cd418b | pebble_tool/util/npm.py | pebble_tool/util/npm.py | # encoding: utf-8
from __future__ import absolute_import, print_function, division
import os
import subprocess
from pebble_tool.exceptions import ToolError
from pebble_tool.util.versions import version_to_key
def check_npm():
try:
npm_version = subprocess.check_output(["npm", "--version"]).strip()
if version_to_key(npm_version)[0] < 3:
raise ToolError("We require npm3; you are using version {}.".format(npm_version))
except subprocess.CalledProcessError:
raise ToolError(u"You must have npm ≥ 3.0.0 available on your path.")
def invoke_npm(args):
check_npm()
subprocess.check_call(["npm"] + args)
def sanity_check():
if not os.path.exists('node_modules'):
return
for d in os.listdir('node_modules'):
if 'node_modules' in os.listdir(os.path.join('node_modules', d)):
raise ToolError("Conflicting npm dependency in {}: {}. Please resolve before continuing."
.format(d, os.listdir(os.path.join('node_modules', d, 'node_modules'))[0]))
| # encoding: utf-8
from __future__ import absolute_import, print_function, division
import os
import subprocess
from pebble_tool.exceptions import ToolError
from pebble_tool.util.versions import version_to_key
def check_npm():
try:
npm_version = subprocess.check_output(["npm", "--version"]).strip()
if version_to_key(npm_version)[0] < 3:
raise ToolError("We require npm3; you are using version {}.".format(npm_version))
except subprocess.CalledProcessError:
raise ToolError(u"You must have npm ≥ 3.0.0 available on your path.")
def invoke_npm(args):
check_npm()
subprocess.check_call(["npm"] + args)
def sanity_check():
if not os.path.exists('node_modules'):
return
for d in os.listdir('node_modules'):
if not os.path.isdir(d):
continue
if 'node_modules' in os.listdir(os.path.join('node_modules', d)):
raise ToolError("Conflicting npm dependency in {}: {}. Please resolve before continuing."
.format(d, os.listdir(os.path.join('node_modules', d, 'node_modules'))[0]))
| Add check for isdir to handle non-directories | Add check for isdir to handle non-directories
| Python | mit | pebble/pebble-tool,pebble/pebble-tool,gregoiresage/pebble-tool,pebble/pebble-tool,gregoiresage/pebble-tool,gregoiresage/pebble-tool,gregoiresage/pebble-tool,pebble/pebble-tool | ---
+++
@@ -26,6 +26,8 @@
if not os.path.exists('node_modules'):
return
for d in os.listdir('node_modules'):
+ if not os.path.isdir(d):
+ continue
if 'node_modules' in os.listdir(os.path.join('node_modules', d)):
raise ToolError("Conflicting npm dependency in {}: {}. Please resolve before continuing."
.format(d, os.listdir(os.path.join('node_modules', d, 'node_modules'))[0])) |
52716c4dc7d95820d2640ba7c9e75fb00f786e85 | lib/ansible/utils/module_docs_fragments/validate.py | lib/ansible/utils/module_docs_fragments/validate.py | # Copyright (c) 2015 Ansible, Inc
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
class ModuleDocFragment(object):
# Standard documentation fragment
DOCUMENTATION = '''
options:
validate:
required: false
description:
- The validation command to run before copying into place. The path to the file to
validate is passed in via '%s' which must be present as in the apache example below.
The command is passed securely so shell features like expansion and pipes won't work.
default: None
'''
| # Copyright (c) 2015 Ansible, Inc
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
class ModuleDocFragment(object):
# Standard documentation fragment
DOCUMENTATION = '''
options:
validate:
required: false
description:
- The validation command to run before copying into place. The path to the file to
validate is passed in via '%s' which must be present as in the example below.
The command is passed securely so shell features like expansion and pipes won't work.
default: None
'''
| Remove mention of 'apache example' | Remove mention of 'apache example'
Removed explicit mention of 'apache' | Python | mit | thaim/ansible,thaim/ansible | ---
+++
@@ -25,7 +25,7 @@
required: false
description:
- The validation command to run before copying into place. The path to the file to
- validate is passed in via '%s' which must be present as in the apache example below.
+ validate is passed in via '%s' which must be present as in the example below.
The command is passed securely so shell features like expansion and pipes won't work.
default: None
''' |
bebde48483e1397a2f45a81c72cc3c79ee7bd150 | djcelery/contrib/test_runner.py | djcelery/contrib/test_runner.py | from __future__ import absolute_import
from django.conf import settings
from django.test.simple import DjangoTestSuiteRunner
USAGE = """\
Custom test runner to allow testing of celery delayed tasks.
"""
class CeleryTestSuiteRunner(DjangoTestSuiteRunner):
"""Django test runner allowing testing of celery delayed tasks.
All tasks are run locally, not in a worker.
To use this runner set ``settings.TEST_RUNNER``::
TEST_RUNNER = "celery.contrib.test_runner.CeleryTestSuiteRunner"
"""
def setup_test_environment(self, **kwargs):
super(CeleryTestSuiteRunner, self).setup_test_environment(**kwargs)
settings.CELERY_ALWAYS_EAGER = True
settings.CELERY_EAGER_PROPAGATES_EXCEPTIONS = True # Issue #75
| from __future__ import absolute_import
from django.conf import settings
from django.test.simple import DjangoTestSuiteRunner
USAGE = """\
Custom test runner to allow testing of celery delayed tasks.
"""
class CeleryTestSuiteRunner(DjangoTestSuiteRunner):
"""Django test runner allowing testing of celery delayed tasks.
All tasks are run locally, not in a worker.
To use this runner set ``settings.TEST_RUNNER``::
TEST_RUNNER = "djcelery.contrib.test_runner.CeleryTestSuiteRunner"
"""
def setup_test_environment(self, **kwargs):
super(CeleryTestSuiteRunner, self).setup_test_environment(**kwargs)
settings.CELERY_ALWAYS_EAGER = True
settings.CELERY_EAGER_PROPAGATES_EXCEPTIONS = True # Issue #75
| Correct documentation for path to load test runner | Correct documentation for path to load test runner | Python | bsd-3-clause | georgewhewell/django-celery,planorama/django-celery,axiom-data-science/django-celery,axiom-data-science/django-celery,ask/django-celery,kanemra/django-celery,CloudNcodeInc/django-celery,celery/django-celery,georgewhewell/django-celery,kanemra/django-celery,tkanemoto/django-celery,tkanemoto/django-celery,iris-edu-int/django-celery,Amanit/django-celery,alexhayes/django-celery,alexhayes/django-celery,CloudNcodeInc/django-celery,digimarc/django-celery,Amanit/django-celery,CloudNcodeInc/django-celery,iris-edu-int/django-celery,planorama/django-celery,celery/django-celery,Amanit/django-celery,nadios/django-celery,georgewhewell/django-celery,kanemra/django-celery,digimarc/django-celery,celery/django-celery,tkanemoto/django-celery,nadios/django-celery,iris-edu-int/django-celery,digimarc/django-celery,axiom-data-science/django-celery,ask/django-celery | ---
+++
@@ -15,7 +15,7 @@
To use this runner set ``settings.TEST_RUNNER``::
- TEST_RUNNER = "celery.contrib.test_runner.CeleryTestSuiteRunner"
+ TEST_RUNNER = "djcelery.contrib.test_runner.CeleryTestSuiteRunner"
"""
def setup_test_environment(self, **kwargs): |
003d3921bb6c801c5a2efdede20ed70ee07edf3d | src/nodeconductor_openstack/openstack/migrations/0031_tenant_backup_storage.py | src/nodeconductor_openstack/openstack/migrations/0031_tenant_backup_storage.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.contenttypes.models import ContentType
from django.db import migrations
from nodeconductor.quotas import models as quotas_models
from .. import models
def delete_backup_storage_quota_from_tenant(apps, schema_editor):
tenant_content_type = ContentType.objects.get_for_model(models.Tenant)
quota_name = 'backup_storage'
quotas_models.Quota.objects.filter(name=quota_name, content_type=tenant_content_type).delete()
class Migration(migrations.Migration):
dependencies = [
('openstack', '0030_subnet_dns_nameservers'),
]
operations = [
migrations.RunPython(delete_backup_storage_quota_from_tenant),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.contenttypes.models import ContentType
from django.db import migrations
from nodeconductor.quotas import models as quotas_models
from .. import models
def cleanup_tenant_quotas(apps, schema_editor):
for obj in models.Tenant.objects.all():
quotas_names = models.Tenant.QUOTAS_NAMES + [f.name for f in models.Tenant.get_quotas_fields()]
obj.quotas.exclude(name__in=quotas_names).delete()
class Migration(migrations.Migration):
dependencies = [
('openstack', '0030_subnet_dns_nameservers'),
]
operations = [
migrations.RunPython(cleanup_tenant_quotas),
]
| Replace quota deletion with cleanup | Replace quota deletion with cleanup [WAL-433]
| Python | mit | opennode/nodeconductor-openstack | ---
+++
@@ -9,10 +9,10 @@
from .. import models
-def delete_backup_storage_quota_from_tenant(apps, schema_editor):
- tenant_content_type = ContentType.objects.get_for_model(models.Tenant)
- quota_name = 'backup_storage'
- quotas_models.Quota.objects.filter(name=quota_name, content_type=tenant_content_type).delete()
+def cleanup_tenant_quotas(apps, schema_editor):
+ for obj in models.Tenant.objects.all():
+ quotas_names = models.Tenant.QUOTAS_NAMES + [f.name for f in models.Tenant.get_quotas_fields()]
+ obj.quotas.exclude(name__in=quotas_names).delete()
class Migration(migrations.Migration):
@@ -22,5 +22,5 @@
]
operations = [
- migrations.RunPython(delete_backup_storage_quota_from_tenant),
+ migrations.RunPython(cleanup_tenant_quotas),
] |
878975b1b82d22bba0ac23cf162eb68b46e76f0a | wagtail/wagtailembeds/finders/__init__.py | wagtail/wagtailembeds/finders/__init__.py | from django.utils.module_loading import import_string
from django.conf import settings
from wagtail.wagtailembeds.finders.oembed import oembed
from wagtail.wagtailembeds.finders.embedly import embedly
MOVED_FINDERS = {
'wagtail.wagtailembeds.embeds.embedly': 'wagtail.wagtailembeds.finders.embedly.embedly',
'wagtail.wagtailembeds.embeds.oembed': 'wagtail.wagtailembeds.finders.oembed.oembed',
}
def get_default_finder():
# Check if the user has set the embed finder manually
if hasattr(settings, 'WAGTAILEMBEDS_EMBED_FINDER'):
finder_name = settings.WAGTAILEMBEDS_EMBED_FINDER
if finder_name in MOVED_FINDERS:
finder_name = MOVED_FINDERS[finder_name]
return import_string(finder_name)
# Use embedly if the embedly key is set
if hasattr(settings, 'WAGTAILEMBEDS_EMBEDLY_KEY'):
return embedly
# Fall back to oembed
return oembed
| from django.utils.module_loading import import_string
from django.conf import settings
MOVED_FINDERS = {
'wagtail.wagtailembeds.embeds.embedly': 'wagtail.wagtailembeds.finders.embedly.embedly',
'wagtail.wagtailembeds.embeds.oembed': 'wagtail.wagtailembeds.finders.oembed.oembed',
}
def get_default_finder():
# Check if the user has set the embed finder manually
if hasattr(settings, 'WAGTAILEMBEDS_EMBED_FINDER'):
finder_name = settings.WAGTAILEMBEDS_EMBED_FINDER
if finder_name in MOVED_FINDERS:
finder_name = MOVED_FINDERS[finder_name]
elif hasattr(settings, 'WAGTAILEMBEDS_EMBEDLY_KEY'):
# Default to Embedly as an embedly key is set
finder_name = 'wagtail.wagtailembeds.finders.embedly.embedly'
else:
# Default to oembed
finder_name = 'wagtail.wagtailembeds.finders.oembed.oembed'
return import_string(finder_name)
| Refactor get_default_finder to work without importing finders | Refactor get_default_finder to work without importing finders
| Python | bsd-3-clause | takeflight/wagtail,mikedingjan/wagtail,JoshBarr/wagtail,gasman/wagtail,chrxr/wagtail,FlipperPA/wagtail,JoshBarr/wagtail,inonit/wagtail,wagtail/wagtail,nilnvoid/wagtail,mikedingjan/wagtail,gasman/wagtail,timorieber/wagtail,torchbox/wagtail,jnns/wagtail,hamsterbacke23/wagtail,nealtodd/wagtail,iansprice/wagtail,timorieber/wagtail,Toshakins/wagtail,gasman/wagtail,zerolab/wagtail,nimasmi/wagtail,kurtw/wagtail,nutztherookie/wagtail,zerolab/wagtail,kurtw/wagtail,iansprice/wagtail,quru/wagtail,kurtw/wagtail,kurtw/wagtail,nimasmi/wagtail,takeflight/wagtail,kaedroho/wagtail,inonit/wagtail,zerolab/wagtail,mikedingjan/wagtail,takeflight/wagtail,kurtrwall/wagtail,gogobook/wagtail,nutztherookie/wagtail,timorieber/wagtail,nealtodd/wagtail,takeflight/wagtail,wagtail/wagtail,kurtrwall/wagtail,davecranwell/wagtail,nilnvoid/wagtail,nutztherookie/wagtail,nealtodd/wagtail,FlipperPA/wagtail,torchbox/wagtail,gasman/wagtail,chrxr/wagtail,davecranwell/wagtail,kaedroho/wagtail,nilnvoid/wagtail,jnns/wagtail,gogobook/wagtail,rsalmaso/wagtail,wagtail/wagtail,kaedroho/wagtail,mixxorz/wagtail,rsalmaso/wagtail,davecranwell/wagtail,inonit/wagtail,torchbox/wagtail,hamsterbacke23/wagtail,JoshBarr/wagtail,JoshBarr/wagtail,nealtodd/wagtail,nutztherookie/wagtail,nilnvoid/wagtail,gogobook/wagtail,mikedingjan/wagtail,thenewguy/wagtail,jnns/wagtail,zerolab/wagtail,nimasmi/wagtail,Toshakins/wagtail,chrxr/wagtail,mixxorz/wagtail,rsalmaso/wagtail,chrxr/wagtail,wagtail/wagtail,thenewguy/wagtail,wagtail/wagtail,hamsterbacke23/wagtail,rsalmaso/wagtail,kaedroho/wagtail,kurtrwall/wagtail,iansprice/wagtail,jnns/wagtail,iansprice/wagtail,kurtrwall/wagtail,timorieber/wagtail,nimasmi/wagtail,thenewguy/wagtail,Toshakins/wagtail,quru/wagtail,mixxorz/wagtail,zerolab/wagtail,quru/wagtail,mixxorz/wagtail,quru/wagtail,hamsterbacke23/wagtail,rsalmaso/wagtail,gasman/wagtail,torchbox/wagtail,inonit/wagtail,thenewguy/wagtail,mixxorz/wagtail,Toshakins/wagtail,thenewguy/wagtail,gogobook/wagtail,FlipperPA/wagtail,kaedroho/wagtail,davecranwell/wagtail,FlipperPA/wagtail | ---
+++
@@ -1,8 +1,5 @@
from django.utils.module_loading import import_string
from django.conf import settings
-
-from wagtail.wagtailembeds.finders.oembed import oembed
-from wagtail.wagtailembeds.finders.embedly import embedly
MOVED_FINDERS = {
@@ -19,11 +16,12 @@
if finder_name in MOVED_FINDERS:
finder_name = MOVED_FINDERS[finder_name]
- return import_string(finder_name)
+ elif hasattr(settings, 'WAGTAILEMBEDS_EMBEDLY_KEY'):
+ # Default to Embedly as an embedly key is set
+ finder_name = 'wagtail.wagtailembeds.finders.embedly.embedly'
- # Use embedly if the embedly key is set
- if hasattr(settings, 'WAGTAILEMBEDS_EMBEDLY_KEY'):
- return embedly
+ else:
+ # Default to oembed
+ finder_name = 'wagtail.wagtailembeds.finders.oembed.oembed'
- # Fall back to oembed
- return oembed
+ return import_string(finder_name) |
a8244c25c5cc7e2279723538daa9889a1d327cae | extensions/ExtGameController.py | extensions/ExtGameController.py | from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
additional_modes = [
GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1)
]
def __init__(self, game=None):
super(ExtGameController, self).__init__(game=game)
self.add_mode(self.additional_modes)
| from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
additional_modes = [
# GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
# GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1)
]
def __init__(self):
super(ExtGameController, self).__init__()
self.add_mode(self.additional_modes)
| Remove new modes for testing. | Remove new modes for testing.
| Python | apache-2.0 | dsandersAzure/python_cowbull_server,dsandersAzure/python_cowbull_server | ---
+++
@@ -4,10 +4,10 @@
class ExtGameController(GameController):
additional_modes = [
- GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
- GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1)
+# GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
+# GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1)
]
- def __init__(self, game=None):
- super(ExtGameController, self).__init__(game=game)
+ def __init__(self):
+ super(ExtGameController, self).__init__()
self.add_mode(self.additional_modes) |
b678d2da0845ae7f567eb6c4cd55471974d5b5e1 | apps/storybase_user/models.py | apps/storybase_user/models.py | from django.contrib.auth.models import User
from django.db import models
from uuidfield.fields import UUIDField
from storybase.fields import ShortTextField
class Organization(models.Model):
""" An organization or a community group that users and stories can be associated with. """
organization_id = UUIDField(auto=True)
name = ShortTextField()
slug = models.SlugField()
website_url = models.URLField(blank=True)
members = models.ManyToManyField(User, related_name='organizations', blank=True)
def __unicode__(self):
return self.name
@models.permalink
def get_absolute_url(self):
# TODO: Implement this view and URL pattern
return ('organization_bootstrap', [self.organization_id])
class Project(models.Model):
"""
A project that collects related stories.
Users can also be related to projects.
"""
project_id = UUIDField(auto=True)
name = models.CharField(max_length=200)
slug = models.SlugField()
members = models.ManyToManyField(User, related_name='projects', blank=True)
def __unicode__(self):
return self.name
| from django.contrib.auth.models import User
from django.db import models
from uuidfield.fields import UUIDField
from storybase.fields import ShortTextField
class Organization(models.Model):
""" An organization or a community group that users and stories can be associated with. """
organization_id = UUIDField(auto=True)
name = ShortTextField()
slug = models.SlugField()
website_url = models.URLField(blank=True)
members = models.ManyToManyField(User, related_name='organizations', blank=True)
def __unicode__(self):
return self.name
@models.permalink
def get_absolute_url(self):
return ('organization_detail', [self.organization_id])
class Project(models.Model):
"""
A project that collects related stories.
Users can also be related to projects.
"""
project_id = UUIDField(auto=True)
name = models.CharField(max_length=200)
slug = models.SlugField()
members = models.ManyToManyField(User, related_name='projects', blank=True)
def __unicode__(self):
return self.name
| Use correct named view for organization detail view | Use correct named view for organization detail view
| Python | mit | denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase | ---
+++
@@ -16,8 +16,7 @@
@models.permalink
def get_absolute_url(self):
- # TODO: Implement this view and URL pattern
- return ('organization_bootstrap', [self.organization_id])
+ return ('organization_detail', [self.organization_id])
class Project(models.Model):
""" |
c09f346f7a2be5bdfd5dca8821ab260494a652af | routines/migrate-all.py | routines/migrate-all.py | from pmxbot import logging
from pmxbot import util
from pmxbot import rss
from pmxbot import storage
storage.migrate_all('sqlite:pmxbot.sqlite', 'mongodb://localhost')
| import importlib
import pmxbot.storage
def run():
# load the storage classes so the migration routine will find them.
for mod in ('pmxbot.logging', 'pmxbot.karma', 'pmxbot.quotes',
'pmxbot.rss'):
importlib.import_module(mod)
pmxbot.storage.migrate_all('sqlite:pmxbot.sqlite', 'mongodb://localhost')
if __name__ == '__main__':
run()
| Update migration script so it only runs if executed as a script. Also updated module references. | Update migration script so it only runs if executed as a script. Also updated module references.
| Python | bsd-3-clause | jamwt/diesel-pmxbot,jamwt/diesel-pmxbot | ---
+++
@@ -1,5 +1,13 @@
-from pmxbot import logging
-from pmxbot import util
-from pmxbot import rss
-from pmxbot import storage
-storage.migrate_all('sqlite:pmxbot.sqlite', 'mongodb://localhost')
+import importlib
+
+import pmxbot.storage
+
+def run():
+ # load the storage classes so the migration routine will find them.
+ for mod in ('pmxbot.logging', 'pmxbot.karma', 'pmxbot.quotes',
+ 'pmxbot.rss'):
+ importlib.import_module(mod)
+ pmxbot.storage.migrate_all('sqlite:pmxbot.sqlite', 'mongodb://localhost')
+
+if __name__ == '__main__':
+ run() |
793baa838b7bc7bfed3eb74a69c297645b4c5da6 | app/passthrough/views.py | app/passthrough/views.py | import boto3
import botocore
from flask import (
abort,
current_app,
flash,
make_response,
redirect,
request,
Response,
url_for,
)
from flask_login import current_user
from . import passthrough_bp
@passthrough_bp.route('/<path:path>')
def passthrough(path):
if not current_user.is_authenticated:
return redirect(url_for('auth.login', next=request.path))
else:
default_page = current_app.config.get('S3_INDEX_DOCUMENT')
if default_page and path.endswith('/'):
path += default_page
s3 = boto3.resource('s3')
bucket = current_app.config.get('S3_BUCKET')
obj = s3.Object(bucket, path)
try:
obj_resp = obj.get()
def generate(result):
for chunk in iter(lambda: result['Body'].read(8192), b''):
yield chunk
response = Response(generate(obj_resp))
response.headers['Content-Type'] = obj_resp['ContentType']
response.headers['Content-Encoding'] = obj_resp['ContentEncoding']
return response
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "404":
abort(404)
elif e.response['Error']['Code'] == 'NoSuchKey':
abort(404)
else:
raise
| import boto3
import botocore
from flask import (
abort,
current_app,
flash,
make_response,
redirect,
request,
Response,
url_for,
)
from flask_login import current_user
from . import passthrough_bp
@passthrough_bp.route('/<path:path>')
def passthrough(path):
if not current_user.is_authenticated:
return redirect(url_for('auth.login', next=request.path))
else:
default_page = current_app.config.get('S3_INDEX_DOCUMENT')
if default_page and (path == '' or path.endswith('/')):
path += default_page
s3 = boto3.resource('s3')
bucket = current_app.config.get('S3_BUCKET')
obj = s3.Object(bucket, path)
try:
obj_resp = obj.get()
def generate(result):
for chunk in iter(lambda: result['Body'].read(8192), b''):
yield chunk
response = Response(generate(obj_resp))
response.headers['Content-Type'] = obj_resp['ContentType']
response.headers['Content-Encoding'] = obj_resp['ContentEncoding']
return response
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "404":
abort(404)
elif e.response['Error']['Code'] == 'NoSuchKey':
abort(404)
else:
raise
| Handle the case of an empty path | Handle the case of an empty path
This will deal with the root domain request going to default page. | Python | mit | iandees/bucket-protection,iandees/bucket-protection | ---
+++
@@ -20,7 +20,7 @@
return redirect(url_for('auth.login', next=request.path))
else:
default_page = current_app.config.get('S3_INDEX_DOCUMENT')
- if default_page and path.endswith('/'):
+ if default_page and (path == '' or path.endswith('/')):
path += default_page
s3 = boto3.resource('s3') |
867195ef9331ec9740efbd6d1dc35c501b373437 | recipes/kaleido-core/run_test.py | recipes/kaleido-core/run_test.py | from subprocess import Popen, PIPE
import json
import platform
# Remove "sys.exit" after feedstock creation when running
# on linux-anvil-cos7-x86_64 image
if platform.system() == "Linux":
import sys
sys.exit(0)
if platform.system() == "Windows":
ext = ".cmd"
else:
ext = ""
p = Popen(
['kaleido' + ext, "plotly", "--disable-gpu"],
stdout=PIPE, stdin=PIPE, stderr=PIPE,
text=True
)
stdout_data = p.communicate(
input=json.dumps({"data": {"data": []}, "format": "png"})
)[0]
assert "iVBOrw" in stdout_data
| from subprocess import Popen, PIPE
import json
import platform
# Remove "sys.exit" after feedstock creation when running
# on linux-anvil-cos7-x86_64 image
if platform.system() == "Linux":
import sys
sys.exit(0)
if platform.system() == "Windows":
ext = ".cmd"
else:
ext = ""
p = Popen(
['kaleido' + ext, "plotly", "--disable-gpu"],
stdout=PIPE, stdin=PIPE, stderr=PIPE,
text=True
)
stdout_data = p.communicate(
input=json.dumps({"data": {"data": []}, "format": "png"})
)[0]
assert "iVBORw" in stdout_data
| Fix test string (Confirmed that incorrect string fails on CI) | Fix test string (Confirmed that incorrect string fails on CI)
| Python | bsd-3-clause | ReimarBauer/staged-recipes,stuertz/staged-recipes,igortg/staged-recipes,conda-forge/staged-recipes,stuertz/staged-recipes,kwilcox/staged-recipes,scopatz/staged-recipes,mariusvniekerk/staged-recipes,ocefpaf/staged-recipes,igortg/staged-recipes,johanneskoester/staged-recipes,conda-forge/staged-recipes,kwilcox/staged-recipes,SylvainCorlay/staged-recipes,mariusvniekerk/staged-recipes,goanpeca/staged-recipes,jakirkham/staged-recipes,hadim/staged-recipes,jochym/staged-recipes,jochym/staged-recipes,SylvainCorlay/staged-recipes,ReimarBauer/staged-recipes,patricksnape/staged-recipes,goanpeca/staged-recipes,scopatz/staged-recipes,ocefpaf/staged-recipes,hadim/staged-recipes,jakirkham/staged-recipes,patricksnape/staged-recipes,johanneskoester/staged-recipes | ---
+++
@@ -22,4 +22,4 @@
stdout_data = p.communicate(
input=json.dumps({"data": {"data": []}, "format": "png"})
)[0]
-assert "iVBOrw" in stdout_data
+assert "iVBORw" in stdout_data |
3daa15b0ccb3fc4891daf55724cbeaa705f923e5 | scripts/clio_daemon.py | scripts/clio_daemon.py |
import logging
import simpledaemon
class clio_daemon(simpledaemon.Daemon):
default_conf = 'clio_daemon.conf'
section = 'clio'
def run(self):
import eventlet
from clio.store import app
logger = logging.getLogger()
if logger.handlers:
[app.logger.addHandler(h) for h in logger.handlers]
app.logger.setLevel(logger.level)
eventlet.serve(eventlet.listen((app.config['HOST'], app.config['PORT']), backlog=2048), app)
if __name__ == '__main__':
clio_daemon().main()
|
import simpledaemon
class clio_daemon(simpledaemon.Daemon):
default_conf = 'clio_daemon.conf'
section = 'clio'
def run(self):
import eventlet
from clio.store import app
eventlet.serve(eventlet.listen((app.config['HOST'], app.config['PORT']), backlog=2048), app)
if __name__ == '__main__':
clio_daemon().main()
| Revert "output flask logging into simpledaemon's log file." | Revert "output flask logging into simpledaemon's log file."
This is completely superfluous - logging does this already
automatically.
This reverts commit 18091efef351ecddb1d29ee7d01d0a7fb567a7b7.
| Python | apache-2.0 | geodelic/clio,geodelic/clio | ---
+++
@@ -1,5 +1,3 @@
-
-import logging
import simpledaemon
@@ -10,10 +8,6 @@
def run(self):
import eventlet
from clio.store import app
- logger = logging.getLogger()
- if logger.handlers:
- [app.logger.addHandler(h) for h in logger.handlers]
- app.logger.setLevel(logger.level)
eventlet.serve(eventlet.listen((app.config['HOST'], app.config['PORT']), backlog=2048), app)
if __name__ == '__main__': |
0d6805bf6dce4b652f1b4f4556696c7521820790 | feder/users/autocomplete_light_registry.py | feder/users/autocomplete_light_registry.py | import autocomplete_light
from models import User
class UserAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields = ['username']
def choices_for_request(self, *args, **kwargs):
qs = super(UserAutocomplete, self).choices_for_request(*args, **kwargs)
return qs.only('username')
autocomplete_light.register(User, UserAutocomplete)
| import autocomplete_light
from .models import User
class UserAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields = ['username']
def choices_for_request(self, *args, **kwargs):
qs = super(UserAutocomplete, self).choices_for_request(*args, **kwargs)
return qs.only('username')
autocomplete_light.register(User, UserAutocomplete)
| Fix typo in users autocomplete | Fix typo in users autocomplete
| Python | mit | watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder | ---
+++
@@ -1,5 +1,5 @@
import autocomplete_light
-from models import User
+from .models import User
class UserAutocomplete(autocomplete_light.AutocompleteModelBase): |
d19f054cdc68d0060731d6c742886f94ac41f3ab | diceclient.py | diceclient.py | #!/usr/bin/env python
import sys
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from twisted.python import usage
from diceserver import RollDice, port
class Options(usage.Options):
optParameters = [
["host", "h", "localhost", "server hostname"],
["port", "p", port, "server port"],
]
def roll_die(host, port):
clientcreator = ClientCreator(reactor, amp.AMP)
d1 = clientcreator.connectTCP(host, port)
d1.addCallback(lambda p: p.callRemote(RollDice, sides=6))
d1.addCallback(lambda result: result['result'])
def done(result):
print 'Got roll:', result
reactor.stop()
d1.addCallback(done)
d1.addErrback(failure)
def failure(error):
print "failed", str(error)
reactor.stop()
if __name__ == '__main__':
options = Options()
try:
options.parseOptions()
except usage.UsageError, err:
print "%s: %s" % (sys.argv[0], err)
print "%s: Try --help for usage details" % sys.argv[0]
sys.exit(1)
host = options["host"]
port = int(options["port"])
roll_die(host, port)
reactor.run()
| #!/usr/bin/env python
import sys
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from twisted.python import usage
from diceserver import RollDice, port
class Options(usage.Options):
optParameters = [
["host", "h", "localhost", "server hostname"],
["port", "p", port, "server port"],
]
def done(result):
print 'Got roll:', result
reactor.stop()
def roll_die(host, port):
clientcreator = ClientCreator(reactor, amp.AMP)
d1 = clientcreator.connectTCP(host, port)
d1.addCallback(lambda p: p.callRemote(RollDice, sides=6))
d1.addCallback(lambda result: result['result'])
d1.addCallback(done)
d1.addErrback(failure)
def failure(error):
print "failed", str(error)
reactor.stop()
if __name__ == '__main__':
options = Options()
try:
options.parseOptions()
except usage.UsageError, err:
print "%s: %s" % (sys.argv[0], err)
print "%s: Try --help for usage details" % sys.argv[0]
sys.exit(1)
host = options["host"]
port = int(options["port"])
roll_die(host, port)
reactor.run()
| Make done a top-level function rather than a nested one. | Make done a top-level function rather than a nested one.
| Python | mit | dripton/ampchat | ---
+++
@@ -16,15 +16,15 @@
["port", "p", port, "server port"],
]
+def done(result):
+ print 'Got roll:', result
+ reactor.stop()
def roll_die(host, port):
clientcreator = ClientCreator(reactor, amp.AMP)
d1 = clientcreator.connectTCP(host, port)
d1.addCallback(lambda p: p.callRemote(RollDice, sides=6))
d1.addCallback(lambda result: result['result'])
- def done(result):
- print 'Got roll:', result
- reactor.stop()
d1.addCallback(done)
d1.addErrback(failure)
|
e31948f3638f4d688b396060eefe301f50f48ce8 | extra/psucontrol_subpluginexample.py | extra/psucontrol_subpluginexample.py | # coding=utf-8
from __future__ import absolute_import
__author__ = "Shawn Bruce <kantlivelong@gmail.com>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2021 Shawn Bruce - Released under terms of the AGPLv3 License"
import octoprint.plugin
class PSUControl_SubPluginExample(octoprint.plugin.StartupPlugin):
def __init__(self):
self.status = False
def on_startup(self, host, port):
psucontrol_helpers = self._plugin_manager.get_helpers("psucontrol")
if 'register_plugin' not in psucontrol_helpers.keys():
self._logger.warning("The version of PSUControl that is installed does not support plugin registration.")
return
self._logger.debug("Registering plugin with PSUControl")
psucontrol_helpers['register_plugin'](self)
def turn_psu_on(self):
self._logger.info("ON")
self.status = True
def turn_psu_off(self):
self._logger.info("OFF")
self.status = False
def get_psu_state(self):
return self.status
__plugin_name__ = "PSU Control - Sub Plugin Example"
__plugin_pythoncompat__ = ">=2.7,<4"
def __plugin_load__():
global __plugin_implementation__
__plugin_implementation__ = PSUControl_SubPluginExample()
| # coding=utf-8
from __future__ import absolute_import
__author__ = "Shawn Bruce <kantlivelong@gmail.com>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2021 Shawn Bruce - Released under terms of the AGPLv3 License"
import octoprint.plugin
class PSUControl_SubPluginExample(octoprint.plugin.StartupPlugin,
octoprint.plugin.RestartNeedingPlugin):
def __init__(self):
self.status = False
def on_startup(self, host, port):
psucontrol_helpers = self._plugin_manager.get_helpers("psucontrol")
if 'register_plugin' not in psucontrol_helpers.keys():
self._logger.warning("The version of PSUControl that is installed does not support plugin registration.")
return
self._logger.debug("Registering plugin with PSUControl")
psucontrol_helpers['register_plugin'](self)
def turn_psu_on(self):
self._logger.info("ON")
self.status = True
def turn_psu_off(self):
self._logger.info("OFF")
self.status = False
def get_psu_state(self):
return self.status
__plugin_name__ = "PSU Control - Sub Plugin Example"
__plugin_pythoncompat__ = ">=2.7,<4"
def __plugin_load__():
global __plugin_implementation__
__plugin_implementation__ = PSUControl_SubPluginExample()
| Update sub-plugin example - Require restart on install | Update sub-plugin example - Require restart on install
| Python | agpl-3.0 | kantlivelong/OctoPrint-PSUControl,kantlivelong/OctoPrint-PSUControl,kantlivelong/OctoPrint-PSUControl | ---
+++
@@ -7,7 +7,8 @@
import octoprint.plugin
-class PSUControl_SubPluginExample(octoprint.plugin.StartupPlugin):
+class PSUControl_SubPluginExample(octoprint.plugin.StartupPlugin,
+ octoprint.plugin.RestartNeedingPlugin):
def __init__(self):
self.status = False |
03c2a7711a07bb85398c66e79777c32f0c995536 | django/applications/catmaid/middleware.py | django/applications/catmaid/middleware.py | import json
from django.http import HttpResponse
from django.conf import settings
class AjaxExceptionMiddleware(object):
def process_exception(self, request, exception):
response = {'error': str(exception)}
if settings.DEBUG:
import sys, traceback
(exc_type, exc_info, tb) = sys.exc_info()
response['type'] = exc_type.__name__
response['info'] = str(exc_info)
response['traceback'] = ''.join(traceback.format_tb(tb))
return HttpResponse(json.dumps(response))
| import json
from django.http import HttpResponse
from django.conf import settings
class AjaxExceptionMiddleware(object):
def process_exception(self, request, exception):
response = {'error': str(exception)}
if settings.DEBUG:
import sys, traceback
(exc_type, exc_info, tb) = sys.exc_info()
response['type'] = exc_type.__name__
response['info'] = str(exc_info)
response['traceback'] = ''.join(traceback.format_tb(tb))
return HttpResponse(json.dumps(response))
| Return exception for non ajax | Return exception for non ajax
| Python | agpl-3.0 | fzadow/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID,fzadow/CATMAID | ---
+++
@@ -15,4 +15,3 @@
response['info'] = str(exc_info)
response['traceback'] = ''.join(traceback.format_tb(tb))
return HttpResponse(json.dumps(response))
- |
cdb546a9db593d79c2b9935b746e9862a2b1221c | winthrop/people/urls.py | winthrop/people/urls.py | from django.conf.urls import url
from django.contrib.admin.views.decorators import staff_member_required
from winthrop.people.views import ViafAutoSuggest
urlpatterns = [
url(r'^autocomplete/viaf/suggest/$', staff_member_required(ViafAutoSuggest.as_view()),
name='autocomplete-suggest'),
]
| from django.conf.urls import url
from django.contrib.admin.views.decorators import staff_member_required
from winthrop.people.views import ViafAutoSuggest
urlpatterns = [
url(r'^autocomplete/viaf/suggest/$', staff_member_required(ViafAutoSuggest.as_view()),
name='viaf-autosuggest'),
]
| Make the url name for autosuggest clearer | Make the url name for autosuggest clearer
| Python | apache-2.0 | Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django | ---
+++
@@ -6,5 +6,5 @@
urlpatterns = [
url(r'^autocomplete/viaf/suggest/$', staff_member_required(ViafAutoSuggest.as_view()),
- name='autocomplete-suggest'),
+ name='viaf-autosuggest'),
] |
556e3ca6d3650b1cf6e80ded98ae6d59fefa5025 | BuildAndRun.py | BuildAndRun.py | import os
import subprocess
# Update to the latest version
for line in os.popen('git fetch -p -q; git merge -q origin/master').readlines():
print line.strip()
# Move the old version over
for line in os.popen('cp sync oldsync').readlines():
print line.strip()
# Rebuild
for line in os.popen('go build ./...').readlines():
print line.strip()
# Rebuild
for line in os.popen('go build').readlines():
print line.strip()
size_1 = os.path.getsize('./oldsync')
size_2 = os.path.getsize('./sync')
if size_1 != size_2:
for line in os.popen('killall sync').readlines():
pass
subprocess.Popen('./discogssyncer --port 50051')
| import os
import subprocess
# Update to the latest version
for line in os.popen('git fetch -p -q; git merge -q origin/master').readlines():
print line.strip()
# Move the old version over
for line in os.popen('cp sync oldsync').readlines():
print line.strip()
# Rebuild
for line in os.popen('go build ./...').readlines():
print line.strip()
# Rebuild
for line in os.popen('go build').readlines():
print line.strip()
size_1 = os.path.getsize('./oldsync')
size_2 = os.path.getsize('./sync')
if size_1 != size_2:
for line in os.popen('killall sync').readlines():
pass
subprocess.Popen(['./discogssyncer', '--port' ,'50051'])
| Fix to the Build and Run script | Fix to the Build and Run script
| Python | mit | brotherlogic/discogssyncer,brotherlogic/discogssyncer | ---
+++
@@ -24,4 +24,4 @@
if size_1 != size_2:
for line in os.popen('killall sync').readlines():
pass
- subprocess.Popen('./discogssyncer --port 50051')
+ subprocess.Popen(['./discogssyncer', '--port' ,'50051']) |
b3cc4e19ea207870b65f60e0ff4a5bc221ca493b | lib/node_modules/@stdlib/math/base/special/logit/test/fixtures/python/runner.py | lib/node_modules/@stdlib/math/base/special/logit/test/fixtures/python/runner.py | #!/usr/bin/env python
"""Generate fixtures."""
import os
import json
import numpy as np
from scipy import special
# Get the file path:
FILE = os.path.realpath(__file__)
# Extract the directory in which this file resides:
DIR = os.path.dirname(FILE)
def gen(x, name):
"""Generates fixture data and writes them to file.
# Arguments
* `x`: domain
* `name::str`: output filename
# Examples
``` python
python> x = linspace( -1000, 1000, 2001 );
python> gen( x, \"./data.json\" );
```
"""
y = special.logit(x)
# Store data to be written to file as a dictionary:
data = {
"x": x.tolist(),
"expected": y.tolist()
}
# Based on the script directory, create an output filepath:
filepath = os.path.join(DIR, name)
with open(filepath, 'w') as outfile:
json.dump(data, outfile)
def main():
"""Generate fixture data."""
x = np.linspace(0.0001, 0.25, 500)
gen(x, "small.json")
x = np.linspace(0.25, 0.75, 500)
gen(x, "medium.json")
x = np.linspace(0.75, 0.9999, 500)
gen(x, "large.json")
if __name__ == "__main__":
main()
| #!/usr/bin/env python
"""Generate fixtures."""
import os
import json
import numpy as np
from scipy import special
# Get the file path:
FILE = os.path.realpath(__file__)
# Extract the directory in which this file resides:
DIR = os.path.dirname(FILE)
def gen(x, name):
"""Generates fixture data and writes them to file.
# Arguments
* `x`: domain
* `name::str`: output filename
# Examples
``` python
python> x = linspace(-1000, 1000, 2001);
python> gen(x, \"./data.json\");
```
"""
y = special.logit(x)
# Store data to be written to file as a dictionary:
data = {
"x": x.tolist(),
"expected": y.tolist()
}
# Based on the script directory, create an output filepath:
filepath = os.path.join(DIR, name)
with open(filepath, 'w') as outfile:
json.dump(data, outfile)
def main():
"""Generate fixture data."""
x = np.linspace(0.0001, 0.25, 500)
gen(x, "small.json")
x = np.linspace(0.25, 0.75, 500)
gen(x, "medium.json")
x = np.linspace(0.75, 0.9999, 500)
gen(x, "large.json")
if __name__ == "__main__":
main()
| Remove whitespace around brackets in example code | Remove whitespace around brackets in example code
| Python | apache-2.0 | stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib | ---
+++
@@ -25,8 +25,8 @@
# Examples
``` python
- python> x = linspace( -1000, 1000, 2001 );
- python> gen( x, \"./data.json\" );
+ python> x = linspace(-1000, 1000, 2001);
+ python> gen(x, \"./data.json\");
```
"""
y = special.logit(x) |
8589af4b858acace99cc856ce118f73568fb96b1 | main.py | main.py | #!/usr/bin/env python3.6
import argparse
import asyncio
import logging
import sys
from pathlib import Path
from MoMMI.logsetup import setup_logs
# Do this BEFORE we import master, because it does a lot of event loop stuff.
if sys.platform == "win32":
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop)
else:
try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except:
pass
from MoMMI.master import master
def main() -> None:
version = sys.version_info
if version.major < 3 or (version.major == 3 and version.minor < 6):
logging.critical("You need at least Python 3.6 to run MoMMI.")
sys.exit(1)
setup_logs()
parser = argparse.ArgumentParser()
parser.add_argument("--config-dir", "-c",
default="./config",
help="The directory to read config files from.",
dest="config",
type=Path)
parser.add_argument("--storage-dir", "-s",
default="./data",
help="The directory to use for server data storage.",
dest="data",
type=Path)
args = parser.parse_args()
master.start(args.config, args.data)
if __name__ == "__main__":
main()
| #!/usr/bin/env python3.6
import argparse
import asyncio
import logging
import sys
from pathlib import Path
from MoMMI.logsetup import setup_logs
# Do this BEFORE we import master, because it does a lot of event loop stuff.
if sys.platform == "win32":
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop)
else:
try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
pass
from MoMMI.master import master
def main() -> None:
version = sys.version_info
if version.major < 3 or (version.major == 3 and version.minor < 6):
logging.critical("You need at least Python 3.6 to run MoMMI.")
sys.exit(1)
setup_logs()
parser = argparse.ArgumentParser()
parser.add_argument("--config-dir", "-c",
default="./config",
help="The directory to read config files from.",
dest="config",
type=Path)
parser.add_argument("--storage-dir", "-s",
default="./data",
help="The directory to use for server data storage.",
dest="data",
type=Path)
args = parser.parse_args()
master.start(args.config, args.data)
if __name__ == "__main__":
main()
| Make uvloop except be explicit ImportError | Make uvloop except be explicit ImportError
| Python | mit | PJB3005/MoMMI,PJB3005/MoMMI,PJB3005/MoMMI | ---
+++
@@ -16,7 +16,7 @@
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
- except:
+ except ImportError:
pass
from MoMMI.master import master |
d57d572d91a5df06bbab97864c6187c7423c0135 | main.py | main.py | # Import blockmodels file
import BlockModels
import webapp2, jinja2, os
from datetime import *
jinja_environment = jinja2.Environment(autoescape=True,
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))
class CST(tzinfo):
def utcoffset(self, dt):
return timedelta(hours=-6)
def tzname(self, dt):
return "US/Central"
def dst(self, dt):
return timedelta(0)
cst = CST()
class MainHandler(webapp2.RequestHandler):
def get(self):
schedule = BlockModels.schedule()
tlocal = datetime.now(cst)
formNow = datetime.strftime(tlocal, "%A, %b %d %I:%M:%S %p")
template_values = {
'schedule': schedule,
'localtime': formNow,
}
template = jinja_environment.get_template('Prototype1.html')
self.response.out.write(template.render(template_values))
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)
| # Import blockmodels file
import BlockModels
import webapp2, jinja2, os
from datetime import *
jinja_environment = jinja2.Environment(autoescape=True,
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))
class CST(tzinfo):
def utcoffset(self, dt):
return timedelta(hours=-6)
def tzname(self, dt):
return "US/Central"
def dst(self, dt):
return timedelta(0)
cst = CST()
class Schedule_Handler(webapp2.RequestHandler):
def get(self):
schedule = BlockModels.schedule()
tlocal = datetime.now(cst)
formNow = datetime.strftime(tlocal, "%A, %b %d %I:%M:%S %p")
template_values = {
'schedule': schedule,
'localtime': formNow,
}
template = jinja_environment.get_template('schedule.html')
self.response.out.write(template.render(template_values))
app = webapp2.WSGIApplication([
('/schedule', Schedule_Handler)
], debug=True)
| Change the MainHandler to Schedule_Handler and changed the “/“ to “/schedule” | Change the MainHandler to Schedule_Handler and changed the “/“ to “/schedule”
| Python | mit | shickey/BearStatus,shickey/BearStatus,shickey/BearStatus | ---
+++
@@ -18,7 +18,7 @@
cst = CST()
-class MainHandler(webapp2.RequestHandler):
+class Schedule_Handler(webapp2.RequestHandler):
def get(self):
schedule = BlockModels.schedule()
tlocal = datetime.now(cst)
@@ -28,11 +28,11 @@
'localtime': formNow,
}
- template = jinja_environment.get_template('Prototype1.html')
+ template = jinja_environment.get_template('schedule.html')
self.response.out.write(template.render(template_values))
app = webapp2.WSGIApplication([
- ('/', MainHandler)
+ ('/schedule', Schedule_Handler)
], debug=True)
|
306dc0d7e96d91b417a702230a9d34fa1dbcc289 | util.py | util.py | import collections
def flatten(l, ltypes=collections.Sequence):
l = list(l)
while l:
if isinstance(l[0], str):
yield l.pop(0)
continue
while l and isinstance(l[0], ltypes):
l[0:1] = l[0]
if l:
yield l.pop(0)
noop = lambda self, *a, **kw: None
passthrough = lambda v: v
| import collections
def flatten(l, ltypes=collections.Sequence):
l = list(l)
while l:
if isinstance(l[0], str):
yield l.pop(0)
continue
while l and isinstance(l[0], ltypes):
l[0:1] = l[0]
if l:
yield l.pop(0)
def getattrpath(obj, path):
'''
path is a dot-delimited chain of attributes to look up.
getattrpath(my_object, 'a.b.c') returns my_object.a.b.c
'''
for attr in path.split('.'):
obj = getattr(obj, attr)
return obj
def prefix_keys(prefix, dict):
for key, value in dict.items():
yield prefix + key, value
noop = lambda self, *a, **kw: None
passthrough = lambda v: v
| Add helpers for nested attributes | Add helpers for nested attributes
getattrpath is for nested retrieval (getting obj.a.b.c with
getattrpath(obj, 'a.b.c))
prefix_keys generates key, value pairs with the prefix prepended to each
key.
| Python | mit | numberoverzero/origami | ---
+++
@@ -12,5 +12,20 @@
if l:
yield l.pop(0)
+
+def getattrpath(obj, path):
+ '''
+ path is a dot-delimited chain of attributes to look up.
+ getattrpath(my_object, 'a.b.c') returns my_object.a.b.c
+ '''
+ for attr in path.split('.'):
+ obj = getattr(obj, attr)
+ return obj
+
+
+def prefix_keys(prefix, dict):
+ for key, value in dict.items():
+ yield prefix + key, value
+
noop = lambda self, *a, **kw: None
passthrough = lambda v: v |
6c7c69fccd924ab65219c7f28dbdef66bec7181a | 4/src.py | 4/src.py | import sys
from itertools import imap
from collections import Counter
class Room:
pass
def parse_room(s):
last_dash = s.rfind("-")
after_name = s[last_dash+1:]
bracket = after_name.find("[")
room = Room()
room.name = s[:last_dash]
room.sector = int(after_name[:bracket])
room.checksum = after_name[bracket+1:-2]
return room
def frequencies(coll):
ret = Counter(coll)
del ret['-']
return ret
def sort_frequencies(dict):
def alphasort((a, i), (b, j)):
if i != j:
return j - i
return ord(a) - ord(b)
return sorted(dict.items(), cmp=alphasort)
def run_checksum(name):
return ''.join([c for (c, n) in sort_frequencies(frequencies(name))[:5]])
def rotate(c, amt):
if c == '-':
return " "
x = ord(c) - ord('a')
return chr((x + amt) % 26 + ord('a'))
if __name__ == '__main__':
sum = 0
for room in imap(parse_room, sys.stdin):
if room.checksum == run_checksum(room.name):
sum = sum + room.sector
if ('northpole object storage' ==
''.join(map(lambda c: rotate(c, room.sector), room.name))):
print "part 2:", room.sector
print "part 1:", sum
| import sys
from itertools import imap
from collections import Counter
class Room:
pass
def parse_room(s):
last_dash = s.rfind("-")
after_name = s[last_dash+1:]
bracket = after_name.find("[")
room = Room()
room.name = s[:last_dash]
room.sector = int(after_name[:bracket])
room.checksum = after_name[bracket+1:-2]
return room
def frequencies(coll):
ret = Counter(coll)
del ret['-']
return ret
def sort_frequencies(dict):
def alphasort((a, i), (b, j)):
if i != j:
return j - i
return ord(a) - ord(b)
return sorted(dict.items(), cmp=alphasort)
def run_checksum(name):
return ''.join([c for (c, n) in sort_frequencies(frequencies(name))[:5]])
def rotate(amt):
def rotator(c):
if c == '-':
return " "
x = ord(c) - ord('a')
return chr((x + amt) % 26 + ord('a'))
return rotator
if __name__ == '__main__':
sum = 0
for room in imap(parse_room, sys.stdin):
if room.checksum == run_checksum(room.name):
sum = sum + room.sector
if ('northpole object storage' ==
''.join(map(rotate(room.sector), room.name))):
print "part 2:", room.sector
print "part 1:", sum
| Replace lambda with higher-order function | Replace lambda with higher-order function
| Python | mit | amalloy/advent-of-code-2016 | ---
+++
@@ -32,11 +32,13 @@
def run_checksum(name):
return ''.join([c for (c, n) in sort_frequencies(frequencies(name))[:5]])
-def rotate(c, amt):
- if c == '-':
- return " "
- x = ord(c) - ord('a')
- return chr((x + amt) % 26 + ord('a'))
+def rotate(amt):
+ def rotator(c):
+ if c == '-':
+ return " "
+ x = ord(c) - ord('a')
+ return chr((x + amt) % 26 + ord('a'))
+ return rotator
if __name__ == '__main__':
sum = 0
@@ -44,6 +46,6 @@
if room.checksum == run_checksum(room.name):
sum = sum + room.sector
if ('northpole object storage' ==
- ''.join(map(lambda c: rotate(c, room.sector), room.name))):
+ ''.join(map(rotate(room.sector), room.name))):
print "part 2:", room.sector
print "part 1:", sum |
3f160ac663ff37b5b8b16ebe630536521969d079 | text.py | text.py | import ibmcnx.filehandle
emp1 = ibmcnx.filehandle.Ibmcnxfile()
emp1.writeToFile( execfile('ibmcnx/doc/JVMSettings.py' ) )
#emp1.writeToFile("Test2")
#emp1.writeToFile("Test3")
emp1.closeFile()
| import ibmcnx.filehandle
import sys
sys.stdout = open("/tmp/documentation.txt", "w")
print "test"
execfile('ibmcnx/doc/JVMSettings.py' )
| Create script to save documentation to a file | 4: Create script to save documentation to a file
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 | ---
+++
@@ -1,8 +1,8 @@
import ibmcnx.filehandle
+import sys
+sys.stdout = open("/tmp/documentation.txt", "w")
-emp1 = ibmcnx.filehandle.Ibmcnxfile()
+print "test"
-emp1.writeToFile( execfile('ibmcnx/doc/JVMSettings.py' ) )
-#emp1.writeToFile("Test2")
-#emp1.writeToFile("Test3")
-emp1.closeFile()
+execfile('ibmcnx/doc/JVMSettings.py' )
+ |
b725eac62c72dd3674f35898ff6704c613e7272d | bears/julia/JuliaLintBear.py | bears/julia/JuliaLintBear.py | from coalib.bearlib.abstractions.Lint import Lint
from coalib.bears.LocalBear import LocalBear
from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY
class JuliaLintBear(LocalBear, Lint):
executable = 'julia'
arguments = '-e \'import Lint.lintfile; lintfile({filename})\''
output_regex = r'(^.*\.jl):(?P<line>\d+) (?P<severity>.)\d+ (?P<message>.*)'
use_stdout = True
severity_map = {
"E": RESULT_SEVERITY.MAJOR,
"W": RESULT_SEVERITY.NORMAL,
"I": RESULT_SEVERITY.INFO
}
def run(self, filename, file):
'''
Lints Julia code using ``Lint.jl``.
https://github.com/tonyhffong/Lint.jl
'''
return self.lint(filename, file)
| from coalib.bearlib.abstractions.Lint import Lint
from coalib.bears.LocalBear import LocalBear
from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY
class JuliaLintBear(LocalBear, Lint):
executable = 'julia'
arguments = '-e \'import Lint.lintfile; lintfile({filename})\''
prerequisite_command = ['julia', '-e', 'import Lint.lintfile']
prerequisite_fail_msg = 'Run `Pkg.add("Lint")` from Julia to install Lint.'
output_regex = r'(^.*\.jl):(?P<line>\d+) (?P<severity>.)\d+ (?P<message>.*)'
use_stdout = True
severity_map = {
"E": RESULT_SEVERITY.MAJOR,
"W": RESULT_SEVERITY.NORMAL,
"I": RESULT_SEVERITY.INFO
}
def run(self, filename, file):
'''
Lints Julia code using ``Lint.jl``.
https://github.com/tonyhffong/Lint.jl
'''
return self.lint(filename, file)
| Add Skip Condition for JuliaBear | bears/julia: Add Skip Condition for JuliaBear
Add prerequisite_command and prerequisite_fail_msg
to JuliaBear.
Fixes https://github.com/coala-analyzer/coala-bears/issues/222
| Python | agpl-3.0 | yash-nisar/coala-bears,naveentata/coala-bears,kaustubhhiware/coala-bears,mr-karan/coala-bears,shreyans800755/coala-bears,sims1253/coala-bears,coala-analyzer/coala-bears,coala/coala-bears,coala-analyzer/coala-bears,chriscoyfish/coala-bears,seblat/coala-bears,Vamshi99/coala-bears,seblat/coala-bears,sounak98/coala-bears,LWJensen/coala-bears,yashtrivedi96/coala-bears,LWJensen/coala-bears,shreyans800755/coala-bears,arjunsinghy96/coala-bears,vijeth-aradhya/coala-bears,mr-karan/coala-bears,incorrectusername/coala-bears,madhukar01/coala-bears,horczech/coala-bears,meetmangukiya/coala-bears,SanketDG/coala-bears,ku3o/coala-bears,srisankethu/coala-bears,horczech/coala-bears,Shade5/coala-bears,ankit01ojha/coala-bears,incorrectusername/coala-bears,sounak98/coala-bears,chriscoyfish/coala-bears,madhukar01/coala-bears,dosarudaniel/coala-bears,yash-nisar/coala-bears,Vamshi99/coala-bears,seblat/coala-bears,Vamshi99/coala-bears,naveentata/coala-bears,mr-karan/coala-bears,kaustubhhiware/coala-bears,meetmangukiya/coala-bears,refeed/coala-bears,horczech/coala-bears,naveentata/coala-bears,Shade5/coala-bears,yash-nisar/coala-bears,meetmangukiya/coala-bears,sals1275/coala-bears,coala/coala-bears,gs0510/coala-bears,vijeth-aradhya/coala-bears,madhukar01/coala-bears,chriscoyfish/coala-bears,Shade5/coala-bears,kaustubhhiware/coala-bears,sals1275/coala-bears,seblat/coala-bears,yash-nisar/coala-bears,sounak98/coala-bears,yashtrivedi96/coala-bears,aptrishu/coala-bears,Shade5/coala-bears,yash-nisar/coala-bears,srisankethu/coala-bears,ku3o/coala-bears,chriscoyfish/coala-bears,yashtrivedi96/coala-bears,sals1275/coala-bears,seblat/coala-bears,chriscoyfish/coala-bears,sounak98/coala-bears,dosarudaniel/coala-bears,kaustubhhiware/coala-bears,coala/coala-bears,srisankethu/coala-bears,horczech/coala-bears,shreyans800755/coala-bears,arjunsinghy96/coala-bears,coala/coala-bears,mr-karan/coala-bears,Vamshi99/coala-bears,dosarudaniel/coala-bears,coala/coala-bears,yashtrivedi96/coala-bears,SanketDG/coala-bears,coala-analyzer/coala-bears,meetmangukiya/coala-bears,arjunsinghy96/coala-bears,damngamerz/coala-bears,srisankethu/coala-bears,gs0510/coala-bears,Asnelchristian/coala-bears,damngamerz/coala-bears,madhukar01/coala-bears,horczech/coala-bears,srisankethu/coala-bears,mr-karan/coala-bears,Shade5/coala-bears,dosarudaniel/coala-bears,chriscoyfish/coala-bears,damngamerz/coala-bears,LWJensen/coala-bears,yashtrivedi96/coala-bears,coala/coala-bears,naveentata/coala-bears,Asnelchristian/coala-bears,SanketDG/coala-bears,madhukar01/coala-bears,Asnelchristian/coala-bears,damngamerz/coala-bears,shreyans800755/coala-bears,damngamerz/coala-bears,refeed/coala-bears,vijeth-aradhya/coala-bears,horczech/coala-bears,Vamshi99/coala-bears,sals1275/coala-bears,LWJensen/coala-bears,sims1253/coala-bears,sounak98/coala-bears,yashtrivedi96/coala-bears,arjunsinghy96/coala-bears,refeed/coala-bears,srisankethu/coala-bears,Asnelchristian/coala-bears,shreyans800755/coala-bears,Asnelchristian/coala-bears,yash-nisar/coala-bears,ku3o/coala-bears,LWJensen/coala-bears,damngamerz/coala-bears,yash-nisar/coala-bears,coala/coala-bears,kaustubhhiware/coala-bears,Shade5/coala-bears,LWJensen/coala-bears,refeed/coala-bears,chriscoyfish/coala-bears,sims1253/coala-bears,meetmangukiya/coala-bears,ankit01ojha/coala-bears,mr-karan/coala-bears,incorrectusername/coala-bears,refeed/coala-bears,refeed/coala-bears,srisankethu/coala-bears,yashtrivedi96/coala-bears,ku3o/coala-bears,ku3o/coala-bears,mr-karan/coala-bears,seblat/coala-bears,SanketDG/coala-bears,ku3o/coala-bears,aptrishu/coala-bears,gs0510/coala-bears,sims1253/coala-bears,aptrishu/coala-bears,sounak98/coala-bears,dosarudaniel/coala-bears,SanketDG/coala-bears,coala-analyzer/coala-bears,arjunsinghy96/coala-bears,sals1275/coala-bears,coala-analyzer/coala-bears,naveentata/coala-bears,Shade5/coala-bears,arjunsinghy96/coala-bears,ankit01ojha/coala-bears,shreyans800755/coala-bears,Asnelchristian/coala-bears,yash-nisar/coala-bears,coala/coala-bears,incorrectusername/coala-bears,aptrishu/coala-bears,sounak98/coala-bears,Shade5/coala-bears,ankit01ojha/coala-bears,kaustubhhiware/coala-bears,SanketDG/coala-bears,shreyans800755/coala-bears,Asnelchristian/coala-bears,naveentata/coala-bears,SanketDG/coala-bears,damngamerz/coala-bears,ankit01ojha/coala-bears,horczech/coala-bears,sims1253/coala-bears,horczech/coala-bears,naveentata/coala-bears,Asnelchristian/coala-bears,Vamshi99/coala-bears,srisankethu/coala-bears,sims1253/coala-bears,sals1275/coala-bears,Vamshi99/coala-bears,dosarudaniel/coala-bears,yashtrivedi96/coala-bears,incorrectusername/coala-bears,dosarudaniel/coala-bears,coala-analyzer/coala-bears,gs0510/coala-bears,Vamshi99/coala-bears,refeed/coala-bears,kaustubhhiware/coala-bears,sals1275/coala-bears,LWJensen/coala-bears,sims1253/coala-bears,coala-analyzer/coala-bears,madhukar01/coala-bears,coala/coala-bears,coala/coala-bears,yash-nisar/coala-bears,vijeth-aradhya/coala-bears,srisankethu/coala-bears,aptrishu/coala-bears,srisankethu/coala-bears,coala-analyzer/coala-bears,coala/coala-bears,gs0510/coala-bears,aptrishu/coala-bears,Asnelchristian/coala-bears,gs0510/coala-bears,ankit01ojha/coala-bears,ankit01ojha/coala-bears,vijeth-aradhya/coala-bears,ankit01ojha/coala-bears,dosarudaniel/coala-bears,incorrectusername/coala-bears,refeed/coala-bears,shreyans800755/coala-bears,incorrectusername/coala-bears,ankit01ojha/coala-bears,damngamerz/coala-bears,coala-analyzer/coala-bears,shreyans800755/coala-bears,gs0510/coala-bears,kaustubhhiware/coala-bears,damngamerz/coala-bears,refeed/coala-bears,aptrishu/coala-bears,kaustubhhiware/coala-bears,meetmangukiya/coala-bears,gs0510/coala-bears,vijeth-aradhya/coala-bears,sals1275/coala-bears,LWJensen/coala-bears,sounak98/coala-bears,Vamshi99/coala-bears,SanketDG/coala-bears,vijeth-aradhya/coala-bears,damngamerz/coala-bears,yash-nisar/coala-bears,seblat/coala-bears,ku3o/coala-bears,refeed/coala-bears,dosarudaniel/coala-bears,madhukar01/coala-bears,SanketDG/coala-bears,arjunsinghy96/coala-bears,Vamshi99/coala-bears,ankit01ojha/coala-bears,incorrectusername/coala-bears,refeed/coala-bears,yashtrivedi96/coala-bears,srisankethu/coala-bears,damngamerz/coala-bears,meetmangukiya/coala-bears,horczech/coala-bears,madhukar01/coala-bears,aptrishu/coala-bears,horczech/coala-bears,gs0510/coala-bears,meetmangukiya/coala-bears,shreyans800755/coala-bears,chriscoyfish/coala-bears,aptrishu/coala-bears,LWJensen/coala-bears,ku3o/coala-bears,horczech/coala-bears,arjunsinghy96/coala-bears,incorrectusername/coala-bears,sims1253/coala-bears,vijeth-aradhya/coala-bears,coala/coala-bears,aptrishu/coala-bears,vijeth-aradhya/coala-bears,Vamshi99/coala-bears,meetmangukiya/coala-bears,naveentata/coala-bears,seblat/coala-bears,naveentata/coala-bears,ankit01ojha/coala-bears,arjunsinghy96/coala-bears,sounak98/coala-bears,yash-nisar/coala-bears,Shade5/coala-bears,aptrishu/coala-bears,ku3o/coala-bears,shreyans800755/coala-bears,madhukar01/coala-bears,mr-karan/coala-bears | ---
+++
@@ -6,6 +6,8 @@
class JuliaLintBear(LocalBear, Lint):
executable = 'julia'
arguments = '-e \'import Lint.lintfile; lintfile({filename})\''
+ prerequisite_command = ['julia', '-e', 'import Lint.lintfile']
+ prerequisite_fail_msg = 'Run `Pkg.add("Lint")` from Julia to install Lint.'
output_regex = r'(^.*\.jl):(?P<line>\d+) (?P<severity>.)\d+ (?P<message>.*)'
use_stdout = True
severity_map = { |
e38f81fff1edf83bc6739804447e4a64a0a76de8 | apps/persona/urls.py | apps/persona/urls.py | from django.conf.urls.defaults import *
from mozorg.util import page
import views
urlpatterns = patterns('',
page('', 'persona/persona.html'),
page('about', 'persona/about.html'),
page('privacy-policy', 'persona/privacy-policy.html'),
page('terms-of-service', 'persona/terms-of-service.html'),
page('developer-faq', 'persona/developer-faq.html')
)
| from django.conf.urls.defaults import *
from mozorg.util import page
urlpatterns = patterns('',
page('', 'persona/persona.html'),
page('about', 'persona/about.html'),
page('privacy-policy', 'persona/privacy-policy.html'),
page('terms-of-service', 'persona/terms-of-service.html'),
page('developer-faq', 'persona/developer-faq.html')
)
| Remove unnecessary 'import views' line | Remove unnecessary 'import views' line
| Python | mpl-2.0 | mmmavis/bedrock,pmclanahan/bedrock,malena/bedrock,craigcook/bedrock,dudepare/bedrock,davehunt/bedrock,flodolo/bedrock,dudepare/bedrock,schalkneethling/bedrock,mahinthjoe/bedrock,analytics-pros/mozilla-bedrock,flodolo/bedrock,mkmelin/bedrock,mermi/bedrock,pmclanahan/bedrock,SujaySKumar/bedrock,mmmavis/bedrock,mahinthjoe/bedrock,petabyte/bedrock,glogiotatidis/bedrock,marcoscaceres/bedrock,MichaelKohler/bedrock,mmmavis/lightbeam-bedrock-website,Sancus/bedrock,ckprice/bedrock,Jobava/bedrock,MichaelKohler/bedrock,mmmavis/lightbeam-bedrock-website,pascalchevrel/bedrock,CSCI-462-01-2017/bedrock,flodolo/bedrock,jgmize/bedrock,ericawright/bedrock,TheJJ100100/bedrock,jpetto/bedrock,alexgibson/bedrock,pascalchevrel/bedrock,sgarrity/bedrock,TheoChevalier/bedrock,pascalchevrel/bedrock,CSCI-462-01-2017/bedrock,l-hedgehog/bedrock,gauthierm/bedrock,Sancus/bedrock,alexgibson/bedrock,glogiotatidis/bedrock,TheoChevalier/bedrock,TheJJ100100/bedrock,craigcook/bedrock,mozilla/mwc,CSCI-462-01-2017/bedrock,l-hedgehog/bedrock,dudepare/bedrock,yglazko/bedrock,mozilla/bedrock,jacshfr/mozilla-bedrock,davidwboswell/documentation_autoresponse,mozilla/bedrock,yglazko/bedrock,TheJJ100100/bedrock,Jobava/bedrock,SujaySKumar/bedrock,TheoChevalier/bedrock,jgmize/bedrock,mmmavis/lightbeam-bedrock-website,davidwboswell/documentation_autoresponse,davehunt/bedrock,hoosteeno/bedrock,mkmelin/bedrock,Sancus/bedrock,elin-moco/bedrock,malena/bedrock,elin-moco/bedrock,schalkneethling/bedrock,pmclanahan/bedrock,ericawright/bedrock,rishiloyola/bedrock,sylvestre/bedrock,mkmelin/bedrock,marcoscaceres/bedrock,gerv/bedrock,amjadm61/bedrock,sylvestre/bedrock,andreadelrio/bedrock,dudepare/bedrock,chirilo/bedrock,mahinthjoe/bedrock,jpetto/bedrock,ericawright/bedrock,gauthierm/bedrock,mkmelin/bedrock,kyoshino/bedrock,alexgibson/bedrock,craigcook/bedrock,sylvestre/bedrock,rishiloyola/bedrock,SujaySKumar/bedrock,mozilla/bedrock,yglazko/bedrock,bensternthal/bedrock,hoosteeno/bedrock,sgarrity/bedrock,jacshfr/mozilla-bedrock,ckprice/bedrock,jacshfr/mozilla-bedrock,CSCI-462-01-2017/bedrock,glogiotatidis/bedrock,amjadm61/bedrock,ckprice/bedrock,flodolo/bedrock,sgarrity/bedrock,gerv/bedrock,schalkneethling/bedrock,SujaySKumar/bedrock,marcoscaceres/bedrock,gerv/bedrock,TheoChevalier/bedrock,jpetto/bedrock,yglazko/bedrock,alexgibson/bedrock,mozilla/mwc,Jobava/bedrock,analytics-pros/mozilla-bedrock,malena/bedrock,jpetto/bedrock,bensternthal/bedrock,petabyte/bedrock,mahinthjoe/bedrock,glogiotatidis/bedrock,pmclanahan/bedrock,schalkneethling/bedrock,andreadelrio/bedrock,jacshfr/mozilla-bedrock,petabyte/bedrock,Sancus/bedrock,elin-moco/bedrock,andreadelrio/bedrock,andreadelrio/bedrock,jacshfr/mozilla-bedrock,kyoshino/bedrock,mozilla/mwc,gauthierm/bedrock,rishiloyola/bedrock,MichaelKohler/bedrock,davidwboswell/documentation_autoresponse,MichaelKohler/bedrock,kyoshino/bedrock,chirilo/bedrock,mmmavis/bedrock,amjadm61/bedrock,jgmize/bedrock,davidwboswell/documentation_autoresponse,pascalchevrel/bedrock,gerv/bedrock,rishiloyola/bedrock,hoosteeno/bedrock,mermi/bedrock,mozilla/mwc,sgarrity/bedrock,mozilla/bedrock,chirilo/bedrock,mermi/bedrock,bensternthal/bedrock,ericawright/bedrock,Jobava/bedrock,marcoscaceres/bedrock,l-hedgehog/bedrock,bensternthal/bedrock,mmmavis/bedrock,davehunt/bedrock,malena/bedrock,davehunt/bedrock,analytics-pros/mozilla-bedrock,petabyte/bedrock,gauthierm/bedrock,elin-moco/bedrock,TheJJ100100/bedrock,sylvestre/bedrock,kyoshino/bedrock,analytics-pros/mozilla-bedrock,amjadm61/bedrock,l-hedgehog/bedrock,hoosteeno/bedrock,jgmize/bedrock,ckprice/bedrock,craigcook/bedrock,amjadm61/bedrock,mermi/bedrock,chirilo/bedrock | ---
+++
@@ -1,6 +1,5 @@
from django.conf.urls.defaults import *
from mozorg.util import page
-import views
urlpatterns = patterns('',
page('', 'persona/persona.html'), |
cd5c50c94f2240c3d4996e38cc1712e5f397120f | datalogger/__init__.py | datalogger/__init__.py | from datalogger import api
from datalogger import analysis
from datalogger import acquisition
from datalogger import analysis_window, acquisition_window
#from datalogger.api import workspace as workspace
from datalogger.api import workspace as workspace
import os.path as _path
_PKG_ROOT = _path.abspath(_path.dirname(__file__))
if _path.isfile(_path.join(_PKG_ROOT, 'VERSION')):
with open(_path.join(_PKG_ROOT, 'VERSION')) as _version_file:
#with open('VERSION') as _version_file:
__version__ = _version_file.read()
| from datalogger import api
from datalogger import analysis
from datalogger import acquisition
from datalogger import analysis_window, acquisition_window
#from datalogger.api import workspace as workspace
from datalogger.api import workspace as workspace
import os.path as _path
_PKG_ROOT = _path.abspath(_path.dirname(__file__))
if _path.isfile(_path.join(_PKG_ROOT, 'VERSION')):
with open(_path.join(_PKG_ROOT, 'VERSION')) as _version_file:
#with open('VERSION') as _version_file:
__version__ = _version_file.read()
else:
__version__ = None | Add __version__=None if no VERSION found | Add __version__=None if no VERSION found
| Python | bsd-3-clause | torebutlin/cued_datalogger | ---
+++
@@ -13,3 +13,5 @@
with open(_path.join(_PKG_ROOT, 'VERSION')) as _version_file:
#with open('VERSION') as _version_file:
__version__ = _version_file.read()
+else:
+ __version__ = None |
493df570353fbeff288d6ee61fb0842622443967 | sleekxmpp/thirdparty/__init__.py | sleekxmpp/thirdparty/__init__.py | try:
from ordereddict import OrderedDict
except:
from sleekxmpp.thirdparty.ordereddict import OrderedDict
| try:
from collections import OrderedDict
except:
from sleekxmpp.thirdparty.ordereddict import OrderedDict
| Fix thirdparty imports for Python3 | Fix thirdparty imports for Python3
| Python | mit | destroy/SleekXMPP-gevent | ---
+++
@@ -1,4 +1,4 @@
try:
- from ordereddict import OrderedDict
+ from collections import OrderedDict
except:
from sleekxmpp.thirdparty.ordereddict import OrderedDict |
53dc5e1029ea905f6e5da86592b33911309d1acd | bdateutil/__init__.py | bdateutil/__init__.py | # bdateutil
# -----------
# Adds business day logic and improved data type flexibility to
# python-dateutil.
#
# Author: ryanss <ryanssdev@icloud.com>
# Website: https://github.com/ryanss/bdateutil
# License: MIT (see LICENSE file)
__version__ = '0.1-dev'
from dateutil.relativedelta import MO, TU, WE, TH, FR, SA, SU
from relativedelta import relativedelta
__all__ = ['relativedelta', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU']
| # bdateutil
# -----------
# Adds business day logic and improved data type flexibility to
# python-dateutil.
#
# Author: ryanss <ryanssdev@icloud.com>
# Website: https://github.com/ryanss/bdateutil
# License: MIT (see LICENSE file)
__version__ = '0.1-dev'
from dateutil.relativedelta import MO, TU, WE, TH, FR, SA, SU
from bdateutil.relativedelta import relativedelta
__all__ = ['relativedelta', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU']
| Fix import statement in Python 3 | Fix import statement in Python 3
| Python | mit | pganssle/bdateutil | ---
+++
@@ -11,7 +11,8 @@
from dateutil.relativedelta import MO, TU, WE, TH, FR, SA, SU
-from relativedelta import relativedelta
+
+from bdateutil.relativedelta import relativedelta
__all__ = ['relativedelta', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'] |
4d7c1fec37943558ccc8bf6a17860b2a86fe1941 | gee_asset_manager/batch_copy.py | gee_asset_manager/batch_copy.py | import ee
import os
import csv
import logging
def copy(source, destination):
with open(source, 'r') as f:
reader = csv.reader(f)
for line in reader:
name = line[0]
gme_id = line[1]
gme_path = 'GME/images/' + gme_id
ee_path = os.path.join(destination, name)
logging.info('Copying asset %s to %s', gme_path, ee_path)
ee.data.copyAsset(gme_path, ee_path)
if __name__ == '__main__':
ee.Initialize()
assets = '/home/tracek/Data/consbio2016/test.csv'
with open(assets, 'r') as f:
reader = csv.reader(f) | import ee
import os
import csv
import logging
def copy(source, destination):
with open(source, 'r') as f:
reader = csv.reader(f)
for line in reader:
name = line[0]
gme_id = line[1]
gme_path = 'GME/images/' + gme_id
ee_path = os.path.join(destination, name)
logging.info('Copying asset %s to %s', gme_path, ee_path)
try:
ee.data.copyAsset(gme_path, ee_path)
except ee.EEException as e:
with open('failed_batch_copy.csv', 'w') as fout:
fout.write('%s,%s,%s,%s', name, gme_id, ee_path,e)
if __name__ == '__main__':
ee.Initialize()
assets = '/home/tracek/Data/consbio2016/test.csv'
with open(assets, 'r') as f:
reader = csv.reader(f) | Add exception handling to batch copy | Add exception handling to batch copy
| Python | apache-2.0 | tracek/gee_asset_manager | ---
+++
@@ -12,7 +12,11 @@
gme_path = 'GME/images/' + gme_id
ee_path = os.path.join(destination, name)
logging.info('Copying asset %s to %s', gme_path, ee_path)
- ee.data.copyAsset(gme_path, ee_path)
+ try:
+ ee.data.copyAsset(gme_path, ee_path)
+ except ee.EEException as e:
+ with open('failed_batch_copy.csv', 'w') as fout:
+ fout.write('%s,%s,%s,%s', name, gme_id, ee_path,e)
if __name__ == '__main__': |
cf4b58ff5afa6c7c8649e89b430b5386fabdc02c | djmoney/serializers.py | djmoney/serializers.py | # coding=utf-8
import json
from decimal import Decimal
from django.core.serializers.python import Deserializer as PythonDeserializer
from django.core.serializers.json import Serializer as JSONSerializer
from django.core.serializers.python import _get_model
from django.utils import six
from djmoney.models.fields import MoneyField
Serializer = JSONSerializer
def Deserializer(stream_or_string, **options):
"""
Deserialize a stream or string of JSON data.
"""
if not isinstance(stream_or_string, (bytes, six.string_types)):
stream_or_string = stream_or_string.read()
if isinstance(stream_or_string, bytes):
stream_or_string = stream_or_string.decode('utf-8')
try:
obj_list = []
for obj in json.loads(stream_or_string):
money_fields = {}
fields = {}
Model = _get_model(obj["model"])
for (field_name, field_value) in obj['fields'].iteritems():
field = Model._meta.get_field(field_name)
if isinstance(field, MoneyField):
money_fields[field_name] = Decimal(
field_value.split(" ")[0])
else:
fields[field_name] = field_value
obj['fields'] = fields
for obj in PythonDeserializer([obj], **options):
for field, value in money_fields.items():
setattr(obj.object, field, value)
yield obj
except GeneratorExit:
raise
| # coding=utf-8
import json
from decimal import Decimal
from django.core.serializers.python import Deserializer as PythonDeserializer
from django.core.serializers.json import Serializer as JSONSerializer
from django.core.serializers.python import _get_model
from django.utils import six
from djmoney.models.fields import MoneyField
from moneyed import Money
Serializer = JSONSerializer
def Deserializer(stream_or_string, **options):
"""
Deserialize a stream or string of JSON data.
"""
if not isinstance(stream_or_string, (bytes, six.string_types)):
stream_or_string = stream_or_string.read()
if isinstance(stream_or_string, bytes):
stream_or_string = stream_or_string.decode('utf-8')
try:
obj_list = []
for obj in json.loads(stream_or_string):
money_fields = {}
fields = {}
Model = _get_model(obj["model"])
for (field_name, field_value) in obj['fields'].iteritems():
field = Model._meta.get_field(field_name)
if isinstance(field, MoneyField):
money_fields[field_name] = Money(field_value, obj['fields']['%s_currency' % field_name])
else:
fields[field_name] = field_value
obj['fields'] = fields
for obj in PythonDeserializer([obj], **options):
for field, value in money_fields.items():
setattr(obj.object, field, value)
yield obj
except GeneratorExit:
raise
| Fix for de-serialization. Using vanilla django-money, when one did the following: | Fix for de-serialization.
Using vanilla django-money, when one did the following:
./manage.py dumpdata
the values were saved properly, i.e:
{
'amount': '12',
'amount_currency': 'USD',
}
however, after the de-serialization:
./manage.py loaddata [fixtures]
the currencies were omitted.
i have no idea (yet) how to write a test that proves that.. :/
| Python | bsd-3-clause | rescale/django-money,tsouvarev/django-money,iXioN/django-money,iXioN/django-money,recklessromeo/django-money,recklessromeo/django-money,tsouvarev/django-money,AlexRiina/django-money | ---
+++
@@ -9,6 +9,7 @@
from django.utils import six
from djmoney.models.fields import MoneyField
+from moneyed import Money
Serializer = JSONSerializer
@@ -30,8 +31,7 @@
for (field_name, field_value) in obj['fields'].iteritems():
field = Model._meta.get_field(field_name)
if isinstance(field, MoneyField):
- money_fields[field_name] = Decimal(
- field_value.split(" ")[0])
+ money_fields[field_name] = Money(field_value, obj['fields']['%s_currency' % field_name])
else:
fields[field_name] = field_value
obj['fields'] = fields |
ceb3a49fc3e3ca149d203e8489bd4b17b286d6c3 | event/urls.py | event/urls.py | from django.conf.urls import url
from . import views
app_name = 'event'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^artist/$', views.ArtistView.as_view(), name='artist'),
url(r'^artist/(?P<pk>\d+)$', views.ArtistDetailView.as_view(), name='artist_detail'),
url(r'^event/$', views.EventView.as_view(), name='event'),
url(r'^venue/$', views.VenueView.as_view(), name='venue'),
url(r'^profile/$', views.ProfileView.as_view(), name='profile'),
]
| from django.conf.urls import url
from . import views
app_name = 'event'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^artist/$', views.ArtistView.as_view(), name='artist'),
url(r'^artist/(?P<pk>\d+)/$', views.ArtistDetailView.as_view(), name='artist_detail'),
url(r'^event/$', views.EventView.as_view(), name='event'),
url(r'^venue/$', views.VenueView.as_view(), name='venue'),
url(r'^profile/$', views.ProfileView.as_view(), name='profile'),
]
| Fix Artist detail view url | Fix Artist detail view url
| Python | mit | FedorSelitsky/eventrack,FedorSelitsky/eventrack,FedorSelitsky/eventrack,FedorSelitsky/eventrack | ---
+++
@@ -6,7 +6,7 @@
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^artist/$', views.ArtistView.as_view(), name='artist'),
- url(r'^artist/(?P<pk>\d+)$', views.ArtistDetailView.as_view(), name='artist_detail'),
+ url(r'^artist/(?P<pk>\d+)/$', views.ArtistDetailView.as_view(), name='artist_detail'),
url(r'^event/$', views.EventView.as_view(), name='event'),
url(r'^venue/$', views.VenueView.as_view(), name='venue'),
url(r'^profile/$', views.ProfileView.as_view(), name='profile'), |
9719a31459e033cc84a5a522e4fc618aa11b45fe | charlesbot/util/http.py | charlesbot/util/http.py | import asyncio
import aiohttp
import logging
log = logging.getLogger(__name__)
@asyncio.coroutine
def http_get_auth_request(auth_string,
url,
content_type="application/json",
auth_method="Token",
payload={}):
headers = {
'Content-type': content_type,
'Authorization': "%s %s" % (auth_method, auth_string),
}
response = yield from aiohttp.get(url, headers=headers, params=payload)
if not response.status == 200:
text = yield from response.text()
log.error("Response status code was %s" % str(response.status))
log.error(response.headers)
log.error(text)
response.close()
return ""
return (yield from response.text())
@asyncio.coroutine
def http_get_request(url, content_type="application/json"):
headers = {
'Content-type': content_type,
}
response = yield from aiohttp.get(url, headers=headers)
if not response.status == 200:
text = yield from response.text()
log.error("Response status code was %s" % str(response.status))
log.error(response.headers)
log.error(text)
response.close()
return ""
return (yield from response.text())
| import asyncio
import aiohttp
import logging
log = logging.getLogger(__name__)
@asyncio.coroutine
def http_get_auth_request(auth_string,
url,
content_type="application/json",
auth_method="Token",
payload={}):
headers = {
'Content-type': content_type,
'Authorization': "%s %s" % (auth_method, auth_string),
}
response = yield from aiohttp.get(url, headers=headers, params=payload)
if not response.status == 200:
text = yield from response.text()
log.error("URL: %s" % url)
log.error("Response status code was %s" % str(response.status))
log.error(response.headers)
log.error(text)
response.close()
return ""
return (yield from response.text())
@asyncio.coroutine
def http_get_request(url, content_type="application/json"):
headers = {
'Content-type': content_type,
}
response = yield from aiohttp.get(url, headers=headers)
if not response.status == 200:
text = yield from response.text()
log.error("URL: %s" % url)
log.error("Response status code was %s" % str(response.status))
log.error(response.headers)
log.error(text)
response.close()
return ""
return (yield from response.text())
| Print the URL that erred out, along with the other info | Print the URL that erred out, along with the other info
| Python | mit | marvinpinto/charlesbot,marvinpinto/charlesbot | ---
+++
@@ -17,6 +17,7 @@
response = yield from aiohttp.get(url, headers=headers, params=payload)
if not response.status == 200:
text = yield from response.text()
+ log.error("URL: %s" % url)
log.error("Response status code was %s" % str(response.status))
log.error(response.headers)
log.error(text)
@@ -33,6 +34,7 @@
response = yield from aiohttp.get(url, headers=headers)
if not response.status == 200:
text = yield from response.text()
+ log.error("URL: %s" % url)
log.error("Response status code was %s" % str(response.status))
log.error(response.headers)
log.error(text) |
9ba0620230e370f9de8dec6e2bdd3eebeb3a986a | __TEMPLATE__.py | __TEMPLATE__.py | # -*- coding: utf-8 -*-
__author__ = """Chris Tabor (dxdstudio@gmail.com)"""
if __name__ == '__main__':
from os import getcwd
from os import sys
sys.path.append(getcwd())
from MOAL.helpers.display import Section
DEBUG = True if __name__ == '__main__' else False
class MyClass(object):
raise NotImplementedError
if DEBUG:
with Section('SOME MODULE TITLE'):
pass
| """Module docstring.
This talks about the module."""
# -*- coding: utf-8 -*-
__author__ = """Chris Tabor (dxdstudio@gmail.com)"""
if __name__ == '__main__':
from os import getcwd
from os import sys
sys.path.append(getcwd())
from MOAL.helpers.display import Section
DEBUG = True if __name__ == '__main__' else False
class MyClass(object):
"""Class docstring."""
raise NotImplementedError
if DEBUG:
with Section('SOME MODULE TITLE'):
pass
| Add Flake-8 docstring pep requirements for template | Add Flake-8 docstring pep requirements for template
| Python | apache-2.0 | christabor/MoAL,christabor/MoAL,christabor/MoAL,christabor/MoAL,christabor/MoAL | ---
+++
@@ -1,3 +1,7 @@
+"""Module docstring.
+
+This talks about the module."""
+
# -*- coding: utf-8 -*-
__author__ = """Chris Tabor (dxdstudio@gmail.com)"""
@@ -13,6 +17,8 @@
class MyClass(object):
+ """Class docstring."""
+
raise NotImplementedError
|
3b2390691544ac8f5bbe7cbfd3b105c2f327d8be | aafig/setup.py | aafig/setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the aafigure Sphinx extension.
Allow embeded ASCII art figure to be rendered as nice images.
'''
requires = ['Sphinx>=0.6']
setup(
name='sphinxcontrib-aafig',
version='0.1',
url='http://bitbucket.org/birkenfeld/sphinx-contrib',
download_url='http://pypi.python.org/pypi/sphinxcontrib-aafig',
license='BSD',
author='Leandro Lucarella',
author_email='llucax@gmail.com',
description='Sphinx extension aafig',
long_description=long_desc,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Documentation',
'Topic :: Utilities',
],
platforms='any',
packages=find_packages(),
include_package_data=True,
install_requires=requires,
namespace_packages=['sphinxcontrib'],
)
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the aafigure_ Sphinx_ extension.
.. _aafigure: http://docutils.sourceforge.net/sandbox/aafigure/
.. _Sphinx: http://sphinx.pocoo.org/
_aafigure is a program and a reStructuredText_ directive to allow embeded ASCII
art figures to be rendered as nice images in various image formats. The
aafigure_ directive needs a *hardcoded* image format, so it doesn't goes well
with Sphinx_ multi-format support.
.. _reStructuredText: http://docutils.sourceforge.net/rst.html
This extension adds the ``aafig`` directive that automatically selects the
image format to use acording to the Sphinx_ writer used to generate the
documentation.
'''
requires = ['Sphinx>=0.6']
setup(
name='sphinxcontrib-aafig',
version='0.1',
url='http://bitbucket.org/birkenfeld/sphinx-contrib',
download_url='http://pypi.python.org/pypi/sphinxcontrib-aafig',
license='BSD',
author='Leandro Lucarella',
author_email='llucax@gmail.com',
description='aafig Sphinx extension',
long_description=long_desc,
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Documentation',
'Topic :: Utilities',
],
platforms='any',
packages=find_packages(),
include_package_data=True,
install_requires=requires,
namespace_packages=['sphinxcontrib'],
)
| Improve package short and long description | aafig: Improve package short and long description
| Python | bsd-2-clause | sphinx-contrib/spelling,sphinx-contrib/spelling | ---
+++
@@ -3,9 +3,21 @@
from setuptools import setup, find_packages
long_desc = '''
-This package contains the aafigure Sphinx extension.
+This package contains the aafigure_ Sphinx_ extension.
-Allow embeded ASCII art figure to be rendered as nice images.
+.. _aafigure: http://docutils.sourceforge.net/sandbox/aafigure/
+.. _Sphinx: http://sphinx.pocoo.org/
+
+_aafigure is a program and a reStructuredText_ directive to allow embeded ASCII
+art figures to be rendered as nice images in various image formats. The
+aafigure_ directive needs a *hardcoded* image format, so it doesn't goes well
+with Sphinx_ multi-format support.
+
+.. _reStructuredText: http://docutils.sourceforge.net/rst.html
+
+This extension adds the ``aafig`` directive that automatically selects the
+image format to use acording to the Sphinx_ writer used to generate the
+documentation.
'''
requires = ['Sphinx>=0.6']
@@ -18,7 +30,7 @@
license='BSD',
author='Leandro Lucarella',
author_email='llucax@gmail.com',
- description='Sphinx extension aafig',
+ description='aafig Sphinx extension',
long_description=long_desc,
zip_safe=False,
classifiers=[ |
d9ab4683a8c5859b8d5e2579dbfe1f718f3ff423 | skylines/tests/test_i18n.py | skylines/tests/test_i18n.py | import os
import sys
import glob
from babel.messages.pofile import read_po
import nose
def get_language_code(filename):
filename = os.path.split(filename)[0]
filename = os.path.split(filename)[0]
filename = os.path.split(filename)[1]
return filename
def test_pofiles():
for filename in glob.glob(os.path.join('skylines', 'translations', '*', 'LC_MESSAGES', 'messages.po')):
test_pofiles.func_doc = ('Python string format placeholders must match '
'(lang: {})'.format(get_language_code(filename)))
yield check_pofile, filename
def check_pofile(filename):
with open(filename) as fileobj:
catalog = read_po(fileobj)
for error in catalog.check():
print 'Error in message: ' + str(error[0])
raise error[1][0]
if __name__ == "__main__":
sys.argv.append(__name__)
nose.run()
| import os
import sys
import glob
from babel.messages.pofile import read_po
import nose
def get_language_code(filename):
filename = os.path.split(filename)[0]
filename = os.path.split(filename)[0]
filename = os.path.split(filename)[1]
return filename
def test_pofiles():
for filename in glob.glob(os.path.join('skylines', 'translations', '*', 'LC_MESSAGES', 'messages.po')):
test_pofiles.func_doc = ('Python string format placeholders must match '
'(lang: {})'.format(get_language_code(filename)))
yield check_pofile, filename
def check_pofile(filename):
with open(filename) as fileobj:
catalog = read_po(fileobj)
for error in catalog.check():
print 'Error in message: ' + str(error[0])
raise AssertionError(error[1][0])
if __name__ == "__main__":
sys.argv.append(__name__)
nose.run()
| Raise AssertionError to mark tests as failed instead of errored | tests: Raise AssertionError to mark tests as failed instead of errored
| Python | agpl-3.0 | snip/skylines,Turbo87/skylines,kerel-fs/skylines,Harry-R/skylines,kerel-fs/skylines,TobiasLohner/SkyLines,Turbo87/skylines,skylines-project/skylines,snip/skylines,RBE-Avionik/skylines,RBE-Avionik/skylines,shadowoneau/skylines,Turbo87/skylines,Harry-R/skylines,TobiasLohner/SkyLines,RBE-Avionik/skylines,Turbo87/skylines,TobiasLohner/SkyLines,Harry-R/skylines,skylines-project/skylines,skylines-project/skylines,shadowoneau/skylines,Harry-R/skylines,kerel-fs/skylines,shadowoneau/skylines,shadowoneau/skylines,RBE-Avionik/skylines,snip/skylines,skylines-project/skylines | ---
+++
@@ -24,7 +24,7 @@
catalog = read_po(fileobj)
for error in catalog.check():
print 'Error in message: ' + str(error[0])
- raise error[1][0]
+ raise AssertionError(error[1][0])
if __name__ == "__main__": |
9e745b0e5ac673d04d978887654627b686813d93 | cms/apps/pages/tests/urls.py | cms/apps/pages/tests/urls.py | from django.conf.urls import patterns, url
def view():
pass
urlpatterns = patterns(
"",
url("^$", view, name="index"),
url("^(?P<url_title>[^/]+)/$", view, name="detail"),
)
| from django.conf.urls import patterns, url
urlpatterns = patterns(
"",
url("^$", lambda: None, name="index"),
url("^(?P<url_title>[^/]+)/$", lambda: None, name="detail"),
)
| Replace page test url views with lambdas. | Replace page test url views with lambdas.
| Python | bsd-3-clause | danielsamuels/cms,jamesfoley/cms,dan-gamble/cms,lewiscollard/cms,jamesfoley/cms,jamesfoley/cms,lewiscollard/cms,danielsamuels/cms,lewiscollard/cms,jamesfoley/cms,dan-gamble/cms,danielsamuels/cms,dan-gamble/cms | ---
+++
@@ -1,11 +1,8 @@
from django.conf.urls import patterns, url
-def view():
- pass
-
urlpatterns = patterns(
"",
- url("^$", view, name="index"),
- url("^(?P<url_title>[^/]+)/$", view, name="detail"),
+ url("^$", lambda: None, name="index"),
+ url("^(?P<url_title>[^/]+)/$", lambda: None, name="detail"),
) |
621a97a0904e085c33ef78d68cd733af0d816aee | app/aflafrettir/routes.py | app/aflafrettir/routes.py | from flask import render_template
from . import aflafrettir
@aflafrettir.route('/')
def index():
return render_template('aflafrettir/index.html')
@talks.route('/user/<username>')
def user(username):
return render_template('aflafrettir/index.html', username = username)
| from flask import render_template
from . import aflafrettir
@aflafrettir.route('/')
def index():
return render_template('aflafrettir/index.html')
@aflafrettir.route('/user/<username>')
def user(username):
return render_template('aflafrettir/user.html', username = username)
| Use the correct template, and call the aflafrettir route decorator | Use the correct template, and call the aflafrettir route decorator
| Python | mit | finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is | ---
+++
@@ -6,6 +6,6 @@
def index():
return render_template('aflafrettir/index.html')
-@talks.route('/user/<username>')
+@aflafrettir.route('/user/<username>')
def user(username):
- return render_template('aflafrettir/index.html', username = username)
+ return render_template('aflafrettir/user.html', username = username) |
28a8de1c23aeb23800bf55bd3045ead082950c81 | example/models.py | example/models.py | from django.db import models
import i18n
from i18n.models import TranslatableModel
class Document(TranslatableModel):
untranslated_charfield = models.CharField(max_length=50, blank=True)
charfield = i18n.LocalizedCharField(max_length=50)
textfield = i18n.LocalizedTextField(max_length=500, blank=True)
filefield = i18n.LocalizedFileField(null=True, upload_to='files', blank=True)
imagefield = i18n.LocalizedImageField(null=True, upload_to='images', blank=True)
booleanfield = i18n.LocalizedBooleanField()
datefield = i18n.LocalizedDateField(blank=True, null=True)
fkfield = i18n.LocalizedForeignKey('self', null=True, blank=True,
related_name='+')
urlfied = i18n.LocalizedURLField(null=True, blank=True)
decimalfield = i18n.LocalizedDecimalField(max_digits=4, decimal_places=2, null=True,
blank=True)
integerfield = i18n.LocalizedIntegerField(null=True, blank=True)
def __str__(self):
return '%d, %s' % (self.pk, self.charfield)
class Meta:
app_label = 'example'
| from django.db import models
import i18n
from i18n.models import TranslatableModel
class Document(TranslatableModel):
untranslated_charfield = models.CharField(max_length=50, blank=True)
charfield = i18n.LocalizedCharField(max_length=50)
textfield = i18n.LocalizedTextField(max_length=500, blank=True)
filefield = i18n.LocalizedFileField(null=True, upload_to='files', blank=True)
imagefield = i18n.LocalizedImageField(null=True, upload_to='images', blank=True)
# booleanfield = i18n.LocalizedBooleanField()
datefield = i18n.LocalizedDateField(blank=True, null=True)
fkfield = i18n.LocalizedForeignKey('self', null=True, blank=True,
related_name='+')
urlfied = i18n.LocalizedURLField(null=True, blank=True)
decimalfield = i18n.LocalizedDecimalField(max_digits=4, decimal_places=2, null=True,
blank=True)
integerfield = i18n.LocalizedIntegerField(null=True, blank=True)
def __str__(self):
return '%d, %s' % (self.pk, self.charfield)
class Meta:
app_label = 'example'
| Remove booleanfield from example app for now | Remove booleanfield from example app for now
We rather want a non required field for testing and should add a
NullBooleanField anyway
| Python | bsd-3-clause | jonasundderwolf/django-localizedfields,jonasundderwolf/django-localizedfields | ---
+++
@@ -9,7 +9,7 @@
textfield = i18n.LocalizedTextField(max_length=500, blank=True)
filefield = i18n.LocalizedFileField(null=True, upload_to='files', blank=True)
imagefield = i18n.LocalizedImageField(null=True, upload_to='images', blank=True)
- booleanfield = i18n.LocalizedBooleanField()
+ # booleanfield = i18n.LocalizedBooleanField()
datefield = i18n.LocalizedDateField(blank=True, null=True)
fkfield = i18n.LocalizedForeignKey('self', null=True, blank=True,
related_name='+') |
517668eeb493bcd72838716258d40abd4a73e039 | alexandria/views/user.py | alexandria/views/user.py | from pyramid.view import (
view_config,
view_defaults,
)
from pyramid.security import (
remember,
forget,
)
@view_defaults(accept='application/json', renderer='json', context='..traversal.User')
class User(object):
def __init__(self, context, request):
self.request = request
self.context = context
@view_config()
def info(self):
if self.request.authenticated_userid is None:
ret = {
'authenticated': False,
}
return ret
@view_config(name='login')
def login(self):
if self.request.body:
print(self.request.json_body)
headers = remember(self.request, "example@example.com")
self.request.response.headers.extend(headers)
return {}
@view_config(name='logout')
def logout(self):
if self.request.body:
print(self.request.json_body)
return {}
| from pyramid.view import (
view_config,
view_defaults,
)
from pyramid.httpexceptions import HTTPSeeOther
from pyramid.security import (
remember,
forget,
)
@view_defaults(accept='application/json', renderer='json', context='..traversal.User')
class User(object):
def __init__(self, context, request):
self.request = request
self.context = context
@view_config()
def info(self):
if self.request.authenticated_userid is None:
ret = {
'authenticated': False,
}
else:
ret = {
'authenticated': True,
'user': {
'username': 'example@example.com',
}
}
return ret
@view_config(name='login')
def login(self):
if self.request.body:
print(self.request.json_body)
headers = remember(self.request, "example@example.com")
return HTTPSeeOther(location=self.request.route_url('main', traverse='user'), headers=headers)
return {}
@view_config(name='logout')
def logout(self):
headers = forget(self.request)
return HTTPSeeOther(location=self.request.route_url('main', traverse='user'), headers=headers)
| Implement the login/logout functionality on the REST endpoints | Implement the login/logout functionality on the REST endpoints
| Python | isc | cdunklau/alexandria,bertjwregeer/alexandria,cdunklau/alexandria,cdunklau/alexandria,bertjwregeer/alexandria | ---
+++
@@ -2,6 +2,8 @@
view_config,
view_defaults,
)
+
+from pyramid.httpexceptions import HTTPSeeOther
from pyramid.security import (
remember,
@@ -20,6 +22,13 @@
ret = {
'authenticated': False,
}
+ else:
+ ret = {
+ 'authenticated': True,
+ 'user': {
+ 'username': 'example@example.com',
+ }
+ }
return ret
@view_config(name='login')
@@ -27,12 +36,10 @@
if self.request.body:
print(self.request.json_body)
headers = remember(self.request, "example@example.com")
- self.request.response.headers.extend(headers)
+ return HTTPSeeOther(location=self.request.route_url('main', traverse='user'), headers=headers)
return {}
@view_config(name='logout')
def logout(self):
- if self.request.body:
- print(self.request.json_body)
- return {}
-
+ headers = forget(self.request)
+ return HTTPSeeOther(location=self.request.route_url('main', traverse='user'), headers=headers) |
36edb0e161fd3c65d2957b7b319b67975e846e7e | src/sentry/templatetags/sentry_assets.py | src/sentry/templatetags/sentry_assets.py | from __future__ import absolute_import
from django.template import Library
from sentry.utils.assets import get_asset_url
register = Library()
@register.simple_tag
def asset_url(module, path):
"""
Returns a versioned asset URL (located within Sentry's static files).
Example:
{% asset_url 'sentry' 'dist/sentry.css' %}
=> "/_static/74d127b78dc7daf2c51f/sentry/dist/sentry.css"
"""
return get_asset_url(module, path)
| from __future__ import absolute_import
from django.template import Library
from sentry.utils.assets import get_asset_url
from sentry.utils.http import absolute_uri
register = Library()
@register.simple_tag
def asset_url(module, path):
"""
Returns a versioned asset URL (located within Sentry's static files).
Example:
{% asset_url 'sentry' 'dist/sentry.css' %}
=> "http://sentry.example.com/_static/74d127b78dc7daf2c51f/sentry/dist/sentry.css"
"""
return absolute_uri(get_asset_url(module, path))
| Make all asset URLs absolute | Make all asset URLs absolute
| Python | bsd-3-clause | mvaled/sentry,looker/sentry,JamesMura/sentry,zenefits/sentry,BuildingLink/sentry,gencer/sentry,ifduyue/sentry,BuildingLink/sentry,fotinakis/sentry,mitsuhiko/sentry,zenefits/sentry,fotinakis/sentry,gencer/sentry,looker/sentry,beeftornado/sentry,gencer/sentry,mitsuhiko/sentry,BayanGroup/sentry,fotinakis/sentry,daevaorn/sentry,daevaorn/sentry,mvaled/sentry,mvaled/sentry,zenefits/sentry,nicholasserra/sentry,JamesMura/sentry,beeftornado/sentry,imankulov/sentry,BayanGroup/sentry,mvaled/sentry,mvaled/sentry,looker/sentry,beeftornado/sentry,imankulov/sentry,zenefits/sentry,JackDanger/sentry,BayanGroup/sentry,ifduyue/sentry,alexm92/sentry,alexm92/sentry,jean/sentry,jean/sentry,fotinakis/sentry,zenefits/sentry,BuildingLink/sentry,nicholasserra/sentry,JamesMura/sentry,ifduyue/sentry,ifduyue/sentry,jean/sentry,daevaorn/sentry,imankulov/sentry,BuildingLink/sentry,mvaled/sentry,looker/sentry,looker/sentry,JamesMura/sentry,daevaorn/sentry,ifduyue/sentry,JackDanger/sentry,JackDanger/sentry,gencer/sentry,JamesMura/sentry,gencer/sentry,jean/sentry,BuildingLink/sentry,jean/sentry,alexm92/sentry,nicholasserra/sentry | ---
+++
@@ -3,6 +3,7 @@
from django.template import Library
from sentry.utils.assets import get_asset_url
+from sentry.utils.http import absolute_uri
register = Library()
@@ -14,6 +15,6 @@
Example:
{% asset_url 'sentry' 'dist/sentry.css' %}
- => "/_static/74d127b78dc7daf2c51f/sentry/dist/sentry.css"
+ => "http://sentry.example.com/_static/74d127b78dc7daf2c51f/sentry/dist/sentry.css"
"""
- return get_asset_url(module, path)
+ return absolute_uri(get_asset_url(module, path)) |
75eacb13930ef03c1ebc1ff619f47b54cde85532 | examples/hello.py | examples/hello.py | from cell import Actor, Agent
from cell.actors import Server
from kombu import Connection
from kombu.log import setup_logging
connection = Connection()
class GreetingActor(Server):
default_routing_key = 'GreetingActor'
class state:
def greet(self, who='world'):
return 'Hello %s' % who
greeting = GreetingActor(connection)
class Printer(Actor):
default_routing_key = 'Printer'
class state:
def echo(self, msg = 'test'):
print 'I am a printer:',msg
#self.output_edge.send(msg)
return msg
printerActor = Printer(connection)
class Ihu(Actor):
default_routing_key = 'Printer'
class state:
def temp(self, msg = 'blabla'):
self.output_server.send(msg)
class GreetingAgent(Agent):
actors = [greeting, printerActor]
if __name__ == '__main__':
consumer = GreetingAgent(connection).consume_from_commandline()
for _ in consumer:
print 'Received'
# Run this script from the command line and try this
# in another console:
#
# >>> from hello import greeting
# >>> greeting.call('greet')
# 'Hello world'
| from cell import Actor, Agent
from cell.actors import Server
from kombu import Connection
from kombu.log import setup_logging
connection = Connection()
class GreetingActor(Server):
default_routing_key = 'GreetingActor'
class state:
def greet(self, who='world'):
return 'Hello %s' % who
greeting = GreetingActor(connection)
class GreetingAgent(Agent):
actors = [greeting]
if __name__ == '__main__':
GreetingAgent(connection).consume_from_commandline()
# Run this script from the command line and try this
# in another console:
#
# >>> from hello import greeting
# >>> greeting.call('greet')
# 'Hello world'
| Use the Server class (an Actor derived class) | Use the Server class (an Actor derived class)
| Python | bsd-3-clause | celery/cell,celery/cell | ---
+++
@@ -11,41 +11,17 @@
default_routing_key = 'GreetingActor'
class state:
-
def greet(self, who='world'):
return 'Hello %s' % who
greeting = GreetingActor(connection)
+
-class Printer(Actor):
- default_routing_key = 'Printer'
-
- class state:
- def echo(self, msg = 'test'):
- print 'I am a printer:',msg
- #self.output_edge.send(msg)
- return msg
-
-printerActor = Printer(connection)
-
-
-
-class Ihu(Actor):
- default_routing_key = 'Printer'
-
- class state:
- def temp(self, msg = 'blabla'):
- self.output_server.send(msg)
-
-
class GreetingAgent(Agent):
- actors = [greeting, printerActor]
+ actors = [greeting]
if __name__ == '__main__':
- consumer = GreetingAgent(connection).consume_from_commandline()
- for _ in consumer:
- print 'Received'
-
+ GreetingAgent(connection).consume_from_commandline()
# Run this script from the command line and try this
# in another console:
# |
ddec6067054cc4408ac174e3ea4ffeca2a962201 | regulations/views/notice_home.py | regulations/views/notice_home.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from operator import itemgetter
import logging
from django.http import Http404
from django.template.response import TemplateResponse
from django.views.generic.base import View
from regulations.generator.api_reader import ApiReader
from regulations.views.preamble import (
notice_data, CommentState)
logger = logging.getLogger(__name__)
class NoticeHomeView(View):
"""
Basic view that provides a list of regulations and notices to the context.
"""
template_name = None # We should probably have a default notice template.
def get(self, request, *args, **kwargs):
notices = ApiReader().notices().get("results", [])
context = {}
notices_meta = []
for notice in notices:
try:
if notice.get("document_number"):
_, meta, _ = notice_data(notice["document_number"])
notices_meta.append(meta)
except Http404:
pass
notices_meta = sorted(notices_meta, key=itemgetter("publication_date"),
reverse=True)
context["notices"] = notices_meta
# Django templates won't show contents of CommentState as an Enum, so:
context["comment_state"] = {state.name: state.value for state in
CommentState}
assert self.template_name
template = self.template_name
return TemplateResponse(request=request, template=template,
context=context)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from operator import itemgetter
import logging
from django.http import Http404
from django.template.response import TemplateResponse
from django.views.generic.base import View
from regulations.generator.api_reader import ApiReader
from regulations.views.preamble import (
notice_data, CommentState)
logger = logging.getLogger(__name__)
class NoticeHomeView(View):
"""
Basic view that provides a list of regulations and notices to the context.
"""
template_name = None # We should probably have a default notice template.
def get(self, request, *args, **kwargs):
notices = ApiReader().notices().get("results", [])
context = {}
notices_meta = []
for notice in notices:
try:
if notice.get("document_number"):
_, meta, _ = notice_data(notice["document_number"])
notices_meta.append(meta)
except Http404:
pass
notices_meta = sorted(notices_meta, key=itemgetter("publication_date"),
reverse=True)
context["notices"] = notices_meta
# Django templates won't show contents of CommentState as an Enum, so:
context["comment_state"] = {state.name: state.value for state in
CommentState}
template = self.template_name
return TemplateResponse(request=request, template=template,
context=context)
| Remove unnecessary assert from view for Notice home. | Remove unnecessary assert from view for Notice home.
| Python | cc0-1.0 | 18F/regulations-site,18F/regulations-site,eregs/regulations-site,tadhg-ohiggins/regulations-site,tadhg-ohiggins/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site,eregs/regulations-site,eregs/regulations-site,tadhg-ohiggins/regulations-site,18F/regulations-site,18F/regulations-site | ---
+++
@@ -45,7 +45,6 @@
context["comment_state"] = {state.name: state.value for state in
CommentState}
- assert self.template_name
template = self.template_name
return TemplateResponse(request=request, template=template,
context=context) |
7a1ddf38db725f0696482a271c32fa297d629316 | backlog/__init__.py | backlog/__init__.py | __version__ = (0, 2, 1, '', 0)
def get_version():
version = '%d.%d.%d' % __version__[0:3]
if __version__[3]:
version = '%s-%s%s' % (version, __version__[3],
(__version__[4] and str(__version__[4])) or '')
return version
| __version__ = (0, 2, 2, 'dev', 0)
def get_version():
version = '%d.%d.%d' % __version__[0:3]
if __version__[3]:
version = '%s-%s%s' % (version, __version__[3],
(__version__[4] and str(__version__[4])) or '')
return version
| Set the version to the next patch release number (in dev mode) | Set the version to the next patch release number (in dev mode)
| Python | bsd-3-clause | jszakmeister/trac-backlog,jszakmeister/trac-backlog | ---
+++
@@ -1,4 +1,4 @@
-__version__ = (0, 2, 1, '', 0)
+__version__ = (0, 2, 2, 'dev', 0)
def get_version():
version = '%d.%d.%d' % __version__[0:3] |
a0af5dc1478fe8b639cc5a37898ad180f1f20a89 | src/twelve_tone/cli.py | src/twelve_tone/cli.py | """
Module that contains the command line app.
Why does this file exist, and why not put this in __main__?
You might be tempted to import things from __main__ later, but that will cause
problems: the code will get executed twice:
- When you run `python -mtwelve_tone` python will execute
``__main__.py`` as a script. That means there won't be any
``twelve_tone.__main__`` in ``sys.modules``.
- When you import __main__ it will get executed again (as a module) because
there's no ``twelve_tone.__main__`` in ``sys.modules``.
Also see (1) from http://click.pocoo.org/5/setuptools/#setuptools-integration
"""
import click
from twelve_tone.composer import Composer
@click.command()
def main():
c = Composer()
c.compose()
click.echo(c.get_melody())
| """
Module that contains the command line app.
Why does this file exist, and why not put this in __main__?
You might be tempted to import things from __main__ later, but that will cause
problems: the code will get executed twice:
- When you run `python -mtwelve_tone` python will execute
``__main__.py`` as a script. That means there won't be any
``twelve_tone.__main__`` in ``sys.modules``.
- When you import __main__ it will get executed again (as a module) because
there's no ``twelve_tone.__main__`` in ``sys.modules``.
Also see (1) from http://click.pocoo.org/5/setuptools/#setuptools-integration
"""
import click
from twelve_tone.composer import Composer
@click.command()
@click.option('--midi', '-m', help='MIDI output file')
def main(midi):
c = Composer()
c.compose()
click.echo(c.get_melody())
if midi is not None:
c.save_to_midi(filename=midi)
| Add --midi option to CLI | Add --midi option to CLI
| Python | bsd-2-clause | accraze/python-twelve-tone | ---
+++
@@ -20,7 +20,10 @@
@click.command()
-def main():
+@click.option('--midi', '-m', help='MIDI output file')
+def main(midi):
c = Composer()
c.compose()
click.echo(c.get_melody())
+ if midi is not None:
+ c.save_to_midi(filename=midi) |
3868a4ef30835ed1904a37318013e20f2295a8a9 | ckanext/cob/plugin.py | ckanext/cob/plugin.py | import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
def groups():
# Return a list of groups
return toolkit.get_action('group_list')(data_dict={'all_fields': True})
def dataset_count():
# Return a count of all datasets
result = toolkit.get_action('package_search')(data_dict={'rows': 1})
return result['count']
class CobPlugin(plugins.SingletonPlugin):
plugins.implements(plugins.IConfigurer)
plugins.implements(plugins.ITemplateHelpers)
# IConfigurer
def update_config(self, config_):
toolkit.add_template_directory(config_, 'templates')
toolkit.add_public_directory(config_, 'public')
toolkit.add_resource('fanstatic', 'cob')
def get_helpers(self):
# Register cob_theme_* helper functions
return {'cob_theme_groups': groups,
'cob_theme_dataset_count': dataset_count}
| import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
def groups():
# Return a list of groups
return toolkit.get_action('group_list')(data_dict={'all_fields': True})
def dataset_count():
# Return a count of all datasets
result = toolkit.get_action('package_search')(data_dict={'rows': 1})
return result['count']
class CobPlugin(plugins.SingletonPlugin):
plugins.implements(plugins.IConfigurer)
plugins.implements(plugins.ITemplateHelpers)
# IConfigurer
def update_config(self, config_):
toolkit.add_template_directory(config_, 'templates')
toolkit.add_public_directory(config_, 'public')
def get_helpers(self):
# Register cob_theme_* helper functions
return {'cob_theme_groups': groups,
'cob_theme_dataset_count': dataset_count}
| Remove fantastic from COB theme | Remove fantastic from COB theme
Updates #10
| Python | agpl-3.0 | City-of-Bloomington/ckanext-cob,City-of-Bloomington/ckanext-cob | ---
+++
@@ -19,7 +19,6 @@
def update_config(self, config_):
toolkit.add_template_directory(config_, 'templates')
toolkit.add_public_directory(config_, 'public')
- toolkit.add_resource('fanstatic', 'cob')
def get_helpers(self):
# Register cob_theme_* helper functions |
bf7562d9f45a777163f2ac775dc9cf4afe99a930 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
# Copyright (c) 2013 Aparajita Fishman
#
# Project: https://github.com/SublimeLinter/SublimeLinter-contrib-jshint
# License: MIT
#
"""This module exports the JSHint plugin linter class."""
from SublimeLinter.lint import Linter
class JSHint(Linter):
"""Provides an interface to the jshint executable."""
language = ('javascript', 'html')
cmd = 'jshint --verbose -'
regex = r'^.+?: line (?P<line>\d+), col (?P<col>\d+), (?P<message>.+) \((?:(?P<error>E)|(?P<warning>W))\d+\)$'
selectors = {
'html': 'source.js.embedded.html'
}
| #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
# Copyright (c) 2013 Aparajita Fishman
#
# Project: https://github.com/SublimeLinter/SublimeLinter-contrib-jshint
# License: MIT
#
"""This module exports the JSHint plugin linter class."""
from SublimeLinter.lint import Linter
class JSHint(Linter):
"""Provides an interface to the jshint executable."""
syntax = ('javascript', 'html')
cmd = 'jshint --verbose -'
regex = r'^.+?: line (?P<line>\d+), col (?P<col>\d+), (?P<message>.+) \((?:(?P<error>E)|(?P<warning>W))\d+\)$'
selectors = {
'html': 'source.js.embedded.html'
}
| Change 'language' to 'syntax', that is more precise terminology. | Change 'language' to 'syntax', that is more precise terminology.
| Python | mit | tylertebbs20/Practice-SublimeLinter-jshint,tylertebbs20/Practice-SublimeLinter-jshint,SublimeLinter/SublimeLinter-jshint | ---
+++
@@ -18,7 +18,7 @@
"""Provides an interface to the jshint executable."""
- language = ('javascript', 'html')
+ syntax = ('javascript', 'html')
cmd = 'jshint --verbose -'
regex = r'^.+?: line (?P<line>\d+), col (?P<col>\d+), (?P<message>.+) \((?:(?P<error>E)|(?P<warning>W))\d+\)$'
selectors = { |
7cac8f8ba591315d68e223503c4e93f976c8d89d | characters/views.py | characters/views.py | from django.shortcuts import get_object_or_404, redirect, render
from characters.forms import CharacterForm
from characters.models import Character, Class, Race
def index(request):
all_characters = Character.objects.all()
context = {'all_characters': all_characters}
return render(request, 'characters/index.html', context)
def view_character(request, character_id):
character = get_object_or_404(Character, pk=character_id)
context = {'character': character}
return render(request, 'characters/view_character.html', context)
def create_character(request):
form = CharacterForm(request.POST or None)
if request.method == 'POST' and form.is_valid():
race = Race.objects.get(id=1)
cclass = Class.objects.get(id=1)
character = Character(
name=request.POST['name'],
background=request.POST['background'],
race=race,
cclass=cclass
)
character.save()
return redirect('characters:view', character_id=character.id)
context = {'form': form}
return render(request, 'characters/create_character.html', context)
| from django.shortcuts import get_object_or_404, redirect, render
from characters.forms import CharacterForm
from characters.models import Character, Class, Race
def index(request):
all_characters = Character.objects.all()
context = {'all_characters': all_characters}
return render(request, 'characters/index.html', context)
def view_character(request, character_id):
character = get_object_or_404(Character, pk=character_id)
context = {'character': character}
return render(request, 'characters/view_character.html', context)
def create_character(request):
form = CharacterForm(request.POST or None)
if request.method == 'POST' and form.is_valid():
character = Character(
name=request.POST['name'],
background=request.POST['background'],
race_id=1,
cclass_id=1
)
character.save()
return redirect('characters:view', character_id=character.id)
context = {'form': form}
return render(request, 'characters/create_character.html', context)
| Set default race and class without extra database queries | Set default race and class without extra database queries
| Python | mit | mpirnat/django-tutorial-v2 | ---
+++
@@ -21,14 +21,11 @@
if request.method == 'POST' and form.is_valid():
- race = Race.objects.get(id=1)
- cclass = Class.objects.get(id=1)
-
character = Character(
name=request.POST['name'],
background=request.POST['background'],
- race=race,
- cclass=cclass
+ race_id=1,
+ cclass_id=1
)
character.save()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.