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
083d71834e82815dd338a873090df4cda64d74f4
test/test_logger.py
test/test_logger.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import print_function, unicode_literals import pytest from simplesqlite import set_log_level, set_logger logbook = pytest.importorskip("logbook", minversion="1.1.0") import logbook # isort:skip class Test_set_logger(object): @pytest.mark.parametrize(["value"], [[True], [False]]) def test_smoke(self, value): set_logger(value) class Test_set_log_level(object): @pytest.mark.parametrize( ["value"], [ [logbook.CRITICAL], [logbook.ERROR], [logbook.WARNING], [logbook.NOTICE], [logbook.INFO], [logbook.DEBUG], [logbook.TRACE], [logbook.NOTSET], ], ) def test_smoke(self, value): set_log_level(value) @pytest.mark.parametrize( ["value", "expected"], [[None, LookupError], ["unexpected", LookupError]] ) def test_exception(self, value, expected): with pytest.raises(expected): set_log_level(value)
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import print_function, unicode_literals import pytest from simplesqlite import set_log_level, set_logger logbook = pytest.importorskip("logbook", minversion="0.12.3") import logbook # isort:skip class Test_set_logger(object): @pytest.mark.parametrize(["value"], [[True], [False]]) def test_smoke(self, value): set_logger(value) class Test_set_log_level(object): @pytest.mark.parametrize( ["value"], [ [logbook.CRITICAL], [logbook.ERROR], [logbook.WARNING], [logbook.NOTICE], [logbook.INFO], [logbook.DEBUG], [logbook.TRACE], [logbook.NOTSET], ], ) def test_smoke(self, value): set_log_level(value) @pytest.mark.parametrize( ["value", "expected"], [[None, LookupError], ["unexpected", LookupError]] ) def test_exception(self, value, expected): with pytest.raises(expected): set_log_level(value)
Update skip condition for tests
Update skip condition for tests
Python
mit
thombashi/SimpleSQLite,thombashi/SimpleSQLite
--- +++ @@ -10,7 +10,7 @@ from simplesqlite import set_log_level, set_logger -logbook = pytest.importorskip("logbook", minversion="1.1.0") +logbook = pytest.importorskip("logbook", minversion="0.12.3") import logbook # isort:skip
ac605b9efdfa0a195a4c9a76800e969098a003ae
test/test_ticket.py
test/test_ticket.py
import unittest from mock import Mock import sys import os import datetime from pytrac import Ticket class TestTicket(unittest.TestCase): def setUp(self): server = Mock() self.ticket = Ticket(server) def testSearchWithAllParams(self): self.ticket.search(summary='test_summary', owner='someowner', status='new') self.ticket.api.query.assert_called_with('max=0&summary~=test_summary&owner=someowner&status=new') class TestUpdateTicket(unittest.TestCase): ticket_id = 1 def setUp(self): server = Mock() self.timestamp = datetime.datetime.now() server.ticket.get.return_value = [self.ticket_id, self.timestamp, self.timestamp, {'_ts': self.timestamp, 'action': 'leave'}] server.ticket.update.return_value = [self.ticket_id, self.timestamp, self.timestamp, {'_ts': self.timestamp, 'action': 'leave'}] self.ticket = Ticket(server) def testComment(self): self.ticket.comment(self.ticket_id, "some comment") self.ticket.api.update.assert_called_with( self.ticket_id, comment="some comment", attrs={'action': 'leave', '_ts': self.timestamp}, notify=True) if __name__ == '__main__': unittest.main()
import pytest from mock import Mock import sys import os import datetime from pytrac import Ticket class TestTicket(object): def setup_class(self): server = Mock() self.ticket = Ticket(server) def testSearchWithAllParams(self): self.ticket.search(summary='test_summary', owner='someowner', status='new') self.ticket.api.query.assert_called_with('max=0&summary~=test_summary&owner=someowner&status=new') class TestUpdateTicket(object): ticket_id = 1 def setup_class(self): server = Mock() self.timestamp = datetime.datetime.now() server.ticket.get.return_value = [self.ticket_id, self.timestamp, self.timestamp, {'_ts': self.timestamp, 'action': 'leave'}] server.ticket.update.return_value = [self.ticket_id, self.timestamp, self.timestamp, {'_ts': self.timestamp, 'action': 'leave'}] self.ticket = Ticket(server) def testComment(self): self.ticket.comment(self.ticket_id, "some comment") self.ticket.api.update.assert_called_with( self.ticket_id, comment="some comment", attrs={'action': 'leave', '_ts': self.timestamp}, notify=True) if __name__ == '__main__': pytest.main(__file__)
Use pytest for unit test
Use pytest for unit test
Python
apache-2.0
Jimdo/pytrac,Jimdo/pytrac
--- +++ @@ -1,4 +1,4 @@ -import unittest +import pytest from mock import Mock import sys import os @@ -7,9 +7,9 @@ from pytrac import Ticket -class TestTicket(unittest.TestCase): +class TestTicket(object): - def setUp(self): + def setup_class(self): server = Mock() self.ticket = Ticket(server) @@ -18,11 +18,11 @@ self.ticket.api.query.assert_called_with('max=0&summary~=test_summary&owner=someowner&status=new') -class TestUpdateTicket(unittest.TestCase): +class TestUpdateTicket(object): ticket_id = 1 - def setUp(self): + def setup_class(self): server = Mock() self.timestamp = datetime.datetime.now() server.ticket.get.return_value = [self.ticket_id, @@ -47,4 +47,4 @@ if __name__ == '__main__': - unittest.main() + pytest.main(__file__)
ea56607fa7ae7257682170e881c67ae5e0f6719c
tests/rest_views.py
tests/rest_views.py
from django.views.generic import View from nap.datamapper.models import ModelDataMapper from nap.rest import views from .models import Poll class PollMapper(ModelDataMapper): class Meta: model = Poll fields = ['question', 'pub_date'] class SinglePollView(views.ObjectGetMixin, views.ObjectPutMixin, views.ObjectPatchMixin, views.ObjectDeleteMixin, views.ObjectMixin, View): model = Poll mapper_class = PollMapper
from django.views.generic import View from nap.datamapper.models import ModelDataMapper from nap.rest import views from .models import Poll class PollMapper(ModelDataMapper): class Meta: model = Poll fields = ['question', 'pub_date'] class SinglePollView(views.ObjectGetMixin, views.ObjectPutMixin, views.ObjectPatchMixin, views.ObjectDeleteMixin, views.BaseObjectView): model = Poll mapper_class = PollMapper
Update test to use Base view
Update test to use Base view
Python
bsd-3-clause
MarkusH/django-nap,limbera/django-nap
--- +++ @@ -12,6 +12,6 @@ fields = ['question', 'pub_date'] -class SinglePollView(views.ObjectGetMixin, views.ObjectPutMixin, views.ObjectPatchMixin, views.ObjectDeleteMixin, views.ObjectMixin, View): +class SinglePollView(views.ObjectGetMixin, views.ObjectPutMixin, views.ObjectPatchMixin, views.ObjectDeleteMixin, views.BaseObjectView): model = Poll mapper_class = PollMapper
9bb1aebbfc0ca0ff893bafe99de3c32c2ba99952
tests/test_model.py
tests/test_model.py
from context import models from models import model import unittest class test_logic_core(unittest.TestCase): def setUp(self): self.room = model.Room(20, 'new_room') self.room1 = model.Room(6, 'new_room1') self.livingspace = model.LivingSpace('orange') self.office = model.Office('manjaro') def test_Room_instance(self): self.assertIsInstance(self.room, model.Room) self.assertIsInstance(self.room1, model.Room) def test_Room_max_occupation(self): self.assertEqual(20, self.room.max_occupants) def test_Room_name(self): self.assertEqual('new_room1', self.room1.name) def test_office_ocupants(self): self.assertEqual(6, self.office.max_occupants) def test_livingspace_ocupants(self): self.assertEqual(4, self.livingspace.max_occupants) def test_sublclass_Room(self): self.assertTrue(issubclass(model.Office, model.Room)) self.assertTrue(issubclass(model.LivingSpace, model.Room))
from context import models from models import model import unittest class test_model(unittest.TestCase): def setUp(self): self.room = model.Room(20, 'new_room') self.room1 = model.Room(6, 'new_room1') self.livingspace = model.LivingSpace('orange') self.office = model.Office('manjaro') def test_Room_instance(self): self.assertIsInstance(self.room, model.Room) self.assertIsInstance(self.room1, model.Room) def test_Room_max_occupation(self): self.assertEqual(20, self.room.max_occupants) def test_Room_name(self): self.assertEqual('new_room1', self.room1.name) self.room1.name = "changedname" self.assertEqual('changedname', self.room1.name) def test_office_ocupants(self): self.assertEqual(6, self.office.max_occupants) def test_livingspace_ocupants(self): self.assertEqual(4, self.livingspace.max_occupants) def test_sublclass_Room(self): self.assertTrue(issubclass(model.Office, model.Room)) self.assertTrue(issubclass(model.LivingSpace, model.Room)) def test_room_current_population(self): self.assertEqual(self.room.current_population, 0)
Refactor model test to test added properties
Refactor model test to test added properties
Python
mit
georgreen/Geoogreen-Mamboleo-Dojo-Project
--- +++ @@ -5,7 +5,7 @@ import unittest -class test_logic_core(unittest.TestCase): +class test_model(unittest.TestCase): def setUp(self): self.room = model.Room(20, 'new_room') self.room1 = model.Room(6, 'new_room1') @@ -21,6 +21,8 @@ def test_Room_name(self): self.assertEqual('new_room1', self.room1.name) + self.room1.name = "changedname" + self.assertEqual('changedname', self.room1.name) def test_office_ocupants(self): self.assertEqual(6, self.office.max_occupants) @@ -31,3 +33,6 @@ def test_sublclass_Room(self): self.assertTrue(issubclass(model.Office, model.Room)) self.assertTrue(issubclass(model.LivingSpace, model.Room)) + + def test_room_current_population(self): + self.assertEqual(self.room.current_population, 0)
3a414d5d4763802bc4bc506a57c1f487655d470a
engineering_project/estimatedtime.py
engineering_project/estimatedtime.py
#!/usr/bin/env python3 import statistics class estimatedtime: def __init__(self, numberofpoints): self.listoftimes = [] self.points = numberofpoints def append(self, timeinseconds, inferprogress=True): # print(timeinseconds) self.listoftimes.append(timeinseconds) if inferprogress is True: self.points -= 1 def ETA(self): return("{0:.5f}".format((statistics.mean(self.listoftimes) * self.points)))
#!/usr/bin/env python3 import statistics class ETC: ''' Estimated Time to Completion ''' def __init__(self, numberofpoints): self.listoftimes = [] self.points = numberofpoints + 1 def append(self, timeinseconds, inferprogress=True): # print(timeinseconds) self.listoftimes.append(timeinseconds) if inferprogress is True: self.points -= 1 def ETC(self): return("{0:.5f}".format((statistics.mean(self.listoftimes) * self.points)))
Change estimated time class to ETC
Change estimated time class to ETC
Python
mit
DavidLutton/EngineeringProject
--- +++ @@ -2,10 +2,11 @@ import statistics -class estimatedtime: +class ETC: + ''' Estimated Time to Completion ''' def __init__(self, numberofpoints): self.listoftimes = [] - self.points = numberofpoints + self.points = numberofpoints + 1 def append(self, timeinseconds, inferprogress=True): # print(timeinseconds) @@ -13,5 +14,5 @@ if inferprogress is True: self.points -= 1 - def ETA(self): + def ETC(self): return("{0:.5f}".format((statistics.mean(self.listoftimes) * self.points)))
77573f639354c35945586bf57222d9125d99e0ba
system/protocols/generic/channel.py
system/protocols/generic/channel.py
from system.translations import Translations __author__ = 'Sean' _ = Translations().get() class Channel(object): name = "" users = None def __init__(self, name, protocol=None): self.name = name self.protocol = protocol self.users = set() def respond(self, message): raise NotImplementedError(_("This method must be overridden")) def add_user(self, user): self.users.add(user) def remove_user(self, user): try: self.users.remove(user) except KeyError: self.protocol.log.debug( "Tried to remove non-existent user \"%s\" from channel \"%s\"" % (user, self) )
from system.translations import Translations __author__ = 'Sean' _ = Translations().get() class Channel(object): """ A channel - Represents a channel on a protocol. Subclass this! @ivar name The name of the channel @ivar users A set containing all the User objects in the channel """ def __init__(self, name, protocol=None): """ Initialise the channel. Remember to call super in subclasses! :arg name: The name of the channel :type name: str :arg protocol: The protocol object this channel belongs to :type protocol: Protocol """ self.name = name # This is essential! self.protocol = protocol # May be None for one-off or fake channels self.users = set() # This is also essential! def respond(self, message): raise NotImplementedError(_("This method must be overridden")) def add_user(self, user): self.users.add(user) def remove_user(self, user): try: self.users.remove(user) except KeyError: self.protocol.log.debug( "Tried to remove non-existent user \"%s\" from channel \"%s\"" % (user, self) )
Remove unneeded properties in base Channel class
Remove unneeded properties in base Channel class
Python
artistic-2.0
UltrosBot/Ultros,UltrosBot/Ultros
--- +++ @@ -6,14 +6,27 @@ class Channel(object): + """ + A channel - Represents a channel on a protocol. Subclass this! - name = "" - users = None + @ivar name The name of the channel + @ivar users A set containing all the User objects in the channel + """ def __init__(self, name, protocol=None): - self.name = name - self.protocol = protocol - self.users = set() + """ + Initialise the channel. Remember to call super in subclasses! + + :arg name: The name of the channel + :type name: str + + :arg protocol: The protocol object this channel belongs to + :type protocol: Protocol + """ + + self.name = name # This is essential! + self.protocol = protocol # May be None for one-off or fake channels + self.users = set() # This is also essential! def respond(self, message): raise NotImplementedError(_("This method must be overridden"))
c6d345d01f59965155d9d912615a1eef939c32cb
Xls/Reader/excel_xlrd.py
Xls/Reader/excel_xlrd.py
import xlrd import json import sys import os import argparse def run(argv): parser = argparse.ArgumentParser() parser.add_argument('--size') parser.add_argument('--start') parser.add_argument('--action') parser.add_argument('--file') args = parser.parse_args() if False == os.path.isfile(args.file): print("File does not exist") sys.exit(1) workbook = xlrd.open_workbook(args.file) sheet = workbook.sheet_by_index(0) if args.action == "count": print(sheet.nrows) elif args.action == "read": reached_end = False rows = [] while len(rows) < int(args.size) and reached_end == False: try: rows.append(sheet.row_values(int(args.start) + len(rows) - 1)) except IndexError: reached_end = True print(json.dumps(rows)) else: print("Unknown command") sys.exit(1) if __name__ == "__main__": run(sys.argv[1:])
import xlrd import json import sys import os import argparse def run(argv): parser = argparse.ArgumentParser() parser.add_argument('--size') parser.add_argument('--start') parser.add_argument('--action') parser.add_argument('--file') parser.add_argument('--max-empty-rows', dest="max_empty_rows") args = parser.parse_args() if False == os.path.isfile(args.file): print("File does not exist") sys.exit(1) workbook = xlrd.open_workbook(args.file) sheet = workbook.sheet_by_index(0) if args.action == "count": print(sheet.nrows) elif args.action == "read": reached_end = False rows = [] while len(rows) < int(args.size) and reached_end == False: try: rows.append(sheet.row_values(int(args.start) + len(rows) - 1)) except IndexError: reached_end = True print(json.dumps(rows)) else: print("Unknown command") sys.exit(1) if __name__ == "__main__": run(sys.argv[1:])
Fix empty argument "max-empty-rows" in xls script We send argument "max-empty-rows" to two different script. In xls need to set, that this argument is available
Fix empty argument "max-empty-rows" in xls script We send argument "max-empty-rows" to two different script. In xls need to set, that this argument is available
Python
mit
arodiss/XlsBundle,arodiss/XlsBundle
--- +++ @@ -10,6 +10,7 @@ parser.add_argument('--start') parser.add_argument('--action') parser.add_argument('--file') + parser.add_argument('--max-empty-rows', dest="max_empty_rows") args = parser.parse_args() if False == os.path.isfile(args.file):
61693f27510567f4f2f5af2b51f95ae465290d9a
tests/test_directory/test_domain.py
tests/test_directory/test_domain.py
''' Creates all tests to serialize XMLs to xml_curl ''' import logging import pytest from lxml import etree from mock import Mock from wirecurly.directory import Domain, User def test_domain_no_users(): domain = Domain('wirephone.com.ar') response = domain.todict() assert domain.domain == 'wirephone.com.ar' assert len(response['children']) == 0 assert not domain.users def test_domain_1_user(): domain = Domain('wirephone.com.ar') user = Mock(User) domain.addUser(user) assert domain.users assert len(domain.users) == 1 assert domain.users[0] == user response = domain.todict() assert len(response['children']) == 1 assert response.get('children')[0] == user.todict()
''' Creates all tests to serialize XMLs to xml_curl ''' import logging import pytest from lxml import etree from mock import Mock from wirecurly.directory import Domain, User def test_domain_no_users(): domain = Domain('wirephone.com.ar') response = domain.todict() assert domain.domain == 'wirephone.com.ar' assert len(response['children']) == 0 assert not domain.users def test_domain_1_user(): domain = Domain('wirephone.com.ar') user = Mock(User) domain.addUser(user) assert domain.users assert len(domain.users) == 1 assert domain.users[0] == user response = domain.todict() assert len(response['children']) == 1 assert response.get('children')[0] == user.todict() def test_domain_with_group(): domain = Domain('wirephone.com.ar') user = Mock(User) domain.addUser(user) domain.addUsersToGroup() response = domain.todict() assert response.get('children')[0]['tag'] == 'groups' assert response.get('children')[0].get('children')[0]['tag'] == 'group' assert response.get('children')[0].get('children')[0].get('children')[0]['tag'] == 'users' def test_domain_with_group_name(): domain = Domain('wirephone.com.ar') user = Mock(User) domain.addUser(user) domain.addUsersToGroup('group_name') response = domain.todict() assert response.get('children')[0].get('children')[0]['attrs']['name'] == 'group_name'
Add tests for addUsersToGroup function
Add tests for addUsersToGroup function
Python
mpl-2.0
IndiciumSRL/wirecurly
--- +++ @@ -27,3 +27,25 @@ response = domain.todict() assert len(response['children']) == 1 assert response.get('children')[0] == user.todict() + +def test_domain_with_group(): + domain = Domain('wirephone.com.ar') + user = Mock(User) + domain.addUser(user) + domain.addUsersToGroup() + + response = domain.todict() + + assert response.get('children')[0]['tag'] == 'groups' + assert response.get('children')[0].get('children')[0]['tag'] == 'group' + assert response.get('children')[0].get('children')[0].get('children')[0]['tag'] == 'users' + +def test_domain_with_group_name(): + domain = Domain('wirephone.com.ar') + user = Mock(User) + domain.addUser(user) + domain.addUsersToGroup('group_name') + + response = domain.todict() + + assert response.get('children')[0].get('children')[0]['attrs']['name'] == 'group_name'
48ea5605807ec9798b77317a73446f4dc335f70a
main.py
main.py
import document import time evalstr = ''' var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText); ''' b = document.createElement('button') b.innerHTML = 'Run' b.setAttribute('id', 'runinjector') b.setAttribute('onclick', evalstr) pre = document.getElementById('edoutput') pre.appendChild(b) bridge = None while True: time.sleep(1) bridge = document.getElementById('injectedcanvas') if bridge != None: break bridge.innerHTML = 'ready' # Put Python<->JS class here. class FakeCanvas: def fillRect(self, x, y, width, height): pass # Your code here
import document import time evalstr = ''' var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText); ''' b = document.createElement('button') b.innerHTML = 'Run' b.setAttribute('id', 'runinjector') b.setAttribute('onclick', evalstr) pre = document.getElementById('edoutput') pre.appendChild(b) bridge = None while True: time.sleep(1) bridge = document.getElementById('injectedcanvas') if bridge != None: break bridge.innerHTML = 'ready' # Put Python<->JS class here. class Canvas: def fillRect(self, x, y, width, height): cmd = document.createElement('span'); cmd.innerHTML = "{0} {1} {2} {3}".format(x, y, width, height) bridge.appendChild(cmd) # Your code here
Implement the Python side of Canvas.fillRect
Implement the Python side of Canvas.fillRect
Python
mit
Zirientis/skulpt-canvas,Zirientis/skulpt-canvas
--- +++ @@ -18,10 +18,11 @@ break bridge.innerHTML = 'ready' # Put Python<->JS class here. -class FakeCanvas: +class Canvas: def fillRect(self, x, y, width, height): - pass - + cmd = document.createElement('span'); + cmd.innerHTML = "{0} {1} {2} {3}".format(x, y, width, height) + bridge.appendChild(cmd)
7559b61aec08dbab4b01affbe017f26a85a108e6
main.py
main.py
#coding=utf-8 #imports import pystache as ps import sys import json import imp views = imp.load_source('views', 'swedish/views.py') #from views import Invoice def main(): configFile = "invoice.json" htmlFile = "invoice.html" if len(sys.argv) == 2 : configFile = sys.argv[1] htmlFile = configFile[:-4] + "html" f = open(configFile, "r") file_content = f.read() content = json.loads(file_content) invoice = views.Invoice(content) renderer = ps.Renderer(file_encoding="utf-8", string_encoding="utf-8") html = renderer.render(invoice) fout = open(htmlFile, "w") fout.write(html.encode("UTF-8")) if __name__ == "__main__": main()
#coding=utf-8 #imports import pystache as ps import sys import json import imp views = imp.load_source('views', 'swedish/views.py') #from views import Invoice def main(): configFile = "invoice.sample.json" htmlFile = "invoice.html" if len(sys.argv) == 2 : configFile = sys.argv[1] htmlFile = configFile[:-4] + "html" f = open(configFile, "r") file_content = f.read() content = json.loads(file_content) invoice = views.Invoice(content) renderer = ps.Renderer(file_encoding="utf-8", string_encoding="utf-8") html = renderer.render(invoice) fout = open(htmlFile, "w") fout.write(html.encode("UTF-8")) if __name__ == "__main__": main()
Change json file to sample one
Change json file to sample one
Python
mit
SudoQ/yig,SudoQ/yig
--- +++ @@ -9,7 +9,7 @@ #from views import Invoice def main(): - configFile = "invoice.json" + configFile = "invoice.sample.json" htmlFile = "invoice.html" if len(sys.argv) == 2 : configFile = sys.argv[1]
0fb7f7950039d937df35f90a44cabc5603d238de
main.py
main.py
import os import json import sys from pprint import pprint def loadJSON(fInput): with open(fInput) as f: return json.load(f) return None if __name__ == '__main__': filePath = 'data/example.json' data = loadJSON(filePath) # check if the data is loaded correctly if data is None: sys.exit('wrong json file'); name = data.get('name') lstTypes = data.get('types') lstFuncs = data.get('functions') from dsFileBuilder import DSFileBuilder dsb = DSFileBuilder(name, lstTypes) dsb.buildDS() dicNumpyDS = dsb.getGeneratedNumpyDS() from kernelFuncBuilder import KernelFuncBuilder kfb = KernelFuncBuilder(name, lstFuncs) kfb.buildKF() dicKFuncDS = kfb.getGeneratedKFuncDS() from oclPyObjGenerator import OCLPyObjGenerator opg = OCLPyObjGenerator(name, dicNumpyDS, dicKFuncDS) opg.generateOCLPyObj() pass
import os import json import sys from pprint import pprint def loadJSON(fInput): with open(fInput) as f: return json.load(f) return None if __name__ == '__main__': filePath = 'data/example.json' data = loadJSON(filePath) # check if the data is loaded correctly if data is None: sys.exit('wrong json file'); name = data.get('name') lstTypes = data.get('types') lstFuncs = data.get('functions') ''' from dsFileBuilder import DSFileBuilder dsb = DSFileBuilder(name, lstTypes) dsb.buildDS() dicNumpyDS = dsb.getGeneratedNumpyDS() from kernelFuncBuilder import KernelFuncBuilder kfb = KernelFuncBuilder(name, lstFuncs) kfb.buildKF() dicKFuncDS = kfb.getGeneratedKFuncDS() from oclPyObjGenerator import OCLPyObjGenerator opg = OCLPyObjGenerator(name, dicNumpyDS, dicKFuncDS) opg.generateOCLPyObj() pass '''
Add method definition generator and some sample for test
Add method definition generator and some sample for test
Python
apache-2.0
kilikkuo/kernel-mapper,PyOCL/kernel-mapper
--- +++ @@ -19,6 +19,7 @@ lstTypes = data.get('types') lstFuncs = data.get('functions') + ''' from dsFileBuilder import DSFileBuilder dsb = DSFileBuilder(name, lstTypes) dsb.buildDS() @@ -33,3 +34,4 @@ opg = OCLPyObjGenerator(name, dicNumpyDS, dicKFuncDS) opg.generateOCLPyObj() pass + '''
f253feac7a4c53bd17958b0c74adbec528ae2e17
rethinkdb/setup-rethinkdb.py
rethinkdb/setup-rethinkdb.py
#!/usr/bin/env python3 import rethinkdb as r import argparse parser = argparse.ArgumentParser(description='Set up RethinkDB locally') args = parser.parse_args() conn = r.connect() r.db_create('muzhack').run(conn) r.db('muzhack').table_create('users').run(conn) r.db('muzhack').table_create('projects').run(conn) r.db('muzhack').table_create('resetPasswordTokens').run(conn)
#!/usr/bin/env python3 import rethinkdb as r import argparse parser = argparse.ArgumentParser(description='Set up RethinkDB') parser.add_argument('-H', '--host', default='localhost', help='Specify host') args = parser.parse_args() conn = r.connect(host=args.host) r.db_create('muzhack').run(conn) r.db('muzhack').table_create('users').run(conn) r.db('muzhack').table_create('projects').run(conn) r.db('muzhack').table_create('resetPasswordTokens').run(conn)
Allow setting up rethinkdb remotely
Allow setting up rethinkdb remotely
Python
mit
muzhack/musitechhub,muzhack/musitechhub,muzhack/musitechhub,muzhack/muzhack,muzhack/muzhack,muzhack/musitechhub,muzhack/muzhack,muzhack/muzhack
--- +++ @@ -3,10 +3,11 @@ import argparse -parser = argparse.ArgumentParser(description='Set up RethinkDB locally') +parser = argparse.ArgumentParser(description='Set up RethinkDB') +parser.add_argument('-H', '--host', default='localhost', help='Specify host') args = parser.parse_args() -conn = r.connect() +conn = r.connect(host=args.host) r.db_create('muzhack').run(conn) r.db('muzhack').table_create('users').run(conn) r.db('muzhack').table_create('projects').run(conn)
5bd9de24e63c557aed1779f6cee611cfeb52ddc0
envs.py
envs.py
import os import gym from gym.spaces.box import Box from baselines import bench from baselines.common.atari_wrappers import wrap_deepmind try: import pybullet_envs except ImportError: pass def make_env(env_id, seed, rank, log_dir): def _thunk(): env = gym.make(env_id) env.seed(seed + rank) env = bench.Monitor(env, os.path.join(log_dir, "{}.monitor.json".format(rank))) # Ugly hack to detect atari. if env.action_space.__class__.__name__ == 'Discrete': env = wrap_deepmind(env) env = WrapPyTorch(env) return env return _thunk class WrapPyTorch(gym.ObservationWrapper): def __init__(self, env=None): super(WrapPyTorch, self).__init__(env) self.observation_space = Box(0.0, 1.0, [1, 84, 84]) def _observation(self, observation): return observation.transpose(2, 0, 1)
import os import gym from gym.spaces.box import Box from baselines import bench from baselines.common.atari_wrappers import wrap_deepmind try: import pybullet_envs except ImportError: pass def make_env(env_id, seed, rank, log_dir): def _thunk(): env = gym.make(env_id) env.seed(seed + rank) env = bench.Monitor(env, os.path.join(log_dir, "{}.monitor.json".format(rank))) # Ugly hack to detect atari. if hasattr(env.env, 'env') and hasattr(env.env.env, 'ale'): env = wrap_deepmind(env) env = WrapPyTorch(env) return env return _thunk class WrapPyTorch(gym.ObservationWrapper): def __init__(self, env=None): super(WrapPyTorch, self).__init__(env) self.observation_space = Box(0.0, 1.0, [1, 84, 84]) def _observation(self, observation): return observation.transpose(2, 0, 1)
Change the ugly hack to detect atari
Change the ugly hack to detect atari
Python
mit
YuhangSong/GTN,YuhangSong/GTN,ikostrikov/pytorch-a2c-ppo-acktr
--- +++ @@ -20,7 +20,7 @@ os.path.join(log_dir, "{}.monitor.json".format(rank))) # Ugly hack to detect atari. - if env.action_space.__class__.__name__ == 'Discrete': + if hasattr(env.env, 'env') and hasattr(env.env.env, 'ale'): env = wrap_deepmind(env) env = WrapPyTorch(env) return env
ee130df5b48d1e4196bb9159de64e279656cdfcf
byceps/blueprints/snippet/views.py
byceps/blueprints/snippet/views.py
""" byceps.blueprints.snippet.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from flask import abort, g from ...services.snippet import mountpoint_service from ...util.framework.blueprint import create_blueprint from .templating import render_snippet_as_page, render_snippet_as_partial blueprint = create_blueprint('snippet', __name__) blueprint.add_app_template_global(render_snippet_as_partial, 'render_snippet') def view_current_version_by_name(name): """Show the current version of the snippet that is mounted with that name. """ # Note: endpoint suffix != snippet name version = mountpoint_service.find_current_snippet_version_for_mountpoint( g.site_id, name ) if version is None: abort(404) return render_snippet_as_page(version)
""" byceps.blueprints.snippet.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from flask import abort, g, url_for from ...services.snippet import mountpoint_service from ...util.framework.blueprint import create_blueprint from .templating import render_snippet_as_page, render_snippet_as_partial blueprint = create_blueprint('snippet', __name__) blueprint.add_app_template_global(render_snippet_as_partial, 'render_snippet') @blueprint.app_template_global() def url_for_snippet(name): return url_for(f'snippet.{name}') def view_current_version_by_name(name): """Show the current version of the snippet that is mounted with that name. """ # Note: endpoint suffix != snippet name version = mountpoint_service.find_current_snippet_version_for_mountpoint( g.site_id, name ) if version is None: abort(404) return render_snippet_as_page(version)
Introduce global template function `url_for_snippet`
Introduce global template function `url_for_snippet` Use it to ease the transition to a multisite-capable snippet URL rule system.
Python
bsd-3-clause
m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
--- +++ @@ -6,7 +6,7 @@ :License: Modified BSD, see LICENSE for details. """ -from flask import abort, g +from flask import abort, g, url_for from ...services.snippet import mountpoint_service from ...util.framework.blueprint import create_blueprint @@ -17,6 +17,11 @@ blueprint = create_blueprint('snippet', __name__) blueprint.add_app_template_global(render_snippet_as_partial, 'render_snippet') + + +@blueprint.app_template_global() +def url_for_snippet(name): + return url_for(f'snippet.{name}') def view_current_version_by_name(name):
0ef1e9b77ad31c13a32c285b4b07e5d19a5d6c92
config.py
config.py
import yaml def load_config(keys=None): with open('config.yml', 'r') as yf: conf = yaml.load(yf) if keys is not None: return [conf[k] for k in keys] return conf
import yaml def load_config(keys=None): with open('config.yml', 'r') as yf: conf = yaml.safe_load(yf) if keys is not None: return [conf[k] for k in keys] return conf
Use safe_load in place of load
Use safe_load in place of load
Python
cc0-1.0
dateutil/tzdata
--- +++ @@ -2,7 +2,7 @@ def load_config(keys=None): with open('config.yml', 'r') as yf: - conf = yaml.load(yf) + conf = yaml.safe_load(yf) if keys is not None: return [conf[k] for k in keys]
0cfb43da3c579bca84be1c774c1306ac2f54ffda
config.py
config.py
import os class Config(object): DEBUG = True # WTF_CSRF_ENABLED = False DATABASE_NAME = "projectp" BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # refers to application_top APP_STATIC = os.path.join(BASE_DIR, 'static') # Database (sqlite) configuration SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASE_DIR, 'app.db') DATABASE_CONNECT_OPTIONS = {} SQLALCHEMY_TRACK_MODIFICATIONS = True class DevelopmentConfig(Config): SECRET_KEY = "aardappelpuree" class ProductionConfig(Config): SECRET_KEY = "appeltaart" config = { 'development': DevelopmentConfig, 'production': DevelopmentConfig }
import os class Config(object): DEBUG = False # WTF_CSRF_ENABLED = False DATABASE_NAME = "projectp" BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # refers to application_top APP_STATIC = os.path.join(BASE_DIR, 'static') # Database (sqlite) configuration SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASE_DIR, 'app.db') DATABASE_CONNECT_OPTIONS = {} SQLALCHEMY_TRACK_MODIFICATIONS = True class DevelopmentConfig(Config): SECRET_KEY = "aardappelpuree" class ProductionConfig(Config): SECRET_KEY = "appeltaart" config = { 'development': DevelopmentConfig, 'production': DevelopmentConfig }
Disable Flask debug - incompatible with SocketIO
Disable Flask debug - incompatible with SocketIO
Python
mit
Proj-P/project-p-api,Proj-P/project-p-api
--- +++ @@ -2,7 +2,7 @@ class Config(object): - DEBUG = True + DEBUG = False # WTF_CSRF_ENABLED = False DATABASE_NAME = "projectp"
26eec2d069075c662d5b935474e8a2eea0d195b5
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Anton Lavrenov # Copyright (c) 2014 Anton Lavrenov # # License: MIT # """This module exports the Tslint plugin class.""" from SublimeLinter.lint import Linter, util class Tslint(Linter): """Provides an interface to tslint.""" syntax = 'typescript' cmd = ('tslint', '@') regex = ( r'^.+?\[(?P<line>\d+), (?P<col>\d+)\]: ' r'(?P<message>.+)' ) error_stream = util.STREAM_BOTH config_file = ('--config', 'tslint.json', '~') tempfile_suffix = 'ts' version_args = '--version' version_requirement = '>= 0.4.0' version_re = r'(?P<version>\d+\.\d+\.\d+)'
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Anton Lavrenov # Copyright (c) 2014 Anton Lavrenov # # License: MIT # """This module exports the Tslint plugin class.""" from SublimeLinter.lint import Linter, util class Tslint(Linter): """Provides an interface to tslint.""" syntax = ('typescript', 'typescriptreact') cmd = ('tslint', '@') regex = ( r'^.+?\[(?P<line>\d+), (?P<col>\d+)\]: ' r'(?P<message>.+)' ) error_stream = util.STREAM_BOTH config_file = ('--config', 'tslint.json', '~') tempfile_suffix = {'typescript': 'ts', 'typescriptreact': 'tsx'} version_args = '--version' version_requirement = '>= 0.4.0' version_re = r'(?P<version>\d+\.\d+\.\d+)'
Add support for typescriptreact *.tsx files
Add support for typescriptreact *.tsx files
Python
mit
lavrton/SublimeLinter-contrib-tslint
--- +++ @@ -17,7 +17,7 @@ """Provides an interface to tslint.""" - syntax = 'typescript' + syntax = ('typescript', 'typescriptreact') cmd = ('tslint', '@') regex = ( r'^.+?\[(?P<line>\d+), (?P<col>\d+)\]: ' @@ -25,7 +25,7 @@ ) error_stream = util.STREAM_BOTH config_file = ('--config', 'tslint.json', '~') - tempfile_suffix = 'ts' + tempfile_suffix = {'typescript': 'ts', 'typescriptreact': 'tsx'} version_args = '--version' version_requirement = '>= 0.4.0' version_re = r'(?P<version>\d+\.\d+\.\d+)'
0b6aabf043cd96e82972376b632067dc624daf0d
test.py
test.py
import requests from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization import base64 r = requests.get('https://api.travis-ci.org/repos/gforsyth/travis_docs_builder/key', headers={'Accept': 'application/vnd.travis-ci.2+json'}) public_key = r.json()['key'].replace("RSA PUBLIC KEY", "PUBLIC KEY").encode('utf-8') key = serialization.load_pem_public_key(public_key, backend=default_backend()) pad = padding.PKCS1v15() print(base64.b64encode(key.encrypt(b'a=b', pad)))
import requests from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization import base64 def encrypt_variable(variable, repo, public_key=None): """ Encrypt an environment variable for repo for Travis ``variable`` should be a bytes object. ``repo`` should be like 'gforsyth/travis_docs_builder' ``public_key`` should be a pem format public key, obtained from Travis if not provided. """ if not isinstance(variable, bytes): raise TypeError("variable should be bytes") if not b"=" in variable: raise ValueError("variable should be of the form 'VARIABLE=value'") if not public_key: # TODO: Error handling r = requests.get('https://api.travis-ci.org/repos/{repo}/key'.format(repo=repo), headers={'Accept': 'application/vnd.travis-ci.2+json'}) public_key = r.json()['key'] public_key = public_key.replace("RSA PUBLIC KEY", "PUBLIC KEY").encode('utf-8') key = serialization.load_pem_public_key(public_key, backend=default_backend()) pad = padding.PKCS1v15() return base64.b64encode(key.encrypt(variable, pad))
Refactor the encryption into a function, with some type checking
Refactor the encryption into a function, with some type checking
Python
mit
gforsyth/doctr_testing,doctrtesting/doctr,drdoctr/doctr
--- +++ @@ -6,11 +6,30 @@ import base64 -r = requests.get('https://api.travis-ci.org/repos/gforsyth/travis_docs_builder/key', headers={'Accept': 'application/vnd.travis-ci.2+json'}) +def encrypt_variable(variable, repo, public_key=None): + """ + Encrypt an environment variable for repo for Travis -public_key = r.json()['key'].replace("RSA PUBLIC KEY", "PUBLIC KEY").encode('utf-8') -key = serialization.load_pem_public_key(public_key, backend=default_backend()) + ``variable`` should be a bytes object. + ``repo`` should be like 'gforsyth/travis_docs_builder' + ``public_key`` should be a pem format public key, obtained from Travis if + not provided. + """ + if not isinstance(variable, bytes): + raise TypeError("variable should be bytes") -pad = padding.PKCS1v15() + if not b"=" in variable: + raise ValueError("variable should be of the form 'VARIABLE=value'") -print(base64.b64encode(key.encrypt(b'a=b', pad))) + if not public_key: + # TODO: Error handling + r = requests.get('https://api.travis-ci.org/repos/{repo}/key'.format(repo=repo), + headers={'Accept': 'application/vnd.travis-ci.2+json'}) + public_key = r.json()['key'] + + public_key = public_key.replace("RSA PUBLIC KEY", "PUBLIC KEY").encode('utf-8') + key = serialization.load_pem_public_key(public_key, backend=default_backend()) + + pad = padding.PKCS1v15() + + return base64.b64encode(key.encrypt(variable, pad))
8dd873a485eba31e5fa99b88708a2771f6ef0240
main.py
main.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import logging from datetime import datetime from flask import Flask from update_wrapper import UpdateWrapper LOG_FILE = datetime.now().strftime("%Y%m%d%H%M%S%f") LOG_DIR = "log" FULL_LOG_PATH = os.path.join(LOG_DIR, LOG_FILE) if not os.path.isdir(LOG_DIR): os.mkdir(LOG_DIR) logging.basicConfig( filename=FULL_LOG_PATH, level=logging.DEBUG) logging.captureWarnings(True) wrapper = UpdateWrapper() wrapper.read_config("config.json") # wrapper.run() app = Flask(__name__) if __name__ == "__main__": app.run()
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import logging from datetime import datetime from flask import Flask from update_wrapper import UpdateWrapper LOG_FILE = datetime.now().strftime("%Y%m%d%H%M%S%f") LOG_DIR = "log" FULL_LOG_PATH = os.path.join(LOG_DIR, LOG_FILE) if not os.path.isdir(LOG_DIR): os.mkdir(LOG_DIR) logging.basicConfig( filename=FULL_LOG_PATH, level=logging.DEBUG) logging.captureWarnings(True) wrapper = UpdateWrapper() wrapper.read_config("config.json") # wrapper.run() app = Flask(__name__) @app.route("/log") def get_log(): with open(FULL_LOG_PATH, 'r') as f: read_data = f.read() f.closed return read_data if __name__ == "__main__": app.run()
Add returning log file content
Add returning log file content
Python
mit
stormaaja/csvconverter,stormaaja/csvconverter,stormaaja/csvconverter
--- +++ @@ -27,5 +27,12 @@ app = Flask(__name__) +@app.route("/log") +def get_log(): + with open(FULL_LOG_PATH, 'r') as f: + read_data = f.read() + f.closed + return read_data + if __name__ == "__main__": app.run()
d79edc34bece193b0cf1bc7117c3559ed62e0a7f
main.py
main.py
#!/usr/bin/python3 # -*- coding: utf8 -* import sys # Fix for file paths errors import os PATH = os.path.dirname(os.path.realpath(__file__)) # Import other files from the project from game import Game from idlerpg import IdleRPG from logger import log, story # Import Graphic Lib from PyQt5.QtWidgets import (QApplication, QMainWindow, QToolTip, QPushButton, QWidget, QStackedWidget, QHBoxLayout, QVBoxLayout, QLabel, QLineEdit, QFormLayout, QDockWidget, QListWidget, QListWidgetItem, QAction, qApp, QButtonGroup, QProgressBar, QSpacerItem) from PyQt5.QtCore import QTimer, Qt from PyQt5.QtGui import QFont, QIcon def main(): # instatiate the game object game = Game() # initiate window app = QApplication(sys.argv) app.setStyleSheet("") idlerpg = IdleRPG(game) # setup timer for the game tick (1 tick per 2 seconds) timer = QTimer() timer.start(1500) timer.timeout.connect(idlerpg.tick) idlerpg.show() # run the main loop sys.exit(app.exec_()) if __name__ == '__main__': log.info("========== STARTING NEW SESSION ============") main() #EOF
#!/usr/bin/python3 # -*- coding: utf8 -* import sys # Fix for file paths errors import os PATH = os.path.dirname(os.path.realpath(__file__)) # Import other files from the project from game import Game from idlerpg import IdleRPG from logger import log, story # Import Graphic Lib from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QTimer def main(): # instatiate the game object game = Game() # initiate window app = QApplication(sys.argv) app.setStyleSheet("") idlerpg = IdleRPG(game) # setup timer for the game tick (1 tick per 2 seconds) timer = QTimer() timer.start(1500) timer.timeout.connect(idlerpg.tick) idlerpg.show() # run the main loop sys.exit(app.exec_()) if __name__ == '__main__': log.info("========== STARTING NEW SESSION ============") main() #EOF
Remove a bunch of unnecessary import
FIX: Remove a bunch of unnecessary import
Python
mit
DanielNautre/idle-rpg
--- +++ @@ -13,12 +13,8 @@ from logger import log, story # Import Graphic Lib -from PyQt5.QtWidgets import (QApplication, QMainWindow, QToolTip, QPushButton, - QWidget, QStackedWidget, QHBoxLayout, QVBoxLayout, QLabel, QLineEdit, - QFormLayout, QDockWidget, QListWidget, QListWidgetItem, QAction, qApp, - QButtonGroup, QProgressBar, QSpacerItem) -from PyQt5.QtCore import QTimer, Qt -from PyQt5.QtGui import QFont, QIcon +from PyQt5.QtWidgets import QApplication +from PyQt5.QtCore import QTimer def main(): # instatiate the game object
c8177562558d4b59d6d0a8f3fb4518c067394a31
comrade/core/decorators.py
comrade/core/decorators.py
from django.utils.decorators import available_attrs from django.utils.http import urlquote from django.http import HttpResponse from django.template import loader, RequestContext from functools import wraps def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance def authorized(test_func, template_name='401.html'): """ Decorator for views that checks that the user passes the given test, redirecting to the unauthorized page if it fails. The test should be a callable that takes the user object and returns True if the user passes. """ def decorator(view_func): def _wrapped_view(request, *args, **kwargs): if test_func(request.user, *args, **kwargs): return view_func(request, *args, **kwargs) path = urlquote(request.get_full_path()) t = loader.get_template(template_name) return HttpResponse(t.render(RequestContext(request)), status=401) return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view) return decorator def admin_login_required(view_func): def _decorator(request, *args, **kwargs): if request.user.is_authenticated() and request.user.is_staff: return view_func(request, *args, **kwargs) else: t = loader.get_template('401.html') return HttpResponse(t.render(RequestContext(request)), status=401) return _decorator
from django.utils.decorators import available_attrs from django.utils.http import urlquote from django.http import HttpResponse from django.template import loader, RequestContext from functools import wraps def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance def authorized(test_func, template_name='401.html'): """ Decorator for views that checks that the user passes the given test, redirecting to the unauthorized page if it fails. The test should be a callable that takes the user object and returns True if the user passes. """ def decorator(view_func): def _wrapped_view(request, *args, **kwargs): if test_func(request.user, *args, **kwargs): return view_func(request, *args, **kwargs) path = urlquote(request.get_full_path()) t = loader.get_template(template_name) return HttpResponse(t.render(RequestContext(request)), status=401) return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view) return decorator
Use authorized + test_func instead of custom decorator.
Use authorized + test_func instead of custom decorator.
Python
mit
bueda/django-comrade
--- +++ @@ -30,13 +30,3 @@ return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view) return decorator - -def admin_login_required(view_func): - def _decorator(request, *args, **kwargs): - if request.user.is_authenticated() and request.user.is_staff: - return view_func(request, *args, **kwargs) - else: - t = loader.get_template('401.html') - return HttpResponse(t.render(RequestContext(request)), status=401) - return _decorator -
30a4281f2602bd6b9d90d89375785a2645854a0d
enthought/enable2/pyglet_backend/pyglet_app.py
enthought/enable2/pyglet_backend/pyglet_app.py
# proxy from enthought.enable.pyglet_backend.pyglet_app import *
# proxy __all__ = ["get_app", "PygletApp"] from enthought.enable.pyglet_backend.pyglet_app import * # Import the objects which are not declared in __all__, # but are still defined in the real module, such that people # can import them explicitly when needed, just as they could # with the real module. # # It is unlikely that someone will import these objects, since # they start with '_'. However, the proxy's job is to mimic the # behavior of the real module as closely as possible. # The proxy's job is not to define or change the API. # from enthought.enable.pyglet_backend.pyglet_app import _CurrentApp, _PygletApp
Improve the proxy module which maps to a module which uses __all__.
Improve the proxy module which maps to a module which uses __all__. The notes I made in the code apply to all proxy modules which map to a module which uses __all__.
Python
bsd-3-clause
tommy-u/enable,tommy-u/enable,tommy-u/enable,tommy-u/enable
--- +++ @@ -1,2 +1,19 @@ -# proxy +# proxy + +__all__ = ["get_app", "PygletApp"] + from enthought.enable.pyglet_backend.pyglet_app import * + + +# Import the objects which are not declared in __all__, +# but are still defined in the real module, such that people +# can import them explicitly when needed, just as they could +# with the real module. +# +# It is unlikely that someone will import these objects, since +# they start with '_'. However, the proxy's job is to mimic the +# behavior of the real module as closely as possible. +# The proxy's job is not to define or change the API. +# +from enthought.enable.pyglet_backend.pyglet_app import _CurrentApp, _PygletApp +
2d0e742c0f8d5f0a9d72b8c2c6fa751ba7842668
tests/test_json.py
tests/test_json.py
from __future__ import absolute_import import fnmatch import os import unittest from . import validate_json_format class TestSettings(unittest.TestCase): def _get_json_files(self, file_pattern, folder='.'): for root, dirnames, filenames in os.walk(folder): for filename in fnmatch.filter(filenames, file_pattern): yield os.path.join(root, filename) for dirname in [d for d in dirnames if d not in ('.git', '.tox', '.idea')]: for f in self._get_json_files( file_pattern, os.path.join(root, dirname)): yield f def test_json_settings(self): """Test each JSON file.""" file_patterns = ( '*.sublime-settings', '*.sublime-commands', '*.sublime-menu' ) for file_pattern in file_patterns: for f in self._get_json_files(file_pattern): print(f) self.assertFalse( validate_json_format.CheckJsonFormat( False, True).check_format(f), "%s does not comform to expected format!" % f)
from __future__ import absolute_import import fnmatch import os import unittest from . import validate_json_format class TestSettings(unittest.TestCase): def _get_json_files(self, file_pattern, folder='.'): for root, dirnames, filenames in os.walk(folder): for filename in fnmatch.filter(filenames, file_pattern): yield os.path.join(root, filename) for dirname in [d for d in dirnames if d not in ('.git', '.tox', '.idea')]: for f in self._get_json_files( file_pattern, os.path.join(root, dirname)): yield f def test_json_settings(self): """Test each JSON file.""" file_patterns = ( '*.sublime-commands', '*.sublime-keymap', '*.sublime-menu', '*.sublime-settings' ) for file_pattern in file_patterns: for f in self._get_json_files(file_pattern): print(f) self.assertFalse( validate_json_format.CheckJsonFormat( False, True).check_format(f), "%s does not comform to expected format!" % f)
Include sublime-keymap files in JSON format tests.
Include sublime-keymap files in JSON format tests.
Python
mit
jonlabelle/Trimmer,jonlabelle/Trimmer
--- +++ @@ -21,9 +21,10 @@ def test_json_settings(self): """Test each JSON file.""" file_patterns = ( - '*.sublime-settings', '*.sublime-commands', - '*.sublime-menu' + '*.sublime-keymap', + '*.sublime-menu', + '*.sublime-settings' ) for file_pattern in file_patterns: for f in self._get_json_files(file_pattern):
ff0ae66ee16bc3ac07cb88ddacb52ffa41779757
tests/test_func.py
tests/test_func.py
from .utils import assert_eval def test_simple_func(): assert_eval('(def @a $a 8) (@a)', 1, 8) def test_simple_func_args(): assert_eval( '(def @a $a $a)' '(@a 1)' '(@a 2)' '(@a 5)', 1, 1, 2, 5) def test_func_args_overwrite_globals(): assert_eval( '(def @a $a 3)' '(set $a 10)' '$a' '(@a 8)' '$a', 1, 10, 10, 3, 8, ) def test_func_args_with_offset(): assert_eval( '(def @a $d (+ $d $i))' '(def @b $i (+ $i $j))' '(@a 1 2 3)' '(@b 8 9 10)' '$a\n$b\n$c\n$d\n$e\n$i\n$j\n$k\n', 1, 1, 4, 17, 0, 0, 0, 1, 2, 8, 9, 10, )
from .utils import assert_eval def test_simple_func(): assert_eval('(def @a $a 8) (@a)', 1, 8) def test_simple_func_args(): assert_eval( '(def @a $a $a)' '(@a 1)' '(@a 2)' '(@a 5)', 1, 1, 2, 5) def test_func_args_overwrite_globals(): assert_eval( '(def @a $a 3)' '(set $a 10)' '$a' '(@a 8)' '$a', 1, 10, 10, 3, 8, ) def test_func_args_with_offset(): assert_eval( '(def @a $d (+ $d $i))' '(def @b $i (+ $i $j))' '(@a 1 2 3)' '(@b 8 9 10)' '$a\n$b\n$c\n$d\n$e\n$i\n$j\n$k\n', 1, 1, 4, 17, 0, 0, 0, 1, 2, 8, 9, 10, ) def test_no_args(): assert_eval( '(def @a (+ 0 5))' '(@a)', 1, 5, ) def test_nested_calls(): assert_eval( '(def @a $a (+ $a $b))' '(def @b (+ (@a 1 2) (@a 3 4)))' '(@b)', 1, 1, 1 + 2 + 3 + 4, )
Add some more function tests.
Add some more function tests.
Python
bsd-3-clause
sapir/tinywhat,sapir/tinywhat,sapir/tinywhat
--- +++ @@ -44,3 +44,23 @@ 17, 0, 0, 0, 1, 2, 8, 9, 10, ) + + +def test_no_args(): + assert_eval( + '(def @a (+ 0 5))' + '(@a)', + 1, + 5, + ) + + +def test_nested_calls(): + assert_eval( + '(def @a $a (+ $a $b))' + '(def @b (+ (@a 1 2) (@a 3 4)))' + '(@b)', + 1, + 1, + 1 + 2 + 3 + 4, + )
95efd017f8adf7b2f3e1b7ee82a865982f8be8df
urls.py
urls.py
from django.conf.urls.defaults import * from django.contrib import admin from django.conf import settings admin.autodiscover() urlpatterns = patterns('', (r'^admin/doc/', include('django.contrib.admindocs.urls')), (r'^admin/', include(admin.site.urls)), url(regex=r'^$', view='core.views.index', name='index'), url(regex=r'^logout/$', view='django.contrib.auth.views.logout', name='logout', kwargs={'next_page': '/'}), url(regex=r'^tos/$', view='django.views.generic.simple.direct_to_template', name='tos', kwargs={'template': 'tos.html'}), url(r'^home/', include('core.urls')), url(r'^contact/', include('contact.urls')), url(r'^project/', include('project.urls')), url(r'^accounts/', include('accounts.urls')), url(r'^issues/', include('bugtracker.urls')), url(r'^user/', include('registration_urls')), ) urlpatterns += patterns('', (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), )
from django.conf.urls.defaults import * from django.contrib import admin from django.conf import settings admin.autodiscover() urlpatterns = patterns('', (r'^admin/doc/', include('django.contrib.admindocs.urls')), (r'^admin/', include(admin.site.urls)), url(regex=r'^$', view='core.views.index', name='index'), url(regex=r'^logout/$', view='django.contrib.auth.views.logout', name='logout', kwargs={'next_page': '/'}), url(regex=r'^tos/$', view='django.views.generic.simple.direct_to_template', name='tos', kwargs={'template': 'tos.html'}), url(r'^home/', include('core.urls')), url(r'^contact/', include('contact.urls')), url(r'^project/', include('project.urls')), url(r'^accounts/', include('accounts.urls')), url(r'^issues/', include('bugtracker.urls')), url(r'^user/', include('registration_urls')), ) if settings.DEBUG: urlpatterns += patterns('', (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), )
Use django for static file only in debug mode
Use django for static file only in debug mode
Python
agpl-3.0
fgaudin/aemanager,fgaudin/aemanager,fgaudin/aemanager
--- +++ @@ -28,7 +28,8 @@ ) -urlpatterns += patterns('', - (r'^static/(?P<path>.*)$', 'django.views.static.serve', - {'document_root': settings.MEDIA_ROOT}), -) +if settings.DEBUG: + urlpatterns += patterns('', + (r'^static/(?P<path>.*)$', 'django.views.static.serve', + {'document_root': settings.MEDIA_ROOT}), + )
c9c618cfcd8caeac9ba23ec1c53d3ebdf32d563d
src/cli/_errors.py
src/cli/_errors.py
""" Error heirarchy for stratis cli. """ class StratisCliError(Exception): """ Top-level stratis cli error. """ pass class StratisCliValueError(StratisCliError): """ Raised when a parameter has an unacceptable value. May also be raised when the parameter has an unacceptable type. """ _FMT_STR = "value '%s' for parameter %s is unacceptable" def __init__(self, value, param, msg=None): """ Initializer. :param object value: the value :param str param: the parameter :param str msg: an explanatory message """ # pylint: disable=super-init-not-called self._value = value self._param = param self._msg = msg def __str__(self): # pragma: no cover if self._msg: fmt_str = self._FMT_STR + ": %s" return fmt_str % (self._value, self._param, self._msg) else: return self._FMT_STR % (self._value, self._param)
""" Error heirarchy for stratis cli. """ class StratisCliError(Exception): """ Top-level stratis cli error. """ pass class StratisCliValueError(StratisCliError): """ Raised when a parameter has an unacceptable value. May also be raised when the parameter has an unacceptable type. """ _FMT_STR = "value '%s' for parameter %s is unacceptable" def __init__(self, value, param, msg=None): """ Initializer. :param object value: the value :param str param: the parameter :param str msg: an explanatory message """ # pylint: disable=super-init-not-called self._value = value self._param = param self._msg = msg def __str__(self): # pragma: no cover if self._msg: fmt_str = self._FMT_STR + ": %s" return fmt_str % (self._value, self._param, self._msg) else: return self._FMT_STR % (self._value, self._param) class StratisCliValueUnimplementedError(StratisCliValueError): """ Raised if a parameter is not intrinsically bad but functionality is unimplemented for this value. """ pass
Add an exception useful for prototyping.
Add an exception useful for prototyping. Signed-off-by: mulhern <7b51bcf507bcd7afb72bf8663752c0ddbeb517f6@redhat.com>
Python
apache-2.0
stratis-storage/stratis-cli,stratis-storage/stratis-cli
--- +++ @@ -34,3 +34,11 @@ return fmt_str % (self._value, self._param, self._msg) else: return self._FMT_STR % (self._value, self._param) + + +class StratisCliValueUnimplementedError(StratisCliValueError): + """ + Raised if a parameter is not intrinsically bad but functionality + is unimplemented for this value. + """ + pass
1b15198842d60582930f828656a2353f85a05d44
apps/events/views.py
apps/events/views.py
#-*- coding: utf-8 -*- from django.shortcuts import render_to_response from django.shortcuts import get_object_or_404 from django.template import RequestContext from apps.events.models import Event, AttendanceEvent, Attendee import datetime def index(request): events = Event.objects.filter(event_start__gte=datetime.date.today()) if len(events) == 1: return details(request, events[0].event_id) return render_to_response('events/index.html', {'events': events}, context_instance=RequestContext(request)) def details(request, event_id): event = get_object_or_404(Event, pk=event_id) is_attendance_event = False try: attendance_event = AttendanceEvent.objects.get(pk=event_id) attendance_event.count_attendees = Attendee.objects.filter(event=attendance_event).count() is_attendance_event = True except AttendanceEvent.DoesNotExist: pass if is_attendance_event: return render_to_response('events/details.html', {'event': event, 'attendance_event': attendance_event}, context_instance=RequestContext(request)) else: return render_to_response('events/details.html', {'event': event}, context_instance=RequestContext(request)) def get_attendee(attendee_id): return get_object_or_404(Attendee, pk=attendee_id)
#-*- coding: utf-8 -*- from django.shortcuts import render_to_response from django.shortcuts import get_object_or_404 from django.template import RequestContext from apps.events.models import Event, AttendanceEvent, Attendee import datetime def index(request): events = Event.objects.filter(event_start__gte=datetime.date.today()) if len(events) == 1: return details(request, events[0].id) return render_to_response('events/index.html', {'events': events}, context_instance=RequestContext(request)) def details(request, event_id): event = get_object_or_404(Event, pk=event_id) is_attendance_event = False try: attendance_event = AttendanceEvent.objects.get(pk=event_id) attendance_event.count_attendees = Attendee.objects.filter(event=attendance_event).count() is_attendance_event = True except AttendanceEvent.DoesNotExist: pass if is_attendance_event: return render_to_response('events/details.html', {'event': event, 'attendance_event': attendance_event}, context_instance=RequestContext(request)) else: return render_to_response('events/details.html', {'event': event}, context_instance=RequestContext(request)) def get_attendee(attendee_id): return get_object_or_404(Attendee, pk=attendee_id)
Fix no table named event_id
Fix no table named event_id
Python
mit
dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4
--- +++ @@ -9,7 +9,7 @@ def index(request): events = Event.objects.filter(event_start__gte=datetime.date.today()) if len(events) == 1: - return details(request, events[0].event_id) + return details(request, events[0].id) return render_to_response('events/index.html', {'events': events}, context_instance=RequestContext(request))
048dcc39703cb00ce5616e9ed2b07be8dbde4038
img_pipe/archival_data/single_channel_clean.py
img_pipe/archival_data/single_channel_clean.py
import sys ''' Cleans an MS with a single channel given a mask and a model ''' vis = sys.argv[4] model = sys.argv[5] mask = sys.argv[6] out_root = vis[:-3] clean(vis=vis, imagename=out_root+'.clean', field='M33*', restfreq='1420.40575177MHz', mode='channel', width=1, nchan=1, start=1, cell='1.5arcsec', multiscale=[0, 4, 8, 20, 40, 80], threshold='2.2mJy/beam', imagermode='mosaic', gain=0.5, imsize=[4096, 4096], weighting='natural', robust=0.0, niter=50000, pbcor=True, minpb=0.7, interpolation='linear', usescratch=True, phasecenter='J2000 01h33m50.904 +30d39m35.79', veltype='radio', outframe='LSRK', modelimage=model, mask=mask)
import sys ''' Cleans an MS with a single channel given a mask and a model ''' vis = sys.argv[4] model = sys.argv[5] mask = sys.argv[6] out_root = vis[:-3] clean(vis=vis, imagename=out_root+'.clean', field='M33*', restfreq='1420.40575177MHz', mode='channel', width=1, nchan=1, start=1, cell='1.5arcsec', multiscale=[0, 4, 8, 20, 40], threshold='2.2mJy/beam', imagermode='mosaic', gain=0.5, imsize=[4096, 4096], weighting='natural', robust=0.0, niter=50000, pbcor=True, minpb=0.7, interpolation='linear', usescratch=True, phasecenter='J2000 01h33m50.904 +30d39m35.79', veltype='radio', outframe='LSRK', modelimage=model, mask=mask)
Remove the largest scale; causes severe artifacts in some channels
Remove the largest scale; causes severe artifacts in some channels
Python
mit
e-koch/canfar_scripts,e-koch/canfar_scripts
--- +++ @@ -14,7 +14,7 @@ clean(vis=vis, imagename=out_root+'.clean', field='M33*', restfreq='1420.40575177MHz', mode='channel', width=1, nchan=1, start=1, - cell='1.5arcsec', multiscale=[0, 4, 8, 20, 40, 80], + cell='1.5arcsec', multiscale=[0, 4, 8, 20, 40], threshold='2.2mJy/beam', imagermode='mosaic', gain=0.5, imsize=[4096, 4096], weighting='natural', robust=0.0, niter=50000, pbcor=True, minpb=0.7, interpolation='linear', usescratch=True,
83fdd99aead08614a12b4eb48f6075599ca60cbe
examples/mayavi/standalone_mlab.py
examples/mayavi/standalone_mlab.py
#!/usr/bin/env python """A simple example of how you can use MayaVi and mlab without using Envisage or the MayaVi envisage application. """ # Author: Gael Varoquaux <gael.varoquaux@normalesup.org> # Copyright (c) 2007, Enthought, Inc. # License: BSD Style. # Mlab imports from enthought.mayavi import mlab from numpy import mgrid, sin, sqrt # Display the MayaVi tree view UI. ui = mlab.show_engine() # Create some data X, Y = mgrid[-1:1:100j, -1:1:100j] R = 10*sqrt(X**2 + Y**2) Z = sin(R)/R # Plot it. mlab.surf(X, Y, Z, colormap='gist_earth') mlab.show()
#!/usr/bin/env python """A simple example of how you can use MayaVi and mlab without using Envisage or the MayaVi envisage application. """ # Author: Gael Varoquaux <gael.varoquaux@normalesup.org> # Copyright (c) 2007, Enthought, Inc. # License: BSD Style. # Mlab imports from enthought.mayavi import mlab from numpy import mgrid, sin, sqrt # Display the MayaVi tree view UI. ui = mlab.show_pipeline() # Create some data X, Y = mgrid[-1:1:100j, -1:1:100j] R = 10*sqrt(X**2 + Y**2) Z = sin(R)/R # Plot it. mlab.surf(X, Y, Z, colormap='gist_earth') mlab.show()
Replace depreciated show_engine to show_pipeline, in examples.
Replace depreciated show_engine to show_pipeline, in examples.
Python
bsd-3-clause
liulion/mayavi,dmsurti/mayavi,alexandreleroux/mayavi,dmsurti/mayavi,liulion/mayavi,alexandreleroux/mayavi
--- +++ @@ -13,7 +13,7 @@ from numpy import mgrid, sin, sqrt # Display the MayaVi tree view UI. -ui = mlab.show_engine() +ui = mlab.show_pipeline() # Create some data X, Y = mgrid[-1:1:100j, -1:1:100j]
8373c005cbf8ebc4069faf5291bb126db2cbb20f
polygraph/types/tests/test_scalars.py
polygraph/types/tests/test_scalars.py
from unittest import TestCase from polygraph.types.scalar import Int class IntTest(TestCase): def test_class_types(self): x = Int(245) self.assertIsInstance(x, int) self.assertIsInstance(x, Int) self.assertEqual(Int(245) + 55, 300) y = Int("506") self.assertIsInstance(y, int) self.assertIsInstance(y, Int) self.assertEqual(y, 506)
from unittest import TestCase from polygraph.types.scalar import Boolean, Float, Int, String class IntTest(TestCase): def test_class_types(self): x = Int(245) self.assertIsInstance(x, int) self.assertIsInstance(x, Int) self.assertEqual(Int(245) + 55, 300) y = Int("506") self.assertIsInstance(y, int) self.assertIsInstance(y, Int) self.assertEqual(y, 506) class StringTest(TestCase): def test_class_types(self): x = String("What is this?") self.assertIsInstance(x, str) self.assertIsInstance(x, String) self.assertEqual(x, "What is this?") class FloatTest(TestCase): def test_class_types(self): x = Float(2.84) self.assertIsInstance(x, float) self.assertIsInstance(x, Float) self.assertEqual(x + 1, 3.84) class BooleanTest(TestCase): def test_class_types(self): self.assertTrue(Boolean(True)) self.assertFalse(Boolean(False)) self.assertEqual(Boolean(True)._type.name, "Boolean")
Add additional tests around scalars
Add additional tests around scalars
Python
mit
polygraph-python/polygraph
--- +++ @@ -1,5 +1,6 @@ from unittest import TestCase -from polygraph.types.scalar import Int + +from polygraph.types.scalar import Boolean, Float, Int, String class IntTest(TestCase): @@ -13,3 +14,26 @@ self.assertIsInstance(y, int) self.assertIsInstance(y, Int) self.assertEqual(y, 506) + + +class StringTest(TestCase): + def test_class_types(self): + x = String("What is this?") + self.assertIsInstance(x, str) + self.assertIsInstance(x, String) + self.assertEqual(x, "What is this?") + + +class FloatTest(TestCase): + def test_class_types(self): + x = Float(2.84) + self.assertIsInstance(x, float) + self.assertIsInstance(x, Float) + self.assertEqual(x + 1, 3.84) + + +class BooleanTest(TestCase): + def test_class_types(self): + self.assertTrue(Boolean(True)) + self.assertFalse(Boolean(False)) + self.assertEqual(Boolean(True)._type.name, "Boolean")
e1ffdcc5f12be623633e2abab2041fcb574173ea
homeassistant/components/zeroconf.py
homeassistant/components/zeroconf.py
""" This module exposes Home Assistant via Zeroconf. Zeroconf is also known as Bonjour, Avahi or Multicast DNS (mDNS). For more details about Zeroconf, please refer to the documentation at https://home-assistant.io/components/zeroconf/ """ import logging import socket from homeassistant.const import (EVENT_HOMEASSISTANT_STOP, __version__) REQUIREMENTS = ["zeroconf==0.17.5"] _LOGGER = logging.getLogger(__name__) DOMAIN = "zeroconf" ZEROCONF_TYPE = "_home-assistant._tcp.local." DEPENDENCIES = ["http"] def setup(hass, config): """Set up Zeroconf and make Home Assistant discoverable.""" from zeroconf import Zeroconf, ServiceInfo zeroconf = Zeroconf() zeroconf_name = "{}.{}".format(hass.config.location_name, ZEROCONF_TYPE) params = {"version": __version__, "base_url": hass.http.base_url, "needs_auth": (hass.http.api_password != "")} info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name, socket.inet_aton(hass.http.routable_address), hass.http.server_address[1], 0, 0, params) zeroconf.register_service(info) def stop_zeroconf(event): """Stop Zeroconf.""" zeroconf.unregister_service(info) hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf) return True
""" This module exposes Home Assistant via Zeroconf. Zeroconf is also known as Bonjour, Avahi or Multicast DNS (mDNS). For more details about Zeroconf, please refer to the documentation at https://home-assistant.io/components/zeroconf/ """ import logging import socket from homeassistant.const import (EVENT_HOMEASSISTANT_STOP, __version__) REQUIREMENTS = ["zeroconf==0.17.5"] DEPENDENCIES = ["api"] _LOGGER = logging.getLogger(__name__) DOMAIN = "zeroconf" ZEROCONF_TYPE = "_home-assistant._tcp.local." def setup(hass, config): """Set up Zeroconf and make Home Assistant discoverable.""" from zeroconf import Zeroconf, ServiceInfo zeroconf = Zeroconf() zeroconf_name = "{}.{}".format(hass.config.location_name, ZEROCONF_TYPE) params = {"version": __version__, "base_url": hass.config.api.base_url, "needs_auth": (hass.config.api.api_password != "")} info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name, socket.inet_aton(hass.config.api.host), hass.config.api.port, 0, 0, params) zeroconf.register_service(info) def stop_zeroconf(event): """Stop Zeroconf.""" zeroconf.unregister_service(info) hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf) return True
Use hass.config.api instead of hass.http
Use hass.config.api instead of hass.http
Python
mit
miniconfig/home-assistant,Julian/home-assistant,toddeye/home-assistant,ct-23/home-assistant,deisi/home-assistant,tchellomello/home-assistant,rohitranjan1991/home-assistant,Julian/home-assistant,Duoxilian/home-assistant,betrisey/home-assistant,keerts/home-assistant,ct-23/home-assistant,tboyce021/home-assistant,kyvinh/home-assistant,leoc/home-assistant,jawilson/home-assistant,JshWright/home-assistant,turbokongen/home-assistant,varunr047/homefile,open-homeautomation/home-assistant,betrisey/home-assistant,GenericStudent/home-assistant,alexmogavero/home-assistant,fbradyirl/home-assistant,eagleamon/home-assistant,kyvinh/home-assistant,toddeye/home-assistant,auduny/home-assistant,aronsky/home-assistant,hmronline/home-assistant,bdfoster/blumate,jaharkes/home-assistant,fbradyirl/home-assistant,srcLurker/home-assistant,morphis/home-assistant,deisi/home-assistant,LinuxChristian/home-assistant,hexxter/home-assistant,sdague/home-assistant,LinuxChristian/home-assistant,shaftoe/home-assistant,stefan-jonasson/home-assistant,adrienbrault/home-assistant,w1ll1am23/home-assistant,tinloaf/home-assistant,soldag/home-assistant,molobrakos/home-assistant,Zyell/home-assistant,HydrelioxGitHub/home-assistant,keerts/home-assistant,molobrakos/home-assistant,varunr047/homefile,jaharkes/home-assistant,xifle/home-assistant,Smart-Torvy/torvy-home-assistant,stefan-jonasson/home-assistant,tboyce1/home-assistant,kennedyshead/home-assistant,sffjunkie/home-assistant,kennedyshead/home-assistant,jnewland/home-assistant,tinloaf/home-assistant,dmeulen/home-assistant,xifle/home-assistant,mikaelboman/home-assistant,Zac-HD/home-assistant,hmronline/home-assistant,partofthething/home-assistant,robjohnson189/home-assistant,lukas-hetzenecker/home-assistant,nugget/home-assistant,aequitas/home-assistant,oandrew/home-assistant,morphis/home-assistant,eagleamon/home-assistant,HydrelioxGitHub/home-assistant,Teagan42/home-assistant,ct-23/home-assistant,Zyell/home-assistant,sffjunkie/home-assistant,tinloaf/home-assistant,philipbl/home-assistant,kyvinh/home-assistant,Julian/home-assistant,PetePriority/home-assistant,sffjunkie/home-assistant,bdfoster/blumate,Teagan42/home-assistant,rohitranjan1991/home-assistant,deisi/home-assistant,miniconfig/home-assistant,robjohnson189/home-assistant,happyleavesaoc/home-assistant,morphis/home-assistant,GenericStudent/home-assistant,soldag/home-assistant,deisi/home-assistant,Duoxilian/home-assistant,persandstrom/home-assistant,w1ll1am23/home-assistant,oandrew/home-assistant,mezz64/home-assistant,DavidLP/home-assistant,morphis/home-assistant,tboyce1/home-assistant,florianholzapfel/home-assistant,Danielhiversen/home-assistant,home-assistant/home-assistant,florianholzapfel/home-assistant,srcLurker/home-assistant,stefan-jonasson/home-assistant,Smart-Torvy/torvy-home-assistant,sdague/home-assistant,kyvinh/home-assistant,balloob/home-assistant,happyleavesaoc/home-assistant,MartinHjelmare/home-assistant,happyleavesaoc/home-assistant,adrienbrault/home-assistant,ewandor/home-assistant,nugget/home-assistant,xifle/home-assistant,MungoRae/home-assistant,robbiet480/home-assistant,MartinHjelmare/home-assistant,alexmogavero/home-assistant,leppa/home-assistant,open-homeautomation/home-assistant,leoc/home-assistant,LinuxChristian/home-assistant,leoc/home-assistant,MartinHjelmare/home-assistant,Julian/home-assistant,miniconfig/home-assistant,lukas-hetzenecker/home-assistant,mikaelboman/home-assistant,joopert/home-assistant,Zac-HD/home-assistant,auduny/home-assistant,Zac-HD/home-assistant,joopert/home-assistant,ma314smith/home-assistant,Zyell/home-assistant,devdelay/home-assistant,srcLurker/home-assistant,hexxter/home-assistant,HydrelioxGitHub/home-assistant,mikaelboman/home-assistant,aequitas/home-assistant,qedi-r/home-assistant,nkgilley/home-assistant,jnewland/home-assistant,deisi/home-assistant,leoc/home-assistant,jaharkes/home-assistant,varunr047/homefile,nugget/home-assistant,hexxter/home-assistant,sander76/home-assistant,fbradyirl/home-assistant,partofthething/home-assistant,jamespcole/home-assistant,persandstrom/home-assistant,jnewland/home-assistant,balloob/home-assistant,leppa/home-assistant,bdfoster/blumate,keerts/home-assistant,shaftoe/home-assistant,pschmitt/home-assistant,philipbl/home-assistant,tboyce1/home-assistant,betrisey/home-assistant,hmronline/home-assistant,sander76/home-assistant,xifle/home-assistant,JshWright/home-assistant,oandrew/home-assistant,PetePriority/home-assistant,varunr047/homefile,dmeulen/home-assistant,tboyce021/home-assistant,alexmogavero/home-assistant,DavidLP/home-assistant,persandstrom/home-assistant,LinuxChristian/home-assistant,philipbl/home-assistant,JshWright/home-assistant,FreekingDean/home-assistant,robbiet480/home-assistant,jabesq/home-assistant,ct-23/home-assistant,hmronline/home-assistant,ma314smith/home-assistant,Smart-Torvy/torvy-home-assistant,JshWright/home-assistant,home-assistant/home-assistant,shaftoe/home-assistant,devdelay/home-assistant,emilhetty/home-assistant,emilhetty/home-assistant,Smart-Torvy/torvy-home-assistant,mKeRix/home-assistant,mKeRix/home-assistant,Danielhiversen/home-assistant,stefan-jonasson/home-assistant,bdfoster/blumate,sffjunkie/home-assistant,bdfoster/blumate,jawilson/home-assistant,florianholzapfel/home-assistant,MungoRae/home-assistant,jaharkes/home-assistant,Cinntax/home-assistant,aronsky/home-assistant,auduny/home-assistant,robjohnson189/home-assistant,florianholzapfel/home-assistant,emilhetty/home-assistant,devdelay/home-assistant,sffjunkie/home-assistant,MungoRae/home-assistant,mikaelboman/home-assistant,Duoxilian/home-assistant,Duoxilian/home-assistant,dmeulen/home-assistant,betrisey/home-assistant,ma314smith/home-assistant,open-homeautomation/home-assistant,DavidLP/home-assistant,robjohnson189/home-assistant,dmeulen/home-assistant,mikaelboman/home-assistant,jamespcole/home-assistant,philipbl/home-assistant,jabesq/home-assistant,emilhetty/home-assistant,oandrew/home-assistant,rohitranjan1991/home-assistant,MungoRae/home-assistant,mKeRix/home-assistant,shaftoe/home-assistant,titilambert/home-assistant,MungoRae/home-assistant,varunr047/homefile,balloob/home-assistant,molobrakos/home-assistant,postlund/home-assistant,happyleavesaoc/home-assistant,mezz64/home-assistant,Zac-HD/home-assistant,ct-23/home-assistant,open-homeautomation/home-assistant,ma314smith/home-assistant,FreekingDean/home-assistant,mKeRix/home-assistant,qedi-r/home-assistant,miniconfig/home-assistant,ewandor/home-assistant,srcLurker/home-assistant,ewandor/home-assistant,PetePriority/home-assistant,postlund/home-assistant,jabesq/home-assistant,alexmogavero/home-assistant,aequitas/home-assistant,devdelay/home-assistant,hexxter/home-assistant,Cinntax/home-assistant,titilambert/home-assistant,emilhetty/home-assistant,tchellomello/home-assistant,keerts/home-assistant,LinuxChristian/home-assistant,eagleamon/home-assistant,nkgilley/home-assistant,hmronline/home-assistant,jamespcole/home-assistant,pschmitt/home-assistant,tboyce1/home-assistant,eagleamon/home-assistant,turbokongen/home-assistant
--- +++ @@ -13,13 +13,13 @@ REQUIREMENTS = ["zeroconf==0.17.5"] +DEPENDENCIES = ["api"] + _LOGGER = logging.getLogger(__name__) DOMAIN = "zeroconf" ZEROCONF_TYPE = "_home-assistant._tcp.local." - -DEPENDENCIES = ["http"] def setup(hass, config): @@ -31,12 +31,12 @@ zeroconf_name = "{}.{}".format(hass.config.location_name, ZEROCONF_TYPE) - params = {"version": __version__, "base_url": hass.http.base_url, - "needs_auth": (hass.http.api_password != "")} + params = {"version": __version__, "base_url": hass.config.api.base_url, + "needs_auth": (hass.config.api.api_password != "")} info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name, - socket.inet_aton(hass.http.routable_address), - hass.http.server_address[1], 0, 0, params) + socket.inet_aton(hass.config.api.host), + hass.config.api.port, 0, 0, params) zeroconf.register_service(info)
c24fa91c900fc4f0d3ac5a10d10bfe5c57c9ef5c
errors.py
errors.py
class ParserError(Exception): """Raised when parsing input fails.""" class OpenParenError(ParserError): """Raised when there are too few opening parenthesis.""" @staticmethod def build(): return OpenParenError("too few opening parenthesis") class CloseParenError(ParserError): """Raised when there are too few closing parenthesis.""" @staticmethod def build(): return CloseParenError("too few closing parenthesis") class SymbolNotFoundError(Exception): """Raised when a symbol could not be found in an environment chain.""" @staticmethod def build(symbol): return SymbolNotFoundError("could not find symbol " + str(symbol)) class IncorrectArgumentCountError(Exception): """Raised when a function is called with the wrong number of arguments.""" @staticmethod def build(expected, actual): return IncorrectArgumentCountError("expected " + str(expected) + ", got " + str(actual)) class WrongArgumentTypeError(Exception): """Raised when an argument is of the wrong type.""" @staticmethod def build(arg, expected_class): return WrongArgumentTypeError("wrong argument type for " + str(arg) + ": expected " + expected_class.__name__.lower() + ", got " + arg.__class__.__name__.lower()) class ApplicationError(Exception): """Raised when a function could not be applied correctly."""
class ParserError(Exception): """Raised when parsing input fails.""" class OpenParenError(ParserError): """Raised when there are too few opening parenthesis.""" @staticmethod def build(): return OpenParenError("too few opening parenthesis") class CloseParenError(ParserError): """Raised when there are too few closing parenthesis.""" @staticmethod def build(): return CloseParenError("too few closing parenthesis") class SymbolNotFoundError(Exception): """Raised when a symbol could not be found in an environment chain.""" @staticmethod def build(symbol): return SymbolNotFoundError("could not find symbol " + str(symbol)) class IncorrectArgumentCountError(Exception): """Raised when a function is called with the wrong number of arguments.""" @staticmethod def build(expected, actual): return IncorrectArgumentCountError("expected " + str(expected) + ", got " + str(actual)) class WrongArgumentTypeError(Exception): """Raised when an argument is of the wrong type.""" @staticmethod def build(arg, expected_class): expected = "" if hasattr(expected_class, "__name__"): expected = expected_class.__name__ + "," else: # support multiple expected classes expected = "one of " expected += ", ".join(map(lambda x: x.__name__, expected_class)) expected += ";" return WrongArgumentTypeError("wrong argument type for " + str(arg) + ": expected " + expected.lower() + " got " + arg.__class__.__name__.lower()) class ApplicationError(Exception): """Raised when a function could not be applied correctly."""
Support class tuples as WATE args
Support class tuples as WATE args
Python
mit
jasontbradshaw/plinth
--- +++ @@ -36,8 +36,17 @@ @staticmethod def build(arg, expected_class): + expected = "" + if hasattr(expected_class, "__name__"): + expected = expected_class.__name__ + "," + else: + # support multiple expected classes + expected = "one of " + expected += ", ".join(map(lambda x: x.__name__, expected_class)) + expected += ";" + return WrongArgumentTypeError("wrong argument type for " + str(arg) + - ": expected " + expected_class.__name__.lower() + ", got " + + ": expected " + expected.lower() + " got " + arg.__class__.__name__.lower()) class ApplicationError(Exception):
9af440d8d7d2dc7b6ecf254ee1150f03d090cb6a
numpy/linalg/setup.py
numpy/linalg/setup.py
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info config = Configuration('linalg',parent_package,top_path) config.add_data_dir('tests') # Configure lapack_lite lapack_info = get_info('lapack_opt',0) # and {} def get_lapack_lite_sources(ext, build_dir): if not lapack_info: print "### Warning: Using unoptimized lapack ###" return ext.depends[:-1] else: return ext.depends[:2] config.add_extension('lapack_lite', sources = [get_lapack_lite_sources], depends= ['lapack_litemodule.c', 'pythonxerbla.c', 'zlapack_lite.c', 'dlapack_lite.c', 'blas_lite.c', 'dlamch.c', 'f2c_lite.c','f2c.h'], extra_info = lapack_info ) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration)
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info config = Configuration('linalg',parent_package,top_path) config.add_data_dir('tests') # Configure lapack_lite lapack_info = get_info('lapack_opt',0) # and {} def get_lapack_lite_sources(ext, build_dir): if not lapack_info: print "### Warning: Using unoptimized lapack ###" return ext.depends[:-1] else: if sys.platform=='win32': print "### Warning: pythonxerbla.c is disabled ###" return ext.depends[:1] return ext.depends[:2] config.add_extension('lapack_lite', sources = [get_lapack_lite_sources], depends= ['lapack_litemodule.c', 'pythonxerbla.c', 'zlapack_lite.c', 'dlapack_lite.c', 'blas_lite.c', 'dlamch.c', 'f2c_lite.c','f2c.h'], extra_info = lapack_info ) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration)
Disable pythonxerbla.c patch for win32 (the MSVC linker failes on multiple defined symbols) when using optimized lapack.
Disable pythonxerbla.c patch for win32 (the MSVC linker failes on multiple defined symbols) when using optimized lapack.
Python
bsd-3-clause
jschueller/numpy,CMartelLML/numpy,cowlicks/numpy,larsmans/numpy,rudimeier/numpy,bertrand-l/numpy,ViralLeadership/numpy,sonnyhu/numpy,mattip/numpy,moreati/numpy,ViralLeadership/numpy,pyparallel/numpy,dato-code/numpy,mattip/numpy,nbeaver/numpy,dch312/numpy,ajdawson/numpy,WarrenWeckesser/numpy,leifdenby/numpy,larsmans/numpy,WillieMaddox/numpy,simongibbons/numpy,pyparallel/numpy,immerrr/numpy,Eric89GXL/numpy,ewmoore/numpy,empeeu/numpy,mhvk/numpy,chatcannon/numpy,WarrenWeckesser/numpy,jakirkham/numpy,numpy/numpy-refactor,cowlicks/numpy,seberg/numpy,jschueller/numpy,jakirkham/numpy,kiwifb/numpy,hainm/numpy,MichaelAquilina/numpy,naritta/numpy,seberg/numpy,stefanv/numpy,dwf/numpy,mwiebe/numpy,pizzathief/numpy,gmcastil/numpy,jorisvandenbossche/numpy,jorisvandenbossche/numpy,bmorris3/numpy,numpy/numpy,anntzer/numpy,stuarteberg/numpy,ewmoore/numpy,BMJHayward/numpy,jankoslavic/numpy,gfyoung/numpy,BMJHayward/numpy,kiwifb/numpy,endolith/numpy,dato-code/numpy,grlee77/numpy,solarjoe/numpy,shoyer/numpy,cjermain/numpy,madphysicist/numpy,ssanderson/numpy,MichaelAquilina/numpy,dimasad/numpy,BabeNovelty/numpy,astrofrog/numpy,tynn/numpy,NextThought/pypy-numpy,cjermain/numpy,bmorris3/numpy,anntzer/numpy,ogrisel/numpy,rmcgibbo/numpy,SiccarPoint/numpy,BMJHayward/numpy,moreati/numpy,pbrod/numpy,charris/numpy,tynn/numpy,dwillmer/numpy,Linkid/numpy,dato-code/numpy,b-carter/numpy,GaZ3ll3/numpy,cjermain/numpy,tdsmith/numpy,rmcgibbo/numpy,pelson/numpy,Yusa95/numpy,pelson/numpy,ekalosak/numpy,kirillzhuravlev/numpy,jonathanunderwood/numpy,ahaldane/numpy,jschueller/numpy,andsor/numpy,rgommers/numpy,SiccarPoint/numpy,ssanderson/numpy,tacaswell/numpy,nguyentu1602/numpy,rajathkumarmp/numpy,felipebetancur/numpy,immerrr/numpy,rajathkumarmp/numpy,mattip/numpy,mortada/numpy,pizzathief/numpy,pdebuyl/numpy,ESSS/numpy,MSeifert04/numpy,njase/numpy,rgommers/numpy,ewmoore/numpy,argriffing/numpy,mortada/numpy,trankmichael/numpy,ajdawson/numpy,bringingheavendown/numpy,gfyoung/numpy,skymanaditya1/numpy,charris/numpy,nbeaver/numpy,empeeu/numpy,jakirkham/numpy,ChanderG/numpy,SunghanKim/numpy,KaelChen/numpy,empeeu/numpy,endolith/numpy,AustereCuriosity/numpy,rudimeier/numpy,jorisvandenbossche/numpy,MSeifert04/numpy,ajdawson/numpy,solarjoe/numpy,SiccarPoint/numpy,pizzathief/numpy,astrofrog/numpy,ChanderG/numpy,BabeNovelty/numpy,rmcgibbo/numpy,dwillmer/numpy,mortada/numpy,mathdd/numpy,argriffing/numpy,yiakwy/numpy,rudimeier/numpy,sinhrks/numpy,KaelChen/numpy,dwf/numpy,ContinuumIO/numpy,WarrenWeckesser/numpy,Eric89GXL/numpy,BabeNovelty/numpy,dimasad/numpy,drasmuss/numpy,sigma-random/numpy,ahaldane/numpy,utke1/numpy,has2k1/numpy,jorisvandenbossche/numpy,kiwifb/numpy,argriffing/numpy,pelson/numpy,ddasilva/numpy,mingwpy/numpy,solarjoe/numpy,musically-ut/numpy,rherault-insa/numpy,mortada/numpy,njase/numpy,groutr/numpy,Srisai85/numpy,Anwesh43/numpy,pizzathief/numpy,jankoslavic/numpy,ESSS/numpy,gfyoung/numpy,b-carter/numpy,sigma-random/numpy,MSeifert04/numpy,has2k1/numpy,pyparallel/numpy,felipebetancur/numpy,dwillmer/numpy,pizzathief/numpy,maniteja123/numpy,sigma-random/numpy,leifdenby/numpy,SunghanKim/numpy,KaelChen/numpy,rherault-insa/numpy,ChanderG/numpy,rajathkumarmp/numpy,dwf/numpy,hainm/numpy,githubmlai/numpy,numpy/numpy,MSeifert04/numpy,sigma-random/numpy,embray/numpy,rhythmsosad/numpy,ChristopherHogan/numpy,jorisvandenbossche/numpy,naritta/numpy,sinhrks/numpy,chatcannon/numpy,grlee77/numpy,brandon-rhodes/numpy,trankmichael/numpy,Yusa95/numpy,numpy/numpy-refactor,Linkid/numpy,ChristopherHogan/numpy,mwiebe/numpy,behzadnouri/numpy,matthew-brett/numpy,nguyentu1602/numpy,pbrod/numpy,NextThought/pypy-numpy,bertrand-l/numpy,GaZ3ll3/numpy,brandon-rhodes/numpy,jakirkham/numpy,ekalosak/numpy,WillieMaddox/numpy,chiffa/numpy,CMartelLML/numpy,WarrenWeckesser/numpy,dimasad/numpy,GrimDerp/numpy,nguyentu1602/numpy,grlee77/numpy,stefanv/numpy,simongibbons/numpy,astrofrog/numpy,madphysicist/numpy,trankmichael/numpy,skymanaditya1/numpy,brandon-rhodes/numpy,mathdd/numpy,Dapid/numpy,cjermain/numpy,musically-ut/numpy,has2k1/numpy,musically-ut/numpy,joferkington/numpy,matthew-brett/numpy,rgommers/numpy,stuarteberg/numpy,anntzer/numpy,cowlicks/numpy,grlee77/numpy,andsor/numpy,CMartelLML/numpy,mingwpy/numpy,madphysicist/numpy,matthew-brett/numpy,GrimDerp/numpy,BMJHayward/numpy,embray/numpy,seberg/numpy,groutr/numpy,ESSS/numpy,has2k1/numpy,ekalosak/numpy,dato-code/numpy,ahaldane/numpy,stefanv/numpy,shoyer/numpy,charris/numpy,rherault-insa/numpy,njase/numpy,sonnyhu/numpy,ChristopherHogan/numpy,numpy/numpy-refactor,dch312/numpy,simongibbons/numpy,simongibbons/numpy,stuarteberg/numpy,felipebetancur/numpy,drasmuss/numpy,bmorris3/numpy,mindw/numpy,MaPePeR/numpy,maniteja123/numpy,dch312/numpy,Anwesh43/numpy,dwf/numpy,rhythmsosad/numpy,ajdawson/numpy,MaPePeR/numpy,mingwpy/numpy,githubmlai/numpy,jankoslavic/numpy,matthew-brett/numpy,ahaldane/numpy,mingwpy/numpy,bringingheavendown/numpy,pbrod/numpy,mathdd/numpy,bringingheavendown/numpy,Dapid/numpy,Srisai85/numpy,SunghanKim/numpy,hainm/numpy,dimasad/numpy,moreati/numpy,Anwesh43/numpy,ogrisel/numpy,mattip/numpy,stuarteberg/numpy,ogrisel/numpy,ddasilva/numpy,jonathanunderwood/numpy,WillieMaddox/numpy,ChristopherHogan/numpy,githubmlai/numpy,pbrod/numpy,yiakwy/numpy,anntzer/numpy,trankmichael/numpy,ViralLeadership/numpy,bertrand-l/numpy,madphysicist/numpy,ogrisel/numpy,immerrr/numpy,jschueller/numpy,GaZ3ll3/numpy,larsmans/numpy,pbrod/numpy,mhvk/numpy,naritta/numpy,naritta/numpy,mindw/numpy,dwillmer/numpy,yiakwy/numpy,embray/numpy,ahaldane/numpy,Anwesh43/numpy,NextThought/pypy-numpy,Srisai85/numpy,NextThought/pypy-numpy,rmcgibbo/numpy,CMartelLML/numpy,mhvk/numpy,mwiebe/numpy,madphysicist/numpy,MichaelAquilina/numpy,kirillzhuravlev/numpy,kirillzhuravlev/numpy,rhythmsosad/numpy,GaZ3ll3/numpy,rajathkumarmp/numpy,andsor/numpy,Srisai85/numpy,jonathanunderwood/numpy,skwbc/numpy,felipebetancur/numpy,bmorris3/numpy,ewmoore/numpy,chatcannon/numpy,groutr/numpy,ekalosak/numpy,mindw/numpy,stefanv/numpy,GrimDerp/numpy,chiffa/numpy,KaelChen/numpy,pelson/numpy,SunghanKim/numpy,tdsmith/numpy,sonnyhu/numpy,MSeifert04/numpy,pdebuyl/numpy,ContinuumIO/numpy,musically-ut/numpy,embray/numpy,astrofrog/numpy,charris/numpy,gmcastil/numpy,tacaswell/numpy,rgommers/numpy,Yusa95/numpy,leifdenby/numpy,numpy/numpy,dch312/numpy,rudimeier/numpy,abalkin/numpy,Yusa95/numpy,sonnyhu/numpy,ddasilva/numpy,matthew-brett/numpy,jakirkham/numpy,tdsmith/numpy,numpy/numpy-refactor,larsmans/numpy,MaPePeR/numpy,joferkington/numpy,AustereCuriosity/numpy,abalkin/numpy,Eric89GXL/numpy,hainm/numpy,nguyentu1602/numpy,tacaswell/numpy,joferkington/numpy,tynn/numpy,numpy/numpy,ssanderson/numpy,behzadnouri/numpy,shoyer/numpy,ContinuumIO/numpy,WarrenWeckesser/numpy,kirillzhuravlev/numpy,SiccarPoint/numpy,ogrisel/numpy,endolith/numpy,empeeu/numpy,MaPePeR/numpy,githubmlai/numpy,shoyer/numpy,Linkid/numpy,mhvk/numpy,jankoslavic/numpy,rhythmsosad/numpy,dwf/numpy,gmcastil/numpy,mindw/numpy,mhvk/numpy,skymanaditya1/numpy,ChanderG/numpy,joferkington/numpy,stefanv/numpy,skwbc/numpy,brandon-rhodes/numpy,numpy/numpy-refactor,embray/numpy,sinhrks/numpy,skymanaditya1/numpy,astrofrog/numpy,BabeNovelty/numpy,endolith/numpy,behzadnouri/numpy,tdsmith/numpy,Dapid/numpy,abalkin/numpy,yiakwy/numpy,seberg/numpy,pelson/numpy,Eric89GXL/numpy,simongibbons/numpy,nbeaver/numpy,shoyer/numpy,pdebuyl/numpy,pdebuyl/numpy,cowlicks/numpy,GrimDerp/numpy,andsor/numpy,drasmuss/numpy,Linkid/numpy,b-carter/numpy,utke1/numpy,grlee77/numpy,MichaelAquilina/numpy,sinhrks/numpy,maniteja123/numpy,mathdd/numpy,immerrr/numpy,ewmoore/numpy,skwbc/numpy,AustereCuriosity/numpy,chiffa/numpy,utke1/numpy
--- +++ @@ -13,6 +13,9 @@ print "### Warning: Using unoptimized lapack ###" return ext.depends[:-1] else: + if sys.platform=='win32': + print "### Warning: pythonxerbla.c is disabled ###" + return ext.depends[:1] return ext.depends[:2] config.add_extension('lapack_lite',
a0b52b5a9b825e1a17d9c92694ac944f09411011
db/database.py
db/database.py
import json import pymongo import praw from pymongo import MongoClient client = MongoClient() db = client.reddit posts = db.data posts.create_index([("text", pymongo.TEXT), ("subreddit", pymongo.ASCENDING), ("created_utc", pymongo.DESCENDING)]); print "Configuring database" def save(obj): toInsert = {} toInsert["id"] = obj.id toInsert["created_utc"] = obj.created_utc toInsert["subreddit"] = str(obj.subreddit) if type(obj) is praw.objects.Submission: toInsert["text"] = obj.title print "Saving a thread" else: toInsert["text"] = obj.body print "Saving a comment" posts.insert_one(toInsert) def get(obj): subreddit = obj["subreddit"] from_time = int(obj["from_time"]) to_time = int(obj["to_time"]) keyword = obj["keyword"] query = {"subreddit": subreddit, "created_utc": {"$gte": from_time, "$lte": to_time}}; if not keyword is None: query["$text"] = {"$search": keyword} return posts.find(query)
import json import pymongo import praw from pymongo import MongoClient client = MongoClient("mongo") db = client.reddit posts = db.data posts.create_index([("text", pymongo.TEXT), ("subreddit", pymongo.ASCENDING), ("created_utc", pymongo.DESCENDING)]); print "Configuring database" def save(obj): toInsert = {} toInsert["id"] = obj.id toInsert["created_utc"] = obj.created_utc toInsert["subreddit"] = str(obj.subreddit) if type(obj) is praw.objects.Submission: toInsert["text"] = obj.title print "Saving a thread" else: toInsert["text"] = obj.body print "Saving a comment" posts.insert_one(toInsert) def get(obj): subreddit = obj["subreddit"] from_time = int(obj["from_time"]) to_time = int(obj["to_time"]) keyword = obj["keyword"] query = {"subreddit": subreddit, "created_utc": {"$gte": from_time, "$lte": to_time}}; if not keyword is None: query["$text"] = {"$search": keyword} return posts.find(query)
Update db host to mongo
db: Update db host to mongo
Python
unlicense
vilie/rp,vilie/rp
--- +++ @@ -4,7 +4,7 @@ from pymongo import MongoClient -client = MongoClient() +client = MongoClient("mongo") db = client.reddit posts = db.data posts.create_index([("text", pymongo.TEXT),
3b01b6b67e8cf05c31f2c30a3e45a59ffbb31adb
djangae/fields/computed.py
djangae/fields/computed.py
from django.db import models class ComputedFieldMixin(object): def __init__(self, func, *args, **kwargs): self.computer = func kwargs["editable"] = False super(ComputedFieldMixin, self).__init__(*args, **kwargs) def pre_save(self, model_instance, add): value = self.computer(model_instance) setattr(model_instance, self.attname, value) return value def deconstruct(self): name, path, args, kwargs = super(ComputedFieldMixin, self).deconstruct() args = [self.computer] + args del kwargs["editable"] return name, path, args, kwargs class ComputedCharField(ComputedFieldMixin, models.CharField): pass class ComputedIntegerField(ComputedFieldMixin, models.IntegerField): pass class ComputedTextField(ComputedFieldMixin, models.TextField): pass class ComputedPositiveIntegerField(ComputedFieldMixin, models.PositiveIntegerField): pass
from django.db import models class ComputedFieldMixin(object): def __init__(self, func, *args, **kwargs): self.computer = func kwargs["editable"] = False super(ComputedFieldMixin, self).__init__(*args, **kwargs) def pre_save(self, model_instance, add): value = self.computer(model_instance) setattr(model_instance, self.attname, value) return value def deconstruct(self): name, path, args, kwargs = super(ComputedFieldMixin, self).deconstruct() args = [self.computer] + args del kwargs["editable"] return name, path, args, kwargs def from_db_value(self, value, expression, connection, context): return self.to_python(value) class ComputedCharField(ComputedFieldMixin, models.CharField): pass class ComputedIntegerField(ComputedFieldMixin, models.IntegerField): pass class ComputedTextField(ComputedFieldMixin, models.TextField): pass class ComputedPositiveIntegerField(ComputedFieldMixin, models.PositiveIntegerField): pass
Add from_db_value instead of removed SubfieldBase fields
Add from_db_value instead of removed SubfieldBase fields
Python
bsd-3-clause
kirberich/djangae,asendecka/djangae,kirberich/djangae,potatolondon/djangae,kirberich/djangae,potatolondon/djangae,grzes/djangae,asendecka/djangae,grzes/djangae,grzes/djangae,asendecka/djangae
--- +++ @@ -20,6 +20,9 @@ del kwargs["editable"] return name, path, args, kwargs + def from_db_value(self, value, expression, connection, context): + return self.to_python(value) + class ComputedCharField(ComputedFieldMixin, models.CharField): pass
fc105f413e6683980c5d2fcc93a471ebbc9fecba
utils/files_provider.py
utils/files_provider.py
from string import Template __author__ = 'maa' templates_folder = 'file_templates_folder\\' def create_and_full_fill_file(template_file_name, destination_file_path, file_name, kwargs): template_file = open(templates_folder + template_file_name, 'r') file_content = template_file.read() template_file.close() template = Template(file_content) final_content = template.substitute(kwargs) final_file = open(destination_file_path + '\\' + file_name, 'w') final_file.write(final_content) final_file.close()
from string import Template __author__ = 'maa' templates_folder = 'file_templates_folder\\' def create_and_full_fill_file(template_file_name, destination_file_path, kwargs): template_file = open(template_file_name, 'r') file_content = template_file.read() template_file.close() template = Template(file_content) final_content = template.substitute(kwargs) final_file = open(destination_file_path, 'w') final_file.write(final_content) final_file.close()
Change method params because they are not necessary.
[dev] Change method params because they are not necessary.
Python
apache-2.0
amatkivskiy/baidu,amatkivskiy/baidu
--- +++ @@ -5,8 +5,8 @@ templates_folder = 'file_templates_folder\\' -def create_and_full_fill_file(template_file_name, destination_file_path, file_name, kwargs): - template_file = open(templates_folder + template_file_name, 'r') +def create_and_full_fill_file(template_file_name, destination_file_path, kwargs): + template_file = open(template_file_name, 'r') file_content = template_file.read() template_file.close() @@ -14,6 +14,6 @@ final_content = template.substitute(kwargs) - final_file = open(destination_file_path + '\\' + file_name, 'w') + final_file = open(destination_file_path, 'w') final_file.write(final_content) final_file.close()
f8d3b5d4c1d3d81dee1c22a4e2563e6b8d116c74
openquake/__init__.py
openquake/__init__.py
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2010-2016 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # OpenQuake 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. __import__('pkg_resources').declare_namespace(__name__)
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2010-2016 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # OpenQuake 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. # Make the namespace compatible with old setuptools, like the one # provided by QGIS 2.1x on Windows try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: __path__ = __import__('pkgutil').extend_path(__path__, __name__)
Make the openquake namespace compatible with old setuptools
Make the openquake namespace compatible with old setuptools Former-commit-id: 529c98ec0a7c5a3fefa4da6cdf2f6a58b5487ebc [formerly e5f4dc01e94694bf9bfcae3ecd6eca34a33a24eb] Former-commit-id: e01df405c03f37a89cdf889c45de410cb1ca9b00
Python
agpl-3.0
gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine
--- +++ @@ -16,4 +16,9 @@ # You should have received a copy of the GNU Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. -__import__('pkg_resources').declare_namespace(__name__) +# Make the namespace compatible with old setuptools, like the one +# provided by QGIS 2.1x on Windows +try: + __import__('pkg_resources').declare_namespace(__name__) +except ImportError: + __path__ = __import__('pkgutil').extend_path(__path__, __name__)
8e67071e82e13ae4131da773947f767f1fe91f40
Code/Python/Kamaelia/Examples/UDP_Systems/SimplePeer_Example.py
Code/Python/Kamaelia/Examples/UDP_Systems/SimplePeer_Example.py
#!/usr/bin/python """ Simple Kamaelia Example that shows how to use a simple UDP Peer. A UDP Peer actually sends and recieves however, so we could have more fun example here with the two peers sending each other messages. It's worth noting that these aren't "connected" peers in any shape or form, and they're fixed who they're sending to, etc, which is why it's a simple peer. """ from Kamaelia.Util.Console import ConsoleEchoer from Kamaelia.Chassis.Pipeline import Pipeline from Kamaelia.Util.Chargen import Chargen from Kamaelia.Internet.UDP import SimplePeer server_addr = "127.0.0.1" server_port = 1600 Pipeline( Chargen(), SimplePeer(receiver_addr=server_addr, receiver_port=server_port), ).activate() Pipeline( SimplePeer(localaddr=server_addr, localport=server_port), ConsoleEchoer() ).run() # RELEASE: MH, MPS
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # 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. """ Simple Kamaelia Example that shows how to use a simple UDP Peer. A UDP Peer actually sends and recieves however, so we could have more fun example here with the two peers sending each other messages. It's worth noting that these aren't "connected" peers in any shape or form, and they're fixed who they're sending to, etc, which is why it's a simple peer. """ from Kamaelia.Util.Console import ConsoleEchoer from Kamaelia.Chassis.Pipeline import Pipeline from Kamaelia.Util.Chargen import Chargen from Kamaelia.Internet.UDP import SimplePeer server_addr = "127.0.0.1" server_port = 1600 Pipeline( Chargen(), SimplePeer(receiver_addr=server_addr, receiver_port=server_port), ).activate() Pipeline( SimplePeer(localaddr=server_addr, localport=server_port), ConsoleEchoer() ).run() # RELEASE: MH, MPS
Change license to Apache 2
Change license to Apache 2
Python
apache-2.0
sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia
--- +++ @@ -1,4 +1,22 @@ #!/usr/bin/python +# -*- coding: utf-8 -*- +# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) +# +# (1) Kamaelia Contributors are listed in the AUTHORS file and at +# http://www.kamaelia.org/AUTHORS - please extend this file, +# not this notice. +# +# 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. """ Simple Kamaelia Example that shows how to use a simple UDP Peer. A UDP Peer actually sends and recieves however, so we could have
1c65ef8eeccd433b256ed2cd1d3db7b6264fe8f2
properties/tests/test_mach_angle.py
properties/tests/test_mach_angle.py
#!/usr/bin/env python """Test Mach angle functions. Test data is obtained from http://www.grc.nasa.gov/WWW/k-12/airplane/machang.html. """ import nose import nose.tools as nt from properties.prandtl_meyer_function import mu_in_deg @nt.raises(ValueError) def test_mach_lesser_than_one(): m = 0.1 mu_in_deg(m) def test_normal_mach(): m1 = 1.5 nt.assert_almost_equal(mu_in_deg(m1), 41.762, places=3) m2 = 2.6 nt.assert_almost_equal(mu_in_deg(m2), 22.594, places=3) if __name__ == '__main__': nose.main()
#!/usr/bin/env python """Test Mach angle functions. """ from __future__ import absolute_import, division import nose import nose.tools as nt from properties.prandtl_meyer_function import mu_in_deg @nt.raises(ValueError) def test_mach_lesser_than_one(): m = 0.1 mu_in_deg(m) def test_normal_mach(): m1 = 1.5 nt.assert_almost_equal(mu_in_deg(m1), 41.8103148, places=3) m2 = 2.6 nt.assert_almost_equal(mu_in_deg(m2), 22.6198649, places=3) if __name__ == '__main__': nose.main()
Correct test data for mach angle
Correct test data for mach angle
Python
mit
iwarobots/TunnelDesign
--- +++ @@ -1,10 +1,9 @@ #!/usr/bin/env python """Test Mach angle functions. - -Test data is obtained from http://www.grc.nasa.gov/WWW/k-12/airplane/machang.html. """ +from __future__ import absolute_import, division import nose import nose.tools as nt @@ -20,10 +19,10 @@ def test_normal_mach(): m1 = 1.5 - nt.assert_almost_equal(mu_in_deg(m1), 41.762, places=3) + nt.assert_almost_equal(mu_in_deg(m1), 41.8103148, places=3) m2 = 2.6 - nt.assert_almost_equal(mu_in_deg(m2), 22.594, places=3) + nt.assert_almost_equal(mu_in_deg(m2), 22.6198649, places=3) if __name__ == '__main__':
d028ada7a1d1c7c66cb6e3e76cd5ed676981bc57
lcp/urls.py
lcp/urls.py
"""lcp URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from rest_framework import routers from planner.views import SchoolViewSet router = routers.DefaultRouter() router.register('schools', SchoolViewSet) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls')), ]
"""lcp URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from rest_framework import routers from planner.views import SchoolViewSet router = routers.DefaultRouter() router.register('schools', SchoolViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^admin/', admin.site.urls), url(r'^api-auth/', include('rest_framework.urls')), ]
Move the API to the root.
Move the API to the root.
Python
bsd-2-clause
mblayman/lcp,mblayman/lcp,mblayman/lcp
--- +++ @@ -23,7 +23,7 @@ router.register('schools', SchoolViewSet) urlpatterns = [ + url(r'^', include(router.urls)), url(r'^admin/', admin.site.urls), - url(r'^api/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls')), ]
f5d61059480a2698fc955641819e78cba28173b3
src/adhocracy_core/adhocracy_core/changelog/test_init.py
src/adhocracy_core/adhocracy_core/changelog/test_init.py
from pytest import mark from pytest import fixture from pyramid import testing def test_changelog_create(): from . import Changelog from . import changelog_meta inst = Changelog() assert inst['/path/'] == changelog_meta @fixture() def integration(config): config.include('adhocracy_core.events') config.include('adhocracy_core.changelog') @fixture() def request_(registry): request = testing.DummyResource(registry=registry) return request @mark.usefixtures('integration') def test_includeme_add_changelog(registry): from . import Changelog assert isinstance(registry.changelog, Changelog) @mark.usefixtures('integration') def test_clear_changelog(context, registry, request_, changelog): from . import clear_changelog_callback changelog['/'] = changelog['/']._replace(resource=context) registry.changelog = changelog clear_changelog_callback(request_) assert changelog['/'].resource is None def test_clear_modification_date(registry, request_): from adhocracy_core.utils import get_modification_date from . import clear_modification_date_callback date_before = get_modification_date(registry) clear_modification_date_callback(request_) date_after = get_modification_date(registry) assert date_before is not date_after
from pytest import mark from pytest import fixture from pyramid import testing def test_changelog_create(): from . import Changelog from . import changelog_meta inst = Changelog() assert inst['/path/'] == changelog_meta @fixture() def integration(config): config.include('adhocracy_core.events') config.include('adhocracy_core.changelog') @fixture() def request_(registry): request = testing.DummyResource(registry=registry) return request @mark.usefixtures('integration') def test_includeme_add_changelog(registry): from . import Changelog assert isinstance(registry.changelog, Changelog) @mark.usefixtures('integration') def test_clear_changelog(context, registry, request_, changelog): from . import clear_changelog_callback changelog['/'] = changelog['/']._replace(resource=context) registry.changelog = changelog clear_changelog_callback(request_) assert changelog['/'].resource is None def test_clear_modification_date(registry, request_): from adhocracy_core.utils import get_modification_date from . import clear_modification_date_callback date_before = get_modification_date(registry) clear_modification_date_callback(request_) date_after = get_modification_date(registry) assert date_before is not date_after def test_create_changelog(): from adhocracy_core.changelog import create_changelog from collections import defaultdict assert type(create_changelog()) is defaultdict def test_create_changelog_mapping(): from adhocracy_core.changelog import create_changelog from adhocracy_core.changelog import changelog_meta from collections import defaultdict changelog = create_changelog() assert changelog['/'] == changelog_meta
Improve test coverage for changelog module
Improve test coverage for changelog module
Python
agpl-3.0
liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator
--- +++ @@ -44,3 +44,15 @@ clear_modification_date_callback(request_) date_after = get_modification_date(registry) assert date_before is not date_after + +def test_create_changelog(): + from adhocracy_core.changelog import create_changelog + from collections import defaultdict + assert type(create_changelog()) is defaultdict + +def test_create_changelog_mapping(): + from adhocracy_core.changelog import create_changelog + from adhocracy_core.changelog import changelog_meta + from collections import defaultdict + changelog = create_changelog() + assert changelog['/'] == changelog_meta
179c13d3fe2589d43e260da86e0465901d149a80
rsk_mind/datasource/datasource_csv.py
rsk_mind/datasource/datasource_csv.py
import csv from datasource import Datasource from ..dataset import Dataset class CSVDatasource(Datasource): def read(self): with open(self.path, 'rb') as infile: reader = csv.reader(infile) header = reader.next() rows = [] for row in reader: rows.append(row) return Dataset(header, rows) def write(self, dataset): with open(self.path, 'w') as outfile: writer = csv.writer(outfile) writer.writerow(dataset.transformed_header) for row in dataset.transformed_rows: writer.writerow(row)
import csv from datasource import Datasource from ..dataset import Dataset class CSVDatasource(Datasource): def __init__(self, path, target=None): super(CSVDatasource, self).__init__(path) self.target = target def read(self): with open(self.path, 'rb') as infile: reader = csv.reader(infile) header = reader.next() rows = [] for row in reader: if self.target is not None: index = header.index(self.target) target = row[index] del row[index] row += [target] rows.append(row) return Dataset(header, rows) def write(self, dataset): with open(self.path, 'w') as outfile: writer = csv.writer(outfile) writer.writerow(dataset.transformed_header) for row in dataset.transformed_rows: writer.writerow(row)
Set targe class on csv document
Set targe class on csv document
Python
mit
rsk-mind/rsk-mind-framework
--- +++ @@ -3,6 +3,10 @@ from ..dataset import Dataset class CSVDatasource(Datasource): + + def __init__(self, path, target=None): + super(CSVDatasource, self).__init__(path) + self.target = target def read(self): with open(self.path, 'rb') as infile: @@ -12,6 +16,11 @@ rows = [] for row in reader: + if self.target is not None: + index = header.index(self.target) + target = row[index] + del row[index] + row += [target] rows.append(row) return Dataset(header, rows) @@ -21,6 +30,6 @@ with open(self.path, 'w') as outfile: writer = csv.writer(outfile) writer.writerow(dataset.transformed_header) - + for row in dataset.transformed_rows: writer.writerow(row)
3e0ecb96845f7b2efbb9b62c5eb1372cbe1452c5
s2motc.py
s2motc.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'Superbil' __version__ = '0.1.0' import shapefile sf = shapefile.Reader("shapefiles/路網數值圖103年_西屯區道路路段") # 確認 shapeType 種類 if sf.shapeType is 3: print("PolyLine") # srs = sf.shapeRecords() mapping = {} index = 0 for f in sf.fields: # 跳過第 0 個這個不是 field if index is not 0: key = f[0] mapping[key] = index index = index + 1 print(mapping)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'Superbil' __version__ = '0.1.0' import shapefile import logging log = logging.getLogger() log.setLevel(logging.DEBUG) sf = shapefile.Reader("shapefiles/路網數值圖103年_西屯區道路路段") # 確認 shapeType 種類 if sf.shapeType is 3: log.debug("PolyLine") # srs = sf.shapeRecords() mapping = {} index = 0 for f in sf.fields: # 跳過第 0 個這個不是 field if index is not 0: key = f[0] mapping[key] = index index = index + 1 log.debug(mapping)
Use logging to keep debug message
Use logging to keep debug message
Python
mit
GIS-FCU/sdi-converter
--- +++ @@ -5,12 +5,15 @@ __version__ = '0.1.0' import shapefile +import logging +log = logging.getLogger() +log.setLevel(logging.DEBUG) sf = shapefile.Reader("shapefiles/路網數值圖103年_西屯區道路路段") # 確認 shapeType 種類 if sf.shapeType is 3: - print("PolyLine") + log.debug("PolyLine") # srs = sf.shapeRecords() mapping = {} index = 0 @@ -21,4 +24,4 @@ mapping[key] = index index = index + 1 - print(mapping) + log.debug(mapping)
42c7b4c7b74a3aeccca73f368a16a2f96295ff3b
radar/radar/models/user_sessions.py
radar/radar/models/user_sessions.py
from sqlalchemy import String, Column, Integer, ForeignKey, DateTime, Index from sqlalchemy.dialects import postgresql from sqlalchemy.orm import relationship from radar.database import db from radar.models.users import User, AnonymousUser from radar.models.logs import log_changes @log_changes class UserSession(db.Model): __tablename__ = 'user_sessions' id = Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('users.id'), nullable=False) user = relationship(User) date = Column(DateTime(timezone=True), nullable=False) ip_address = Column(postgresql.INET, nullable=False) user_agent = Column(String, nullable=True) @classmethod def is_authenticated(cls): return True Index('user_sessions_user_idx', UserSession.user_id) class AnonymousSession(object): user = AnonymousUser() @classmethod def is_authenticated(cls): return False
from sqlalchemy import String, Column, Integer, ForeignKey, DateTime, Index from sqlalchemy.dialects import postgresql from sqlalchemy.orm import relationship, backref from radar.database import db from radar.models.users import User, AnonymousUser from radar.models.logs import log_changes @log_changes class UserSession(db.Model): __tablename__ = 'user_sessions' id = Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='CASCADE'), nullable=False) user = relationship('User', backref=backref('user_sessions', cascade='all, delete-orphan', passive_deletes=True)) date = Column(DateTime(timezone=True), nullable=False) ip_address = Column(postgresql.INET, nullable=False) user_agent = Column(String, nullable=True) @classmethod def is_authenticated(cls): return True Index('user_sessions_user_idx', UserSession.user_id) class AnonymousSession(object): user = AnonymousUser() @classmethod def is_authenticated(cls): return False
Delete user sessions with user
Delete user sessions with user
Python
agpl-3.0
renalreg/radar,renalreg/radar,renalreg/radar,renalreg/radar
--- +++ @@ -1,6 +1,6 @@ from sqlalchemy import String, Column, Integer, ForeignKey, DateTime, Index from sqlalchemy.dialects import postgresql -from sqlalchemy.orm import relationship +from sqlalchemy.orm import relationship, backref from radar.database import db from radar.models.users import User, AnonymousUser @@ -13,8 +13,8 @@ id = Column(Integer, primary_key=True) - user_id = Column(Integer, ForeignKey('users.id'), nullable=False) - user = relationship(User) + user_id = Column(Integer, ForeignKey('users.id', onupdate='CASCADE', ondelete='CASCADE'), nullable=False) + user = relationship('User', backref=backref('user_sessions', cascade='all, delete-orphan', passive_deletes=True)) date = Column(DateTime(timezone=True), nullable=False) ip_address = Column(postgresql.INET, nullable=False)
c2b53224eecd6b5651e75b821ba68a471ed558d6
runapp.py
runapp.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Runs the development server of the downstream_node app. # Not for production use. import argparse from downstream_node.startup import app, db def initdb(sys=None): db.engine.execute("CREATE DATABASE downstream") db.create_all() def eval_args(args): if args.initdb: initdb() else: app.run(debug=True) def parse_args(): parser = argparse.ArgumentParser('downstream') parser.add_argument('--initdb', action='store_true') return parser.parse_args() def main(): args = parse_args() eval_args(args) if __name__ == '__main__': main()
#!/usr/bin/env python # -*- coding: utf-8 -*- # Runs the development server of the downstream_node app. # Not for production use. import argparse from downstream_node.startup import app, db def initdb(): db.create_all() def eval_args(args): if args.initdb: initdb() else: app.run(debug=True) def parse_args(): parser = argparse.ArgumentParser('downstream') parser.add_argument('--initdb', action='store_true') return parser.parse_args() def main(): args = parse_args() eval_args(args) if __name__ == '__main__': main()
Remove database engine command in initdb
Remove database engine command in initdb
Python
mit
Storj/downstream-node,Storj/downstream-node
--- +++ @@ -9,8 +9,7 @@ from downstream_node.startup import app, db -def initdb(sys=None): - db.engine.execute("CREATE DATABASE downstream") +def initdb(): db.create_all()
38d9a85bc23bfcf3e44081d3077bbd5ca333fdf3
src/damis/api/serializers.py
src/damis/api/serializers.py
from django.contrib.auth.models import User, Group from rest_framework import serializers from damis.models import Dataset, Algorithm, Experiment class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'groups') class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ('url', 'name') class DatasetSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Dataset fields = ('title', 'licence', 'description', 'author', 'created', 'file', 'file_format') class AlgorithmSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Algorithm fields = ('title', 'user', 'file', 'executable_file', 'created', 'updated') class ExperimentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Experiment fields = ('title', 'start', 'finish', 'user')
from django.contrib.auth.models import User, Group from rest_framework import serializers from damis.models import Dataset, Algorithm, Experiment class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'groups') class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ('url', 'name') class DatasetSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Dataset fields = ('title', 'licence', 'description', 'author', 'created', 'file', 'file_format') class AlgorithmSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Algorithm fields = ('title', 'user', 'file', 'executable_file', 'created', 'updated') class ExperimentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Experiment fields = ('title', 'start', 'finish', 'user', 'status')
Allow modify experiment status via REST API.
Allow modify experiment status via REST API.
Python
agpl-3.0
InScience/DAMIS-old,InScience/DAMIS-old
--- +++ @@ -26,4 +26,4 @@ class ExperimentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Experiment - fields = ('title', 'start', 'finish', 'user') + fields = ('title', 'start', 'finish', 'user', 'status')
c265b49a5961f48542d22d8a4174ee885568c08c
luigi/tasks/export/fasta/__init__.py
luigi/tasks/export/fasta/__init__.py
# -*- coding: utf-8 -*- """ Copyright [2009-2017] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import luigi from .active import ActiveFastaExport from .active import SpeciesSpecificFastaExport from .inactive import InactiveFastaExport from .nhmmer import NHmmerIncludedExport from .nhmmer import NHmmerExcludedExport from .compress import CompressExport from .readme import FastaReadme class FastaExport(luigi.WrapperTask): """ This is the main class to generate all FASTA file exports. """ def requires(self): yield FastaReadme() yield CompressExport() yield ActiveFastaExport() yield InactiveFastaExport() yield SpeciesSpecificFastaExport() yield NHmmerExcludedExport() yield NHmmerIncludedExport() class NHmmerExport(luigi.WrapperTask): """ This does the exports required for nhmmer. """ def requires(self): yield NHmmerExcludedExport() yield NHmmerIncludedExport()
# -*- coding: utf-8 -*- """ Copyright [2009-2017] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import luigi from .active import ActiveFastaExport from .active import SpeciesSpecificFastaExport from .inactive import InactiveFastaExport from .nhmmer import NHmmerIncludedExport from .nhmmer import NHmmerExcludedExport from .compress import CompressExport from .readme import FastaReadme class FastaExport(luigi.WrapperTask): """ This is the main class to generate all FASTA file exports. """ def requires(self): yield FastaReadme() yield NHmmerExport() yield CompressExport() class NHmmerExport(luigi.WrapperTask): """ This does the exports required for nhmmer. """ def requires(self): yield NHmmerExcludedExport() yield NHmmerIncludedExport()
Simplify the general Fasta export task
Simplify the general Fasta export task It doesn't need to be so complicated, so we simplify it.
Python
apache-2.0
RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline
--- +++ @@ -31,12 +31,8 @@ def requires(self): yield FastaReadme() + yield NHmmerExport() yield CompressExport() - yield ActiveFastaExport() - yield InactiveFastaExport() - yield SpeciesSpecificFastaExport() - yield NHmmerExcludedExport() - yield NHmmerIncludedExport() class NHmmerExport(luigi.WrapperTask):
dcdfe91570e185df19daef49be9a368276e20483
src/core/migrations/0039_fix_reviewer_url.py
src/core/migrations/0039_fix_reviewer_url.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.28 on 2020-05-15 15:52 from __future__ import unicode_literals import re from django.db import migrations REGEX = re.compile("({%\ ?journal_url 'do_review' review_assignment.id\ ?%})") OUTPUT = "{{ review_url }}" def replace_template(apps, schema_editor): SettingValueTranslation = apps.get_model('core', 'SettingValueTranslation') settings = SettingValueTranslation.objects.all() for setting in settings: setting.value = re.sub(REGEX, OUTPUT, setting.value) setting.save() class Migration(migrations.Migration): dependencies = [ ('core', '0038_xslt_1-3-8'), ] operations = [ migrations.RunPython(replace_template, reverse_code=migrations.RunPython.noop) ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.28 on 2020-05-15 15:52 from __future__ import unicode_literals import re from django.db import migrations REGEX = re.compile("({%\ ?journal_url 'do_review' review_assignment.id\ ?%})") OUTPUT = "{{ review_url }}" def replace_template(apps, schema_editor): SettingValueTranslation = apps.get_model('core', 'SettingValueTranslation') settings = SettingValueTranslation.objects.all() for setting in settings: if isinstance(setting.value, str): setting.value = re.sub(REGEX, OUTPUT, setting.value) setting.save() class Migration(migrations.Migration): dependencies = [ ('core', '0038_xslt_1-3-8'), ] operations = [ migrations.RunPython(replace_template, reverse_code=migrations.RunPython.noop) ]
Handle migrating non-string values (i.e.: NULL)
Handle migrating non-string values (i.e.: NULL)
Python
agpl-3.0
BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway
--- +++ @@ -13,8 +13,9 @@ settings = SettingValueTranslation.objects.all() for setting in settings: - setting.value = re.sub(REGEX, OUTPUT, setting.value) - setting.save() + if isinstance(setting.value, str): + setting.value = re.sub(REGEX, OUTPUT, setting.value) + setting.save() class Migration(migrations.Migration):
43c62ea6d5558b0e6e5104eb05d45d89239e70b8
q3/FindAllAbbreviations.py
q3/FindAllAbbreviations.py
import sys def prependAbbrev(front, abbr): if type(front) is type(abbr[0]): return [front + abbr[0]] + abbr[1:] else: return [front] + abbr def prefixAll(p, lst): return [prependAbbrev(p, l) for l in lst] def findAllAbbrev(s): if len(s) == 1: return [[s], [1]] else: rest = findAllAbbrev(s[1:]) return prefixAll(s[0], rest) + prefixAll(1, rest) for s in findAllAbbrev(sys.argv[1]): print ''.join([str(i) for i in s])
import sys def prependAbbrev(front, abbr): if type(front) is type(abbr[0]): return [front + abbr[0]] + abbr[1:] else: return [front] + abbr def prefixAll(p, lst): return [prependAbbrev(p, l) for l in lst] def findAllAbbrev(s): if len(s) == 1: return [[s], [1]] else: rest = findAllAbbrev(s[1:]) return prefixAll(s[0], rest) + prefixAll(1, rest) if __name__ == '__main__': if len(sys.argv) == 1: print ' '.join(['usage:', sys.argv[0], '<word>']) else: for s in findAllAbbrev(sys.argv[1]): print ''.join([str(i) for i in s])
Print usage if no word given
Print usage if no word given
Python
mit
UW-UPL/InterviewPrepJan2016,UW-UPL/InterviewPrepJan2016,UW-UPL/InterviewPrepJan2016,UW-UPL/InterviewPrepJan2016
--- +++ @@ -16,5 +16,9 @@ rest = findAllAbbrev(s[1:]) return prefixAll(s[0], rest) + prefixAll(1, rest) -for s in findAllAbbrev(sys.argv[1]): - print ''.join([str(i) for i in s]) +if __name__ == '__main__': + if len(sys.argv) == 1: + print ' '.join(['usage:', sys.argv[0], '<word>']) + else: + for s in findAllAbbrev(sys.argv[1]): + print ''.join([str(i) for i in s])
a050d510bce159ba646de322de31b05fede349e7
catwatch/blueprints/billing/forms.py
catwatch/blueprints/billing/forms.py
from flask_wtf import Form from wtforms import StringField, HiddenField, SubmitField from wtforms.validators import DataRequired, Length from flask_babel import lazy_gettext as _ class CreditCardForm(Form): stripe_key = HiddenField(_('Stripe key'), [DataRequired(), Length(1, 254)]) plan = HiddenField(_('Plan'), [DataRequired(), Length(1, 254)]) name = StringField(_('Name on card'), [DataRequired(), Length(1, 254)]) submit = SubmitField(_('Process payment')) class CancelSubscriptionForm(Form): submit = SubmitField(_('Cancel subscriptiption'))
from flask_wtf import Form from wtforms import StringField, HiddenField, SubmitField from wtforms.validators import DataRequired, Length from flask_babel import lazy_gettext as _ class CreditCardForm(Form): stripe_key = HiddenField(_('Stripe key'), [DataRequired(), Length(1, 254)]) plan = HiddenField(_('Plan'), [DataRequired(), Length(1, 254)]) name = StringField(_('Name on card'), [DataRequired(), Length(1, 254)]) submit = SubmitField(_('Process payment')) class CancelSubscriptionForm(Form): submit = SubmitField(_('Cancel subscription'))
Fix typo in cancel subscription submit button
Fix typo in cancel subscription submit button
Python
mit
nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask
--- +++ @@ -15,4 +15,4 @@ class CancelSubscriptionForm(Form): - submit = SubmitField(_('Cancel subscriptiption')) + submit = SubmitField(_('Cancel subscription'))
d85d04da0f6ce283f53678bd81bd0987f59ce766
curldrop/cli.py
curldrop/cli.py
import click import os from .app import app from .server import StandaloneServer @click.command() @click.option( '--port', default=8000, help='Port to listen on, default is 8000' ) @click.option( '--upload-dir', default=os.getcwd(), help='Directory where uploads are stored, if not specified the current working directory will be used' ) @click.option( '--baseurl', default=None, help='Base URL, e.g. http://example.com/' ) def main(port, upload_dir, baseurl): if baseurl is None: baseurl = 'http://{host}:{port}/'.format(host='localhost', port=port) click.echo( click.style('You did not specify a Base URL, using default: ' + baseurl, fg='yellow') ) app.config['UPLOAD_DIR'] = upload_dir app.config['BASE_URL'] = baseurl server_options = { 'bind': '{ip}:{port}'.format( ip='0.0.0.0', port=port ), 'workers': 4, } StandaloneServer(app, server_options).run() if __name__ == '__main__': main()
import click import os from .app import app from .server import StandaloneServer @click.command() @click.option( '--port', default=8000, help='Port to listen on, default is 8000' ) @click.option( '--upload-dir', default=os.getcwd(), help='Directory where uploads are stored, if not specified the current working directory will be used' ) @click.option( '--baseurl', default=None, help='Base URL, e.g. http://example.com/' ) def main(port, upload_dir, baseurl): if baseurl is None: baseurl = 'http://{host}:{port}/'.format(host='localhost', port=port) click.echo( click.style('You did not specify a Base URL, using default: ' + baseurl, fg='yellow') ) app.config['UPLOAD_DIR'] = upload_dir app.config['BASE_URL'] = baseurl server_options = { 'bind': '{ip}:{port}'.format( ip='0.0.0.0', port=port ), 'workers': 4, 'accesslog': '-', 'errorlog': '-' } StandaloneServer(app, server_options).run() if __name__ == '__main__': main()
Make gunicorn log to stdout/stderr
Make gunicorn log to stdout/stderr
Python
mit
kennell/curldrop,kevvvvv/curldrop
--- +++ @@ -36,6 +36,8 @@ port=port ), 'workers': 4, + 'accesslog': '-', + 'errorlog': '-' } StandaloneServer(app, server_options).run()
3e03d66c5351ac5e71f82a56aa01ba06865e1c25
conda_verify/cli.py
conda_verify/cli.py
import os import sys from optparse import OptionParser from conda_verify.errors import RecipeError from conda_verify.verify import Verify from conda_verify.utilities import render_metadata, iter_cfgs def cli(): p = OptionParser( usage="usage: %prog [options] <path to recipes or packages>", description="tool for (passively) verifying conda recipes and conda " "packages for the Anaconda distribution") p.add_option('-v', '--version', help="display the version being used and exit", action="store_true") opts, args = p.parse_args() if opts.version: from conda_verify import __version__ sys.exit('conda-verify {}' .format(__version__)) verifier = Verify() for path in args: if os.path.isfile(os.path.join(path, 'meta.yaml')): print("==> %s <==" % path) for cfg in iter_cfgs(): meta = render_metadata(path, cfg) try: verifier.verify_recipe(rendered_meta=meta, recipe_dir=path) except RecipeError as e: sys.stderr.write("RecipeError: %s\n" % e) elif path.endswith(('.tar.bz2', '.tar')): print('Verifying {}...' .format(path)) verifier.verify_package(path_to_package=path)
import os import sys from optparse import OptionParser from conda_verify.errors import RecipeError from conda_verify.verify import Verify from conda_verify.utilities import render_metadata, iter_cfgs def cli(): p = OptionParser( usage="usage: %prog [options] <path to recipes or packages>", description="tool for (passively) verifying conda recipes and conda " "packages for the Anaconda distribution") p.add_option('-v', '--version', help="display the version being used and exit", action="store_true") opts, args = p.parse_args() if opts.version: from conda_verify import __version__ sys.exit('conda-verify {}' .format(__version__)) verifier = Verify() for path in args: meta_file = os.path.join(path, 'meta.yaml') if os.path.isfile(meta_file): print('Verifying {}...' .format(meta_file)) for cfg in iter_cfgs(): meta = render_metadata(path, cfg) try: verifier.verify_recipe(rendered_meta=meta, recipe_dir=path) except RecipeError as e: sys.stderr.write("RecipeError: %s\n" % e) elif path.endswith(('.tar.bz2', '.tar')): print('Verifying {}...' .format(path)) verifier.verify_package(path_to_package=path)
Change script run message output
Change script run message output
Python
bsd-3-clause
mandeep/conda-verify
--- +++ @@ -26,8 +26,9 @@ verifier = Verify() for path in args: - if os.path.isfile(os.path.join(path, 'meta.yaml')): - print("==> %s <==" % path) + meta_file = os.path.join(path, 'meta.yaml') + if os.path.isfile(meta_file): + print('Verifying {}...' .format(meta_file)) for cfg in iter_cfgs(): meta = render_metadata(path, cfg) try:
67637039b95f4030a462edb35d614bb678426dd3
conversion_check.py
conversion_check.py
def check_iso_mcp(input_file): """ Checks if MCP conversion is allowed for the given file. MCP files are only created if the DIF has an ISO Topic Category of "OCEANS". """ allowed = False # Cannot use the following check: # oceans_tag = '<ISO_Topic_Category>OCEANS</ISO_Topic_Category>' # This is because some of these tags include a "uuid" attribute, so they # will not be marked OK for conversion. oceans_tag = '>OCEANS</ISO_Topic_Category>' with open(input_file) as r: content = r.read() if 0 <= content.find(oceans_tag): allowed = True return allowed
def check_iso_mcp(input_file): """ Checks if MCP conversion is allowed for the given file. MCP files are only created if the DIF has an ISO Topic Category of "OCEANS". """ allowed = False # Cannot use the following check: # oceans_tag = '<ISO_Topic_Category>OCEANS</ISO_Topic_Category>' # This is because some of these tags include a "uuid" attribute, so they # will not be marked OK for conversion. oceans_tag = '>OCEANS</ISO_Topic_Category>' with open(input_file) as r: content = r.read() if 0 <= content.find(oceans_tag): allowed = True return allowed def check_ands_rif_cs(file_path): folder_path, file_name = os.path.split(file_path) base_name, ext_name = os.path.splitext(file_name) return not base_name.endswith('AAD_RIFCS_ISO')
Add ANDS RIF-CS conversion check function
Add ANDS RIF-CS conversion check function
Python
mit
AustralianAntarcticDataCentre/metadata_xml_convert,AustralianAntarcticDataCentre/metadata_xml_convert
--- +++ @@ -20,3 +20,9 @@ allowed = True return allowed + + +def check_ands_rif_cs(file_path): + folder_path, file_name = os.path.split(file_path) + base_name, ext_name = os.path.splitext(file_name) + return not base_name.endswith('AAD_RIFCS_ISO')
a57d4e3e1fa65b11b55d6f46dd778cdaf1ed8504
webstack_django_sorting/middleware.py
webstack_django_sorting/middleware.py
def get_field(self): try: field = self.REQUEST['sort'] except (KeyError, ValueError, TypeError): field = '' return (self.direction == 'desc' and '-' or '') + field def get_direction(self): try: return self.REQUEST['dir'] except (KeyError, ValueError, TypeError): return 'desc' class SortingMiddleware(object): """ Inserts a variable representing the field (with direction of sorting) onto the request object if it exists in either **GET** or **POST** portions of the request. """ def process_request(self, request): request.__class__.field = property(get_field) request.__class__.direction = property(get_direction)
def get_field(self): try: field = self.GET['sort'] except (KeyError, ValueError, TypeError): field = '' return (self.direction == 'desc' and '-' or '') + field def get_direction(self): try: return self.GET['dir'] except (KeyError, ValueError, TypeError): return 'desc' class SortingMiddleware(object): """ Inserts a variable representing the field (with direction of sorting) onto the request object if it exists in **GET** portions of the request. """ def process_request(self, request): request.__class__.field = property(get_field) request.__class__.direction = property(get_direction)
Fix deprecated use of REQUEST and only read the GET request
Fix deprecated use of REQUEST and only read the GET request RemovedInDjango19Warning: `request.REQUEST` is deprecated, use `request.GET` or `request.POST` instead.
Python
bsd-3-clause
artscoop/webstack-django-sorting,artscoop/webstack-django-sorting
--- +++ @@ -1,22 +1,21 @@ def get_field(self): try: - field = self.REQUEST['sort'] + field = self.GET['sort'] except (KeyError, ValueError, TypeError): field = '' return (self.direction == 'desc' and '-' or '') + field def get_direction(self): try: - return self.REQUEST['dir'] + return self.GET['dir'] except (KeyError, ValueError, TypeError): return 'desc' class SortingMiddleware(object): """ - Inserts a variable representing the field (with direction of sorting) - onto the request object if it exists in either **GET** or **POST** - portions of the request. + Inserts a variable representing the field (with direction of sorting) onto + the request object if it exists in **GET** portions of the request. """ def process_request(self, request): request.__class__.field = property(get_field)
1b44849f9fac68c6ce0732baded63681cbf58ccb
osmaxx-py/osmaxx/contrib/auth/tests/test_frontend_permissions.py
osmaxx-py/osmaxx/contrib/auth/tests/test_frontend_permissions.py
from django.test import TestCase from django.contrib.auth.models import User, Group from osmaxx.contrib.auth.frontend_permissions import user_in_osmaxx_group, FRONTEND_USER_GROUP class TestFrontendPermissions(TestCase): def test_superuser_can_access_frontend_even_if_not_in_osmaxx_group(self): an_admin = User.objects.create_superuser('A. D. Min', 'admin@example.com', 'password') self.assertTrue(user_in_osmaxx_group(an_admin)) def test_user_can_access_frontend_when_in_osmaxx_group(self): a_user = User.objects.create_user('U. Ser', 'user@example.com', 'password') a_user.groups.add(Group.objects.get(name=FRONTEND_USER_GROUP)) self.assertTrue(user_in_osmaxx_group(a_user))
from django.test import TestCase from django.contrib.auth.models import User, Group from osmaxx.contrib.auth.frontend_permissions import user_in_osmaxx_group, FRONTEND_USER_GROUP class TestFrontendPermissions(TestCase): def test_user_can_not_access_frontend_by_default(self): a_user = User.objects.create_user('U. Ser', 'user@example.com', 'password') self.assertFalse(user_in_osmaxx_group(a_user)) def test_superuser_can_access_frontend_even_if_not_in_osmaxx_group(self): an_admin = User.objects.create_superuser('A. D. Min', 'admin@example.com', 'password') self.assertTrue(user_in_osmaxx_group(an_admin)) def test_user_can_access_frontend_when_in_osmaxx_group(self): a_user = User.objects.create_user('U. Ser', 'user@example.com', 'password') a_user.groups.add(Group.objects.get(name=FRONTEND_USER_GROUP)) self.assertTrue(user_in_osmaxx_group(a_user))
Test that users can not access frontend by default
Test that users can not access frontend by default
Python
mit
geometalab/osmaxx,geometalab/osmaxx-frontend,geometalab/osmaxx-frontend,geometalab/drf-utm-zone-info,geometalab/osmaxx-frontend,geometalab/osmaxx,geometalab/drf-utm-zone-info,geometalab/osmaxx,geometalab/osmaxx-frontend,geometalab/osmaxx
--- +++ @@ -4,6 +4,10 @@ class TestFrontendPermissions(TestCase): + def test_user_can_not_access_frontend_by_default(self): + a_user = User.objects.create_user('U. Ser', 'user@example.com', 'password') + self.assertFalse(user_in_osmaxx_group(a_user)) + def test_superuser_can_access_frontend_even_if_not_in_osmaxx_group(self): an_admin = User.objects.create_superuser('A. D. Min', 'admin@example.com', 'password') self.assertTrue(user_in_osmaxx_group(an_admin))
428ff9d74f52d938b9ee5ac03aec975dd5af191a
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jon Surrell # Copyright (c) 2014 Jon Surrell # # License: MIT # """This module exports the Govet plugin class.""" from SublimeLinter.lint import Linter, util class Govet(Linter): """Provides an interface to go vet.""" syntax = ('go', 'gosublime-go') cmd = ('go', 'tool', 'vet') regex = r'^.+:(?P<line>\d+):(?P<col>\d+):\s+(?P<message>.+)' tempfile_suffix = 'go' error_stream = util.STREAM_STDERR
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jon Surrell # Copyright (c) 2014 Jon Surrell # # License: MIT # """This module exports the Govet plugin class.""" from SublimeLinter.lint import Linter, util class Govet(Linter): """Provides an interface to go vet.""" syntax = ('go', 'gosublime-go') cmd = ('go', 'tool', 'vet') regex = r'^.+:(?P<line>\d+):(?P<col>\d+):\s+(?P<message>.+)' tempfile_suffix = 'go' error_stream = util.STREAM_STDERR
Fix pep257 - D211: No blank lines allowed before class docstring (found 1)
Fix pep257 - D211: No blank lines allowed before class docstring (found 1)
Python
mit
sirreal/SublimeLinter-contrib-govet
--- +++ @@ -14,7 +14,6 @@ class Govet(Linter): - """Provides an interface to go vet.""" syntax = ('go', 'gosublime-go')
43c3a8a94c7783aadb440e529645f7db7c7913ff
successstories/forms.py
successstories/forms.py
from django import forms from .models import Story from cms.forms import ContentManageableModelForm class StoryForm(ContentManageableModelForm): class Meta: model = Story fields = ( 'name', 'company_name', 'company_url', 'category', 'author', 'author_email', 'pull_quote', 'content' ) def clean_name(self): name = self.cleaned_data.get('name') story = Story.objects.filter(name=name).exclude(pk=self.instance.pk) if name is not None and story.exists(): raise forms.ValidationError('Please use a unique name.') return name
from django import forms from .models import Story from cms.forms import ContentManageableModelForm class StoryForm(ContentManageableModelForm): pull_quote = forms.CharField(widget=forms.Textarea(attrs={'rows': 5})) class Meta: model = Story fields = ( 'name', 'company_name', 'company_url', 'category', 'author', 'author_email', 'pull_quote', 'content' ) def clean_name(self): name = self.cleaned_data.get('name') story = Story.objects.filter(name=name).exclude(pk=self.instance.pk) if name is not None and story.exists(): raise forms.ValidationError('Please use a unique name.') return name
Reduce textarea height in Story form
Reduce textarea height in Story form
Python
apache-2.0
proevo/pythondotorg,manhhomienbienthuy/pythondotorg,manhhomienbienthuy/pythondotorg,Mariatta/pythondotorg,python/pythondotorg,python/pythondotorg,Mariatta/pythondotorg,manhhomienbienthuy/pythondotorg,proevo/pythondotorg,Mariatta/pythondotorg,python/pythondotorg,manhhomienbienthuy/pythondotorg,python/pythondotorg,Mariatta/pythondotorg,proevo/pythondotorg,proevo/pythondotorg
--- +++ @@ -5,6 +5,8 @@ class StoryForm(ContentManageableModelForm): + pull_quote = forms.CharField(widget=forms.Textarea(attrs={'rows': 5})) + class Meta: model = Story fields = (
e56e47828d381022cb2742b06f7f47d3fb64a499
hiicart/gateway/braintree/tasks.py
hiicart/gateway/braintree/tasks.py
import logging from celery.decorators import task from hiicart.models import HiiCart from hiicart.gateway.braintree.ipn import BraintreeIPN log = logging.getLogger('hiicart.gateway.braintree.tasks') @task def update_payment_status(hiicart_id, transaction_id, tries=0): """Check the payment status of a Braintree transaction.""" hiicart = HiiCart.objects.get(pk=hiicart_id) handler = BraintreeIPN(hiicart) done = handler.update_order_status(transaction_id) # Reschedule the failed payment to run in 4 hours if not done: # After 18 tries (72 hours) we will void and fail the payment if tries >= 18: handler.void_order(transaction_id) else: tries = tries + 1 update_payment_status.apply_async(args=[hiicart_id, transaction_id, tries], countdown=14400)
import logging from celery.decorators import task from hiicart.models import HiiCart from hiicart.gateway.braintree.ipn import BraintreeIPN log = logging.getLogger('hiicart.gateway.braintree.tasks') @task def update_payment_status(hiicart_id, transaction_id, tries=0, cart_class=HiiCart): """Check the payment status of a Braintree transaction.""" hiicart = cart_class.objects.get(pk=hiicart_id) handler = BraintreeIPN(hiicart) done = handler.update_order_status(transaction_id) # Reschedule the failed payment to run in 4 hours if not done: # After 18 tries (72 hours) we will void and fail the payment if tries >= 18: handler.void_order(transaction_id) else: tries = tries + 1 update_payment_status.apply_async(args=[hiicart_id, transaction_id, tries], countdown=14400)
Make cart class configurable for braintree task
Make cart class configurable for braintree task
Python
mit
hiidef/hiicart,hiidef/hiicart
--- +++ @@ -9,9 +9,9 @@ @task -def update_payment_status(hiicart_id, transaction_id, tries=0): +def update_payment_status(hiicart_id, transaction_id, tries=0, cart_class=HiiCart): """Check the payment status of a Braintree transaction.""" - hiicart = HiiCart.objects.get(pk=hiicart_id) + hiicart = cart_class.objects.get(pk=hiicart_id) handler = BraintreeIPN(hiicart) done = handler.update_order_status(transaction_id) # Reschedule the failed payment to run in 4 hours
2bedbab8eb7d2efb9ff8e39a821fd2796dd4ce3f
police_api/service.py
police_api/service.py
import logging import requests logger = logging.getLogger(__name__) class APIError(Exception): pass class BaseService(object): def __init__(self, api, **config): self.api = api self.requester = requests.session() self.config = { 'base_url': 'http://data.police.uk/api/', } self.config.update(config) self.set_credentials(self.config.get('username'), self.config.get('password')) def set_credentials(self, username, password): if username and password: self.requester.auth = (username, password) def request(self, verb, method, **kwargs): verb = verb.upper() request_kwargs = {} if method == 'GET': request_kwargs['params'] = kwargs else: request_kwargs['data'] = kwargs url = self.config['base_url'] + method logger.debug('%s %s' % (verb, url)) r = self.requester.request(verb, url, **request_kwargs) if r.status_code != 200: raise APIError(r.status_code) return r.json()
import logging import requests logger = logging.getLogger(__name__) class APIError(Exception): pass class BaseService(object): def __init__(self, api, **config): self.api = api self.requester = requests.session() self.config = { 'base_url': 'http://data.police.uk/api/', } self.config.update(config) self.set_credentials(self.config.get('username'), self.config.get('password')) def set_credentials(self, username, password): if username and password: self.requester.auth = (username, password) def request(self, verb, method, **kwargs): verb = verb.upper() request_kwargs = {} if verb == 'GET': request_kwargs['params'] = kwargs else: request_kwargs['data'] = kwargs url = self.config['base_url'] + method logger.debug('%s %s' % (verb, url)) r = self.requester.request(verb, url, **request_kwargs) if r.status_code != 200: raise APIError(r.status_code) return r.json()
Fix GET params bug with BaseService.request
Fix GET params bug with BaseService.request
Python
mit
rkhleics/police-api-client-python
--- +++ @@ -28,7 +28,7 @@ def request(self, verb, method, **kwargs): verb = verb.upper() request_kwargs = {} - if method == 'GET': + if verb == 'GET': request_kwargs['params'] = kwargs else: request_kwargs['data'] = kwargs
53d3adce196d38278ccbdf5e8223c3c1d4543ffc
app/handlers/__init__.py
app/handlers/__init__.py
__version__ = "2018.12.1" __versionfull__ = __version__
__version__ = "2018.12.2" __versionfull__ = __version__
Bump app version to 2018.12.2
Bump app version to 2018.12.2 Signed-off-by: Guillaume Tucker <e7e20b7c30f19d4ca6b81319ef81bf200369d137@collabora.com>
Python
lgpl-2.1
kernelci/kernelci-backend,kernelci/kernelci-backend
--- +++ @@ -1,2 +1,2 @@ -__version__ = "2018.12.1" +__version__ = "2018.12.2" __versionfull__ = __version__
e960bf04d3885228c0df9c182c8d073e800ec122
dbaas/dashboard/templatetags/menu.py
dbaas/dashboard/templatetags/menu.py
# -*- coding: utf-8 -*- from django import template from physical.models import EngineType, Environment, Plan register = template.Library() @register.inclusion_tag('dashboard/menu.html') def render_menu(): data_engines = [] for engine_type in EngineType.objects.all(): data_engine = { 'name': engine_type.name, 'environments': [], } for environment in Environment.objects.filter(plan__in=Plan.objects.filter(engine__engine_type=engine_type)).distinct(): data_environment = { 'id': environment.id, 'name': environment.name, } data_engine['environments'].append(data_environment) if data_engine['environments']: data_engines.append(data_engine) context = { 'engines': data_engines } return context
# -*- coding: utf-8 -*- from django import template from physical.models import EngineType, Environment, Plan register = template.Library() @register.inclusion_tag('dashboard/menu.html') def render_menu(): data_engines = [] for engine_type in EngineType.objects.all(): data_engine = { 'name': engine_type.name, 'environments': [], } for environment in Environment.objects.filter(plans__in=Plan.objects.filter(engine__engine_type=engine_type)).distinct(): data_environment = { 'id': environment.id, 'name': environment.name, } data_engine['environments'].append(data_environment) if data_engine['environments']: data_engines.append(data_engine) context = { 'engines': data_engines } return context
Fix change on raleted name (Plan x Environment)
Fix change on raleted name (Plan x Environment)
Python
bsd-3-clause
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
--- +++ @@ -16,7 +16,7 @@ 'environments': [], } - for environment in Environment.objects.filter(plan__in=Plan.objects.filter(engine__engine_type=engine_type)).distinct(): + for environment in Environment.objects.filter(plans__in=Plan.objects.filter(engine__engine_type=engine_type)).distinct(): data_environment = { 'id': environment.id, 'name': environment.name,
a03f3ae483e7cdacbd50ad0646273b7e0c18b10f
manage.py
manage.py
import functools import os from flask.ext.debugtoolbar import DebugToolbarExtension from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.script import Manager from flask_app.app import app from flask_app.models import db manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) _FROM_HERE = functools.partial(os.path.join, os.path.dirname(__file__)) @manager.command def testserver(): app.config["DEBUG"] = True app.config["TESTING"] = True app.config["SECRET_KEY"] = "dummy secret key" toolbar = DebugToolbarExtension(app) app.run(port=8000, extra_files=[ _FROM_HERE("flask_app", "app.yml") ]) if __name__ == '__main__': manager.run()
import functools import os from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.script import Manager from flask_app.app import app from flask_app.models import db manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) _FROM_HERE = functools.partial(os.path.join, os.path.dirname(__file__)) @manager.command def testserver(): from flask.ext.debugtoolbar import DebugToolbarExtension app.config["DEBUG"] = True app.config["TESTING"] = True app.config["SECRET_KEY"] = "dummy secret key" DebugToolbarExtension(app) app.run(port=8000, extra_files=[ _FROM_HERE("flask_app", "app.yml") ]) if __name__ == '__main__': manager.run()
Fix DebugToolbar requirement in non-debug envs
Fix DebugToolbar requirement in non-debug envs
Python
mit
getslash/mailboxer,getslash/mailboxer,vmalloc/mailboxer,getslash/mailboxer,Infinidat/lanister,Infinidat/lanister,vmalloc/mailboxer,vmalloc/mailboxer
--- +++ @@ -1,7 +1,6 @@ import functools import os -from flask.ext.debugtoolbar import DebugToolbarExtension from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.script import Manager @@ -18,10 +17,12 @@ @manager.command def testserver(): + from flask.ext.debugtoolbar import DebugToolbarExtension app.config["DEBUG"] = True app.config["TESTING"] = True app.config["SECRET_KEY"] = "dummy secret key" - toolbar = DebugToolbarExtension(app) + + DebugToolbarExtension(app) app.run(port=8000, extra_files=[ _FROM_HERE("flask_app", "app.yml") ])
cb9b7dcd01495999fac0671acd9e4bf138bd71ea
scripts/spotify-current.py
scripts/spotify-current.py
#!/usr/bin/python # -*- coding: utf-8 -*- import dbus session_bus = dbus.SessionBus() spotify_bus = session_bus.get_object('org.mpris.MediaPlayer2.spotify', '/org/mpris/MediaPlayer2') spotify_properties = dbus.Interface(spotify_bus, 'org.freedesktop.DBus.Properties') metadata = spotify_properties.Get('org.mpris.MediaPlayer2.Player', 'Metadata') print '♫', metadata['xesam:artist'][0], '-', metadata['xesam:title']
#!/usr/bin/python # -*- coding: utf-8 -*- import dbus session_bus = dbus.SessionBus() spotify_bus = session_bus.get_object('org.mpris.MediaPlayer2.spotify', '/org/mpris/MediaPlayer2') spotify_properties = dbus.Interface(spotify_bus, 'org.freedesktop.DBus.Properties') metadata = spotify_properties.Get('org.mpris.MediaPlayer2.Player', 'Metadata') title = metadata['xesam:artist'][0] + ' - ' + metadata['xesam:title'] title = (title[:35] + '...') if len(title) > 38 else title print '♫', title
Truncate spotify current song if it is too long
Truncate spotify current song if it is too long
Python
mit
EllisV/dotfiles,EllisV/dotfiles
--- +++ @@ -8,4 +8,7 @@ spotify_properties = dbus.Interface(spotify_bus, 'org.freedesktop.DBus.Properties') metadata = spotify_properties.Get('org.mpris.MediaPlayer2.Player', 'Metadata') -print '♫', metadata['xesam:artist'][0], '-', metadata['xesam:title'] +title = metadata['xesam:artist'][0] + ' - ' + metadata['xesam:title'] +title = (title[:35] + '...') if len(title) > 38 else title + +print '♫', title
26de8a5b63d6da42bbafaa3d520fe0fbbb3a7d54
cms/utils/encoder.py
cms/utils/encoder.py
# -*- coding: utf-8 -*- from django.utils.html import conditional_escape from django.core.serializers.json import DjangoJSONEncoder class SafeJSONEncoder(DjangoJSONEncoder): def _recursive_escape(self, o, esc=conditional_escape): if isinstance(o, dict): return type(o)((esc(k), self._recursive_escape(v)) for (k, v) in o.iteritems()) if isinstance(o, (list, tuple)): return type(o)(self._recursive_escape(v) for v in o) try: return type(o)(esc(o)) except ValueError: return esc(o) def encode(self, o): value = self._recursive_escape(o) return super(SafeJSONEncoder, self).encode(value)
# -*- coding: utf-8 -*- from django.utils.html import conditional_escape from django.core.serializers.json import DjangoJSONEncoder class SafeJSONEncoder(DjangoJSONEncoder): def _recursive_escape(self, o, esc=conditional_escape): if isinstance(o, dict): return type(o)((esc(k), self._recursive_escape(v)) for (k, v) in o.iteritems()) if isinstance(o, (list, tuple)): return type(o)(self._recursive_escape(v) for v in o) if type(o) is bool: return o try: return type(o)(esc(o)) except ValueError: return esc(o) def encode(self, o): value = self._recursive_escape(o) return super(SafeJSONEncoder, self).encode(value)
Fix copy page when permission is disabled
Fix copy page when permission is disabled
Python
bsd-3-clause
frnhr/django-cms,andyzsf/django-cms,jeffreylu9/django-cms,timgraham/django-cms,qnub/django-cms,leture/django-cms,mkoistinen/django-cms,chmberl/django-cms,saintbird/django-cms,datakortet/django-cms,keimlink/django-cms,josjevv/django-cms,youprofit/django-cms,Livefyre/django-cms,takeshineshiro/django-cms,chkir/django-cms,bittner/django-cms,mkoistinen/django-cms,chkir/django-cms,sznekol/django-cms,sznekol/django-cms,takeshineshiro/django-cms,leture/django-cms,netzkolchose/django-cms,benzkji/django-cms,evildmp/django-cms,qnub/django-cms,rscnt/django-cms,yakky/django-cms,FinalAngel/django-cms,AlexProfi/django-cms,nimbis/django-cms,kk9599/django-cms,vad/django-cms,FinalAngel/django-cms,vxsx/django-cms,robmagee/django-cms,owers19856/django-cms,Jaccorot/django-cms,chmberl/django-cms,kk9599/django-cms,stefanfoulis/django-cms,dhorelik/django-cms,saintbird/django-cms,rscnt/django-cms,dhorelik/django-cms,stefanw/django-cms,DylannCordel/django-cms,memnonila/django-cms,qnub/django-cms,vad/django-cms,andyzsf/django-cms,benzkji/django-cms,netzkolchose/django-cms,SofiaReis/django-cms,jeffreylu9/django-cms,keimlink/django-cms,nimbis/django-cms,SmithsonianEnterprises/django-cms,andyzsf/django-cms,czpython/django-cms,divio/django-cms,stefanw/django-cms,rryan/django-cms,rsalmaso/django-cms,stefanfoulis/django-cms,SachaMPS/django-cms,DylannCordel/django-cms,farhaadila/django-cms,stefanw/django-cms,stefanfoulis/django-cms,mkoistinen/django-cms,rryan/django-cms,datakortet/django-cms,josjevv/django-cms,liuyisiyisi/django-cms,bittner/django-cms,vad/django-cms,youprofit/django-cms,Vegasvikk/django-cms,philippze/django-cms,SachaMPS/django-cms,benzkji/django-cms,evildmp/django-cms,datakortet/django-cms,SmithsonianEnterprises/django-cms,yakky/django-cms,rsalmaso/django-cms,stefanw/django-cms,wyg3958/django-cms,vad/django-cms,Vegasvikk/django-cms,divio/django-cms,rryan/django-cms,chmberl/django-cms,iddqd1/django-cms,robmagee/django-cms,czpython/django-cms,cyberintruder/django-cms,timgraham/django-cms,isotoma/django-cms,vxsx/django-cms,rryan/django-cms,kk9599/django-cms,yakky/django-cms,petecummings/django-cms,youprofit/django-cms,benzkji/django-cms,SachaMPS/django-cms,bittner/django-cms,leture/django-cms,datakortet/django-cms,intip/django-cms,sephii/django-cms,divio/django-cms,AlexProfi/django-cms,isotoma/django-cms,farhaadila/django-cms,liuyisiyisi/django-cms,jsma/django-cms,czpython/django-cms,frnhr/django-cms,nimbis/django-cms,Livefyre/django-cms,vxsx/django-cms,sznekol/django-cms,DylannCordel/django-cms,mkoistinen/django-cms,owers19856/django-cms,jproffitt/django-cms,SmithsonianEnterprises/django-cms,jsma/django-cms,wyg3958/django-cms,FinalAngel/django-cms,sephii/django-cms,jeffreylu9/django-cms,owers19856/django-cms,jproffitt/django-cms,jsma/django-cms,cyberintruder/django-cms,Jaccorot/django-cms,SofiaReis/django-cms,rsalmaso/django-cms,nimbis/django-cms,jproffitt/django-cms,czpython/django-cms,evildmp/django-cms,yakky/django-cms,takeshineshiro/django-cms,frnhr/django-cms,bittner/django-cms,rsalmaso/django-cms,petecummings/django-cms,isotoma/django-cms,cyberintruder/django-cms,irudayarajisawa/django-cms,Livefyre/django-cms,intip/django-cms,memnonila/django-cms,Vegasvikk/django-cms,iddqd1/django-cms,intip/django-cms,wyg3958/django-cms,evildmp/django-cms,SofiaReis/django-cms,netzkolchose/django-cms,petecummings/django-cms,liuyisiyisi/django-cms,saintbird/django-cms,netzkolchose/django-cms,jproffitt/django-cms,jeffreylu9/django-cms,philippze/django-cms,webu/django-cms,vxsx/django-cms,iddqd1/django-cms,andyzsf/django-cms,isotoma/django-cms,Jaccorot/django-cms,divio/django-cms,timgraham/django-cms,jsma/django-cms,rscnt/django-cms,chkir/django-cms,josjevv/django-cms,frnhr/django-cms,stefanfoulis/django-cms,memnonila/django-cms,irudayarajisawa/django-cms,farhaadila/django-cms,keimlink/django-cms,AlexProfi/django-cms,webu/django-cms,robmagee/django-cms,irudayarajisawa/django-cms,FinalAngel/django-cms,dhorelik/django-cms,sephii/django-cms,philippze/django-cms,webu/django-cms,Livefyre/django-cms,sephii/django-cms,intip/django-cms
--- +++ @@ -9,6 +9,8 @@ return type(o)((esc(k), self._recursive_escape(v)) for (k, v) in o.iteritems()) if isinstance(o, (list, tuple)): return type(o)(self._recursive_escape(v) for v in o) + if type(o) is bool: + return o try: return type(o)(esc(o)) except ValueError:
ad2ec120cb890de622d54f61104353c9427c788a
src/sentry/rules/__init__.py
src/sentry/rules/__init__.py
""" sentry.rules ~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import from .base import * # NOQA from .registry import RuleRegistry # NOQA def init_registry(): from sentry.constants import SENTRY_RULES from sentry.plugins import plugins from sentry.utils.imports import import_string from sentry.utils.safe import safe_execute registry = RuleRegistry() for rule in SENTRY_RULES: cls = import_string(rule) registry.add(cls) for plugin in plugins.all(version=2): for cls in (safe_execute(plugin.get_rules) or ()): register.add(cls) return registry rules = init_registry()
""" sentry.rules ~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import from .base import * # NOQA from .registry import RuleRegistry # NOQA def init_registry(): from sentry.constants import SENTRY_RULES from sentry.plugins import plugins from sentry.utils.imports import import_string from sentry.utils.safe import safe_execute registry = RuleRegistry() for rule in SENTRY_RULES: cls = import_string(rule) registry.add(cls) for plugin in plugins.all(version=2): for cls in (safe_execute(plugin.get_rules) or ()): registry.add(cls) return registry rules = init_registry()
Correct rules registry addition via plugin (refs GH-2404)
Correct rules registry addition via plugin (refs GH-2404)
Python
bsd-3-clause
JamesMura/sentry,looker/sentry,jean/sentry,fotinakis/sentry,ifduyue/sentry,alexm92/sentry,fotinakis/sentry,mvaled/sentry,gencer/sentry,gencer/sentry,zenefits/sentry,ifduyue/sentry,BuildingLink/sentry,gencer/sentry,beeftornado/sentry,ifduyue/sentry,jean/sentry,BuildingLink/sentry,fotinakis/sentry,daevaorn/sentry,JamesMura/sentry,JackDanger/sentry,zenefits/sentry,gencer/sentry,nicholasserra/sentry,mvaled/sentry,mitsuhiko/sentry,mvaled/sentry,ifduyue/sentry,mvaled/sentry,JamesMura/sentry,zenefits/sentry,ifduyue/sentry,daevaorn/sentry,nicholasserra/sentry,daevaorn/sentry,jean/sentry,looker/sentry,BuildingLink/sentry,looker/sentry,zenefits/sentry,jean/sentry,daevaorn/sentry,JamesMura/sentry,JackDanger/sentry,alexm92/sentry,BuildingLink/sentry,beeftornado/sentry,JackDanger/sentry,looker/sentry,mvaled/sentry,BuildingLink/sentry,nicholasserra/sentry,looker/sentry,zenefits/sentry,mvaled/sentry,fotinakis/sentry,jean/sentry,beeftornado/sentry,alexm92/sentry,gencer/sentry,mitsuhiko/sentry,JamesMura/sentry
--- +++ @@ -24,7 +24,7 @@ registry.add(cls) for plugin in plugins.all(version=2): for cls in (safe_execute(plugin.get_rules) or ()): - register.add(cls) + registry.add(cls) return registry
f74f46e4a3222fe0f6e10e38c204d2e3108bbf18
git_reviewers/reviewers.py
git_reviewers/reviewers.py
#!/usr/bin/env python3 try: import configparser except ImportError: raise ImportError("Must be using Python 3") import argparse import os import subprocess UBER=True def extract_username(shortlog): shortlog = shortlog.strip() email = shortlog[shortlog.rfind("<")+1:] email = email[:email.find(">")] if UBER: if email[-9:] == '@uber.com': return email[:-9] else: return None return email def get_reviewers(): reviewers = [] git_shortlog_command = ['git', 'shortlog', '-sne'] process = subprocess.run(git_shortlog_command, stdout=subprocess.PIPE) git_shortlog = process.stdout.decode("utf-8").split("\n") reviewers = [extract_username(shortlog) for shortlog in git_shortlog] reviewers = [username for username in reviewers if username] return reviewers def show_reviewers(reviewers): print(", ".join(reviewers)) def main(): description = "Suggest reviewers for your diff.\n" description += "https://github.com/albertyw/git-reviewers" parser = argparse.ArgumentParser(description=description) args = parser.parse_args() reviewers = get_reviewers() show_reviewers(reviewers) if __name__ == "__main__": main()
Add basic script to get most common committers
Add basic script to get most common committers
Python
mit
albertyw/git-reviewers,albertyw/git-reviewers
--- +++ @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 + +try: + import configparser +except ImportError: + raise ImportError("Must be using Python 3") + +import argparse +import os +import subprocess + + +UBER=True + + +def extract_username(shortlog): + shortlog = shortlog.strip() + email = shortlog[shortlog.rfind("<")+1:] + email = email[:email.find(">")] + if UBER: + if email[-9:] == '@uber.com': + return email[:-9] + else: + return None + return email + + +def get_reviewers(): + reviewers = [] + git_shortlog_command = ['git', 'shortlog', '-sne'] + process = subprocess.run(git_shortlog_command, stdout=subprocess.PIPE) + git_shortlog = process.stdout.decode("utf-8").split("\n") + reviewers = [extract_username(shortlog) for shortlog in git_shortlog] + reviewers = [username for username in reviewers if username] + return reviewers + + +def show_reviewers(reviewers): + print(", ".join(reviewers)) + +def main(): + description = "Suggest reviewers for your diff.\n" + description += "https://github.com/albertyw/git-reviewers" + parser = argparse.ArgumentParser(description=description) + args = parser.parse_args() + + reviewers = get_reviewers() + show_reviewers(reviewers) + + +if __name__ == "__main__": + main()
ce25be4609f6206343cdcb34b5342843f09f557b
server.py
server.py
from flask import Flask from SPARQLWrapper import SPARQLWrapper, JSON from flask import request, jsonify from flask.ext.cors import CORS app = Flask(__name__) CORS(app) @app.route('/') def hello_world(): auth = request.authorization query = request.args.get('query') if not auth is None and not query is None: sparql = SPARQLWrapper('https://knowledgestore2.fbk.eu/nwr/dutchhouse/sparql') sparql.setQuery(query) sparql.setCredentials(auth.username, auth.password) sparql.setReturnFormat(JSON) results = sparql.query().convert() return jsonify(**results) else: msg = [] if auth is None: msg.append('authorization error') if query is None: msg.append('no query') response = jsonify({'status': 404, 'statusText': ' '.join(msg)}) response.status_code = 404 return response if __name__ == '__main__': app.run()
from flask import Flask from SPARQLWrapper import SPARQLWrapper, JSON from flask import request, jsonify from flask.ext.cors import CORS app = Flask(__name__) CORS(app) @app.route('/') def hello_world(): return 'hello world' @app.route('/sparql') def do_sparql(): auth = request.authorization query = request.args.get('query') if not auth is None and not query is None: sparql = SPARQLWrapper('https://knowledgestore2.fbk.eu/nwr/dutchhouse/sparql') sparql.setQuery(query) sparql.setCredentials(auth.username, auth.password) sparql.setReturnFormat(JSON) results = sparql.query().convert() return jsonify(**results) else: msg = [] if auth is None: msg.append('authorization error') if query is None: msg.append('no query') response = jsonify({'status': 404, 'statusText': ' '.join(msg)}) response.status_code = 404 return response if __name__ == '__main__': app.run()
Add test route for heroku
Add test route for heroku
Python
apache-2.0
jvdzwaan/visun-flask
--- +++ @@ -8,6 +8,10 @@ @app.route('/') def hello_world(): + return 'hello world' + +@app.route('/sparql') +def do_sparql(): auth = request.authorization query = request.args.get('query')
99be36b77741a9b2e3d330eb89e0e381b3a3081f
api.py
api.py
import json from os import environ from eve import Eve from eve.io.mongo import Validator from settings import API_NAME, URL_PREFIX class KeySchemaValidator(Validator): def _validate_keyschema(self, schema, field, dct): "Validate all keys of dictionary `dct` against schema `schema`." for key, value in dct.items(): self._validate_schema(schema, key, value) api = Eve(API_NAME, validator=KeySchemaValidator) def add_document(resource, document): "Add a new document to the given resource." return api.test_client().post('/' + URL_PREFIX + '/' + resource, data=json.dumps(document), content_type='application/json') if __name__ == '__main__': # Heroku support: bind to PORT if defined, otherwise default to 5000. if 'PORT' in environ: port = int(environ.get('PORT')) host = '0.0.0.0' else: port = 5000 host = '127.0.0.1' api.run(host=host, port=port)
import json from os import environ from eve import Eve from eve.io.mongo import Validator from settings import API_NAME, URL_PREFIX class KeySchemaValidator(Validator): def _validate_keyschema(self, schema, field, dct): "Validate all keys of dictionary `dct` against schema `schema`." for key, value in dct.items(): self._validate_schema(schema, key, value) api = Eve(API_NAME, validator=KeySchemaValidator) def add_document(resource, document): "Add a new document to the given resource." return api.test_client().post('/' + URL_PREFIX + '/' + resource, data=json.dumps(document), content_type='application/json') def delete_resource(resource): "Delete all documents of the given resource." return api.test_client().delete('/' + URL_PREFIX + '/' + resource) if __name__ == '__main__': # Heroku support: bind to PORT if defined, otherwise default to 5000. if 'PORT' in environ: port = int(environ.get('PORT')) host = '0.0.0.0' else: port = 5000 host = '127.0.0.1' api.run(host=host, port=port)
Add utility method to delete all documents of given resource
Add utility method to delete all documents of given resource
Python
apache-2.0
gwob/Maarifa,gwob/Maarifa,gwob/Maarifa,gwob/Maarifa,gwob/Maarifa
--- +++ @@ -22,6 +22,11 @@ data=json.dumps(document), content_type='application/json') + +def delete_resource(resource): + "Delete all documents of the given resource." + return api.test_client().delete('/' + URL_PREFIX + '/' + resource) + if __name__ == '__main__': # Heroku support: bind to PORT if defined, otherwise default to 5000. if 'PORT' in environ:
6be8e85b17d390abea25897bd7a2703fb3300261
app.py
app.py
import logging import os import tornado.ioloop import tornado.log import tornado.web def configure_tornado_logging(): fh = logging.handlers.RotatingFileHandler( '/var/log/ipborg/tornado.log', maxBytes=2**29, backupCount=10) fmt = logging.Formatter('%(asctime)s:%(levelname)s:%(name)s:%(message)s') fh.setFormatter(fmt) logger = logging.getLogger('tornado') logger.setLevel(logging.DEBUG) logger.addHandler(fh) tornado.log.enable_pretty_logging(logger=logger) configure_tornado_logging() class MainHandler(tornado.web.RequestHandler): def get(self): self.write('{}'.format(os.environ.get('MC_PORT'))) application = tornado.web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
import logging import os import tornado.ioloop import tornado.log import tornado.options import tornado.web tornado.options.define('tornado_log_file', default='/var/log/ipborg/torando.log', type=str) tornado.options.define('app_log_file', default='/var/log/ipborg/app.log', type=str) tornado.options.parse_command_line() def configure_tornado_logging(): fh = logging.handlers.RotatingFileHandler( tornado.options.options.tornado_log_file, maxBytes=2**29, backupCount=10) fmt = logging.Formatter('%(asctime)s:%(levelname)s:%(name)s:%(message)s') fh.setFormatter(fmt) logger = logging.getLogger('tornado') logger.setLevel(logging.DEBUG) logger.addHandler(fh) tornado.log.enable_pretty_logging(logger=logger) configure_tornado_logging() settings = { 'static_path': os.path.join(os.path.dirname(__file__), 'static'), 'template_path': os.path.join(os.path.dirname(__file__), 'templates'), 'debug': True, 'gzip': True } class MainHandler(tornado.web.RequestHandler): def get(self): self.write('{}'.format(os.environ.get('MC_PORT'))) application = tornado.web.Application([ (r"/", MainHandler), ], **settings) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
Add Tornado settings and log location command line options.
Add Tornado settings and log location command line options.
Python
mit
jiffyclub/ipythonblocks.org,jiffyclub/ipythonblocks.org
--- +++ @@ -3,12 +3,23 @@ import tornado.ioloop import tornado.log +import tornado.options import tornado.web + + +tornado.options.define('tornado_log_file', + default='/var/log/ipborg/torando.log', + type=str) +tornado.options.define('app_log_file', + default='/var/log/ipborg/app.log', + type=str) +tornado.options.parse_command_line() def configure_tornado_logging(): fh = logging.handlers.RotatingFileHandler( - '/var/log/ipborg/tornado.log', maxBytes=2**29, backupCount=10) + tornado.options.options.tornado_log_file, + maxBytes=2**29, backupCount=10) fmt = logging.Formatter('%(asctime)s:%(levelname)s:%(name)s:%(message)s') fh.setFormatter(fmt) @@ -21,13 +32,23 @@ configure_tornado_logging() +settings = { + 'static_path': os.path.join(os.path.dirname(__file__), 'static'), + 'template_path': os.path.join(os.path.dirname(__file__), 'templates'), + 'debug': True, + 'gzip': True +} + + class MainHandler(tornado.web.RequestHandler): def get(self): self.write('{}'.format(os.environ.get('MC_PORT'))) + application = tornado.web.Application([ (r"/", MainHandler), -]) +], **settings) + if __name__ == "__main__": application.listen(8888)
fea4ef7bc124da42c00989d8e4d69ff463854f02
bot.py
bot.py
#! /usr/bin/env python from time import gmtime, strftime from foaas import foaas from diaspy_client import Client import re import urllib2 client = Client() notify = client.notifications() for n in notify: if not n.unread: continue idm = re.search('href=\\"/posts/(\d+?)\\"', n._data['note_html']) if hasattr(idm, 'group'): post_id = idm.group(1) text = client.getPostText(post_id) m = re.search('^\s*\@\{[^\};]+;[^\};]+\}\s+(\/.+?)$', text) if hasattr(m, 'group'): try: command = m.group(1) client.post(foaas(command)) except urllib2.URLError: client.comment(post_id, "Fuck this! Something went wrong :\\") # mark as read if it # is not a mention n.mark() client.logout()
#! /usr/bin/env python from time import gmtime, strftime from foaas import foaas from diaspy_client import Client import re import urllib2 client = Client() notify = client.notifications() for n in notify: if not n.unread: continue idm = re.search('href=\\"/posts/(\d+?)\\"', n._data['note_html']) if hasattr(idm, 'group'): post_id = idm.group(1) text = client.getPostText(post_id) m = re.search('^\s*\@\{[^\};]+;[^\};]+\}\s+(\/.+?)$', text) if hasattr(m, 'group'): try: command = m.group(1) client.post(foaas(command)) except urllib2.URLError: client.comment(post_id, "Fuck this! Something went wrong :\\") else: client.comment(post_id, "Fuck this! Your command is not well-formed.\n" "Check my profile description or " "[fuck around with him...](/posts/0f99d95040130133bbca14dae9b624ce)") # mark as read if it # is not a mention n.mark() client.logout()
Add helper on not-well-formed commands
Add helper on not-well-formed commands
Python
mit
Zauberstuhl/foaasBot
--- +++ @@ -23,6 +23,11 @@ client.post(foaas(command)) except urllib2.URLError: client.comment(post_id, "Fuck this! Something went wrong :\\") + else: + client.comment(post_id, + "Fuck this! Your command is not well-formed.\n" + "Check my profile description or " + "[fuck around with him...](/posts/0f99d95040130133bbca14dae9b624ce)") # mark as read if it # is not a mention
b8aaaeb454f933b642bcd3a5a5931ca0286addd2
api.py
api.py
import simplejson as json import os import sys import urllib2 from pprint import pprint from collections import defaultdict from flask import Flask, render_template, request, jsonify, redirect import time api = Flask(__name__) @api.route("/api") def index(): return "API stats" @api.route("/api/comment/ipsum/twitter/<source>") def ipsum_from_twitter(): pass @api.route("/api/comment/reddit/<source>") def ipsum_from_reddit(): pass if __name__ == "__main__": app.run(debug=True, host='0.0.0.0')
from flask import Flask, render_template, request, jsonify, redirect import reddit api = Flask(__name__) @api.route("/api") def index(): return "API stats" @api.route("/api/comment/ipsum/twitter/<source>") def ipsum_from_twitter(): pass @api.route("/api/comment/reddit", methods=["POST"]) def ipsum_from_reddit(): data = request.form count = data.get("count") count_type = data.get("count_type") source = data.get("source") if count and count_type and source: comments = reddit.get_comments_from_short_url(source) comments_text = reddit.get_text_from_comments(int(count), count_type, comments) text = reddit.get_jumbled_text(comments_text) output = {"text": text} return jsonify(**output) if __name__ == "__main__": api.run(debug=True, host='0.0.0.0')
Add reddit endpoint to API
Add reddit endpoint to API
Python
mit
captainsafia/dont-read-the-ipsum,captainsafia/dont-read-the-ipsum,captainsafia/dont-read-the-ipsum
--- +++ @@ -1,11 +1,5 @@ -import simplejson as json -import os -import sys -import urllib2 -from pprint import pprint -from collections import defaultdict from flask import Flask, render_template, request, jsonify, redirect -import time +import reddit api = Flask(__name__) @@ -17,9 +11,20 @@ def ipsum_from_twitter(): pass -@api.route("/api/comment/reddit/<source>") +@api.route("/api/comment/reddit", methods=["POST"]) def ipsum_from_reddit(): - pass + data = request.form + count = data.get("count") + count_type = data.get("count_type") + source = data.get("source") + + if count and count_type and source: + comments = reddit.get_comments_from_short_url(source) + comments_text = reddit.get_text_from_comments(int(count), + count_type, comments) + text = reddit.get_jumbled_text(comments_text) + output = {"text": text} + return jsonify(**output) if __name__ == "__main__": - app.run(debug=True, host='0.0.0.0') + api.run(debug=True, host='0.0.0.0')
4c2c0e9da70459063c6f1f682a181e4d350e853c
do_the_tests.py
do_the_tests.py
# pop the current directory from search path # python interpreter adds this to a top level script # but we will likely have a name conflict (runtests.py .vs runtests package) import sys; sys.path.pop(0) from runtests import Tester import os.path tester = Tester(os.path.abspath(__file__), "fake_spectra") tester.main(sys.argv[1:])
from runtests import Tester import os.path tester = Tester(os.path.abspath(__file__), "fake_spectra") tester.main(sys.argv[1:])
Remove now not needed path munging
Remove now not needed path munging
Python
mit
sbird/fake_spectra,sbird/fake_spectra,sbird/fake_spectra
--- +++ @@ -1,7 +1,3 @@ -# pop the current directory from search path -# python interpreter adds this to a top level script -# but we will likely have a name conflict (runtests.py .vs runtests package) -import sys; sys.path.pop(0) from runtests import Tester import os.path
eb8862c6048dea7612bdb808156b42792669d61a
apps/bplan/models.py
apps/bplan/models.py
from django.contrib.auth.models import AnonymousUser from django.db import models from adhocracy4.models.base import TimeStampedModel from adhocracy4.modules import models as module_models from apps.extprojects.models import ExternalProject class Bplan(ExternalProject): office_worker_email = models.EmailField() class AnonymousItem(TimeStampedModel): module = models.ForeignKey(module_models.Module, on_delete=models.CASCADE) @property def project(self): return self.module.project @property def creator(self): return AnonymousUser() @creator.setter def creator(self, value): pass class Meta: abstract = True class Statement(AnonymousItem): name = models.CharField(max_length=255) email = models.EmailField(blank=True) statement = models.TextField(max_length=17500) street_number = models.CharField(max_length=255) postal_code_city = models.CharField(max_length=255)
from django.contrib.auth.models import AnonymousUser from django.db import models from django.utils.translation import ugettext_lazy as _ from adhocracy4.models.base import TimeStampedModel from adhocracy4.modules import models as module_models from apps.extprojects.models import ExternalProject class Bplan(ExternalProject): office_worker_email = models.EmailField() class AnonymousItem(TimeStampedModel): module = models.ForeignKey(module_models.Module, on_delete=models.CASCADE) @property def project(self): return self.module.project @property def creator(self): return AnonymousUser() @creator.setter def creator(self, value): pass class Meta: abstract = True class Statement(AnonymousItem): name = models.CharField(max_length=255, verbose_name=_('Your Name')) email = models.EmailField(blank=True, verbose_name=_('Email address')) statement = models.TextField(max_length=17500, verbose_name=_('Statement')) street_number = models.CharField(max_length=255, verbose_name=_('Street, House number')) postal_code_city = models.CharField(max_length=255, verbose_name=_('Postal code, City'))
Add bplan model field verbose names
Add bplan model field verbose names
Python
agpl-3.0
liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin
--- +++ @@ -1,5 +1,6 @@ from django.contrib.auth.models import AnonymousUser from django.db import models +from django.utils.translation import ugettext_lazy as _ from adhocracy4.models.base import TimeStampedModel from adhocracy4.modules import models as module_models @@ -31,9 +32,14 @@ class Statement(AnonymousItem): - name = models.CharField(max_length=255) - email = models.EmailField(blank=True) - statement = models.TextField(max_length=17500) + name = models.CharField(max_length=255, + verbose_name=_('Your Name')) + email = models.EmailField(blank=True, + verbose_name=_('Email address')) + statement = models.TextField(max_length=17500, + verbose_name=_('Statement')) - street_number = models.CharField(max_length=255) - postal_code_city = models.CharField(max_length=255) + street_number = models.CharField(max_length=255, + verbose_name=_('Street, House number')) + postal_code_city = models.CharField(max_length=255, + verbose_name=_('Postal code, City'))
563eb0c209a0cc75742d8acbae5dd6053e60636c
apps/welcome/urls.py
apps/welcome/urls.py
from django.conf.urls.defaults import * from django.core.urlresolvers import reverse # Smrtr # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^1$', 'welcome.views.profile', name='welcome-1' ), url(r'^2$', 'network.views.search', {'next': '/'}, name='welcome-2' ), # Skip this so user gets the welcome message and instruction (keeps it easy to follow) #url(r'^3$', 'challenge.views.challenge_search', {'next': '/'}, name='welcome-3' ) )
from django.conf.urls.defaults import * from django.core.urlresolvers import reverse # Smrtr # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^1$', 'welcome.views.profile', name='welcome-1' ), #url(r'^2$', 'network.views.search', {'next': '/'}, name='welcome-2' ), # Skip this so user gets the welcome message and instruction (keeps it easy to follow) url(r'^2$', 'challenge.views.search', {'next': '/'}, name='welcome-2' ) )
Remove networks from welcome activation, replace with challenges
Remove networks from welcome activation, replace with challenges
Python
bsd-3-clause
mfitzp/smrtr,mfitzp/smrtr
--- +++ @@ -10,8 +10,8 @@ urlpatterns = patterns('', url(r'^1$', 'welcome.views.profile', name='welcome-1' ), - url(r'^2$', 'network.views.search', {'next': '/'}, name='welcome-2' ), + #url(r'^2$', 'network.views.search', {'next': '/'}, name='welcome-2' ), # Skip this so user gets the welcome message and instruction (keeps it easy to follow) - #url(r'^3$', 'challenge.views.challenge_search', {'next': '/'}, name='welcome-3' ) + url(r'^2$', 'challenge.views.search', {'next': '/'}, name='welcome-2' ) )
0c5165bdddbce057cc4777d91cb1e4fc661b5925
zuora/transport.py
zuora/transport.py
""" Transport for Zuora SOAP API """ import httplib2 from suds.transport import Reply from suds.transport.http import HttpTransport from suds.transport.http import HttpAuthenticated class HttpTransportWithKeepAlive(HttpAuthenticated, object): def __init__(self): super(HttpTransportWithKeepAlive, self).__init__() self.http = httplib2.Http(timeout=5) def open(self, request): return HttpTransport.open(self, request) def send(self, request): headers, message = self.http.request(request.url, "POST", body=request.message, headers=request.headers) response = Reply(200, headers, message) return response
""" Transport for Zuora SOAP API """ import httplib2 from suds.transport import Reply from suds.transport.http import HttpTransport from suds.transport.http import HttpAuthenticated class HttpTransportWithKeepAlive(HttpAuthenticated, object): def __init__(self): super(HttpTransportWithKeepAlive, self).__init__() self.http = httplib2.Http(timeout=20) def open(self, request): return HttpTransport.open(self, request) def send(self, request): headers, message = self.http.request(request.url, "POST", body=request.message, headers=request.headers) response = Reply(200, headers, message) return response
Set timeout to 20 seconds
Set timeout to 20 seconds
Python
bsd-3-clause
liberation/zuora-client
--- +++ @@ -12,7 +12,7 @@ def __init__(self): super(HttpTransportWithKeepAlive, self).__init__() - self.http = httplib2.Http(timeout=5) + self.http = httplib2.Http(timeout=20) def open(self, request): return HttpTransport.open(self, request)
11f7c1ecadbbc68aa0a7d87570d25b24efb71fe6
tests/run/ass2global.py
tests/run/ass2global.py
""" >>> getg() 5 >>> setg(42) >>> getg() 42 """ g = 5 def setg(a): global g g = a def getg(): return g class Test(object): """ >>> global_in_class 9 >>> Test.global_in_class Traceback (most recent call last): AttributeError: type object 'Test' has no attribute 'global_in_class' >>> Test().global_in_class Traceback (most recent call last): AttributeError: 'Test' object has no attribute 'global_in_class' """ global global_in_class global_in_class = 9
# mode: run # tag: pyglobal """ >>> getg() 5 >>> getg() 5 >>> getg() 5 >>> setg(42) >>> getg() 42 >>> getg() 42 >>> getg() 42 """ g = 5 def setg(a): global g g = a def getg(): return g class Test(object): """ >>> global_in_class 9 >>> Test.global_in_class Traceback (most recent call last): AttributeError: type object 'Test' has no attribute 'global_in_class' >>> Test().global_in_class Traceback (most recent call last): AttributeError: 'Test' object has no attribute 'global_in_class' """ global global_in_class global_in_class = 9
Extend test to see if global name caching actually works.
Extend test to see if global name caching actually works.
Python
apache-2.0
cython/cython,cython/cython,da-woods/cython,da-woods/cython,da-woods/cython,cython/cython,cython/cython,scoder/cython,scoder/cython,da-woods/cython,scoder/cython,scoder/cython
--- +++ @@ -1,9 +1,20 @@ +# mode: run +# tag: pyglobal + """ - >>> getg() - 5 - >>> setg(42) - >>> getg() - 42 +>>> getg() +5 +>>> getg() +5 +>>> getg() +5 +>>> setg(42) +>>> getg() +42 +>>> getg() +42 +>>> getg() +42 """ g = 5
fbc4154aeabd644390b9abca1a2382c0cc4298e0
app.py
app.py
from flask import Flask from flask import render_template from queries import get_filenames, get_metadata app = Flask(__name__) @app.route("/") @app.route("/<item>") def index(item="002341336"): files = get_filenames(item) metadata = get_metadata(item) return render_template("landing.html", file_id=item, files=files, metadata=metadata) if __name__ == "__main__": app.run(debug=True)
from flask import Flask from flask import render_template from queries import get_filenames, get_metadata app = Flask(__name__) @app.route("/") @app.route("/<item>") def index(item="002341336"): files = sorted(get_filenames(item)) print files metadata = get_metadata(item) return render_template("landing.html", file_id=item, files=files, metadata=metadata) if __name__ == "__main__": app.run(debug=True)
Sort file names so they are displayed in alpha order
Sort file names so they are displayed in alpha order
Python
mit
MITLibraries/ebooks,MITLibraries/ebooks
--- +++ @@ -8,7 +8,8 @@ @app.route("/") @app.route("/<item>") def index(item="002341336"): - files = get_filenames(item) + files = sorted(get_filenames(item)) + print files metadata = get_metadata(item) return render_template("landing.html", file_id=item, files=files, metadata=metadata)
c9ba5f2e402b46036f0b9a86bf34ac94db51edfb
server.py
server.py
from flask import Flask from flask import render_template import argparse import games import json GAMES_COUNT = 100 app = Flask(__name__) @app.route("/") def index(): return render_template('games_list.html') @app.route("/api/") def games_api(): return json.dumps(game_list) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("players", type=file, help="JSON file with a list of players") args = parser.parse_args() with args.players as players_file: players = json.load(players_file) game_gen = games.game_data(players, GAMES_COUNT) game_list = list(game_gen) app.run(debug=True)
from flask import Flask from flask import render_template from flask import request import argparse import games import json GAMES_COUNT = 100 app = Flask(__name__) @app.route("/") def index(): return render_template('games_list.html') @app.route("/api/") def games_api(): limit = request.args.get('limit') or GAMES_COUNT skip = request.args.get('skip') or 0 return json.dumps(game_list[int(skip):int(skip)+int(limit)]) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("players", type=file, help="JSON file with a list of players") args = parser.parse_args() with args.players as players_file: players = json.load(players_file) game_gen = games.game_data(players, GAMES_COUNT) game_list = list(game_gen) app.run(debug=True)
Use query parameters to limit results
Use query parameters to limit results
Python
bsd-3-clause
siggame/ng-games,siggame/ng-games,siggame/ng-games
--- +++ @@ -1,5 +1,6 @@ from flask import Flask from flask import render_template +from flask import request import argparse import games @@ -19,7 +20,9 @@ @app.route("/api/") def games_api(): - return json.dumps(game_list) + limit = request.args.get('limit') or GAMES_COUNT + skip = request.args.get('skip') or 0 + return json.dumps(game_list[int(skip):int(skip)+int(limit)]) if __name__ == "__main__":
98550946e8bc0da9a1ecdec8f0e53490f8fd5e91
conftest.py
conftest.py
import shutil import pytest try: import six except ImportError: from django.utils import six from django.conf import settings def teardown_assets_directory(): # Removing the temporary TEMP_DIR. Ensure we pass in unicode # so that it will successfully remove temp trees containing # non-ASCII filenames on Windows. (We're assuming the temp dir # name itself does not contain non-ASCII characters.) shutil.rmtree(six.text_type(settings.TEMP_DIR)) @pytest.fixture(scope="session", autouse=True) def assets_directory(request): request.addfinalizer(teardown_assets_directory)
import shutil import pytest try: import six except ImportError: from django.utils import six from django.conf import settings def teardown_assets_directory(): # Removing the temporary TEMP_DIR. Ensure we pass in unicode # so that it will successfully remove temp trees containing # non-ASCII filenames on Windows. (We're assuming the temp dir # name itself does not contain non-ASCII characters.) shutil.rmtree(six.text_type(settings.TEMP_DIR)) @pytest.fixture(scope="session", autouse=True) def assets_directory(request): request.addfinalizer(teardown_assets_directory) def get_collect_ignore(): mapping = { 'widgy.contrib.widgy_mezzanine': ['widgy/contrib/widgy_mezzanine/'], 'widgy.contrib.form_builder': ['widgy/contrib/form_builder/'], 'widgy.contrib.page_builder': ['widgy/contrib/page_builder/'], 'widgy.contrib.urlconf_include': ['widgy/contrib/urlconf_include/'], 'widgy.contrib.widgy_i18n': ['widgy/contrib/urlconf_include/'], } acc = [] for app, path_list in mapping.items(): if app not in settings.INSTALLED_APPS: acc.extend(path_list) return acc collect_ignore = get_collect_ignore()
Make pytest autodiscover tests depending on the INSTALLED_APPS
Make pytest autodiscover tests depending on the INSTALLED_APPS
Python
apache-2.0
j00bar/django-widgy,j00bar/django-widgy,j00bar/django-widgy
--- +++ @@ -19,3 +19,22 @@ @pytest.fixture(scope="session", autouse=True) def assets_directory(request): request.addfinalizer(teardown_assets_directory) + + +def get_collect_ignore(): + mapping = { + 'widgy.contrib.widgy_mezzanine': ['widgy/contrib/widgy_mezzanine/'], + 'widgy.contrib.form_builder': ['widgy/contrib/form_builder/'], + 'widgy.contrib.page_builder': ['widgy/contrib/page_builder/'], + 'widgy.contrib.urlconf_include': ['widgy/contrib/urlconf_include/'], + 'widgy.contrib.widgy_i18n': ['widgy/contrib/urlconf_include/'], + } + + + acc = [] + for app, path_list in mapping.items(): + if app not in settings.INSTALLED_APPS: + acc.extend(path_list) + return acc + +collect_ignore = get_collect_ignore()
e6c91c06005c131805edeaf6b4980ff7f73b87b6
conftest.py
conftest.py
'''py.test standard config file.''' import sys # pylint: disable=invalid-name collect_ignore = ('setup.py',) # pylint: enable=invalid-name def pytest_cmdline_preparse(args): is_pylint_compatible = (2, 7) <= sys.version_info < (3, 5) if not is_pylint_compatible: args.remove('--pylint')
'''py.test standard config file.''' import sys # pylint: disable=invalid-name collect_ignore = ('setup.py',) # pylint: enable=invalid-name def pytest_cmdline_preparse(args): is_pylint_compatible = (2, 7) <= sys.version_info < (3, 6) if not is_pylint_compatible: args.remove('--pylint')
Raise supported Python version for currently pinned pylint
Raise supported Python version for currently pinned pylint
Python
bsd-3-clause
jvanasco/tldextract,john-kurkowski/tldextract
--- +++ @@ -9,6 +9,6 @@ # pylint: enable=invalid-name def pytest_cmdline_preparse(args): - is_pylint_compatible = (2, 7) <= sys.version_info < (3, 5) + is_pylint_compatible = (2, 7) <= sys.version_info < (3, 6) if not is_pylint_compatible: args.remove('--pylint')
7de22e999bb63cd83f8af6065638a97eeb3ba2d6
bongo/settings/travis.py
bongo/settings/travis.py
from prod import * # The same settings as production, but no database password. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'bongo_test', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '5432', }, } INSTALLED_APPS += ( 'django_nose', ) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' NOSE_ARGS = ['--with-fixture-bundling', '--nologcapture'] NOSE_TESTMATCH = '(?:^|[b_./-])[Tt]ests'
from prod import * # The same settings as production, but no database password. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'bongo_test', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '5432', }, } INSTALLED_APPS += ( 'django_nose', ) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' NOSE_ARGS = ['--with-fixture-bundling', '--nologcapture'] NOSE_TESTMATCH = '(?:^|[b_./-])[Tt]ests' RAVEN_CONFIG = { "dsn": "http://dd2c825ff9b1417d88a99573903ebf80:91631495b10b45f8a1cdbc492088da6a@localhost:9000/1", }
Throw this Raven DSN from the docs at Travis to make it shut up
Throw this Raven DSN from the docs at Travis to make it shut up
Python
mit
BowdoinOrient/bongo,BowdoinOrient/bongo,BowdoinOrient/bongo,BowdoinOrient/bongo
--- +++ @@ -22,3 +22,7 @@ NOSE_ARGS = ['--with-fixture-bundling', '--nologcapture'] NOSE_TESTMATCH = '(?:^|[b_./-])[Tt]ests' + +RAVEN_CONFIG = { + "dsn": "http://dd2c825ff9b1417d88a99573903ebf80:91631495b10b45f8a1cdbc492088da6a@localhost:9000/1", +}
9b4f83ec89c76d8a5b5d0502e2903e2821078271
logger.py
logger.py
#! /usr/bin/env python # logger.py """Log the serial output from the Arduino to a text file. """ import sys import serial def log_serial(filename, device='/dev/ttyACM0', baud=9600): ser = serial.Serial(device, baud) outfile = open(filename, 'w') while True: line = ser.readline() outfile.write(line) if __name__ == '__main__': filename = sys.argv[1] log_serial(filename)
#! /usr/bin/env python # logger.py """Log the serial output from the Arduino to a text file. """ import sys import serial def log_serial(filename, device='/dev/ttyACM0', baud=9600): ser = serial.Serial(device, baud) outfile = open(filename, 'w') while True: line = ser.readline() print(line) outfile.write(line) if __name__ == '__main__': filename = sys.argv[1] log_serial(filename)
Print lines that are logged
Print lines that are logged
Python
mit
wapcaplet/ardiff
--- +++ @@ -12,6 +12,7 @@ outfile = open(filename, 'w') while True: line = ser.readline() + print(line) outfile.write(line) if __name__ == '__main__':
723efad0416dbc16a3a7f94a62236673e60dc5a3
goodtablesio/utils/frontend.py
goodtablesio/utils/frontend.py
from flask import render_template from flask_login import current_user from goodtablesio import settings # Module API def render_component(component, props=None): """Render frontend component within html layout. Args: component (str): component name props (dict): component props Returns: str: rendered component """ filename = 'index.min.html' if settings.DEBUG: filename = 'index.html' if not props: props = {} # Common props if props == {} or (props and 'userName' not in props): user_name = getattr(current_user, 'display_name') if not user_name: user_name = getattr(current_user, 'name') props['userName'] = user_name return render_template( filename, component=component, props=props.copy(), google_analytics_code=settings.GOOGLE_ANALYTICS_CODE)
from flask import render_template from flask_login import current_user from goodtablesio import settings # Module API def render_component(component, props=None): """Render frontend component within html layout. Args: component (str): component name props (dict): component props Returns: str: rendered component """ filename = 'index.min.html' if settings.DEBUG: filename = 'index.html' if not props: props = {} # Common props if props == {} or (props and 'userName' not in props): user_name = getattr(current_user, 'display_name', None) if not user_name: user_name = getattr(current_user, 'name', None) props['userName'] = user_name return render_template( filename, component=component, props=props.copy(), google_analytics_code=settings.GOOGLE_ANALYTICS_CODE)
Handle users with no name
Handle users with no name
Python
agpl-3.0
frictionlessdata/goodtables.io,frictionlessdata/goodtables.io,frictionlessdata/goodtables.io,frictionlessdata/goodtables.io
--- +++ @@ -26,9 +26,9 @@ # Common props if props == {} or (props and 'userName' not in props): - user_name = getattr(current_user, 'display_name') + user_name = getattr(current_user, 'display_name', None) if not user_name: - user_name = getattr(current_user, 'name') + user_name = getattr(current_user, 'name', None) props['userName'] = user_name return render_template( filename, component=component, props=props.copy(),
5238fed5b5557b8a282a9120380eee01abb49bc5
fuzzers/038-cfg/add_constant_bits.py
fuzzers/038-cfg/add_constant_bits.py
import sys constant_bits = { "CFG_CENTER_MID.ALWAYS_ON_PROP1": "26_2206", "CFG_CENTER_MID.ALWAYS_ON_PROP2": "26_2207", "CFG_CENTER_MID.ALWAYS_ON_PROP3": "27_2205" } with open(sys.argv[1], "a") as f: for bit_name, bit_value in constant_bits.items(): f.write(bit_name + " " + bit_value + "\n")
""" Add bits that are considered always on to the db file. This script is Zynq specific. There are three bits that are present in all Zynq bitstreams. The investigation that was done to reach this conclusion is captured on GH (https://github.com/SymbiFlow/prjxray/issues/746) In brief, these bits seem to be bitstream properties related, but no evidence of this could be found. Due to the fact that the base address of these bits is the same as for the CFG_CENTER_MID tile it has been decided to append the bits to its db file. """ import sys constant_bits = { "CFG_CENTER_MID.ALWAYS_ON_PROP1": "26_2206", "CFG_CENTER_MID.ALWAYS_ON_PROP2": "26_2207", "CFG_CENTER_MID.ALWAYS_ON_PROP3": "27_2205" } with open(sys.argv[1], "a") as f: for bit_name, bit_value in constant_bits.items(): f.write(bit_name + " " + bit_value + "\n")
Add background to script's purpose
Add background to script's purpose Signed-off-by: Tomasz Michalak <a2fdaa543b4cc5e3d6cd8672ec412c0eb393b86e@antmicro.com>
Python
isc
SymbiFlow/prjxray,SymbiFlow/prjxray,SymbiFlow/prjxray,SymbiFlow/prjxray,SymbiFlow/prjxray
--- +++ @@ -1,3 +1,17 @@ +""" +Add bits that are considered always on to the db file. + +This script is Zynq specific. + +There are three bits that are present in all Zynq bitstreams. +The investigation that was done to reach this conclusion is captured on GH +(https://github.com/SymbiFlow/prjxray/issues/746) +In brief, these bits seem to be bitstream properties related, +but no evidence of this could be found. +Due to the fact that the base address of these bits is the same as for the +CFG_CENTER_MID tile it has been decided to append the bits to its db file. +""" + import sys constant_bits = {
9e67babf85a46128b96dd6818fa860447b4052e7
tests/integration/ssh/test_mine.py
tests/integration/ssh/test_mine.py
# -*- coding: utf-8 -*- # Import Python libs from __future__ import absolute_import # Import Salt Testing Libs from tests.support.case import SSHCase from tests.support.unit import skipIf # Import Salt Libs import salt.utils @skipIf(salt.utils.is_windows(), 'salt-ssh not available on Windows') class SSHMineTest(SSHCase): ''' testing salt-ssh with mine ''' def test_ssh_mine_get(self): ''' test salt-ssh with mine ''' ret = self.run_function('mine.get', ['localhost test.arg'], wipe=False) self.assertEqual(ret['localhost']['args'], ['itworked'])
# -*- coding: utf-8 -*- # Import Python libs from __future__ import absolute_import import os import shutil # Import Salt Testing Libs from tests.support.case import SSHCase from tests.support.unit import skipIf # Import Salt Libs import salt.utils @skipIf(salt.utils.is_windows(), 'salt-ssh not available on Windows') class SSHMineTest(SSHCase): ''' testing salt-ssh with mine ''' def test_ssh_mine_get(self): ''' test salt-ssh with mine ''' ret = self.run_function('mine.get', ['localhost test.arg'], wipe=False) self.assertEqual(ret['localhost']['args'], ['itworked']) def tearDown(self): ''' make sure to clean up any old ssh directories ''' salt_dir = self.run_function('config.get', ['thin_dir'], wipe=False) if os.path.exists(salt_dir): shutil.rmtree(salt_dir)
Add teardown to remove ssh dir
Add teardown to remove ssh dir
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -2,6 +2,8 @@ # Import Python libs from __future__ import absolute_import +import os +import shutil # Import Salt Testing Libs from tests.support.case import SSHCase @@ -22,3 +24,11 @@ ''' ret = self.run_function('mine.get', ['localhost test.arg'], wipe=False) self.assertEqual(ret['localhost']['args'], ['itworked']) + + def tearDown(self): + ''' + make sure to clean up any old ssh directories + ''' + salt_dir = self.run_function('config.get', ['thin_dir'], wipe=False) + if os.path.exists(salt_dir): + shutil.rmtree(salt_dir)
13e4d867e724f408b5d2dd21888b2f8a28d8fbc6
fabfile.py
fabfile.py
# -*- coding: utf-8 -* """ Simple fabric file to test oinspect output """ from __future__ import print_function import webbrowser import oinspect.sphinxify as oi def test_basic(): """Test with an empty context""" docstring = 'A test' content = oi.sphinxify(docstring, oi.generate_context()) page_name = '/tmp/test_basic.html' with open(page_name, 'w') as f: f.write(content) webbrowser.open_new_tab(page_name) def run_all(): """Run all tests""" test_basic()
# -*- coding: utf-8 -* """ Simple fabric file to test oinspect output """ from __future__ import print_function import webbrowser import oinspect.sphinxify as oi def _show_page(content, fname): with open(fname, 'w') as f: f.write(content) webbrowser.open_new_tab(fname) def test_basic(): """Test with an empty context""" docstring = 'A test' content = oi.sphinxify(docstring, oi.generate_context()) _show_page(content, '/tmp/test_basic.html') def test_math(): """Test a docstring with Latex on it""" docstring = 'This is a rational number :math:`\\frac{x}{y}`' content = oi.sphinxify(docstring, oi.generate_context()) _show_page(content, '/tmp/test_math.html') def run_all(): """Run all tests""" test_basic()
Add a test for math
Add a test for math
Python
bsd-3-clause
techtonik/docrepr,spyder-ide/docrepr,techtonik/docrepr,techtonik/docrepr,spyder-ide/docrepr,spyder-ide/docrepr
--- +++ @@ -10,14 +10,22 @@ import oinspect.sphinxify as oi +def _show_page(content, fname): + with open(fname, 'w') as f: + f.write(content) + webbrowser.open_new_tab(fname) + def test_basic(): """Test with an empty context""" docstring = 'A test' content = oi.sphinxify(docstring, oi.generate_context()) - page_name = '/tmp/test_basic.html' - with open(page_name, 'w') as f: - f.write(content) - webbrowser.open_new_tab(page_name) + _show_page(content, '/tmp/test_basic.html') + +def test_math(): + """Test a docstring with Latex on it""" + docstring = 'This is a rational number :math:`\\frac{x}{y}`' + content = oi.sphinxify(docstring, oi.generate_context()) + _show_page(content, '/tmp/test_math.html') def run_all(): """Run all tests"""
c7ee6f0094535aa0ea37becfc4e9403a3d511304
tests/src/core/views/test_index.py
tests/src/core/views/test_index.py
#/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2010-2012 Cidadania S. Coop. Galega # # This file is part of e-cidadania. # # e-cidadania 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. # # e-cidadania 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 e-cidadania. If not, see <http://www.gnu.org/licenses/>. from tests.test_utils import ECDTestCase class IndexTestCase(ECDTestCase): """Class to test index related views. """ def testIndexView(self): """Tests the index view. """ #url = self.getUrl(url_names.SITE_INDEX) url = '/' response = self.get(url) self.assertResponseOK(response)
#/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2010-2012 Cidadania S. Coop. Galega # # This file is part of e-cidadania. # # e-cidadania 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. # # e-cidadania 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 e-cidadania. If not, see <http://www.gnu.org/licenses/>. from e_cidadania import url_names from tests.test_utils import ECDTestCase class IndexTestCase(ECDTestCase): """Class to test index related views. """ def testIndexView(self): """Tests the index view. """ response = self.get(url_name=url_names.SITE_INDEX) self.assertResponseOK(response) def testIndexEntriesFeed(self): """Tests the index entries feed view. """ response = self.get(url_name=url_names.SITE_FEED) self.assertResponseOK(response)
Add tests for core.views.index.py. The tests presently test only if the corresponding urls can be accessed.
Add tests for core.views.index.py. The tests presently test only if the corresponding urls can be accessed.
Python
apache-2.0
cidadania/e-cidadania,cidadania/e-cidadania
--- +++ @@ -18,11 +18,12 @@ # You should have received a copy of the GNU General Public License # along with e-cidadania. If not, see <http://www.gnu.org/licenses/>. +from e_cidadania import url_names from tests.test_utils import ECDTestCase -class IndexTestCase(ECDTestCase): +class IndexTestCase(ECDTestCase): """Class to test index related views. """ @@ -30,7 +31,12 @@ """Tests the index view. """ - #url = self.getUrl(url_names.SITE_INDEX) - url = '/' - response = self.get(url) + response = self.get(url_name=url_names.SITE_INDEX) self.assertResponseOK(response) + + def testIndexEntriesFeed(self): + """Tests the index entries feed view. + """ + + response = self.get(url_name=url_names.SITE_FEED) + self.assertResponseOK(response)
f9eeb75292f9a3f134f4b33849ee2d6a51bc4e4e
jasylibrary.py
jasylibrary.py
#import os, json #from jasy.core.Util import executeCommand #import jasy.core.Console as Console #import urllib.parse # Little helper to allow python modules in current jasylibrarys path import sys, os.path, inspect filename = inspect.getframeinfo(inspect.currentframe()).filename path = os.path.dirname(os.path.abspath(filename)) sys.path.append(path) import konstrukteur.Konstrukteur import jasy.asset.Manager @share def build(profile, regenerate = False): """ Build static website """ def getPartUrl(part, type): folder = "" if type == "css": folder = profile.getCssFolder() outputPath = folder #os.path.join(profile.getDestinationPath(), folder) filename = profile.expandFileName("%s/%s-{{id}}.%s" % (outputPath, part, type)) return filename session.addCommand("part.url", getPartUrl, "url") for permutation in profile.permutate(): konstrukteur.Konstrukteur.build(regenerate, profile)
#import os, json #from jasy.core.Util import executeCommand #import jasy.core.Console as Console #import urllib.parse # Little helper to allow python modules in current jasylibrarys path import sys, os.path, inspect filename = inspect.getframeinfo(inspect.currentframe()).filename path = os.path.dirname(os.path.abspath(filename)) sys.path.append(path) import konstrukteur.Konstrukteur import jasy.asset.Manager @share def build(profile, regenerate = False): """ Build static website """ def getPartUrl(part, type): folder = "" if type == "css": folder = profile.getCssFolder() outputPath = folder #os.path.join(profile.getDestinationPath(), folder) filename = profile.expandFileName("%s/%s-{{id}}.%s" % (outputPath, part, type)) return filename profile.addCommand("part.url", getPartUrl, "url") for permutation in profile.permutate(): konstrukteur.Konstrukteur.build(regenerate, profile)
Add part loading command on profile instead of session
Add part loading command on profile instead of session
Python
mit
fastner/konstrukteur,fastner/konstrukteur,fastner/konstrukteur
--- +++ @@ -25,7 +25,7 @@ filename = profile.expandFileName("%s/%s-{{id}}.%s" % (outputPath, part, type)) return filename - session.addCommand("part.url", getPartUrl, "url") + profile.addCommand("part.url", getPartUrl, "url") for permutation in profile.permutate(): konstrukteur.Konstrukteur.build(regenerate, profile)
a04a5a80057e86af2c5df0e87a7d2c3c221123ae
rpc_server/CouchDBViewDefinitions.py
rpc_server/CouchDBViewDefinitions.py
definitions = ( { "doc": "basicStats", "view": "addCar", "map": """ function(doc) { // car creations for (var id in doc.cars){ if (doc.cars[id].state && doc.cars[id].state === 'add') { emit(id, {'time': doc.time}); } } }""" }, { "doc": "basicStats", "view": "deleteCar", "map": """ function(doc) { for (var id in doc.cars){ if (doc.cars[id].state && doc.cars[id].state === 'del') { emit(id, {'time': doc.time}); } } } """ } ,)
definitions = ( { "doc": "basicStats", "view": "addCar", "map": """ function(doc) { // car creations for (var id in doc.cars){ if (doc.cars[id].state && doc.cars[id].state === 'add') { emit(id, {'time': doc.time}); } } }""" }, { "doc": "basicStats", "view": "deleteCar", "map": """ function(doc) { for (var id in doc.cars){ if (doc.cars[id].state && doc.cars[id].state === 'del') { emit(id, {'time': doc.time}); } } } """ }, { "doc": "manage", "view": "jobs", "map": """ function(doc) { if (doc.type === 'job'){ emit(doc.name, doc._id); } } """ } ,)
Add view to get project jobs.
Add view to get project jobs.
Python
apache-2.0
anthony-kolesov/kts46,anthony-kolesov/kts46,anthony-kolesov/kts46,anthony-kolesov/kts46
--- +++ @@ -21,5 +21,15 @@ } } """ + }, + { + "doc": "manage", "view": "jobs", + "map": """ + function(doc) { + if (doc.type === 'job'){ + emit(doc.name, doc._id); + } + } + """ } ,)
b7ce3042c67c17a203590dd78014590626abbc48
fragdev/urls.py
fragdev/urls.py
from django.conf import settings from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Blog URLs url(r'^blog/(?P<path>.*)', include('wiblog.urls', namespace='wiblog')), # Handle all of the "static" pages url(r'^$', 'fragdev.views.home', name='home'), url(r'^about$', 'fragdev.views.about', name='about'), url(r'^contact$', 'fragdev.views.contact', name='contact'), url(r'^contacted$', 'fragdev.views.contacted', name='contacted'), url(r'^projects$', 'fragdev.views.projects', name='projects'), url(r'^resume$', 'fragdev.views.resume', name='resume'), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), # Static files: Should be handled by the web server! #url(r'^css/(?P<path>.*)$', 'django.views.static.serve', # {'document_root': '/data/documents/web/fragdev4000/css'}), #url(r'^fonts/(?P<path>.*)$', 'django.views.static.serve', # {'document_root': '/data/documents/web/fragdev4000/fonts'}), )
from django.conf import settings from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Blog URLs #url(r'^blog/(?P<path>.*)', include('wiblog.urls', namespace='wiblog')), # Handle all of the "static" pages url(r'^$', 'fragdev.views.home', name='home'), url(r'^about$', 'fragdev.views.about', name='about'), url(r'^contact$', 'fragdev.views.contact', name='contact'), url(r'^contacted$', 'fragdev.views.contacted', name='contacted'), url(r'^projects$', 'fragdev.views.projects', name='projects'), url(r'^resume$', 'fragdev.views.resume', name='resume'), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), )
Remove Debugging Paths, Comment Out Unfinished Portions
Remove Debugging Paths, Comment Out Unfinished Portions
Python
agpl-3.0
lo-windigo/fragdev,lo-windigo/fragdev
--- +++ @@ -7,7 +7,7 @@ urlpatterns = patterns('', # Blog URLs - url(r'^blog/(?P<path>.*)', include('wiblog.urls', namespace='wiblog')), + #url(r'^blog/(?P<path>.*)', include('wiblog.urls', namespace='wiblog')), # Handle all of the "static" pages url(r'^$', 'fragdev.views.home', name='home'), @@ -19,10 +19,4 @@ # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), - - # Static files: Should be handled by the web server! - #url(r'^css/(?P<path>.*)$', 'django.views.static.serve', - # {'document_root': '/data/documents/web/fragdev4000/css'}), - #url(r'^fonts/(?P<path>.*)$', 'django.views.static.serve', - # {'document_root': '/data/documents/web/fragdev4000/fonts'}), )
e2a7e7c80ef4d9c82b0a57908398f43f24234c63
setup.py
setup.py
import setuptools setuptools.setup( name="inidiff", version="0.1.0", url="https://github.com/kragniz/inidiff", author="Louis Taylor", author_email="louis@kragniz.eu", description="Find the differences between two ini config files", long_description=open('README.rst').read(), packages=setuptools.find_packages(), install_requires=[ 'six', 'ordered-set' ], entry_points = { 'console_scripts': ['inidiff=inidiff:main'], }, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', ], )
import setuptools setuptools.setup( name="inidiff", version="0.1.0", url="https://github.com/kragniz/inidiff", author="Louis Taylor", author_email="louis@kragniz.eu", description="Find the differences between two ini config files", long_description=open('README.rst').read(), packages=setuptools.find_packages(), install_requires=[ 'six', 'ordered-set' ], entry_points = { 'console_scripts': ['inidiff=inidiff:main'], }, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', ], )
Set python classifiers to py34
Set python classifiers to py34
Python
mit
kragniz/inidiff
--- +++ @@ -28,6 +28,6 @@ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.3', + 'Programming Language :: Python :: 3.4', ], )
bbba98884aff75e2b0d6af81150a3596a7c76038
setup.py
setup.py
import codecs from os import path from setuptools import find_packages, setup def read(*parts): filename = path.join(path.dirname(__file__), *parts) with codecs.open(filename, encoding="utf-8") as fp: return fp.read() NAME = "pinax-blog" DESCRIPTION = "a Django blog app" AUTHOR = "Pinax Team" AUTHOR_EMAIL = "team@pinaxproject.com" URL = "https://github.com/pinax/pinax-blog" setup( name=NAME, version="3.1.3", description=DESCRIPTION, long_description=read("README.rst"), url=URL, license="MIT", packages=find_packages(), package_data={ "pinax.blog": [ "templates/pinax/blog/*.xml", ] }, install_requires=[ "django-appconf>=1.0.1", "Pillow>=2.0", "Markdown>=2.4", "Pygments>=1.6" ], test_suite="runtests.runtests", classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Framework :: Django", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", ], zip_safe=False )
import codecs from os import path from setuptools import find_packages, setup def read(*parts): filename = path.join(path.dirname(__file__), *parts) with codecs.open(filename, encoding="utf-8") as fp: return fp.read() NAME = "pinax-blog" DESCRIPTION = "a Django blog app" AUTHOR = "Pinax Team" AUTHOR_EMAIL = "team@pinaxproject.com" URL = "https://github.com/pinax/pinax-blog" setup( name=NAME, version="3.1.3", description=DESCRIPTION, long_description=read("README.rst"), url=URL, license="MIT", packages=find_packages(), package_data={ "pinax.blog": [ "templates/pinax/blog/*.xml", ] }, install_requires=[ "django-appconf>=1.0.1", "Pillow>=2.0", "Markdown>=2.6", "Pygments>=2.0.2" ], test_suite="runtests.runtests", classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Framework :: Django", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", ], zip_safe=False )
Use more recent packages as minimum requirements
Use more recent packages as minimum requirements
Python
mit
swilcox/pinax-blog,cdvv7788/pinax-blog,miurahr/pinax-blog,salamer/pinax-blog,pinax/pinax-blog,swilcox/pinax-blog,miurahr/pinax-blog,easton402/pinax-blog,easton402/pinax-blog,pinax/pinax-blog,pinax/pinax-blog
--- +++ @@ -33,8 +33,8 @@ install_requires=[ "django-appconf>=1.0.1", "Pillow>=2.0", - "Markdown>=2.4", - "Pygments>=1.6" + "Markdown>=2.6", + "Pygments>=2.0.2" ], test_suite="runtests.runtests", classifiers=[
11e89d42949ff49890cc380f72061aac0e6b02e0
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup with open('README.rst') as f: long_description = f.read() setup( name='pylint-venv', version='2.0.0.dev0', description='pylint-venv provides a Pylint init-hook to use the same ' 'Pylint installation with different virtual environments.', long_description=long_description, author='Jan Gosmann, Federico Jaramillo', author_email='jan@hyper-world.de, federicojaramillom@gmail.com', url='https://github.com/jgosmann/pylint-venv/', py_modules=['pylint_venv'], provides=['pylint_venv'], license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Plugins', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Topic :: Software Development', ] )
#!/usr/bin/env python from distutils.core import setup with open('README.rst') as f: long_description = f.read() setup( name='pylint-venv', version='1.1.0', description='pylint-venv provides a Pylint init-hook to use the same ' 'Pylint installation with different virtual environments.', long_description=long_description, author='Jan Gosmann, Federico Jaramillo', author_email='jan@hyper-world.de, federicojaramillom@gmail.com', url='https://github.com/jgosmann/pylint-venv/', py_modules=['pylint_venv'], provides=['pylint_venv'], license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Plugins', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Topic :: Software Development', ] )
Revert major version, bump minor version 1.1.0
Revert major version, bump minor version 1.1.0
Python
mit
jgosmann/pylint-venv
--- +++ @@ -8,7 +8,7 @@ setup( name='pylint-venv', - version='2.0.0.dev0', + version='1.1.0', description='pylint-venv provides a Pylint init-hook to use the same ' 'Pylint installation with different virtual environments.', long_description=long_description,
7f226d265c65cca2d74988695502d2edff3aa6a3
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup from setuputils import find_version, read setup( name='astor', version=find_version('astor/__init__.py'), description='Read/rewrite/write Python ASTs', long_description=read('README.rst'), author='Patrick Maupin', author_email='pmaupin@gmail.com', platforms="Independent", url='https://github.com/pmaupin/astor.git', packages=['astor'], py_modules=['setuputils'], license="BSD", classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Topic :: Software Development :: Code Generators', 'Topic :: Software Development :: Compilers', ], keywords='ast', )
#!/usr/bin/env python from setuptools import setup from setuputils import find_version, read setup( name='astor', version=find_version('astor/__init__.py'), description='Read/rewrite/write Python ASTs', long_description=read('README.rst'), author='Patrick Maupin', author_email='pmaupin@gmail.com', platforms="Independent", url='https://github.com/pmaupin/astor.git', packages=['astor'], py_modules=['setuputils'], license="BSD", classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Topic :: Software Development :: Code Generators', 'Topic :: Software Development :: Compilers', ], keywords='ast', )
Set development status to stable.
Set development status to stable.
Python
bsd-3-clause
berkerpeksag/astor,zackmdavis/astor
--- +++ @@ -18,7 +18,7 @@ py_modules=['setuputils'], license="BSD", classifiers=[ - 'Development Status :: 3 - Alpha', + 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License',
539c8cbb91465fe1aabc25452bce7067c7474da5
setup.py
setup.py
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='8.0.1', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='8.0.2', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
Update the PyPI version to 8.0.2.
Update the PyPI version to 8.0.2.
Python
mit
Doist/todoist-python
--- +++ @@ -10,7 +10,7 @@ setup( name='todoist-python', - version='8.0.1', + version='8.0.2', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com',
1cb261bce94e7eb5bccccd282f938074e758f5bc
setup.py
setup.py
#!/usr/bin/env python # Copyright Least Authority Enterprises. # See LICENSE for details. import setuptools _metadata = {} with open("src/txkube/_metadata.py") as f: exec(f.read(), _metadata) setuptools.setup( name="txkube", version=_metadata["version_string"], description="A Twisted-based Kubernetes client.", author="txkube Developers", url="https://github.com/leastauthority.com/txkube", license="MIT", package_dir={"": "src"}, packages=setuptools.find_packages(where="src"), include_package_data=True, zip_safe=False, install_requires=[ "zope.interface", "attrs", "pyrsistent", "incremental", # See https://github.com/twisted/treq/issues/167 # And https://twistedmatrix.com/trac/ticket/9032 "twisted[tls]!=17.1.0", "pem", "eliot", "python-dateutil", "pykube", "treq", "klein", ], extras_require={ "dev": [ "testtools", "hypothesis", "eliot-tree>=17.0.0", ], }, )
#!/usr/bin/env python # Copyright Least Authority Enterprises. # See LICENSE for details. import setuptools _metadata = {} with open("src/txkube/_metadata.py") as f: exec(f.read(), _metadata) with open("README.rst") as f: _metadata["description"] = f.read() setuptools.setup( name="txkube", version=_metadata["version_string"], description="A Twisted-based Kubernetes client.", long_description=_metadata["description"], author="txkube Developers", url="https://github.com/leastauthority.com/txkube", license="MIT", package_dir={"": "src"}, packages=setuptools.find_packages(where="src"), include_package_data=True, zip_safe=False, install_requires=[ "zope.interface", "attrs", "pyrsistent", "incremental", # See https://github.com/twisted/treq/issues/167 # And https://twistedmatrix.com/trac/ticket/9032 "twisted[tls]!=17.1.0", "pem", "eliot", "python-dateutil", "pykube", "treq", "klein", ], extras_require={ "dev": [ "testtools", "hypothesis", "eliot-tree>=17.0.0", ], }, )
Add the README as the long description.
Add the README as the long description.
Python
mit
LeastAuthority/txkube
--- +++ @@ -8,11 +8,14 @@ _metadata = {} with open("src/txkube/_metadata.py") as f: exec(f.read(), _metadata) +with open("README.rst") as f: + _metadata["description"] = f.read() setuptools.setup( name="txkube", version=_metadata["version_string"], description="A Twisted-based Kubernetes client.", + long_description=_metadata["description"], author="txkube Developers", url="https://github.com/leastauthority.com/txkube", license="MIT",
b1a92e41e31e18d2a273c476414e702daf1c1847
setup.py
setup.py
"""Defines the setup for the declxml library""" from setuptools import setup setup( name='declxml', description='Declarative XML processing library', version='0.11.0', url='http://declxml.readthedocs.io/', author='Greg Atkin', author_email='greg.scott.atkin@gmail.com', license='MIT', py_modules=['declxml'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', ], keywords='XML, Parsing, Serialization' )
"""Defines the setup for the declxml library""" from io import open import os.path from setuptools import setup readme_path = os.path.join(os.path.dirname(__file__), 'README.md') with open(readme_path, encoding='utf-8') as readme: long_description = readme.read() setup( name='declxml', description='Declarative XML processing library', long_description=long_description, long_description_content_type='text/markdown', version='1.0', url='http://declxml.readthedocs.io/', project_urls={ 'Documentation': 'http://declxml.readthedocs.io/', 'Source': 'https://github.com/gatkin/declxml', 'Tracker': 'https://github.com/gatkin/declxml/issues', }, author='Greg Atkin', author_email='greg.scott.atkin@gmail.com', license='MIT', py_modules=['declxml'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', ], keywords='XML, Parsing, Serialization' )
Bump version for PyPi release
Bump version for PyPi release
Python
mit
gatkin/declxml
--- +++ @@ -1,11 +1,26 @@ """Defines the setup for the declxml library""" +from io import open +import os.path from setuptools import setup + + +readme_path = os.path.join(os.path.dirname(__file__), 'README.md') +with open(readme_path, encoding='utf-8') as readme: + long_description = readme.read() + setup( name='declxml', description='Declarative XML processing library', - version='0.11.0', + long_description=long_description, + long_description_content_type='text/markdown', + version='1.0', url='http://declxml.readthedocs.io/', + project_urls={ + 'Documentation': 'http://declxml.readthedocs.io/', + 'Source': 'https://github.com/gatkin/declxml', + 'Tracker': 'https://github.com/gatkin/declxml/issues', + }, author='Greg Atkin', author_email='greg.scott.atkin@gmail.com', license='MIT',
c89157c748bedb65d74f4109a7398cafc7e58f9d
neuroimaging/algorithms/tests/test_onesample.py
neuroimaging/algorithms/tests/test_onesample.py
from neuroimaging.testing import * from neuroimaging.algorithms.onesample import ImageOneSample from neuroimaging.core.api import load_image from neuroimaging.utils.tests.data import repository class test_OneSample(TestCase): @dec.slow @dec.data def test_onesample1(self): im1 = load_image('FIAC/fiac3/fonc3/fsl/fmristat_run/contrasts/speaker/effect.nii.gz', repository) im2 = load_image('FIAC/fiac4/fonc3/fsl/fmristat_run/contrasts/speaker/effect.nii.gz', repository) im3 = load_image('FIAC/fiac5/fonc2/fsl/fmristat_run/contrasts/speaker/effect.nii.gz', repository) x = ImageOneSample([im1,im2,im3], clobber=True) x.fit()
from neuroimaging.testing import * from neuroimaging.algorithms.onesample import ImageOneSample from neuroimaging.core.api import load_image from neuroimaging.utils.tests.data import repository class test_OneSample(TestCase): @dec.skipknownfailure @dec.slow @dec.data def test_onesample1(self): # FIXME: When we replace nipy's datasource with numpy's # datasource, remove the string casting. _fullpath returns a # 'path' object. fp1 = repository._fullpath('FIAC/fiac3/fonc3/fsl/fmristat_run/contrasts/speaker/effect.nii.gz') fp1 = str(fp1) im1 = load_image(fp1) fp2 = repository._fullpath('FIAC/fiac4/fonc3/fsl/fmristat_run/contrasts/speaker/effect.nii.gz') fp2 = str(fp2) im2 = load_image(fp2) fp3 = repository._fullpath('FIAC/fiac5/fonc2/fsl/fmristat_run/contrasts/speaker/effect.nii.gz') fp3 = str(fp3) im3 = load_image(fp3) # FIXME: ImageSequenceIterator is not defined. # ImageOneSample.__init__ fails. # File "/Users/cburns/src/nipy-trunk/neuroimaging/algorithms/onesample.py", line 68, in __init__ # self.iterator = ImageSequenceIterator(input) # NameError: global name 'ImageSequenceIterator' is not defined x = ImageOneSample([im1,im2,im3], clobber=True) x.fit()
Update data file references. Skip known test failure to undefined image iterator.
Update data file references. Skip known test failure to undefined image iterator.
Python
bsd-3-clause
alexis-roche/nireg,arokem/nipy,arokem/nipy,alexis-roche/nipy,bthirion/nipy,nipy/nipy-labs,alexis-roche/nipy,bthirion/nipy,alexis-roche/register,alexis-roche/register,alexis-roche/nireg,bthirion/nipy,nipy/nireg,alexis-roche/register,nipy/nipy-labs,alexis-roche/nipy,alexis-roche/niseg,arokem/nipy,arokem/nipy,alexis-roche/nipy,bthirion/nipy,alexis-roche/niseg,nipy/nireg
--- +++ @@ -5,14 +5,29 @@ from neuroimaging.utils.tests.data import repository class test_OneSample(TestCase): + @dec.skipknownfailure @dec.slow @dec.data def test_onesample1(self): - im1 = load_image('FIAC/fiac3/fonc3/fsl/fmristat_run/contrasts/speaker/effect.nii.gz', - repository) - im2 = load_image('FIAC/fiac4/fonc3/fsl/fmristat_run/contrasts/speaker/effect.nii.gz', - repository) - im3 = load_image('FIAC/fiac5/fonc2/fsl/fmristat_run/contrasts/speaker/effect.nii.gz', - repository) + # FIXME: When we replace nipy's datasource with numpy's + # datasource, remove the string casting. _fullpath returns a + # 'path' object. + fp1 = repository._fullpath('FIAC/fiac3/fonc3/fsl/fmristat_run/contrasts/speaker/effect.nii.gz') + fp1 = str(fp1) + im1 = load_image(fp1) + + fp2 = repository._fullpath('FIAC/fiac4/fonc3/fsl/fmristat_run/contrasts/speaker/effect.nii.gz') + fp2 = str(fp2) + im2 = load_image(fp2) + + fp3 = repository._fullpath('FIAC/fiac5/fonc2/fsl/fmristat_run/contrasts/speaker/effect.nii.gz') + fp3 = str(fp3) + im3 = load_image(fp3) + + # FIXME: ImageSequenceIterator is not defined. + # ImageOneSample.__init__ fails. + # File "/Users/cburns/src/nipy-trunk/neuroimaging/algorithms/onesample.py", line 68, in __init__ + # self.iterator = ImageSequenceIterator(input) + # NameError: global name 'ImageSequenceIterator' is not defined x = ImageOneSample([im1,im2,im3], clobber=True) x.fit()
3d04bb1774e286df4cda3695b938251e0a6266ae
grip/patcher.py
grip/patcher.py
import re INCOMPLETE_TASK_RE = re.compile(r'<li>\[ \] (.*?)(<ul.*?>|</li>)', re.DOTALL) INCOMPLETE_TASK_SUB = (r'<li class="task-list-item">' r'<input type="checkbox" ' r'class="task-list-item-checkbox" disabled=""> \1\2') COMPLETE_TASK_RE = re.compile(r'<li>\[x\] (.*?)(<ul.*?>|</li>)', re.DOTALL) COMPLETE_TASK_SUB = (r'<li class="task-list-item">' r'<input type="checkbox" class="task-list-item-checkbox" ' r'checked="" disabled=""> \1\2') def patch(html, user_content=False): """ Processes the HTML rendered by the GitHub API, patching any inconsistencies from the main site. """ # FUTURE: Remove this once GitHub API renders task lists # https://github.com/isaacs/github/issues/309 if not user_content: html = INCOMPLETE_TASK_RE.sub(INCOMPLETE_TASK_SUB, html) html = COMPLETE_TASK_RE.sub(COMPLETE_TASK_SUB, html) return html
import re INCOMPLETE_TASK_RE = re.compile(r'<li>\[ \] (.*?)(<ul.*?>|</li>)', re.DOTALL) INCOMPLETE_TASK_SUB = (r'<li class="task-list-item">' r'<input type="checkbox" ' r'class="task-list-item-checkbox" disabled=""> \1\2') COMPLETE_TASK_RE = re.compile(r'<li>\[x\] (.*?)(<ul.*?>|</li>)', re.DOTALL) COMPLETE_TASK_SUB = (r'<li class="task-list-item">' r'<input type="checkbox" class="task-list-item-checkbox" ' r'checked="" disabled=""> \1\2') HEADER_PATCH_RE = re.compile(r'<span>{:"aria-hidden"=&gt;"true", :class=&gt;' r'"octicon octicon-link"}</span>', re.DOTALL) HEADER_PATCH_SUB = r'<span class="octicon octicon-link"></span>' def patch(html, user_content=False): """ Processes the HTML rendered by the GitHub API, patching any inconsistencies from the main site. """ # FUTURE: Remove this once GitHub API renders task lists # https://github.com/isaacs/github/issues/309 if not user_content: html = INCOMPLETE_TASK_RE.sub(INCOMPLETE_TASK_SUB, html) html = COMPLETE_TASK_RE.sub(COMPLETE_TASK_SUB, html) # FUTURE: Remove this once GitHub API fixes the header bug # https://github.com/joeyespo/grip/issues/244 html = HEADER_PATCH_RE.sub(HEADER_PATCH_SUB, html) return html
Patch the GitHub API response to work around the header bug
Patch the GitHub API response to work around the header bug
Python
mit
joeyespo/grip,joeyespo/grip
--- +++ @@ -11,6 +11,11 @@ r'checked="" disabled=""> \1\2') +HEADER_PATCH_RE = re.compile(r'<span>{:"aria-hidden"=&gt;"true", :class=&gt;' + r'"octicon octicon-link"}</span>', re.DOTALL) +HEADER_PATCH_SUB = r'<span class="octicon octicon-link"></span>' + + def patch(html, user_content=False): """ Processes the HTML rendered by the GitHub API, patching @@ -22,4 +27,8 @@ html = INCOMPLETE_TASK_RE.sub(INCOMPLETE_TASK_SUB, html) html = COMPLETE_TASK_RE.sub(COMPLETE_TASK_SUB, html) + # FUTURE: Remove this once GitHub API fixes the header bug + # https://github.com/joeyespo/grip/issues/244 + html = HEADER_PATCH_RE.sub(HEADER_PATCH_SUB, html) + return html
d5094e3b9ea2ff62483093e3415dee1044fd9974
setup.py
setup.py
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, "README.md"), encoding="utf-8") as f: long_description = f.read() setup( name="pdf2image", version="1.9.0", description="A wrapper around the pdftoppm and pdftocairo command line tools to convert PDF to a PIL Image list.", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/Belval/pdf2image", author="Edouard Belval", author_email="edouard@belval.org", # Choose your license license="MIT", # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ # 3 - Alpha # 4 - Beta # 5 - Production/Stable "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", ], keywords="pdf image png jpeg jpg convert", packages=find_packages(exclude=["contrib", "docs", "tests"]), install_requires=["pillow"], )
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, "README.md"), encoding="utf-8") as f: long_description = f.read() setup( name="pdf2image", version="1.9.1", description="A wrapper around the pdftoppm and pdftocairo command line tools to convert PDF to a PIL Image list.", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/Belval/pdf2image", author="Edouard Belval", author_email="edouard@belval.org", # Choose your license license="MIT", # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ # 3 - Alpha # 4 - Beta # 5 - Production/Stable "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", ], keywords="pdf image png jpeg jpg convert", packages=find_packages(exclude=["contrib", "docs", "tests"]), install_requires=["pillow"], )
Add Python 3.8 to supported versions
Add Python 3.8 to supported versions
Python
mit
Kankroc/pdf2image,Belval/pdf2image
--- +++ @@ -12,7 +12,7 @@ setup( name="pdf2image", - version="1.9.0", + version="1.9.1", description="A wrapper around the pdftoppm and pdftocairo command line tools to convert PDF to a PIL Image list.", long_description=long_description, long_description_content_type="text/markdown", @@ -33,6 +33,7 @@ "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", ], keywords="pdf image png jpeg jpg convert", packages=find_packages(exclude=["contrib", "docs", "tests"]),