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
bb2c92732ee7cf834d937025a03c87d7ee5bc343
tests/modules/test_traffic.py
tests/modules/test_traffic.py
import mock import unittest import tests.mocks as mocks from bumblebee.modules.traffic import Module class TestTrafficModule(unittest.TestCase): def setUp(self): mocks.setup_test(self, Module) def test_default_format(self): self.assertEqual(self.module._format, "{:.2f}") def test_get_minwidth_str(self): # default value (two digits after dot) self.assertEqual(self.module.get_minwidth_str(), "1000.00MB") # integer value self.module._format = "{:.0f}" self.assertEqual(self.module.get_minwidth_str(), "1000MB") # just one digit after dot self.module._format = "{:.1f}" self.assertEqual(self.module.get_minwidth_str(), "1000.0MB")
import mock import unittest import tests.mocks as mocks from bumblebee.modules.traffic import Module class TestTrafficModule(unittest.TestCase): def setUp(self): mocks.setup_test(self, Module) def test_default_format(self): self.assertEqual(self.module._format, "{:.2f}") def test_get_minwidth_str(self): # default value (two digits after dot) self.assertEqual(self.module.get_minwidth_str(), "1000.00KiB/s") # integer value self.module._format = "{:.0f}" self.assertEqual(self.module.get_minwidth_str(), "1000KiB/s") # just one digit after dot self.module._format = "{:.1f}" self.assertEqual(self.module.get_minwidth_str(), "1000.0KiB/s")
Fix tests for module traffic
[tests/traffic] Fix tests for module traffic
Python
mit
tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status
--- +++ @@ -14,10 +14,10 @@ def test_get_minwidth_str(self): # default value (two digits after dot) - self.assertEqual(self.module.get_minwidth_str(), "1000.00MB") + self.assertEqual(self.module.get_minwidth_str(), "1000.00KiB/s") # integer value self.module._format = "{:.0f}" - self.assertEqual(self.module.get_minwidth_str(), "1000MB") + self.assertEqual(self.module.get_minwidth_str(), "1000KiB/s") # just one digit after dot self.module._format = "{:.1f}" - self.assertEqual(self.module.get_minwidth_str(), "1000.0MB") + self.assertEqual(self.module.get_minwidth_str(), "1000.0KiB/s")
37bccb59874dd2e50a0ace482461e156ee5b7240
pytips/util.py
pytips/util.py
# -*- coding: utf-8 -*- """Utility functions for PyTips.""" from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import from __future__ import division import html5lib from dateutil.parser import parse as parse_date def extract_publication_date(html): """Extract publish date from ``html``; assumes it's like an embedded tweet.""" root = html5lib.parse(html, treebuilder='lxml', namespaceHTMLElements=False) publication_date_string = root.xpath("//a/@data-datetime")[0] return parse_date(publication_date_string)
# -*- coding: utf-8 -*- """Utility functions for PyTips.""" from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import from __future__ import division import signal from decorator import decorator import html5lib from dateutil.parser import parse as parse_date def extract_publication_date(html): """Extract publish date from ``html``; assumes it's like an embedded tweet.""" root = html5lib.parse(html, treebuilder='lxml', namespaceHTMLElements=False) publication_date_string = root.xpath("//a/@data-datetime")[0] return parse_date(publication_date_string) # The following block of code was inspired by http://code.activestate.com/recipes/307871-timing-out-function/ class TimedOutException(Exception): """Raised when a function times out.""" def __init__(self, value = "Timed Out"): super(TimedOutException, self).__init__() self.value = value def __str__(self): return repr(self.value) def timeout(s): """Prevent a function from running more than ``s`` seconds. :param s: the amount of time (in seconds) to let the function attempt to finish """ def _timeout(f, *args, **kwargs): def handle_timeout(signal_number, frame): raise TimedOutException # Grab a handle to the old alarm. old = signal.signal(signal.SIGALRM, handle_timeout) # Start our timeout logic. signal.alarm(s) try: result = f(*args, **kwargs) finally: # Put the old stuff back old = signal.signal(signal.SIGALRM, old) # Wipe out all alarms. signal.alarm(0) return result return decorator(_timeout)
Add a decorator to time out long-running functions.
Add a decorator to time out long-running functions.
Python
isc
gthank/pytips,gthank/pytips,gthank/pytips,gthank/pytips
--- +++ @@ -6,6 +6,10 @@ from __future__ import division +import signal + + +from decorator import decorator import html5lib from dateutil.parser import parse as parse_date @@ -15,3 +19,41 @@ root = html5lib.parse(html, treebuilder='lxml', namespaceHTMLElements=False) publication_date_string = root.xpath("//a/@data-datetime")[0] return parse_date(publication_date_string) + + +# The following block of code was inspired by http://code.activestate.com/recipes/307871-timing-out-function/ +class TimedOutException(Exception): + """Raised when a function times out.""" + def __init__(self, value = "Timed Out"): + super(TimedOutException, self).__init__() + self.value = value + + def __str__(self): + return repr(self.value) + + +def timeout(s): + """Prevent a function from running more than ``s`` seconds. + + :param s: the amount of time (in seconds) to let the function attempt to finish + """ + def _timeout(f, *args, **kwargs): + def handle_timeout(signal_number, frame): + raise TimedOutException + + # Grab a handle to the old alarm. + old = signal.signal(signal.SIGALRM, handle_timeout) + + # Start our timeout logic. + signal.alarm(s) + try: + result = f(*args, **kwargs) + finally: + # Put the old stuff back + old = signal.signal(signal.SIGALRM, old) + + # Wipe out all alarms. + signal.alarm(0) + + return result + return decorator(_timeout)
0762dbb9b0a43eb6bd01f43d88ac990e90da2303
chandra_suli/filter_reg.py
chandra_suli/filter_reg.py
""" Take evt3 file and use region files to subtract off sources that are already known - image will have lots of holes Goals by Friday 6/31 - Get script working for one image at a time below = code used by Giacomo to create filtered image ftcopy 'acisf00635_000N001_evt3.fits[EVENTS][regfilter("my_source.reg")]' test.fits """
#!/usr/bin/env python """ Take evt3 file and use region files to subtract off sources that are already known - image will have lots of holes Goals by Friday 6/31 - Get script working for one image at a time below = code used by Giacomo to create filtered image ftcopy 'acisf00635_000N001_evt3.fits[EVENTS][regfilter("my_source.reg")]' test.fits code that works with CIAO dmcopy "acisf00635_000N001_evt3.fits[exclude sky=region(acisf00635_000N001_r0101_reg3.fits)]" filter_test.fits opt=all """ import argparse import subprocess import os if __name__=="__main__": parser = argparse.ArgumentParser(description='Filter known sources out of level 3 event file') parser.add_argument("--obsid",help="Observation ID Numbers",nargs='+',type=int,required=True) # assumption = all region files and event files are already downloaded into same directory args = parser.parse_args() #changes me from chandra_suli folder up three levels to VM_shared folder, where evt3 and reg3 files are held os.chdir("../../../") for i in args.obsid: subprocess.call("find %d -name \"*reg3.fits.gz\" > %d_reg.txt" %(i,i), shell=True)
Copy reg file names into text file
Copy reg file names into text file
Python
bsd-3-clause
nitikayad96/chandra_suli
--- +++ @@ -1,4 +1,4 @@ - +#!/usr/bin/env python """ Take evt3 file and use region files to subtract off sources that are already known - image will have lots of holes @@ -6,4 +6,30 @@ below = code used by Giacomo to create filtered image ftcopy 'acisf00635_000N001_evt3.fits[EVENTS][regfilter("my_source.reg")]' test.fits + +code that works with CIAO +dmcopy "acisf00635_000N001_evt3.fits[exclude sky=region(acisf00635_000N001_r0101_reg3.fits)]" filter_test.fits opt=all """ + +import argparse +import subprocess +import os + +if __name__=="__main__": + + parser = argparse.ArgumentParser(description='Filter known sources out of level 3 event file') + parser.add_argument("--obsid",help="Observation ID Numbers",nargs='+',type=int,required=True) + + # assumption = all region files and event files are already downloaded into same directory + + args = parser.parse_args() + + #changes me from chandra_suli folder up three levels to VM_shared folder, where evt3 and reg3 files are held + os.chdir("../../../") + + for i in args.obsid: + + subprocess.call("find %d -name \"*reg3.fits.gz\" > %d_reg.txt" %(i,i), shell=True) + + +
4ba9bc552e8d6cec598718c688cf5989769876c2
cla_backend/settings/jenkins.py
cla_backend/settings/jenkins.py
import os from .testing import * DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS = ( ('CLA', 'cla-alerts@digital.justice.gov.uk'), ) MANAGERS = ADMINS INSTALLED_APPS += ('django_jenkins',) JENKINS_TASKS = ( 'django_jenkins.tasks.with_coverage', ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('DB_USERNAME', ''), 'TEST_NAME': 'test_cla_backend%s' % os.environ.get('BACKEND_TEST_DB_SUFFIX', ''), 'USER': os.environ.get('DB_USERNAME', ''), 'PASSWORD': os.environ.get('DB_PASSWORD', ''), 'HOST': os.environ.get('DB_HOST', ''), 'PORT': os.environ.get('DB_PORT', ''), } } JENKINS_TEST_RUNNER = 'core.testing.CLADiscoverRunner' #HOST_NAME = "" ALLOWED_HOSTS = [ '*' ]
import os from .testing import * DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS = ( ('CLA', 'cla-alerts@digital.justice.gov.uk'), ) MANAGERS = ADMINS INSTALLED_APPS += ('django_jenkins',) JENKINS_TASKS = ( 'django_jenkins.tasks.with_coverage', ) DATABASES = { 'default': { 'ENGINE': 'cla_backend.apps.reports.db.backend', 'NAME': os.environ.get('DB_USERNAME', ''), 'TEST_NAME': 'test_cla_backend%s' % os.environ.get('BACKEND_TEST_DB_SUFFIX', ''), 'USER': os.environ.get('DB_USERNAME', ''), 'PASSWORD': os.environ.get('DB_PASSWORD', ''), 'HOST': os.environ.get('DB_HOST', ''), 'PORT': os.environ.get('DB_PORT', ''), } } JENKINS_TEST_RUNNER = 'core.testing.CLADiscoverRunner' #HOST_NAME = "" ALLOWED_HOSTS = [ '*' ]
Use custom reports backend for test DB in Jenkins
Use custom reports backend for test DB in Jenkins As Django test runner does not support replica DBs (MIRROR setting just redirects to use the other connection), change the default connection to use the custom engine when running in jenkins. Tests fail during BST due to the connection not being UTC if using the default postgres engine.
Python
mit
ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend
--- +++ @@ -18,7 +18,7 @@ DATABASES = { 'default': { - 'ENGINE': 'django.db.backends.postgresql_psycopg2', + 'ENGINE': 'cla_backend.apps.reports.db.backend', 'NAME': os.environ.get('DB_USERNAME', ''), 'TEST_NAME': 'test_cla_backend%s' % os.environ.get('BACKEND_TEST_DB_SUFFIX', ''), 'USER': os.environ.get('DB_USERNAME', ''),
3bf918d7c303371651e9e9890576dbb5a827629b
library/sensors/SensePressure.py
library/sensors/SensePressure.py
# -*- coding: utf-8 -*- import sys from sense_hat import SenseHat #add the project folder to pythpath sys.path.append('../../') from library.components.SensorModule import SensorModule as Sensor from library.components.MetaData import MetaData as MetaData class SensePressure(Sensor): def __init__(self): super(SensePressure, self).__init__() tempMetaData = MetaData('millibars') tempMetaData.setValueCallback(self.getPressureValue) tempMetaData.setUnitCallback(self.getPressureUnit) self.addMetaData(tempMetaData) def getPressureValue(self): sense = SenseHat() return str(sense.pressure) def getPressureUnit(self): return " Millibars" def getMetaData(self): return super(SensePressure, self).getMetaData()
# -*- coding: utf-8 -*- import sys from sense_hat import SenseHat #add the project folder to pythpath sys.path.append('../../') from library.components.SensorModule import SensorModule as Sensor from library.components.MetaData import MetaData as MetaData class SensePressure(Sensor): def __init__(self): super(SensePressure, self).__init__() tempMetaData = MetaData('Millibars') tempMetaData.setValueCallback(self.getPressureValue) tempMetaData.setUnitCallback(self.getPressureUnit) self.addMetaData(tempMetaData) def getPressureValue(self): sense = SenseHat() return str(sense.pressure) def getPressureUnit(self): return " Millibars" def getMetaData(self): return super(SensePressure, self).getMetaData()
Fix to the pressure sensor
Fix to the pressure sensor
Python
mit
OpenSpaceProgram/pyOSP,OpenSpaceProgram/pyOSP
--- +++ @@ -13,7 +13,7 @@ def __init__(self): super(SensePressure, self).__init__() - tempMetaData = MetaData('millibars') + tempMetaData = MetaData('Millibars') tempMetaData.setValueCallback(self.getPressureValue) tempMetaData.setUnitCallback(self.getPressureUnit) self.addMetaData(tempMetaData)
ba9a758161b6863704b2be7b28f6638e2191d8dd
test/test_nc.py
test/test_nc.py
#!/usr/bin/env python """ Unittests for csvnc module """ import os import pytest from csvnc import csvnc def test_generated_file_should_have_extention_nc(): data_file = 'data.csv' assert 'data.nc' == csvnc.new_name(data_file)
#!/usr/bin/env python """ Unittests for csvnc module """ import os import pytest from csvnc import csvnc class TestCsvnc(object): def test_generated_file_should_have_extention_nc(self): data_file = 'data.csv' assert 'data.nc' == csvnc.new_name(data_file)
Add test class for grouping tests
Add test class for grouping tests
Python
mit
qba73/nc
--- +++ @@ -9,7 +9,8 @@ from csvnc import csvnc -def test_generated_file_should_have_extention_nc(): - data_file = 'data.csv' - assert 'data.nc' == csvnc.new_name(data_file) +class TestCsvnc(object): + def test_generated_file_should_have_extention_nc(self): + data_file = 'data.csv' + assert 'data.nc' == csvnc.new_name(data_file)
1b0253f09196d3824481451f8daee6b486825fa6
prismriver/qt/gui.py
prismriver/qt/gui.py
import sys from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QApplication from prismriver.qt.window import MainWindow from prismriver import util def run(): util.init_logging(False, True, None) app = QApplication(sys.argv) app.setWindowIcon(QIcon('prismriver/pixmaps/prismriver-lunasa.png')) main = MainWindow() main.setGeometry(0, 0, 1024, 1000) main.setWindowTitle('Lunasa Prismriver') main.show() sys.exit(app.exec_())
import sys from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QApplication from prismriver.qt.window import MainWindow from prismriver import util def run(): util.init_logging(False, True, None) app = QApplication(sys.argv) app.setWindowIcon(QIcon('prismriver/pixmaps/prismriver-lunasa.png')) app.setApplicationName('Lunasa Prismriver') main = MainWindow() main.setGeometry(0, 0, 1024, 1000) main.setWindowTitle('Lunasa Prismriver') main.show() sys.exit(app.exec_())
Set application name to "Lunasa Prismriver"
[qt] Set application name to "Lunasa Prismriver" That value will be used as WM_CLASS of application.
Python
mit
anlar/prismriver-lyrics,anlar/prismriver-lyrics,anlar/prismriver,anlar/prismriver
--- +++ @@ -13,6 +13,7 @@ app = QApplication(sys.argv) app.setWindowIcon(QIcon('prismriver/pixmaps/prismriver-lunasa.png')) + app.setApplicationName('Lunasa Prismriver') main = MainWindow() main.setGeometry(0, 0, 1024, 1000)
e852a210a84e91369752ef8fcfbbf52c27b3db59
pycrest/visualize.py
pycrest/visualize.py
import matplotlib.pyplot as plt from matplotlib.pyplot import triplot from mpl_toolkits.mplot3d import Axes3D from pycrest.mesh import Mesh2d def plot_triangulation(tri: Mesh2d, standalone=True, *args, **kwargs): figure = plt.figure() if standalone else None triplot(tri.vertices[:, 0], tri.vertices[:, 1], tri.elements, *args, **kwargs) if figure: figure.show()
import matplotlib.pyplot as plt from matplotlib.pyplot import triplot from mpl_toolkits.mplot3d import Axes3D from pycrest.mesh import Mesh2d def plot_triangulation(tri: Mesh2d, standalone=True, *args, **kwargs): figure = plt.figure() if standalone else None triplot(tri.vertices[:, 0], tri.vertices[:, 1], tri.elements, *args, **kwargs) xmin = tri.vertices[:, 0].min() xmax = tri.vertices[:, 0].max() ymin = tri.vertices[:, 1].min() ymax = tri.vertices[:, 1].max() padding = 0.05 * (max(xmax - xmin, ymax - ymin)) plt.axis('square') plt.xlabel("x") plt.ylabel("y") plt.xlim((xmin - padding, xmax + padding)) plt.ylim((ymin - padding, ymax + padding)) if figure: figure.show()
Make pycrest mesh viz more capable
Make pycrest mesh viz more capable
Python
mit
Andlon/crest,Andlon/crest,Andlon/crest
--- +++ @@ -8,5 +8,15 @@ def plot_triangulation(tri: Mesh2d, standalone=True, *args, **kwargs): figure = plt.figure() if standalone else None triplot(tri.vertices[:, 0], tri.vertices[:, 1], tri.elements, *args, **kwargs) + xmin = tri.vertices[:, 0].min() + xmax = tri.vertices[:, 0].max() + ymin = tri.vertices[:, 1].min() + ymax = tri.vertices[:, 1].max() + padding = 0.05 * (max(xmax - xmin, ymax - ymin)) + plt.axis('square') + plt.xlabel("x") + plt.ylabel("y") + plt.xlim((xmin - padding, xmax + padding)) + plt.ylim((ymin - padding, ymax + padding)) if figure: figure.show()
e1092caacec94bd016283b8452ad4399dba0f231
cogs/gaming_tasks.py
cogs/gaming_tasks.py
from discord.ext import commands from .utils import checks import asyncio import discord import web.wsgi from django.utils import timezone from django.db import models from django.utils import timezone from gaming.models import DiscordUser, Game, GameUser, Server, Role, GameSearch, Channel class GamingTasks: def __init__(self, bot, task): self.bot = bot self.task = task def __unload(self): self.task.cancel() @asyncio.coroutine def run_tasks(bot): while True: yield from asyncio.sleep(15) channels = Channel.objects.filter(private=False, expire_date__lte=timezone.now(), deleted=False) if channels.count() >= 1: for channel in channels: try: c = bot.get_channel(channel.channel_id) yield from bot.delete_channel(c) except Exception as e: # Channel no longer exists on server print(e) finally: channel.deleted = True channel.save() yield from asyncio.sleep(1) else: # No channels found to be deleted pass def setup(bot): loop = asyncio.get_event_loop() task = loop.create_task(GamingTasks.run_tasks(bot)) bot.add_cog(GamingTasks(bot, task))
from discord.ext import commands from .utils import checks import asyncio import discord import web.wsgi from django.utils import timezone from django.db import models from django.utils import timezone from gaming.models import DiscordUser, Game, GameUser, Server, Role, GameSearch, Channel class GamingTasks: def __init__(self, bot, task): self.bot = bot self.task = task def __unload(self): self.task.cancel() @asyncio.coroutine def run_tasks(bot): while True: yield from asyncio.sleep(15) channels = Channel.objects.filter(private=False, expire_date__lte=timezone.now(), deleted=False) if channels.count() >= 1: for channel in channels: if channel is None: continue try: c = bot.get_channel(channel.channel_id) if c is not None: yield from bot.delete_channel(c) except Exception as e: # Channel no longer exists on server print(e) finally: channel.deleted = True channel.save() yield from asyncio.sleep(1) else: # No channels found to be deleted pass def setup(bot): loop = asyncio.get_event_loop() task = loop.create_task(GamingTasks.run_tasks(bot)) bot.add_cog(GamingTasks(bot, task))
Check if it is None before continuing
Check if it is None before continuing
Python
mit
bsquidwrd/Squid-Bot,bsquidwrd/Squid-Bot
--- +++ @@ -25,9 +25,12 @@ channels = Channel.objects.filter(private=False, expire_date__lte=timezone.now(), deleted=False) if channels.count() >= 1: for channel in channels: + if channel is None: + continue try: c = bot.get_channel(channel.channel_id) - yield from bot.delete_channel(c) + if c is not None: + yield from bot.delete_channel(c) except Exception as e: # Channel no longer exists on server print(e)
955d39c4ae1190b9bc4a0c7db9aa914a08acf8d5
pwnedcheck/__init__.py
pwnedcheck/__init__.py
__author__ = 'Casey Dunham' __version__ = "0.1.0" import urllib import urllib2 import json PWNED_API_URL = "https://haveibeenpwned.com/api/breachedaccount/%s" class InvalidEmail(Exception): pass def check(email): req = urllib.Request(PWNED_API_URL % urllib.quote(email)) try: resp = urllib.urlopen(req) return json.loads(resp.read()) except urllib2.HTTPError, e: if e.code == 400: raise InvalidEmail("Email address does not appear to be a valid email") return []
__author__ = 'Casey Dunham' __version__ = "0.1.0" import urllib import urllib2 import json PWNED_API_URL = "https://haveibeenpwned.com/api/breachedaccount/%s" class InvalidEmail(Exception): pass def check(email): req = urllib2.Request(PWNED_API_URL % urllib.quote(email)) try: resp = urllib2.urlopen(req) return json.loads(resp.read()) except urllib2.HTTPError, e: if e.code == 400: raise InvalidEmail("Email address does not appear to be a valid email") return []
Fix stupid typo in urllib
Fix stupid typo in urllib
Python
mit
caseydunham/PwnedCheck
--- +++ @@ -15,9 +15,9 @@ def check(email): - req = urllib.Request(PWNED_API_URL % urllib.quote(email)) + req = urllib2.Request(PWNED_API_URL % urllib.quote(email)) try: - resp = urllib.urlopen(req) + resp = urllib2.urlopen(req) return json.loads(resp.read()) except urllib2.HTTPError, e: if e.code == 400:
99764a2d1f99cd6a2b61b35c4a262d730a26ba1f
pytest_hidecaptured.py
pytest_hidecaptured.py
# -*- coding: utf-8 -*- def pytest_runtest_logreport(report): """Overwrite report by removing any captured stderr.""" # print("PLUGIN SAYS -> report -> {0}".format(report)) # print("PLUGIN SAYS -> report.sections -> {0}".format(report.sections)) # print("PLUGIN SAYS -> dir(report) -> {0}".format(dir(report))) # print("PLUGIN SAYS -> type(report) -> {0}".format(type(report))) sections = [item for item in report.sections if item[0] not in ("Captured stdout call", "Captured stderr call", "Captured stdout setup", "Captured stderr setup")] # print("PLUGIN SAYS -> sections -> {0}".format(sections)) report.sections = sections
# -*- coding: utf-8 -*- def pytest_runtest_logreport(report): """Overwrite report by removing any captured stderr.""" # print("PLUGIN SAYS -> report -> {0}".format(report)) # print("PLUGIN SAYS -> report.sections -> {0}".format(report.sections)) # print("PLUGIN SAYS -> dir(report) -> {0}".format(dir(report))) # print("PLUGIN SAYS -> type(report) -> {0}".format(type(report))) sections = [item for item in report.sections if item[0] not in ("Captured stdout call", "Captured stderr call", "Captured stdout setup", "Captured stderr setup", "Captured stdout teardown", "Captured stderr teardown")] # print("PLUGIN SAYS -> sections -> {0}".format(sections)) report.sections = sections
Fix failing tests for captured output in teardown
Fix failing tests for captured output in teardown
Python
mit
hamzasheikh/pytest-hidecaptured
--- +++ @@ -5,6 +5,6 @@ # print("PLUGIN SAYS -> report.sections -> {0}".format(report.sections)) # print("PLUGIN SAYS -> dir(report) -> {0}".format(dir(report))) # print("PLUGIN SAYS -> type(report) -> {0}".format(type(report))) - sections = [item for item in report.sections if item[0] not in ("Captured stdout call", "Captured stderr call", "Captured stdout setup", "Captured stderr setup")] + sections = [item for item in report.sections if item[0] not in ("Captured stdout call", "Captured stderr call", "Captured stdout setup", "Captured stderr setup", "Captured stdout teardown", "Captured stderr teardown")] # print("PLUGIN SAYS -> sections -> {0}".format(sections)) report.sections = sections
08aefdf3e5a991293ad9ce1cc7f1112a01e4506d
trade_server.py
trade_server.py
import threading import socket import SocketServer messages = [] class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): try: while True: data = self.request.recv(1024) if data: messages.append(data) print "MESSAGES: {}".format(messages) cur_thread = threading.current_thread() response = "{}: {}".format(cur_thread.name, data) self.request.sendall(response) except socket.error: # Surpress errno 13 Broken Pipe pass class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass def create_server(host="localhost", port=0): server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler) server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() return server
import json import threading import socket import SocketServer from orderbook import match_bid, offers, bids messages = [] class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): try: while True: data = self.request.recv(1024) if data: data = json.loads(data) messages.append(data) print "MESSAGES: {}".format(messages) if data['type'] == 'bid': response = handle_bid(data) elif data['type'] == 'offer': response = handle_offer(data) cur_thread = threading.current_thread() response = "\n{}: {}".format(cur_thread.name, data) self.request.sendall(response) except socket.error: # Surpress errno 13 Broken Pipe pass class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass def create_server(host="localhost", port=0): server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler) server_thread = threading.Thread(target=server.serve_forever) server_thread.daemon = True server_thread.start() return server def handle_offer(offer): offers.append(offer) def handle_bid(bid): bids.append(bid)
Add basic handling of incoming bids and offers.
Add basic handling of incoming bids and offers.
Python
mit
Tribler/decentral-market
--- +++ @@ -1,6 +1,9 @@ +import json import threading import socket import SocketServer + +from orderbook import match_bid, offers, bids messages = [] @@ -12,10 +15,15 @@ while True: data = self.request.recv(1024) if data: + data = json.loads(data) messages.append(data) print "MESSAGES: {}".format(messages) + if data['type'] == 'bid': + response = handle_bid(data) + elif data['type'] == 'offer': + response = handle_offer(data) cur_thread = threading.current_thread() - response = "{}: {}".format(cur_thread.name, data) + response = "\n{}: {}".format(cur_thread.name, data) self.request.sendall(response) except socket.error: # Surpress errno 13 Broken Pipe @@ -32,3 +40,10 @@ server_thread.daemon = True server_thread.start() return server + + +def handle_offer(offer): + offers.append(offer) + +def handle_bid(bid): + bids.append(bid)
c8828d563a3db96a52544c6bbe4ca219efd364c5
falmer/events/filters.py
falmer/events/filters.py
from django_filters import FilterSet, CharFilter, IsoDateTimeFilter from . import models class EventFilterSet(FilterSet): class Meta: model = models.Event fields = ( 'title', 'venue', 'type', 'bundle', 'parent', 'brand', 'student_group', 'from_time', 'to_time', ) title = CharFilter(lookup_expr='icontains') brand = CharFilter(field_name='brand__slug') to_time = IsoDateTimeFilter(field_name='start_time', lookup_expr='lte') from_time = IsoDateTimeFilter(field_name='end_time', lookup_expr='gte')
from django_filters import FilterSet, CharFilter, IsoDateTimeFilter from . import models class EventFilterSet(FilterSet): class Meta: model = models.Event fields = ( 'title', 'venue', 'type', 'bundle', 'parent', 'brand', 'student_group', 'from_time', 'to_time', 'audience_just_for_pgs', 'audience_suitable_kids_families', 'audience_good_to_meet_people', 'is_over_18_only', 'cost', 'alcohol', 'type' ) title = CharFilter(lookup_expr='icontains') brand = CharFilter(field_name='brand__slug') to_time = IsoDateTimeFilter(field_name='start_time', lookup_expr='lte') from_time = IsoDateTimeFilter(field_name='end_time', lookup_expr='gte')
Add filtering options to events
Add filtering options to events
Python
mit
sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer
--- +++ @@ -15,6 +15,14 @@ 'student_group', 'from_time', 'to_time', + + 'audience_just_for_pgs', + 'audience_suitable_kids_families', + 'audience_good_to_meet_people', + 'is_over_18_only', + 'cost', + 'alcohol', + 'type' ) title = CharFilter(lookup_expr='icontains')
45501645e06743bd6341cfd6d2573f6c5f36d094
netmiko/ubiquiti/__init__.py
netmiko/ubiquiti/__init__.py
from netmiko.ubiquiti.edge_ssh import UbiquitiEdgeSSH from netmiko.ubiquiti.edgerouter_ssh import UbiquitiEdgeRouterSSH from netmiko.ubiquiti.unifiswitch_ssh import UbiquitiUnifiSwitchSSH __all__ = [ "UbiquitiEdgeRouterSSH", "UbiquitiEdgeSSH", "UnifiSwitchSSH", "UbiquitiUnifiSwitchSSH", ]
from netmiko.ubiquiti.edge_ssh import UbiquitiEdgeSSH from netmiko.ubiquiti.edgerouter_ssh import UbiquitiEdgeRouterSSH from netmiko.ubiquiti.unifiswitch_ssh import UbiquitiUnifiSwitchSSH __all__ = [ "UbiquitiEdgeRouterSSH", "UbiquitiEdgeSSH", "UbiquitiUnifiSwitchSSH", ]
Fix __all__ import for ubiquiti
Fix __all__ import for ubiquiti
Python
mit
ktbyers/netmiko,ktbyers/netmiko
--- +++ @@ -5,6 +5,5 @@ __all__ = [ "UbiquitiEdgeRouterSSH", "UbiquitiEdgeSSH", - "UnifiSwitchSSH", "UbiquitiUnifiSwitchSSH", ]
34c85636d11bc156a4ce4e5956ed1a19fe7f6f1f
buffer/models/profile.py
buffer/models/profile.py
import json from buffer.response import ResponseObject PATHS = { 'GET_PROFILES': 'profiles.json', 'GET_PROFILE': 'profiles/%s.json', 'GET_SCHEDULES': 'profiles/%s/schedules.json', 'UPDATE_SCHEDULES': 'profiles/%s/schedules/update.json' } class Profile(ResponseObject): def __init__(self, api, raw_response): super(Profile, self).__init__(raw_response) self.api = api def __getattr__(self, name): if callable(name): name() if hasattr(self, name): return getattr(self, name) if hasattr(self, "_get_%s" % name): return getattr(self, "_get_%s" % name)() def _get_schedules(self): url = PATHS['GET_SCHEDULES'] % self.id self.schedules = self.api.get(url=url, parser=json.loads) return self.schedules
import json from buffer.response import ResponseObject PATHS = { 'GET_PROFILES': 'profiles.json', 'GET_PROFILE': 'profiles/%s.json', 'GET_SCHEDULES': 'profiles/%s/schedules.json', 'UPDATE_SCHEDULES': 'profiles/%s/schedules/update.json' } class Profile(ResponseObject): def __init__(self, api, raw_response): super(Profile, self).__init__(raw_response) self.api = api def __getattr__(self, name): if callable(name): name() if hasattr(self, name): return getattr(self, name) if hasattr(self, "_get_%s" % name): return getattr(self, "_get_%s" % name)() def _post_schedules(self, schedules): url = PATHS['UPDATE_SCHEDULES'] % self.id data_format = "schedules[0][%s][]=%s&" post_data = "" for format_type, values in schedules.iteritems(): for value in values: post_data += data_format % (format_type, value) self.api.post(url=url, parser=json.loads, data=post_data) def _get_schedules(self): url = PATHS['GET_SCHEDULES'] % self.id self.schedules = self.api.get(url=url, parser=json.loads) return self.schedules
Update the schedules times and days
Update the schedules times and days
Python
mit
vtemian/buffpy,bufferapp/buffer-python
--- +++ @@ -26,6 +26,18 @@ if hasattr(self, "_get_%s" % name): return getattr(self, "_get_%s" % name)() + def _post_schedules(self, schedules): + url = PATHS['UPDATE_SCHEDULES'] % self.id + + data_format = "schedules[0][%s][]=%s&" + post_data = "" + + for format_type, values in schedules.iteritems(): + for value in values: + post_data += data_format % (format_type, value) + + self.api.post(url=url, parser=json.loads, data=post_data) + def _get_schedules(self): url = PATHS['GET_SCHEDULES'] % self.id
c4406ffae02a4ea87a139b1d67d98d9c0c7a468b
train.py
train.py
import tensorflow as tf import driving_data import model sess = tf.InteractiveSession() loss = tf.reduce_mean(tf.square(tf.sub(model.y_, model.y))) train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss) sess.run(tf.initialize_all_variables()) saver = tf.train.Saver() #train over the dataset about 30 times for i in range(int(driving_data.num_images * 0.3)): xs, ys = driving_data.LoadBatch(100) train_step.run(feed_dict={model.x: xs, model.y_: ys, model.keep_prob: 0.8}) if i % 10 == 0: print("step %d, train loss %g"%(i, loss.eval(feed_dict={ model.x:xs, model.y_: ys, model.keep_prob: 1.0}))) if i % 100 == 0: save_path = saver.save(sess, "save/model.ckpt") print("Model saved in file: %s" % save_path)
import os import tensorflow as tf import driving_data import model LOGDIR = './save' sess = tf.InteractiveSession() loss = tf.reduce_mean(tf.square(tf.sub(model.y_, model.y))) train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss) sess.run(tf.initialize_all_variables()) saver = tf.train.Saver() #train over the dataset about 30 times for i in range(int(driving_data.num_images * 0.3)): xs, ys = driving_data.LoadBatch(100) train_step.run(feed_dict={model.x: xs, model.y_: ys, model.keep_prob: 0.8}) if i % 10 == 0: print("step %d, train loss %g"%(i, loss.eval(feed_dict={ model.x:xs, model.y_: ys, model.keep_prob: 1.0}))) if i % 100 == 0: if not os.path.exists(LOGDIR): os.makedirs(LOGDIR) checkpoint_path = os.path.join(LOGDIR, "model.ckpt") filename = saver.save(sess, checkpoint_path) print("Model saved in file: %s" % filename)
Add check for folder to save checkpoints
Add check for folder to save checkpoints
Python
apache-2.0
tmaila/autopilot,tmaila/autopilot,SullyChen/Autopilot-TensorFlow,tmaila/autopilot
--- +++ @@ -1,6 +1,9 @@ +import os import tensorflow as tf import driving_data import model + +LOGDIR = './save' sess = tf.InteractiveSession() @@ -18,5 +21,8 @@ print("step %d, train loss %g"%(i, loss.eval(feed_dict={ model.x:xs, model.y_: ys, model.keep_prob: 1.0}))) if i % 100 == 0: - save_path = saver.save(sess, "save/model.ckpt") - print("Model saved in file: %s" % save_path) + if not os.path.exists(LOGDIR): + os.makedirs(LOGDIR) + checkpoint_path = os.path.join(LOGDIR, "model.ckpt") + filename = saver.save(sess, checkpoint_path) + print("Model saved in file: %s" % filename)
7eedd155f9f6e6361bdfc6fe84311ae38574d3fe
config/fuzzer_params.py
config/fuzzer_params.py
switch_failure_rate = 0.05 switch_recovery_rate = 0.05 dataplane_drop_rate = 0.0 dataplane_delay_rate = 0.0 controlplane_block_rate = 0.0 controlplane_unblock_rate = 1.0 ofp_message_receipt_rate = 1.0 link_failure_rate = 0.05 link_recovery_rate = 0.05 controller_crash_rate = 0.0 controller_recovery_rate = 0.0 traffic_generation_rate = 0.1 host_migration_rate = 0.05
switch_failure_rate = 0.0 switch_recovery_rate = 0.0 dataplane_drop_rate = 0.0 dataplane_delay_rate = 0.0 controlplane_block_rate = 0.0 controlplane_unblock_rate = 1.0 ofp_message_receipt_rate = 1.0 link_failure_rate = 0.0 link_recovery_rate = 0.0 controller_crash_rate = 0.0 controller_recovery_rate = 0.0 traffic_generation_rate = 0.3 host_migration_rate = 0.0
Set fuzzer params to zero for now
Set fuzzer params to zero for now
Python
apache-2.0
jmiserez/sts,ucb-sts/sts,jmiserez/sts,ucb-sts/sts
--- +++ @@ -1,13 +1,13 @@ -switch_failure_rate = 0.05 -switch_recovery_rate = 0.05 +switch_failure_rate = 0.0 +switch_recovery_rate = 0.0 dataplane_drop_rate = 0.0 dataplane_delay_rate = 0.0 controlplane_block_rate = 0.0 controlplane_unblock_rate = 1.0 ofp_message_receipt_rate = 1.0 -link_failure_rate = 0.05 -link_recovery_rate = 0.05 +link_failure_rate = 0.0 +link_recovery_rate = 0.0 controller_crash_rate = 0.0 controller_recovery_rate = 0.0 -traffic_generation_rate = 0.1 -host_migration_rate = 0.05 +traffic_generation_rate = 0.3 +host_migration_rate = 0.0
c1f8a586e4e4dcad16c0fc9261f61f93b2488830
content/test/gpu/gpu_tests/pixel_expectations.py
content/test/gpu/gpu_tests/pixel_expectations.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import test_expectations # Valid expectation conditions are: # # Operating systems: # win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion, # linux, chromeos, android # # GPU vendors: # amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm, # vivante # # Specific GPUs can be listed as a tuple with vendor name and device ID. # Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604') # Device IDs must be paired with a GPU vendor. class PixelExpectations(test_expectations.TestExpectations): def SetExpectations(self): # Sample Usage: # self.Fail('Pixel.Canvas2DRedBox', # ['mac', 'amd', ('nvidia', 0x1234)], bug=123) pass
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import test_expectations # Valid expectation conditions are: # # Operating systems: # win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion, # linux, chromeos, android # # GPU vendors: # amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm, # vivante # # Specific GPUs can be listed as a tuple with vendor name and device ID. # Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604') # Device IDs must be paired with a GPU vendor. class PixelExpectations(test_expectations.TestExpectations): def SetExpectations(self): # Sample Usage: # self.Fail('Pixel.Canvas2DRedBox', # ['mac', 'amd', ('nvidia', 0x1234)], bug=123) self.Fail('Pixel.CSS3DBlueBox', bug=368495) pass
Revert 273986 "Remove failing expectations for pixel tests."
Revert 273986 "Remove failing expectations for pixel tests." Re-enable the failing expectations for the Pixel.CSS3DBlueBox test. The <meta viewport> tag added to this test is causing failures on some desktop bots. See Issue 368495. > Remove failing expectations for pixel tests. > > This is a follow-up patch for r273755. > > BUG=368495 > TBR=kbr@chromium.org > > Review URL: https://codereview.chromium.org/304183008 TBR=alokp@chromium.org Review URL: https://codereview.chromium.org/306303002 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@274176 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
M4sse/chromium.src,Chilledheart/chromium,ondra-novak/chromium.src,jaruba/chromium.src,ltilve/chromium,littlstar/chromium.src,ltilve/chromium,dushu1203/chromium.src,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,chuan9/chromium-crosswalk,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,chuan9/chromium-crosswalk,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,littlstar/chromium.src,fujunwei/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,markYoungH/chromium.src,axinging/chromium-crosswalk,dushu1203/chromium.src,dednal/chromium.src,bright-sparks/chromium-spacewalk,Just-D/chromium-1,ltilve/chromium,fujunwei/chromium-crosswalk,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,ltilve/chromium,markYoungH/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,markYoungH/chromium.src,M4sse/chromium.src,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,Chilledheart/chromium,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,jaruba/chromium.src,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,littlstar/chromium.src,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,dednal/chromium.src,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ltilve/chromium,dednal/chromium.src,dednal/chromium.src,ltilve/chromium,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,Chilledheart/chromium,markYoungH/chromium.src,M4sse/chromium.src,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,dushu1203/chromium.src,Fireblend/chromium-crosswalk,jaruba/chromium.src,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,axinging/chromium-crosswalk,Just-D/chromium-1,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,jaruba/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,Just-D/chromium-1,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,dednal/chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,dednal/chromium.src,Jonekee/chromium.src,M4sse/chromium.src,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,markYoungH/chromium.src,Just-D/chromium-1,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,littlstar/chromium.src,Just-D/chromium-1,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,M4sse/chromium.src,jaruba/chromium.src,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,Just-D/chromium-1,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,chuan9/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,Jonekee/chromium.src,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,M4sse/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,fujunwei/chromium-crosswalk,M4sse/chromium.src,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,dushu1203/chromium.src,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,dednal/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,Just-D/chromium-1,ondra-novak/chromium.src
--- +++ @@ -24,4 +24,6 @@ # self.Fail('Pixel.Canvas2DRedBox', # ['mac', 'amd', ('nvidia', 0x1234)], bug=123) + self.Fail('Pixel.CSS3DBlueBox', bug=368495) + pass
06356979dd377137c77139c45a0b40deea3f5b27
tests/test_api.py
tests/test_api.py
import scipy.interpolate import numpy as np import naturalneighbor def test_output_size_matches_scipy(): points = np.random.rand(10, 3) values = np.random.rand(10) grid_ranges = [ [0, 4, 0.6], # step isn't a multiple [-3, 3, 1.0], # step is a multiple [0, 1, 3], # step is larger than stop - start ] mesh_grids = tuple(np.mgrid[ grid_ranges[0][0]:grid_ranges[0][1]:grid_ranges[0][2], grid_ranges[1][0]:grid_ranges[1][1]:grid_ranges[1][2], grid_ranges[2][0]:grid_ranges[2][1]:grid_ranges[2][2], ]) scipy_result = scipy.interpolate.griddata(points, values, mesh_grids) nn_result = naturalneighbor.griddata(points, values, grid_ranges) assert scipy_result.shape == nn_result.shape
import scipy.interpolate import numpy as np import pytest import naturalneighbor @pytest.mark.parametrize("grid_ranges", [ [[0, 4, 0.6], [-3, 3, 1.0], [0, 1, 3]], [[0, 2, 1], [0, 2, 1j], [0, 2, 2j]], ]) def test_output_size_matches_scipy(grid_ranges): points = np.random.rand(10, 3) values = np.random.rand(10) mesh_grids = tuple(np.mgrid[ grid_ranges[0][0]:grid_ranges[0][1]:grid_ranges[0][2], grid_ranges[1][0]:grid_ranges[1][1]:grid_ranges[1][2], grid_ranges[2][0]:grid_ranges[2][1]:grid_ranges[2][2], ]) scipy_result = scipy.interpolate.griddata(points, values, mesh_grids) nn_result = naturalneighbor.griddata(points, values, grid_ranges) assert scipy_result.shape == nn_result.shape
Add test for complex indexing
Add test for complex indexing
Python
mit
innolitics/natural-neighbor-interpolation,innolitics/natural-neighbor-interpolation,innolitics/natural-neighbor-interpolation
--- +++ @@ -1,18 +1,17 @@ import scipy.interpolate import numpy as np +import pytest import naturalneighbor -def test_output_size_matches_scipy(): +@pytest.mark.parametrize("grid_ranges", [ + [[0, 4, 0.6], [-3, 3, 1.0], [0, 1, 3]], + [[0, 2, 1], [0, 2, 1j], [0, 2, 2j]], +]) +def test_output_size_matches_scipy(grid_ranges): points = np.random.rand(10, 3) values = np.random.rand(10) - - grid_ranges = [ - [0, 4, 0.6], # step isn't a multiple - [-3, 3, 1.0], # step is a multiple - [0, 1, 3], # step is larger than stop - start - ] mesh_grids = tuple(np.mgrid[ grid_ranges[0][0]:grid_ranges[0][1]:grid_ranges[0][2],
9a3b0e2fc81187a0ec91230552552805dc6593e4
profile_collection/startup/50-scans.py
profile_collection/startup/50-scans.py
# vim: sw=4 ts=4 sts expandtab smarttab # HXN step-scan configuration import hxntools.scans from bluesky.global_state import get_gs gs = get_gs() hxntools.scans.setup() ct = hxntools.scans.count ascan = hxntools.scans.absolute_scan dscan = hxntools.scans.relative_scan fermat = hxntools.scans.relative_fermat spiral = hxntools.scans.relative_spiral mesh = hxntools.scans.absolute_mesh dmesh = hxntools.scans.relative_mesh gs.DETS = [zebra, sclr1, merlin1, xspress3, smll, lakeshore2, xbpm, s1] gs.TABLE_COLS = ['sclr1_ch2','sclr1_ch3', 'sclr1_ch4', 'sclr1_ch4_calc', 'ssx', 'ssy', 'ssz', 't_base', 't_sample', 't_vlens', 't_hlens'] # Plot this by default versus motor position: gs.PLOT_Y = 'Det2_Pt' gs.OVERPLOT = False gs.BASELINE_DEVICES = []
# vim: sw=4 ts=4 sts expandtab smarttab # HXN step-scan configuration import hxntools.scans from bluesky.global_state import get_gs gs = get_gs() hxntools.scans.setup() ct = hxntools.scans.count ascan = hxntools.scans.absolute_scan dscan = hxntools.scans.relative_scan fermat = hxntools.scans.relative_fermat spiral = hxntools.scans.relative_spiral mesh = hxntools.scans.absolute_mesh dmesh = hxntools.scans.relative_mesh gs.DETS = [zebra, sclr1, merlin1, timepix1, xspress3, lakeshore2, xbpm, s1, roi1_tot] gs.TABLE_COLS = ['sclr1_ch2','sclr1_ch3', 'sclr1_ch4', 'sclr1_ch4_calc', 'ssx', 'ssy', 'ssz','roi1_tot', 't_base', 't_sample', 't_vlens', 't_hlens'] # Plot this by default versus motor position: gs.PLOT_Y = 'Det2_Pt' gs.OVERPLOT = False gs.BASELINE_DEVICES = [dcm, smll]
Move smll and dcm to baseline devices
Move smll and dcm to baseline devices
Python
bsd-2-clause
NSLS-II-HXN/ipython_ophyd,NSLS-II-HXN/ipython_ophyd
--- +++ @@ -15,12 +15,12 @@ mesh = hxntools.scans.absolute_mesh dmesh = hxntools.scans.relative_mesh -gs.DETS = [zebra, sclr1, merlin1, xspress3, smll, lakeshore2, xbpm, s1] -gs.TABLE_COLS = ['sclr1_ch2','sclr1_ch3', 'sclr1_ch4', 'sclr1_ch4_calc', 'ssx', 'ssy', 'ssz', +gs.DETS = [zebra, sclr1, merlin1, timepix1, xspress3, lakeshore2, xbpm, s1, roi1_tot] +gs.TABLE_COLS = ['sclr1_ch2','sclr1_ch3', 'sclr1_ch4', 'sclr1_ch4_calc', 'ssx', 'ssy', 'ssz','roi1_tot', 't_base', 't_sample', 't_vlens', 't_hlens'] # Plot this by default versus motor position: gs.PLOT_Y = 'Det2_Pt' gs.OVERPLOT = False -gs.BASELINE_DEVICES = [] +gs.BASELINE_DEVICES = [dcm, smll]
5adfc507d00da4b38486f3bf80880b91828d673e
trac/upgrades/tests/db44.py
trac/upgrades/tests/db44.py
# -*- coding: utf-8 -*- # # Copyright (C) 2017 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.org/wiki/TracLicense. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://trac.edgewall.org/log/. import unittest from trac.upgrades import db44 class UpgradeTestCase(unittest.TestCase): def test_replace_sql_fragment(self): fragments = [(" description AS _description, ", " t.description AS _description, "), (" description AS _description_, ", " t.description AS _description_, "), (" t.description AS _description,", None)] for query, expected in fragments: self.assertEquals(expected, db44.replace_sql_fragment(query)) def test_suite(): return unittest.makeSuite(UpgradeTestCase) if __name__ == '__main__': unittest.main(defaultTest='test_suite')
# -*- coding: utf-8 -*- # # Copyright (C) 2017 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.org/wiki/TracLicense. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://trac.edgewall.org/log/. import unittest from trac.upgrades import db44 class UpgradeTestCase(unittest.TestCase): def test_replace_sql_fragment(self): fragments = [(" description AS _description, ", " t.description AS _description, "), (" description AS _description_, ", " t.description AS _description_, "), (" t.description AS _description,", None)] for query, expected in fragments: self.assertEqual(expected, db44.replace_sql_fragment(query)) def test_suite(): return unittest.makeSuite(UpgradeTestCase) if __name__ == '__main__': unittest.main(defaultTest='test_suite')
Remove use of deprecated `assertEquals`
1.3.2dev: Remove use of deprecated `assertEquals` git-svn-id: 0d96b0c1a6983ccc08b3732614f4d6bfcf9cbb42@15981 af82e41b-90c4-0310-8c96-b1721e28e2e2
Python
bsd-3-clause
rbaumg/trac,rbaumg/trac,rbaumg/trac,rbaumg/trac
--- +++ @@ -26,7 +26,7 @@ (" t.description AS _description,", None)] for query, expected in fragments: - self.assertEquals(expected, db44.replace_sql_fragment(query)) + self.assertEqual(expected, db44.replace_sql_fragment(query)) def test_suite():
d857c08ce1207c10aaec30878fc119ddacf44363
tohu/derived_generators.py
tohu/derived_generators.py
from operator import attrgetter from .base import logger, DependentGenerator __all__ = ['ExtractAttribute'] class ExtractAttribute(DependentGenerator): """ Generator which produces items that are attributes extracted from the items produced by a different generator. """ def __init__(self, g, attr_name): logger.debug(f"Extracting attribute '{attr_name}' from parent={g}") self.parent = g self.gen = g.clone() self.attr_name = attr_name self.attrgetter = attrgetter(attr_name) def __repr__(self): return f"<ExtractAttribute '{self.attr_name}' from {self.parent} >" def _spawn_and_reattach_parent(self, new_parent): logger.debug(f'Spawning dependent generator {self} and re-attaching to new parent {new_parent}') return ExtractAttribute(new_parent, self.attr_name) def __next__(self): return self.attrgetter(next(self.gen))
from operator import attrgetter from .base import logger, DependentGenerator __all__ = ['ExtractAttribute', 'Lookup'] class ExtractAttribute(DependentGenerator): """ Generator which produces items that are attributes extracted from the items produced by a different generator. """ def __init__(self, g, attr_name): logger.debug(f"Extracting attribute '{attr_name}' from parent={g}") self.parent = g self.gen = g.clone() self.attr_name = attr_name self.attrgetter = attrgetter(attr_name) def __repr__(self): return f"<ExtractAttribute '{self.attr_name}' from {self.parent} >" def _spawn_and_reattach_parent(self, new_parent): logger.debug(f'Spawning dependent generator {self} and re-attaching to new parent {new_parent}') return ExtractAttribute(new_parent, self.attr_name) def __next__(self): return self.attrgetter(next(self.gen)) class Lookup(DependentGenerator): def __init__(self, g, mapping): self.parent = g self.gen = g.clone() self.mapping = mapping def __repr__(self): return f"<Lookup, parent={self.parent}, mapping={self.mapping}>" def _spawn_and_reattach_parent(self, new_parent): logger.debug(f'Spawning dependent generator {self} and re-attaching to new parent {new_parent}') return Lookup(new_parent, self.mapping) def __next__(self): return self.mapping[next(self.gen)]
Add generator Lookup which emulates a dictionary lookup for generators
Add generator Lookup which emulates a dictionary lookup for generators
Python
mit
maxalbert/tohu
--- +++ @@ -1,7 +1,7 @@ from operator import attrgetter from .base import logger, DependentGenerator -__all__ = ['ExtractAttribute'] +__all__ = ['ExtractAttribute', 'Lookup'] class ExtractAttribute(DependentGenerator): @@ -26,3 +26,21 @@ def __next__(self): return self.attrgetter(next(self.gen)) + + +class Lookup(DependentGenerator): + + def __init__(self, g, mapping): + self.parent = g + self.gen = g.clone() + self.mapping = mapping + + def __repr__(self): + return f"<Lookup, parent={self.parent}, mapping={self.mapping}>" + + def _spawn_and_reattach_parent(self, new_parent): + logger.debug(f'Spawning dependent generator {self} and re-attaching to new parent {new_parent}') + return Lookup(new_parent, self.mapping) + + def __next__(self): + return self.mapping[next(self.gen)]
2d7c286321683a9d3241d0e923f1f182adfd84be
sr/templatetags/sr.py
sr/templatetags/sr.py
from django import template register = template.Library() from .. import sr as sr_func @register.simple_tag(name='sr') def sr_tag(key, *args, **kwargs): return sr_func(key, *args, **kwargs) try: from django_jinja.base import Library jinja_register = Library() jinja_register.global_function("sr", sr_func) except ImportError: pass
from django import template register = template.Library() from .. import sr as sr_func @register.simple_tag(name='sr') def sr_tag(key, *args, **kwargs): return sr_func(key, *args, **kwargs) try: from django_jinja import library as jinja_library jinja_library.global_function("sr", sr_func) except ImportError: pass
Update support for new django-jinja versions. (backward incompatible)
Update support for new django-jinja versions. (backward incompatible)
Python
bsd-3-clause
jespino/django-sr
--- +++ @@ -7,10 +7,9 @@ def sr_tag(key, *args, **kwargs): return sr_func(key, *args, **kwargs) + try: - from django_jinja.base import Library - jinja_register = Library() - - jinja_register.global_function("sr", sr_func) + from django_jinja import library as jinja_library + jinja_library.global_function("sr", sr_func) except ImportError: pass
60ef934e3bef7c00fc2d1823901babb665a4888f
get_study_attachments.py
get_study_attachments.py
import sys import boto3 BUCKET_NAME = 'mitLookit' def get_all_study_attachments(study_uuid): s3 = boto3.resource('s3') bucket = s3.Bucket(BUCKET_NAME) study_files = [] for key in bucket.objects.filter(Prefix=f'videoStream_{study_uuid}'): study_files.append(key) return study_files if __name__ == '__main__': study_uuid = sys.argv[1] get_study_keys(study_uuid)
import sys import boto3 BUCKET_NAME = 'mitLookit' def get_all_study_attachments(study_uuid): s3 = boto3.resource('s3') bucket = s3.Bucket(BUCKET_NAME) return bucket.objects.filter(Prefix=f'videoStream_{study_uuid}') if __name__ == '__main__': study_uuid = sys.argv[1] get_study_keys(study_uuid)
Remove looping through items and appending them to list.
Remove looping through items and appending them to list.
Python
apache-2.0
CenterForOpenScience/lookit-api,pattisdr/lookit-api,pattisdr/lookit-api,pattisdr/lookit-api,CenterForOpenScience/lookit-api,CenterForOpenScience/lookit-api
--- +++ @@ -5,12 +5,8 @@ def get_all_study_attachments(study_uuid): s3 = boto3.resource('s3') - bucket = s3.Bucket(BUCKET_NAME) - study_files = [] - for key in bucket.objects.filter(Prefix=f'videoStream_{study_uuid}'): - study_files.append(key) - return study_files + return bucket.objects.filter(Prefix=f'videoStream_{study_uuid}') if __name__ == '__main__': study_uuid = sys.argv[1]
16c372c905f44608a1d1ccabb949ad9cb736dae6
tileserver.py
tileserver.py
import logging import os import json import TileStache if 'AWS_ACCESS_KEY_ID' in os.environ and \ 'AWS_SECRET_ACCESS_KEY' in os.environ: cache = { "name": "S3", "bucket": "telostats-tiles", "access": os.environ['AWS_ACCESS_KEY_ID'], "secret": os.environ['AWS_SECRET_ACCESS_KEY'] } else: cache = {"name": "Test"} cache = { 'name': 'memcache', 'servers': [os.environ.get('MEMCACHE_SERVERS')], 'username': os.environ.get('MEMCACHE_USERNAME'), 'password': os.environ.get('MEMCACHE_PASSWORD'), } config_dict = { "cache": cache, "layers": { "telaviv": { "provider": {"name": "mbtiles", "tileset": "Telostats.mbtiles"}, "projection": "spherical mercator" } } } config = TileStache.Config.buildConfiguration(config_dict, '.') application = TileStache.WSGITileServer(config=config, autoreload=False)
import logging import os import json import TileStache if 'AWS_ACCESS_KEY_ID' in os.environ and \ 'AWS_SECRET_ACCESS_KEY' in os.environ: cache = { "name": "S3", "bucket": "telostats-tiles", "access": os.environ['AWS_ACCESS_KEY_ID'], "secret": os.environ['AWS_SECRET_ACCESS_KEY'] } else: cache = {"name": "Test"} cache = { 'name': 'Memcache', 'servers': [os.environ.get('MEMCACHIER_SERVERS')], 'username': os.environ.get('MEMCACHIER_USERNAME'), 'password': os.environ.get('MEMCACHIER_PASSWORD'), } config_dict = { "cache": cache, "layers": { "telaviv": { "provider": {"name": "mbtiles", "tileset": "Telostats.mbtiles"}, "projection": "spherical mercator" } } } config = TileStache.Config.buildConfiguration(config_dict, '.') application = TileStache.WSGITileServer(config=config, autoreload=False)
Switch to memcachier dev plan
Switch to memcachier dev plan
Python
bsd-3-clause
idan/telostats-tiles
--- +++ @@ -16,10 +16,10 @@ cache = {"name": "Test"} cache = { - 'name': 'memcache', - 'servers': [os.environ.get('MEMCACHE_SERVERS')], - 'username': os.environ.get('MEMCACHE_USERNAME'), - 'password': os.environ.get('MEMCACHE_PASSWORD'), + 'name': 'Memcache', + 'servers': [os.environ.get('MEMCACHIER_SERVERS')], + 'username': os.environ.get('MEMCACHIER_USERNAME'), + 'password': os.environ.get('MEMCACHIER_PASSWORD'), } config_dict = {
4bfa74aa2ea9ef936d5ec5efbf32f2d6a8a10634
adr/recipes/config_durations.py
adr/recipes/config_durations.py
""" Get the average and total runtime for build platforms and types. .. code-block:: bash adr config_durations [--branch <branch>] """ from __future__ import absolute_import, print_function from ..query import run_query def run(config, args): # process config data data = run_query('config_durations', config, args)["data"] result = [] for record in data: if not record or not record[args.sort_key]: continue if isinstance(record[1], list): record[1] = record[1][-1] if record[2] is None: continue if record[3] is None: continue record[3] = round(record[3] / 60, 2) record.append(int(round(record[2] * record[3], 0))) result.append(record) result = sorted(result, key=lambda k: k[args.sort_key], reverse=True)[:args.limit] result.insert(0, ['Platform', 'Type', 'Num Jobs', 'Average Hours', 'Total Hours']) return result
""" Get the average and total runtime for build platforms and types. .. code-block:: bash adr config_durations [--branch <branch>] """ from __future__ import absolute_import, print_function from ..query import run_query BROKEN = True def run(config, args): # process config data data = run_query('config_durations', config, args)["data"] result = [] for record in data: if not record or not record[args.sort_key]: continue if isinstance(record[1], list): record[1] = record[1][-1] if record[2] is None: continue if record[3] is None: continue record[3] = round(record[3] / 60, 2) record.append(int(round(record[2] * record[3], 0))) result.append(record) result = sorted(result, key=lambda k: k[args.sort_key], reverse=True)[:args.limit] result.insert(0, ['Platform', 'Type', 'Num Jobs', 'Average Hours', 'Total Hours']) return result
Disable failing recipe in CRON tests
Disable failing recipe in CRON tests
Python
mpl-2.0
ahal/active-data-recipes,ahal/active-data-recipes
--- +++ @@ -8,6 +8,8 @@ from __future__ import absolute_import, print_function from ..query import run_query + +BROKEN = True def run(config, args):
ba75572bd7de9a441cad72fe90d7ec233e9c1a15
test/adapt.py
test/adapt.py
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: Apache 2.0 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> from __future__ import absolute_import, division, print_function, unicode_literals import sys from __init__ import TestCase from html5_parser import parse HTML = ''' <html lang="en" xml:lang="en"> <head><script>a < & " b</script><title>title</title></head> <body> <p>A <span>test</span> of text and tail <p><svg viewbox="v"><image xlink:href="h"> </body> <!-- A -- comment ---> </html> ''' class AdaptTest(TestCase): def test_etree(self): from xml.etree.ElementTree import tostring root = parse(HTML, treebuilder='etree') self.ae(root.tag, 'html') self.ae(root.attrib, {'xml:lang': 'en', 'lang': 'en'}) self.ae(root.find('./head/script').text, 'a < & " b') self.ae( tostring(root.find('body').find('p'), method='text').decode('ascii'), 'A test of text and tail\n') if sys.version_info.major > 2: self.assertIn('<!-- A -- comment --->', tostring(root))
#!/usr/bin/env python # vim:fileencoding=utf-8 # License: Apache 2.0 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> from __future__ import absolute_import, division, print_function, unicode_literals import sys from __init__ import TestCase from html5_parser import parse HTML = ''' <html lang="en" xml:lang="en"> <head><script>a < & " b</script><title>title</title></head> <body> <p>A <span>test</span> of text and tail <p><svg viewbox="v"><image xlink:href="h"> </body> <!-- A -- comment ---> </html> ''' class AdaptTest(TestCase): def test_etree(self): from xml.etree.ElementTree import tostring root = parse(HTML, treebuilder='etree') self.ae(root.tag, 'html') self.ae(root.attrib, {'xml:lang': 'en', 'lang': 'en'}) self.ae(root.find('./head/script').text, 'a < & " b') self.ae( tostring(root.find('body').find('p'), method='text').decode('ascii'), 'A test of text and tail\n') if sys.version_info.major > 2: self.assertIn('<!-- A -- comment --->', tostring(root).decode('ascii'))
Fix test failing on python 3
Fix test failing on python 3
Python
apache-2.0
kovidgoyal/html5-parser,kovidgoyal/html5-parser
--- +++ @@ -33,4 +33,4 @@ tostring(root.find('body').find('p'), method='text').decode('ascii'), 'A test of text and tail\n') if sys.version_info.major > 2: - self.assertIn('<!-- A -- comment --->', tostring(root)) + self.assertIn('<!-- A -- comment --->', tostring(root).decode('ascii'))
9ca0549ceff05f9f8a391c8ec2b685af48c0a5a8
scripts/common.py
scripts/common.py
import sys import psycopg2 import os import yaml if 'CATMAID_CONFIGURATION' in os.environ: path = os.environ['CATMAID_CONFIGURATION'] else: path = os.path.join(os.environ['HOME'], '.catmaid-db') try: conf = yaml.load(open(path)) except: print >> sys.stderr, '''Your %s file should look like: host: localhost database: catmaid username: catmaid_user password: password_of_your_catmaid_user''' % (path,) sys.exit(1) db_connection = psycopg2.connect(host=conf['host'], database=conf['database'], user=conf['username'], password=conf['password'])
import sys import psycopg2 import os import yaml if 'CATMAID_CONFIGURATION' in os.environ: path = os.environ['CATMAID_CONFIGURATION'] else: path = os.path.join(os.environ['HOME'], '.catmaid-db') try: conf = yaml.load(open(path)) except: print >> sys.stderr, '''Your %s file should look like: host: localhost database: catmaid username: catmaid_user password: password_of_your_catmaid_user''' % (path,) sys.exit(1) # Make a variable for each of these so that they can be imported: db_host = conf['host'] db_database = conf['database'] db_username = conf['username'] db_password = conf['password'] db_connection = psycopg2.connect(host=db_host, database=db_database, user=db_username, password=db_password)
Define variables for the DB name, host, etc. so they can be imported
Define variables for the DB name, host, etc. so they can be imported
Python
agpl-3.0
fzadow/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID,fzadow/CATMAID
--- +++ @@ -19,7 +19,13 @@ password: password_of_your_catmaid_user''' % (path,) sys.exit(1) -db_connection = psycopg2.connect(host=conf['host'], - database=conf['database'], - user=conf['username'], - password=conf['password']) +# Make a variable for each of these so that they can be imported: +db_host = conf['host'] +db_database = conf['database'] +db_username = conf['username'] +db_password = conf['password'] + +db_connection = psycopg2.connect(host=db_host, + database=db_database, + user=db_username, + password=db_password)
a26dc400c479572be59bfe90d8e809d2e9e65a63
python_humble_utils/pytest_commands.py
python_humble_utils/pytest_commands.py
import os def generate_tmp_file_path(tmpdir_factory, file_name_with_extension: str, tmp_dir_path: str = None) -> str: """ Generate file path rooted in a temporary dir. :param tmpdir_factory: py.test's tmpdir_factory fixture. :param file_name_with_extension: e.g. 'file.ext' :param tmp_dir_path: generated tmp file directory path relative to base tmp dir, e.g. 'file/is/here'. :return: generated file path. """ basetemp = tmpdir_factory.getbasetemp() if tmp_dir_path: if os.path.isabs(tmp_dir_path): raise ValueError('tmp_dir_path is not a relative path!') # http://stackoverflow.com/a/16595356/1557013 for tmp_file_dir_path_part in os.path.normpath(tmp_dir_path).split(os.sep): # Accounting for possible path separator at the end. if tmp_file_dir_path_part: tmpdir_factory.mktemp(tmp_file_dir_path_part) tmp_file_path = os.path.join(str(basetemp), tmp_dir_path, file_name_with_extension) else: tmp_file_path = str(basetemp.join(file_name_with_extension)) return tmp_file_path
import os def generate_tmp_file_path(tmpdir_factory, file_name_with_extension: str, tmp_dir_path: str = None) -> str: """ Generate file path relative to a temporary directory. :param tmpdir_factory: py.test's `tmpdir_factory` fixture. :param file_name_with_extension: file name with extension e.g. `file_name.ext`. :param tmp_dir_path: path to directory (relative to the temporary one created by `tmpdir_factory`) where the generated file path should reside. # noqa :return: file path. """ basetemp = tmpdir_factory.getbasetemp() if tmp_dir_path: if os.path.isabs(tmp_dir_path): raise ValueError('tmp_dir_path is not a relative path!') # http://stackoverflow.com/a/16595356/1557013 for tmp_file_dir_path_part in os.path.normpath(tmp_dir_path).split(os.sep): # Accounting for possible path separator at the end. if tmp_file_dir_path_part: tmpdir_factory.mktemp(tmp_file_dir_path_part) tmp_file_path = os.path.join(str(basetemp), tmp_dir_path, file_name_with_extension) else: tmp_file_path = str(basetemp.join(file_name_with_extension)) return tmp_file_path
Improve generate_tmp_file_path pytest command docs
Improve generate_tmp_file_path pytest command docs
Python
mit
webyneter/python-humble-utils
--- +++ @@ -5,13 +5,12 @@ file_name_with_extension: str, tmp_dir_path: str = None) -> str: """ - Generate file path rooted in a temporary dir. + Generate file path relative to a temporary directory. - :param tmpdir_factory: py.test's tmpdir_factory fixture. - :param file_name_with_extension: e.g. 'file.ext' - :param tmp_dir_path: generated tmp file directory path relative to base tmp dir, - e.g. 'file/is/here'. - :return: generated file path. + :param tmpdir_factory: py.test's `tmpdir_factory` fixture. + :param file_name_with_extension: file name with extension e.g. `file_name.ext`. + :param tmp_dir_path: path to directory (relative to the temporary one created by `tmpdir_factory`) where the generated file path should reside. # noqa + :return: file path. """ basetemp = tmpdir_factory.getbasetemp()
058e2e75384052dcc2b90690cef695e4533eb854
scripts/insert_demo.py
scripts/insert_demo.py
"""Insert the demo into the codemirror site.""" from __future__ import print_function import os import fileinput import shutil proselint_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) code_mirror_path = os.path.join( proselint_path, "plugins", "webeditor") code_mirror_demo_path = os.path.join(code_mirror_path, "index.html") live_write_path = os.path.join(proselint_path, "site", "write") shutil.copytree(code_mirror_path, live_write_path) demo_path = os.path.join(proselint_path, "proselint", "demo.md") with open(demo_path, "r") as f: demo = f.read() for line in fileinput.input( os.path.join(live_write_path, "index.html"), inplace=True): if "##DEMO_PLACEHOLDER##" in line: print(demo, end=' ') else: print(line, end=' ')
"""Insert the demo into the codemirror site.""" from __future__ import print_function import os import fileinput import shutil proselint_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) code_mirror_path = os.path.join( proselint_path, "plugins", "webeditor") code_mirror_demo_path = os.path.join(code_mirror_path, "index.html") live_write_path = os.path.join(proselint_path, "site", "write") if os.path.exists(live_write_path): shutil.rmtree(live_write_path) shutil.copytree(code_mirror_path, live_write_path) demo_path = os.path.join(proselint_path, "proselint", "demo.md") with open(demo_path, "r") as f: demo = f.read() for line in fileinput.input( os.path.join(live_write_path, "index.html"), inplace=True): if "##DEMO_PLACEHOLDER##" in line: print(demo, end=' ') else: print(line, end=' ')
Delete live writing demo before loading new one
Delete live writing demo before loading new one
Python
bsd-3-clause
jstewmon/proselint,amperser/proselint,amperser/proselint,amperser/proselint,amperser/proselint,amperser/proselint,jstewmon/proselint,jstewmon/proselint
--- +++ @@ -16,6 +16,8 @@ live_write_path = os.path.join(proselint_path, "site", "write") +if os.path.exists(live_write_path): + shutil.rmtree(live_write_path) shutil.copytree(code_mirror_path, live_write_path) demo_path = os.path.join(proselint_path, "proselint", "demo.md")
6620032e9f8574c3e1dad37c111040eca570a751
features/memberships/models.py
features/memberships/models.py
from django.contrib.contenttypes import fields as contenttypes from django.db import models class Membership(models.Model): created_by = models.ForeignKey( 'gestalten.Gestalt', related_name='memberships_created') date_joined = models.DateField(auto_now_add=True) group = models.ForeignKey('groups.Group', related_name='memberships') member = models.ForeignKey('gestalten.Gestalt', related_name='memberships') def __str__(self): return "%s is member of %s since %s" % ( str(self.member.user.get_username()), str(self.group.slug), str(self.date_joined) ) class Meta: unique_together = ('group', 'member') class Application(models.Model): group = models.ForeignKey('groups.Group', related_name='applications') contributions = contenttypes.GenericRelation( 'contributions.Contribution', content_type_field='contribution_type', object_id_field='contribution_id', related_query_name='membership_application') @property def contribution(self): return self.contributions.first()
from django.contrib.contenttypes import fields as contenttypes from django.db import models from . import querysets class Membership(models.Model): class Meta: unique_together = ('group', 'member') created_by = models.ForeignKey( 'gestalten.Gestalt', related_name='memberships_created') date_joined = models.DateField(auto_now_add=True) group = models.ForeignKey('groups.Group', related_name='memberships') member = models.ForeignKey('gestalten.Gestalt', related_name='memberships') objects = models.Manager.from_queryset(querysets.MembershipQuerySet)() def __str__(self): return "%s is member of %s since %s" % ( str(self.member.user.get_username()), str(self.group.slug), str(self.date_joined) ) class Application(models.Model): group = models.ForeignKey('groups.Group', related_name='applications') contributions = contenttypes.GenericRelation( 'contributions.Contribution', content_type_field='contribution_type', object_id_field='contribution_id', related_query_name='membership_application') @property def contribution(self): return self.contributions.first()
Add queryset for ordering memberships by activity
Add queryset for ordering memberships by activity
Python
agpl-3.0
stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten
--- +++ @@ -1,22 +1,26 @@ from django.contrib.contenttypes import fields as contenttypes from django.db import models +from . import querysets + class Membership(models.Model): + class Meta: + unique_together = ('group', 'member') + created_by = models.ForeignKey( 'gestalten.Gestalt', related_name='memberships_created') date_joined = models.DateField(auto_now_add=True) group = models.ForeignKey('groups.Group', related_name='memberships') member = models.ForeignKey('gestalten.Gestalt', related_name='memberships') + objects = models.Manager.from_queryset(querysets.MembershipQuerySet)() + def __str__(self): return "%s is member of %s since %s" % ( str(self.member.user.get_username()), str(self.group.slug), str(self.date_joined) ) - - class Meta: - unique_together = ('group', 'member') class Application(models.Model):
13301dfe93bcdd44218166bdab1c7aeacd4e4a7c
winthrop/annotation/models.py
winthrop/annotation/models.py
from urllib.parse import urlparse from django.db import models from django.urls import resolve, Resolver404 from annotator_store.models import BaseAnnotation from djiffy.models import Canvas from winthrop.people.models import Person class Annotation(BaseAnnotation): # NOTE: do we want to associate explicitly with canvas in the db? # could just use uri, but faster lookup if we associate... canvas = models.ForeignKey(Canvas, null=True, blank=True) author = models.ForeignKey(Person, null=True, blank=True) def info(self): info = super(Annotation, self).info() info['extra_data'] = 'foo' return info def save(self, *args, **kwargs): # NOTE: could set the canvas uri in javascript instead # of using page uri, but for now determine canvas id # based on the page uri try: match = resolve(urlparse(self.uri).path) if match.url_name == 'page' and 'djiffy' in match.namespaces: self.canvas = Canvas.objects.get( short_id=match.kwargs['id'], book__short_id=match.kwargs['book_id'] ) except Resolver404: pass super(Annotation, self).save()
from urllib.parse import urlparse from django.db import models from django.urls import resolve, Resolver404 from annotator_store.models import BaseAnnotation from djiffy.models import Canvas from winthrop.people.models import Person class Annotation(BaseAnnotation): # NOTE: do we want to associate explicitly with canvas in the db? # could just use uri, but faster lookup if we associate... canvas = models.ForeignKey(Canvas, null=True, blank=True) author = models.ForeignKey(Person, null=True, blank=True) def info(self): info = super(Annotation, self).info() info['extra_data'] = 'foo' return info def save(self, *args, **kwargs): # for image annotation, URI should be set to canvas URI; look up # canvas by URI and associate with the record self.canvas = None try: self.canvas = Canvas.objects.get(uri=self.uri) except Canvas.DoesNotExist: pass super(Annotation, self).save() def handle_extra_data(self, data, request): '''Handle any "extra" data that is not part of the stock annotation data model. Use this method to customize the logic for updating an annotation from request data.''' if 'author' in data: self.author = Person.objects.get(id=data['author']['id']) del data['author'] return data def info(self): # extend the default info impleentation (used to generate json) # to include local database fields in the output info = super(Annotation, self).info() if self.author: info['author'] = { 'name': self.author.authorized_name, 'id': self.author.id } return info
Add author field & autocomplete to annotation model+interface
Add author field & autocomplete to annotation model+interface
Python
apache-2.0
Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django
--- +++ @@ -19,21 +19,38 @@ return info def save(self, *args, **kwargs): - # NOTE: could set the canvas uri in javascript instead - # of using page uri, but for now determine canvas id - # based on the page uri + # for image annotation, URI should be set to canvas URI; look up + # canvas by URI and associate with the record + self.canvas = None try: - match = resolve(urlparse(self.uri).path) - if match.url_name == 'page' and 'djiffy' in match.namespaces: - self.canvas = Canvas.objects.get( - short_id=match.kwargs['id'], - book__short_id=match.kwargs['book_id'] - ) - except Resolver404: + self.canvas = Canvas.objects.get(uri=self.uri) + except Canvas.DoesNotExist: pass super(Annotation, self).save() + def handle_extra_data(self, data, request): + '''Handle any "extra" data that is not part of the stock annotation + data model. Use this method to customize the logic for updating + an annotation from request data.''' + if 'author' in data: + self.author = Person.objects.get(id=data['author']['id']) + del data['author'] + + return data + + def info(self): + # extend the default info impleentation (used to generate json) + # to include local database fields in the output + info = super(Annotation, self).info() + if self.author: + info['author'] = { + 'name': self.author.authorized_name, + 'id': self.author.id + } + return info + +
045ead44ef69d6ebf2cb0dddf084762efcc62995
handlers/base_handler.py
handlers/base_handler.py
from collections import OrderedDict class BaseHandler: def __init__(self, file, file_name): self.file = file self.file_name = file_name self.info = OrderedDict() def read(self, offset, size): return self.file[offset:offset + size]
from collections import OrderedDict class BaseHandler: def __init__(self, file, file_name): self.file = file self.file_name = file_name self.info = OrderedDict() def read(self, offset, size): if offset < 0: raise IndexError("File offset must be greater than 0") if offset + size >= len(self.file): raise IndexError("Cannot read beyond the end of the file") return self.file[offset:offset + size]
Add bounds checking to BaseHandler.read()
Add bounds checking to BaseHandler.read()
Python
mit
drx/rom-info
--- +++ @@ -8,4 +8,10 @@ self.info = OrderedDict() def read(self, offset, size): + if offset < 0: + raise IndexError("File offset must be greater than 0") + + if offset + size >= len(self.file): + raise IndexError("Cannot read beyond the end of the file") + return self.file[offset:offset + size]
7d4b58da2fd5040052ce2d7be924f1fd34be4ee7
picaxe/local_settings_example.py
picaxe/local_settings_example.py
__author__ = 'peter' # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Your uploaded files will be stored in <MEDIA_ROOT>/photologue/, so set it correctly! MEDIA_ROOT = './media/' MEDIA_URL = '/media/'
__author__ = 'peter' # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Turn debugging off for production environments! DEBUG = False # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Your uploaded files will be stored in <MEDIA_ROOT>/photologue/, so set it correctly! MEDIA_ROOT = './media/' MEDIA_URL = '/media/'
Add debugging setting to local_settings
Add debugging setting to local_settings
Python
mit
TuinfeesT/PicAxe
--- +++ @@ -3,6 +3,9 @@ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) + +# Turn debugging off for production environments! +DEBUG = False # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases
d153696d44220523d072653b9ff0f0d01eef325f
django_enum_js/__init__.py
django_enum_js/__init__.py
import json class EnumWrapper: def __init__(self): self.registered_enums = {} def register_enum(self, enum_class): self.registered_enums[enum_class.__name__] = enum_class def _enum_to_dict(self, enum_class): return dict([(k,v) for k,v in enum_class.__dict__.items() if not k[:2] == '__']) def _json_dump_enum(self, enum_class): return json.dumps(self._enum_to_dict(enum_class)) def get_json_formatted_enums(self): data = {} for identifier, enum_content in self.registered_enums.items(): data[identifier] = self._enum_to_dict(enum_content) return json.dumps(data) enum_wrapper = EnumWrapper()
import json class EnumWrapper: def __init__(self): self.registered_enums = {} def register_enum(self, enum_class): self.registered_enums[enum_class.__name__] = enum_class return enum_class def _enum_to_dict(self, enum_class): return dict([(k,v) for k,v in enum_class.__dict__.items() if not k[:2] == '__']) def _json_dump_enum(self, enum_class): return json.dumps(self._enum_to_dict(enum_class)) def get_json_formatted_enums(self): data = {} for identifier, enum_content in self.registered_enums.items(): data[identifier] = self._enum_to_dict(enum_content) return json.dumps(data) enum_wrapper = EnumWrapper()
Allow using register_enum as a decorator
Allow using register_enum as a decorator By returning the original class instance, it'd be possible to use `enum_wrapper.register_enum` as a decorator, making the usage cleaner while staying backwards compatible: ```python @enum_wrapper.register_enum class MyAwesomeClass: pass ```
Python
mit
leifdenby/django_enum_js
--- +++ @@ -6,6 +6,7 @@ def register_enum(self, enum_class): self.registered_enums[enum_class.__name__] = enum_class + return enum_class def _enum_to_dict(self, enum_class): return dict([(k,v) for k,v in enum_class.__dict__.items() if not k[:2] == '__'])
6dcb33004c3775d707f362a6f2c8217c1d558f56
kobin/server_adapters.py
kobin/server_adapters.py
from typing import Dict, Any class ServerAdapter: quiet = False def __init__(self, host: str='127.0.0.1', port: int=8080, **options) -> None: self.options = options self.host = host self.port = int(port) def run(self, handler): pass def __repr__(self): args = ', '.join(['%s=%s' % (k, repr(v)) for k, v in self.options.items()]) return "%s(%s)" % (self.__class__.__name__, args) class WSGIRefServer(ServerAdapter): def run(self, app): from wsgiref.simple_server import make_server # type: ignore self.httpd = make_server(self.host, self.port, app) self.port = self.httpd.server_port try: self.httpd.serve_forever() except KeyboardInterrupt: self.httpd.server_close() raise servers = { 'wsgiref': WSGIRefServer, } # type: Dict[str, Any]
from typing import Dict, Any class ServerAdapter: quiet = False def __init__(self, host: str='127.0.0.1', port: int=8080, **options) -> None: self.options = options self.host = host self.port = int(port) def run(self, handler): pass def __repr__(self): args = ', '.join(['%s=%s' % (k, repr(v)) for k, v in self.options.items()]) return "%s(%s)" % (self.__class__.__name__, args) class WSGIRefServer(ServerAdapter): def run(self, app): from wsgiref.simple_server import make_server # type: ignore self.httpd = make_server(self.host, self.port, app) self.port = self.httpd.server_port try: self.httpd.serve_forever() except KeyboardInterrupt: self.httpd.server_close() raise class GunicornServer(ServerAdapter): def run(self, handler): from gunicorn.app.base import Application config = {'bind': "%s:%d" % (self.host, int(self.port))} config.update(self.options) class GunicornApplication(Application): def init(self, parser, opts, args): return config def load(self): return handler GunicornApplication().run() servers = { 'wsgiref': WSGIRefServer, 'gunicorn': GunicornServer, } # type: Dict[str, Any]
Add a gunicorn server adpter
Add a gunicorn server adpter
Python
mit
kobinpy/kobin,kobinpy/kobin,c-bata/kobin,c-bata/kobin
--- +++ @@ -30,6 +30,24 @@ self.httpd.server_close() raise + +class GunicornServer(ServerAdapter): + def run(self, handler): + from gunicorn.app.base import Application + + config = {'bind': "%s:%d" % (self.host, int(self.port))} + config.update(self.options) + + class GunicornApplication(Application): + def init(self, parser, opts, args): + return config + + def load(self): + return handler + + GunicornApplication().run() + servers = { 'wsgiref': WSGIRefServer, + 'gunicorn': GunicornServer, } # type: Dict[str, Any]
b7486b64cabc0ad4c022a520bb630fb88cb35e53
feincms/content/raw/models.py
feincms/content/raw/models.py
from django.db import models from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ from django import forms class RawContent(models.Model): text = models.TextField(_('content'), blank=True) class Meta: abstract = True verbose_name = _('raw content') verbose_name_plural = _('raw contents') @property def media(self): return forms.Media( css={'all': ('whatever.css',)}, js=('something.js',), ) def render(self, **kwargs): return mark_safe(self.text)
from django.db import models from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ from django import forms class RawContent(models.Model): text = models.TextField(_('content'), blank=True) class Meta: abstract = True verbose_name = _('raw content') verbose_name_plural = _('raw contents') def render(self, **kwargs): return mark_safe(self.text)
Remove test content type media from RawContent
Remove test content type media from RawContent
Python
bsd-3-clause
feincms/feincms,joshuajonah/feincms,pjdelport/feincms,feincms/feincms,matthiask/django-content-editor,joshuajonah/feincms,nickburlett/feincms,nickburlett/feincms,michaelkuty/feincms,mjl/feincms,joshuajonah/feincms,matthiask/django-content-editor,nickburlett/feincms,michaelkuty/feincms,matthiask/feincms2-content,nickburlett/feincms,matthiask/django-content-editor,hgrimelid/feincms,feincms/feincms,hgrimelid/feincms,michaelkuty/feincms,matthiask/feincms2-content,pjdelport/feincms,matthiask/feincms2-content,pjdelport/feincms,michaelkuty/feincms,mjl/feincms,hgrimelid/feincms,mjl/feincms,matthiask/django-content-editor,joshuajonah/feincms
--- +++ @@ -12,13 +12,6 @@ verbose_name = _('raw content') verbose_name_plural = _('raw contents') - @property - def media(self): - return forms.Media( - css={'all': ('whatever.css',)}, - js=('something.js',), - ) - def render(self, **kwargs): return mark_safe(self.text)
34be718d554b7a1563e253710bc6d70cd81d77bd
normandy/recipes/validators.py
normandy/recipes/validators.py
import json import jsonschema from django.core.exceptions import ValidationError # Add path to required validator so we can get property name def _required(validator, required, instance, schema): '''Validate 'required' properties.''' if not validator.is_type(instance, 'object'): return for index, requirement in enumerate(required): if requirement not in instance or instance[requirement] == '': error = jsonschema.ValidationError( 'This field may not be blank.', path=[requirement] ) yield error # Construct validator as extension of Json Schema Draft 4. JSONSchemaValidator = jsonschema.validators.extend( validator=jsonschema.validators.Draft4Validator, validators={ 'required': _required } ) def validate_json(value): """ Validate that a given value can be successfully parsed as JSON. """ try: json.loads(value) except json.JSONDecodeError as err: raise ValidationError('%s is not valid JSON: %s', params=(value, err.msg))
import json import jsonschema from django.core.exceptions import ValidationError # Add path to required validator so we can get property name def _required(validator, required, instance, schema): """Validate 'required' properties.""" if not validator.is_type(instance, 'object'): return for index, requirement in enumerate(required): if requirement not in instance or instance[requirement] == '': error = jsonschema.ValidationError( 'This field may not be blank.', path=[requirement] ) yield error # Construct validator as extension of Json Schema Draft 4. JSONSchemaValidator = jsonschema.validators.extend( validator=jsonschema.validators.Draft4Validator, validators={ 'required': _required } ) def validate_json(value): """ Validate that a given value can be successfully parsed as JSON. """ try: json.loads(value) except json.JSONDecodeError as err: raise ValidationError('%s is not valid JSON: %s', params=(value, err.msg))
Use triple double quotes rather than single
Use triple double quotes rather than single
Python
mpl-2.0
mozilla/normandy,mozilla/normandy,Osmose/normandy,Osmose/normandy,mozilla/normandy,Osmose/normandy,Osmose/normandy,mozilla/normandy
--- +++ @@ -6,7 +6,7 @@ # Add path to required validator so we can get property name def _required(validator, required, instance, schema): - '''Validate 'required' properties.''' + """Validate 'required' properties.""" if not validator.is_type(instance, 'object'): return
64636185744a9a64b1b04fcd81ee32930bb145af
scores.py
scores.py
from nameko.rpc import rpc, RpcProxy class ScoreService(object): name = 'score_service' player_service = RpcProxy('players_service') @rpc def leaderboard(self): players = self.player_service.get_players() return sorted(players, key=lambda player: player.score, reverse=True)
from nameko.rpc import rpc, RpcProxy class ScoreService(object): name = 'score_service' player_rpc = RpcProxy('players_service') @rpc def leaderboard(self): players = self.player_rpc.get_players() sorted_players = sorted(players, key=lambda player: player.score, reverse=True) return [(p.name, p.score) for p in players] @rpc def update_player_score(self, player_id, score): player = self.player_rpc.get_player(player_id) player.add_score(score)
Add method to update a player's score
Add method to update a player's score
Python
mit
radekj/poke-battle,skooda/poke-battle
--- +++ @@ -4,9 +4,15 @@ class ScoreService(object): name = 'score_service' - player_service = RpcProxy('players_service') + player_rpc = RpcProxy('players_service') @rpc def leaderboard(self): - players = self.player_service.get_players() - return sorted(players, key=lambda player: player.score, reverse=True) + players = self.player_rpc.get_players() + sorted_players = sorted(players, key=lambda player: player.score, reverse=True) + return [(p.name, p.score) for p in players] + + @rpc + def update_player_score(self, player_id, score): + player = self.player_rpc.get_player(player_id) + player.add_score(score)
3f41dc9ee418c76548f1d69482bc3117739697fe
signbank/video/urls.py
signbank/video/urls.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.urls import path # Views from . import views # Application namespace app_name = 'video' urlpatterns = [ path('<intvideoid>/', views.video_view, name='glossvideo'), path('poster/<int:videoid>', views.poster_view, name='glossvideo_poster'), path('upload/', views.upload_glossvideo_view, name='upload_glossvideo'), path('upload/gloss/', views.upload_glossvideo_gloss_view, name='upload_glossvideo_gloss'), path('upload/recorded/', views.add_recorded_video_view, name='add_recorded_video'), # View to upload multiple videos with no foreign key to gloss. path('add/', views.addvideos_formview, name='upload_videos'), # View that shows a list of glossvideos with no foreign key to gloss, user can add fk to gloss for glossvideos. path('uploaded/', views.uploaded_glossvideos_listview, name='manage_videos'), # View that updates a glossvideo path('update/', views.update_glossvideo_view, name='glossvideo_update'), # View that handles the upload of poster file path('add/poster', views.add_poster_view, name='add_poster'), # Change priority of video path('order/', views.change_glossvideo_order, name='change_glossvideo_order'), # Change publicity of video path('publicity/', views.change_glossvideo_publicity, name='change_glossvideo_publicity'), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.urls import path # Views from . import views # Application namespace app_name = 'video' urlpatterns = [ path('<int:videoid>/', views.video_view, name='glossvideo'), path('poster/<int:videoid>', views.poster_view, name='glossvideo_poster'), path('upload/', views.upload_glossvideo_view, name='upload_glossvideo'), path('upload/gloss/', views.upload_glossvideo_gloss_view, name='upload_glossvideo_gloss'), path('upload/recorded/', views.add_recorded_video_view, name='add_recorded_video'), # View to upload multiple videos with no foreign key to gloss. path('add/', views.addvideos_formview, name='upload_videos'), # View that shows a list of glossvideos with no foreign key to gloss, user can add fk to gloss for glossvideos. path('uploaded/', views.uploaded_glossvideos_listview, name='manage_videos'), # View that updates a glossvideo path('update/', views.update_glossvideo_view, name='glossvideo_update'), # View that handles the upload of poster file path('add/poster', views.add_poster_view, name='add_poster'), # Change priority of video path('order/', views.change_glossvideo_order, name='change_glossvideo_order'), # Change publicity of video path('publicity/', views.change_glossvideo_publicity, name='change_glossvideo_publicity'), ]
Fix missing colon in video url
Fix missing colon in video url
Python
bsd-3-clause
Signbank/FinSL-signbank,Signbank/FinSL-signbank,Signbank/FinSL-signbank
--- +++ @@ -9,7 +9,7 @@ app_name = 'video' urlpatterns = [ - path('<intvideoid>/', views.video_view, name='glossvideo'), + path('<int:videoid>/', views.video_view, name='glossvideo'), path('poster/<int:videoid>', views.poster_view, name='glossvideo_poster'), path('upload/', views.upload_glossvideo_view, name='upload_glossvideo'), path('upload/gloss/', views.upload_glossvideo_gloss_view, name='upload_glossvideo_gloss'),
39ba5da2f6e80bc78ca061edb34c8a2dd7e9c199
shortwave/urls.py
shortwave/urls.py
from django.conf.urls.defaults import * from shortwave.views import wave_list, wave_detail urlpatterns = patterns('', url(r'^$', wave_list, name='shortwave-wave-list'), url(r'^(?P<username>[-\w]+)/$', wave_detail, name='shortwave-wave-detail'), )
from django.conf.urls.defaults import * from shortwave.views import wave_list, wave_detail urlpatterns = patterns('', url(r'^$', wave_list, name='shortwave-wave-list', ), url(r'^(?P<username>[-\w]+)/$', wave_detail, name='shortwave-wave-detail', ), )
Format URL patterns into more readable form.
Format URL patterns into more readable form.
Python
bsd-3-clause
benspaulding/django-shortwave
--- +++ @@ -4,6 +4,12 @@ urlpatterns = patterns('', - url(r'^$', wave_list, name='shortwave-wave-list'), - url(r'^(?P<username>[-\w]+)/$', wave_detail, name='shortwave-wave-detail'), + url(r'^$', + wave_list, + name='shortwave-wave-list', + ), + url(r'^(?P<username>[-\w]+)/$', + wave_detail, + name='shortwave-wave-detail', + ), )
ddf87057213c1068eaf81c47796eb5f77be310b2
docs/src/examples/over2.py
docs/src/examples/over2.py
import numpy as np from scikits.audiolab import Format, Sndfile filename = 'foo.wav' # Create some data to save as audio data: one second of stereo white noise data = np.random.randn(48000, 2) # Create a Sndfile instance for writing wav files @ 48000 Hz format = Format('wav') f = Sndfile(filename, 'w', format, 2, 48000) # Write the first 500 frames of the signal Note that the write_frames method # uses tmp's numpy dtype to determine how to write to the file; sndfile also # converts the data on the fly if necessary f.write_frames(data, 500) f.close()
import numpy as np from scikits.audiolab import Format, Sndfile filename = 'foo.wav' # Create some data to save as audio data: one second of stereo white noise data = np.random.randn(48000, 2) # Create a Sndfile instance for writing wav files @ 48000 Hz format = Format('wav') f = Sndfile(filename, 'w', format, 2, 48000) # Write the first 500 frames of the signal. Note that the write_frames method # uses tmp's numpy dtype to determine how to write to the file; sndfile also # converts the data on the fly if necessary f.write_frames(data[:500]) f.close()
Update example to new write_frames API.
Update example to new write_frames API.
Python
lgpl-2.1
cournape/audiolab,cournape/audiolab,cournape/audiolab
--- +++ @@ -10,9 +10,9 @@ format = Format('wav') f = Sndfile(filename, 'w', format, 2, 48000) -# Write the first 500 frames of the signal Note that the write_frames method +# Write the first 500 frames of the signal. Note that the write_frames method # uses tmp's numpy dtype to determine how to write to the file; sndfile also # converts the data on the fly if necessary -f.write_frames(data, 500) +f.write_frames(data[:500]) f.close()
071f42389aef9c57cb4f0a0434d8297ccba05ab2
openquake/hazardlib/general.py
openquake/hazardlib/general.py
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2014, 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 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 os import subprocess def git_suffix(fname): """ :returns: `<short git hash>` if Git repository found """ try: po = subprocess.Popen( ['git', 'rev-parse', '--short', 'HEAD'], stdout=subprocess.PIPE, stderr=open(os.devnull, 'w'), cwd=os.path.dirname(fname)) return "-git" + po.stdout.read().strip() except: # trapping everything on purpose; git may not be installed or it # may not work properly return ''
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2014, 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 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 os import subprocess def git_suffix(fname): """ :returns: `<short git hash>` if Git repository found """ try: po = subprocess.check_output( ['git', 'rev-parse', '--short', 'HEAD'], cwd=os.path.dirname(fname)) return "-git" + po.stdout.read().strip() except: # trapping everything on purpose; git may not be installed or it # may not work properly return ''
Replace subprocess.Popen with check_output to avoid git zombies
Replace subprocess.Popen with check_output to avoid git zombies
Python
agpl-3.0
larsbutler/oq-hazardlib,larsbutler/oq-hazardlib,gem/oq-engine,gem/oq-hazardlib,mmpagani/oq-hazardlib,gem/oq-engine,gem/oq-engine,mmpagani/oq-hazardlib,silviacanessa/oq-hazardlib,gem/oq-engine,larsbutler/oq-hazardlib,silviacanessa/oq-hazardlib,silviacanessa/oq-hazardlib,gem/oq-hazardlib,gem/oq-engine,vup1120/oq-hazardlib,g-weatherill/oq-hazardlib,vup1120/oq-hazardlib,g-weatherill/oq-hazardlib,g-weatherill/oq-hazardlib,mmpagani/oq-hazardlib,rcgee/oq-hazardlib,silviacanessa/oq-hazardlib,gem/oq-hazardlib,g-weatherill/oq-hazardlib,rcgee/oq-hazardlib,vup1120/oq-hazardlib
--- +++ @@ -26,9 +26,9 @@ :returns: `<short git hash>` if Git repository found """ try: - po = subprocess.Popen( - ['git', 'rev-parse', '--short', 'HEAD'], stdout=subprocess.PIPE, - stderr=open(os.devnull, 'w'), cwd=os.path.dirname(fname)) + po = subprocess.check_output( + ['git', 'rev-parse', '--short', 'HEAD'], + cwd=os.path.dirname(fname)) return "-git" + po.stdout.read().strip() except: # trapping everything on purpose; git may not be installed or it
da51cd8b14231a3fa9850d0d1b939168ae7b0534
sites/shared_conf.py
sites/shared_conf.py
from datetime import datetime import os import sys import alabaster # Alabaster theme html_theme_path = [alabaster.get_path()] # Paths relative to invoking conf.py - not this shared file html_static_path = ['../_shared_static'] html_theme = 'alabaster' html_theme_options = { 'description': "A Python implementation of SSHv2.", 'github_user': 'paramiko', 'github_repo': 'paramiko', 'gittip_user': 'bitprophet', 'analytics_id': 'UA-18486793-2', 'link': '#3782BE', 'link_hover': '#3782BE', } html_sidebars = { # Landing page (no ToC) 'index': [ 'about.html', 'searchbox.html', 'donate.html', ], # Inner pages get a ToC '**': [ 'about.html', 'localtoc.html', 'searchbox.html', 'donate.html', ] } # Regular settings project = u'Paramiko' year = datetime.now().year copyright = u'2013-%d Jeff Forcier, 2003-2012 Robey Pointer' % year master_doc = 'index' templates_path = ['_templates'] exclude_trees = ['_build'] source_suffix = '.rst' default_role = 'obj'
from datetime import datetime import os import sys import alabaster # Alabaster theme html_theme_path = [alabaster.get_path()] # Paths relative to invoking conf.py - not this shared file html_static_path = ['../_shared_static'] html_theme = 'alabaster' html_theme_options = { 'description': "A Python implementation of SSHv2.", 'github_user': 'paramiko', 'github_repo': 'paramiko', 'gittip_user': 'bitprophet', 'analytics_id': 'UA-18486793-2', 'extra_nav_links': { "API Docs": 'http://docs.paramiko.org', }, 'link': '#3782BE', 'link_hover': '#3782BE', } html_sidebars = { '**': [ 'about.html', 'navigation.html', 'searchbox.html', 'donate.html', ] } # Regular settings project = u'Paramiko' year = datetime.now().year copyright = u'2013-%d Jeff Forcier, 2003-2012 Robey Pointer' % year master_doc = 'index' templates_path = ['_templates'] exclude_trees = ['_build'] source_suffix = '.rst' default_role = 'obj'
Update to new alabaster-driven nav sidebar
Update to new alabaster-driven nav sidebar
Python
lgpl-2.1
jorik041/paramiko,anadigi/paramiko,toby82/paramiko,zarr12steven/paramiko,mirrorcoder/paramiko,paramiko/paramiko,varunarya10/paramiko,redixin/paramiko,zpzgone/paramiko,davidbistolas/paramiko,mhdaimi/paramiko,torkil/paramiko,digitalquacks/paramiko,fvicente/paramiko,dlitz/paramiko,thisch/paramiko,jaraco/paramiko,dorianpula/paramiko,remram44/paramiko,Automatic/paramiko,ameily/paramiko,SebastianDeiss/paramiko,esc/paramiko,thusoy/paramiko,reaperhulk/paramiko,selboo/paramiko,CptLemming/paramiko,rcorrieri/paramiko
--- +++ @@ -17,21 +17,18 @@ 'gittip_user': 'bitprophet', 'analytics_id': 'UA-18486793-2', + 'extra_nav_links': { + "API Docs": 'http://docs.paramiko.org', + }, + 'link': '#3782BE', 'link_hover': '#3782BE', } html_sidebars = { - # Landing page (no ToC) - 'index': [ - 'about.html', - 'searchbox.html', - 'donate.html', - ], - # Inner pages get a ToC '**': [ 'about.html', - 'localtoc.html', + 'navigation.html', 'searchbox.html', 'donate.html', ]
6c645b69b91b6a29d4e8786c07e6438d16667415
emds/formats/exceptions.py
emds/formats/exceptions.py
""" Various parser-related exceptions. """ class ParseError(Exception): """ Raise this when some unrecoverable error happens while parsing serialized market data. """ pass
""" Various parser-related exceptions. """ from emds.exceptions import EMDSError class ParseError(EMDSError): """ Raise this when some unrecoverable error happens while parsing serialized market data. """ pass
Make ParseError a child of EMDSError.
Make ParseError a child of EMDSError.
Python
mit
gtaylor/EVE-Market-Data-Structures
--- +++ @@ -1,8 +1,9 @@ """ Various parser-related exceptions. """ +from emds.exceptions import EMDSError -class ParseError(Exception): +class ParseError(EMDSError): """ Raise this when some unrecoverable error happens while parsing serialized market data.
955fd5b8525e7edd6477d5f74d7cbe7b743a127c
wind_model.py
wind_model.py
#!/usr/bin/env python """ Reduced Gravity Shallow Water Model based Matlab code by: Francois Primeau UC Irvine 2011 Kelsey Jordahl kjordahl@enthought.com Time-stamp: <Tue Apr 10 08:44:50 EDT 2012> """ from scipy.io.netcdf import netcdf_file from ocean_model import ShallowWaterModel, OceanPlot from traits.api import Int class WindDrivenModel(ShallowWaterModel): """Class for wind driven model Set flat initial conditions on Lake Superior """ def __init__(self): self.nx = 151 self.ny = 151 self.Lbump = 0.0 self.Lx = 600e3 self.Ly = 600e3 self.lat = 43 # Latitude of Lake Superior super(WindDrivenModel, self).__init__() def set_mask(self): n = netcdf_file('superior_mask.grd', 'r') z = n.variables['z'] self.msk = z.data def main(): swm = WindDrivenModel() plot = OceanPlot(swm) swm.set_plot(plot) import enaml with enaml.imports(): from wind_view import WindView view = WindView(model=swm, plot=plot) view.show() if __name__ == '__main__': main()
#!/usr/bin/env python """ Reduced Gravity Shallow Water Model based Matlab code by: Francois Primeau UC Irvine 2011 Kelsey Jordahl kjordahl@enthought.com Time-stamp: <Tue Apr 10 10:42:40 EDT 2012> """ from scipy.io.netcdf import netcdf_file from ocean_model import ShallowWaterModel, OceanPlot from traits.api import Int class WindDrivenModel(ShallowWaterModel): """Class for wind driven model Set flat initial conditions on Lake Superior """ def __init__(self): self.nx = 151 self.ny = 151 self.Lbump = 0.0 self.Lx = 600e3 self.Ly = 600e3 self.lat = 43 # Latitude of Lake Superior self.H = 150 super(WindDrivenModel, self).__init__() def set_mask(self): n = netcdf_file('superior_mask.grd', 'r') z = n.variables['z'] self.msk = z.data def main(): swm = WindDrivenModel() plot = OceanPlot(swm) swm.set_plot(plot) import enaml with enaml.imports(): from wind_view import WindView view = WindView(model=swm, plot=plot) view.show() if __name__ == '__main__': main()
Set depth for Lake Superior
Set depth for Lake Superior
Python
bsd-3-clause
kjordahl/swm
--- +++ @@ -5,7 +5,7 @@ Kelsey Jordahl kjordahl@enthought.com -Time-stamp: <Tue Apr 10 08:44:50 EDT 2012> +Time-stamp: <Tue Apr 10 10:42:40 EDT 2012> """ from scipy.io.netcdf import netcdf_file @@ -25,6 +25,7 @@ self.Lx = 600e3 self.Ly = 600e3 self.lat = 43 # Latitude of Lake Superior + self.H = 150 super(WindDrivenModel, self).__init__() def set_mask(self):
70f5669bd0ec39bbb8e785b7306ef97b646c8aae
helga_prod_fixer.py
helga_prod_fixer.py
import random from helga.plugins import command RESPONSES = [ 'There is no hope for {thing}, {nick}', 'It looks ok to me...', 'Turning {thing} off and back on again', 'I really wish I could, but it looks past the point of no return', ] @command('fix', help='Usage: helga fix <thing>') def fix(client, channel, nick, message, cmd, args): return random.choice(RESPONSES).format(nick=nick, thing=''.join(args))
import random from helga.plugins import command RESPONSES = [ 'There is no hope for {thing}, {nick}', 'It looks ok to me...', 'Turning {thing} off and back on again', 'I really wish I could, but it looks past the point of no return', ] @command('fix', help='Usage: helga fix <thing>') def fix(client, channel, nick, message, cmd, args): return random.choice(RESPONSES).format(nick=nick, thing=' '.join(args))
Join with a space, duh
Join with a space, duh
Python
mit
shaunduncan/helga-prod-fixer
--- +++ @@ -13,4 +13,4 @@ @command('fix', help='Usage: helga fix <thing>') def fix(client, channel, nick, message, cmd, args): - return random.choice(RESPONSES).format(nick=nick, thing=''.join(args)) + return random.choice(RESPONSES).format(nick=nick, thing=' '.join(args))
181da4be123dd63135592580f8fb567d5586d24b
apps/accounts/models.py
apps/accounts/models.py
from apps.teilar.models import Departments from django.contrib.auth.models import User from django.db import models class UserProfile(models.Model): user = models.ForeignKey(User, unique = True) dionysos_username = models.CharField(max_length = 15, unique = True) dionysos_password = models.CharField(max_length = 30) eclass_username = models.CharField(max_length = 30, null = True, blank = True) eclass_password = models.CharField(max_length = 30, null = True, blank = True) eclass_lessons = models.TextField(null = True, blank = True) introduction_year = models.CharField(max_length = 5) registration_number = models.CharField(max_length = 8) school = models.ForeignKey(Departments) semester = models.CharField(max_length = 2) webmail_username = models.CharField(max_length = 30, null = True, blank = True) webmail_password = models.CharField(max_length = 30, null = True, blank = True) teacher_announcements = models.TextField(null = True, blank = True) other_announcements = models.TextField(null = True, blank = True) declaration = models.TextField(null = True, blank = True) grades = models.TextField(null = True, blank = True) def __unicode__(self): return self.user.username
from apps.teilar.models import Departments from django.contrib.auth.models import User from django.db import models class UserProfile(models.Model): user = models.ForeignKey(User, unique = True) dionysos_username = models.CharField(max_length = 15, unique = True) dionysos_password = models.CharField(max_length = 30) eclass_username = models.CharField(max_length = 30, null = True, blank = True) eclass_password = models.CharField(max_length = 30, null = True, blank = True) eclass_lessons = models.TextField(null = True, blank = True) introduction_year = models.CharField(max_length = 5) registration_number = models.CharField(max_length = 8) school = models.ForeignKey(Departments) semester = models.CharField(max_length = 2) webmail_username = models.CharField(max_length = 30, null = True, blank = True) webmail_password = models.CharField(max_length = 30, null = True, blank = True) teacher_announcements = models.TextField(null = True, blank = True) other_announcements = models.TextField(null = True, blank = True) declaration = models.TextField(null = True, blank = True) grades = models.TextField(null = True, blank = True) deprecated = models.BooleanField(default = False) def __unicode__(self): return self.user.username
Add deprecated field in students
Add deprecated field in students
Python
agpl-3.0
LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr
--- +++ @@ -19,6 +19,7 @@ other_announcements = models.TextField(null = True, blank = True) declaration = models.TextField(null = True, blank = True) grades = models.TextField(null = True, blank = True) + deprecated = models.BooleanField(default = False) def __unicode__(self): return self.user.username
c94f7e5f2c838c3fdd007229175da680de256b04
tests/configurations/nginx/tests_file_size_limit.py
tests/configurations/nginx/tests_file_size_limit.py
#! coding: utf-8 import subprocess import nose.tools as nt from tests import TestPortalAndino class TestFileSizeLimit(TestPortalAndino.TestPortalAndino): @classmethod def setUpClass(cls): super(TestFileSizeLimit, cls).setUpClass() def test_nginx_configuration_uses_1024_MB_as_file_size_limit(self): size_line = subprocess.check_output('docker exec -it andino-nginx cat /etc/nginx/conf.d/default.conf | ' 'grep client_max_body_size', shell=True).strip() print subprocess.check_output('docker exec -it andino-nginx cat /etc/nginx/conf.d/default.conf', shell=True).strip() nt.assert_true('1024' in size_line)
#! coding: utf-8 import subprocess import nose.tools as nt from tests import TestPortalAndino class TestFileSizeLimit(TestPortalAndino.TestPortalAndino): @classmethod def setUpClass(cls): super(TestFileSizeLimit, cls).setUpClass() def test_nginx_configuration_uses_1024_MB_as_file_size_limit(self): size_line = subprocess.check_output( 'docker exec -it andino-nginx cat /etc/nginx/conf.d/default.conf | grep client_max_body_size', shell=True) nt.assert_true('1024' in size_line)
Revert "Hago un strip del output de subprocess"
Revert "Hago un strip del output de subprocess" This reverts commit f5f21d78d87be641617a7cb920d0869975175e58.
Python
mit
datosgobar/portal-andino,datosgobar/portal-andino
--- +++ @@ -12,8 +12,6 @@ super(TestFileSizeLimit, cls).setUpClass() def test_nginx_configuration_uses_1024_MB_as_file_size_limit(self): - size_line = subprocess.check_output('docker exec -it andino-nginx cat /etc/nginx/conf.d/default.conf | ' - 'grep client_max_body_size', shell=True).strip() - print subprocess.check_output('docker exec -it andino-nginx cat /etc/nginx/conf.d/default.conf', - shell=True).strip() + size_line = subprocess.check_output( + 'docker exec -it andino-nginx cat /etc/nginx/conf.d/default.conf | grep client_max_body_size', shell=True) nt.assert_true('1024' in size_line)
1a271575d92a6d7df1bc7dedf346b29a778f2261
update.py
update.py
"""DJRivals database updater.""" from random import shuffle from time import localtime, sleep, strftime, time import pop import dj import image import html def continuous(): """continuous() -> None Continuous incremental updates of the DJRivals database. """ while(True): print("Beginning new cycle...\n") disc_list = list(pop.index().keys()) interval = int(24 * 60 * 60 / len(disc_list)) shuffle(disc_list) for disc in disc_list: pop.database([disc]) print("\nNext incremental update at: " + strftime("%H:%M:%S", localtime(time() + interval))) print("Ctrl-C to quit.\n") sleep(interval) dj.database() image.icons() html.html() print("Full database update complete.\n") def index(): """index() -> None Update the index file and retrieve new disc images if available. """ pop.index(True) image.discs()
"""DJRivals database updater.""" from collections import OrderedDict from time import localtime, sleep, strftime, time import json from common import _link import pop import dj import image import html def continuous(): """continuous() -> None Continuous incremental updates of the DJRivals database. """ index_file = _link("index_file") while(True): print("Beginning new cycle...\n") disc_list = pop.index() disc_list = sorted(disc_list.keys(), key=lambda x: disc_list[x]["timestamp"]) interval = int(24 * 60 * 60 / len(disc_list)) for disc in disc_list: pop.database([disc]) with open(index_file, "rb") as f: data = json.loads(f.read().decode(), object_pairs_hook=OrderedDict) data[disc]["timestamp"] = int(time()) with open(index_file, "wb") as f: f.write(json.dumps(data, indent=4).encode()) print("\nNext incremental update at: " + strftime("%H:%M:%S", localtime(time() + interval))) print("Ctrl-C to quit.\n") sleep(interval) dj.database() image.icons() html.html() print("Full database update complete.\n") def index(): """index() -> None Update the index file and retrieve new disc images if available. """ pop.index(True) image.discs()
Sort the disc list by timestamp.
Sort the disc list by timestamp.
Python
bsd-2-clause
chingc/DJRivals,chingc/DJRivals
--- +++ @@ -1,7 +1,9 @@ """DJRivals database updater.""" -from random import shuffle +from collections import OrderedDict from time import localtime, sleep, strftime, time +import json +from common import _link import pop import dj import image @@ -14,13 +16,19 @@ Continuous incremental updates of the DJRivals database. """ + index_file = _link("index_file") while(True): print("Beginning new cycle...\n") - disc_list = list(pop.index().keys()) + disc_list = pop.index() + disc_list = sorted(disc_list.keys(), key=lambda x: disc_list[x]["timestamp"]) interval = int(24 * 60 * 60 / len(disc_list)) - shuffle(disc_list) for disc in disc_list: pop.database([disc]) + with open(index_file, "rb") as f: + data = json.loads(f.read().decode(), object_pairs_hook=OrderedDict) + data[disc]["timestamp"] = int(time()) + with open(index_file, "wb") as f: + f.write(json.dumps(data, indent=4).encode()) print("\nNext incremental update at: " + strftime("%H:%M:%S", localtime(time() + interval))) print("Ctrl-C to quit.\n") sleep(interval)
b4a0f37c22f69da352ae178da78eb99c97a757d5
zou/app/utils/csv_utils.py
zou/app/utils/csv_utils.py
try: from StringIO import StringIO except ImportError: from io import StringIO import csv from zou.app import config from flask import make_response from slugify import slugify def build_csv_response(csv_content, file_name="export"): """ Construct a Flask response that returns content of a csv a file. """ file_name = build_csv_file_name(file_name) response_body = build_csv_string(csv_content) csv_response = make_response(response_body) csv_response = build_csv_headers(csv_response, file_name) return csv_response def build_csv_file_name(file_name): """ Add application name as prefix of the file name. """ return "%s_%s" % ( slugify(config.APP_NAME, separator="_"), slugify(file_name, separator="_") ) def build_csv_string(csv_content): """ Build a CSV formatted string from an array. """ string_wrapper = StringIO() csv_writer = csv.writer(string_wrapper) csv_writer.writerows(csv_content) return string_wrapper.getvalue() def build_csv_headers(csv_response, file_name): """ Build HTTP response headers needed to return CSV content as a file. """ csv_response.headers["Content-Disposition"] = \ "attachment; filename=%s.csv" % file_name csv_response.headers["Content-type"] = "text/csv" return csv_response
try: from StringIO import StringIO except ImportError: from io import StringIO import csv from zou.app import config from flask import make_response from slugify import slugify def build_csv_response(csv_content, file_name="export"): """ Construct a Flask response that returns content of a csv a file. """ file_name = build_csv_file_name(file_name) response_body = build_csv_string(csv_content) csv_response = make_response(response_body) csv_response = build_csv_headers(csv_response, file_name) return csv_response def build_csv_file_name(file_name): """ Add application name as prefix of the file name. """ return "%s_%s" % ( slugify(config.APP_NAME, separator="_"), slugify(file_name, separator="_") ) def build_csv_string(csv_content): """ Build a CSV formatted string from an array. """ string_wrapper = StringIO() csv_writer = csv.writer(string_wrapper) csv_writer.writerows(csv_content) return string_wrapper.getvalue() def build_csv_headers(csv_response, file_name): """ Build HTTP response headers needed to return CSV content as a file. """ csv_response.headers["Content-Disposition"] = \ "attachment; filename=%s.csv" % file_name csv_response.headers["Content-type"] = "text/csv" return csv_response
Fix non unicode chars problem
Fix non unicode chars problem
Python
agpl-3.0
cgwire/zou
--- +++ @@ -33,7 +33,7 @@ def build_csv_string(csv_content): """ - Build a CSV formatted string from an array. + Build a CSV formatted string from an array. """ string_wrapper = StringIO() csv_writer = csv.writer(string_wrapper) @@ -43,7 +43,7 @@ def build_csv_headers(csv_response, file_name): """ - Build HTTP response headers needed to return CSV content as a file. + Build HTTP response headers needed to return CSV content as a file. """ csv_response.headers["Content-Disposition"] = \ "attachment; filename=%s.csv" % file_name
b2b1c2b8543cae37990262b2a811a9b0f26327da
arm/utils/locker.py
arm/utils/locker.py
# -*- coding: utf-8 -*- from kvs import CacheKvs class Locker(object): """ locker for move the locker """ LOCKER_KEY = 'locker' EXPIRES = 5 # 5 sec def __init__(self, key=None): self.key = self.LOCKER_KEY if key: self.key += '.{}'.format(key) self.locker = CacheKvs(self.key) def lock(self): self.locker.set('locked', expires=self.EXPIRES, nx=True) def unlock(self): self.locker.delete() def is_lock(self): return self.locker.get() == 'locked' def on_lock(self, func): def wrapper(*args, **kwargs): if self.is_lock(): return self.lock() try: return func(*args, **kwargs) except Exception as e: raise e finally: self.unlock() return wrapper
# -*- coding: utf-8 -*- from kvs import CacheKvs class Locker(object): """ locker for move the locker """ LOCKER_KEY = 'locker' EXPIRES = 5 # 5 sec def __init__(self, key=None): self.key = self.LOCKER_KEY if key: self.key += '.{}'.format(key) self.locker = CacheKvs(self.key) def lock(self): self.locker.set('locked', expires=self.EXPIRES, nx=True) def unlock(self): self.locker.delete() def is_lock(self): return self.locker.get() == 'locked' def on_lock(self, func): def wrapper(*args, **kwargs): if self.lock(): try: return func(*args, **kwargs) except Exception as e: raise e finally: self.unlock() return wrapper
Fix redis lock, use SETNX
Fix redis lock, use SETNX
Python
mit
mapler/tuesday,mapler/tuesday,mapler/tuesday
--- +++ @@ -27,13 +27,11 @@ def on_lock(self, func): def wrapper(*args, **kwargs): - if self.is_lock(): - return - self.lock() - try: - return func(*args, **kwargs) - except Exception as e: - raise e - finally: - self.unlock() + if self.lock(): + try: + return func(*args, **kwargs) + except Exception as e: + raise e + finally: + self.unlock() return wrapper
34ea2629aa8a97580567535a5a6885b06cce3419
examples/test_client.py
examples/test_client.py
import asyncio import platform import time from zeep import AsyncClient from zeep.cache import InMemoryCache from zeep.transports import AsyncTransport # Spyne SOAP client using Zeep and async transport. Run with python -m examples.test_client # Allow CTRL+C on windows console w/ asyncio if platform.system() == "Windows": import signal signal.signal(signal.SIGINT, signal.SIG_DFL) async def do_call(client, text, number): result = await client.service.say_hello(text=text, number=number) return result == "{} {}".format(text, number) def generate_tasks(client): tasks = [] for m in range(10000): tasks.append(asyncio.ensure_future(do_call(client, "Tester", m))) return tasks async def send_messages(client): start = time.time() results = await asyncio.gather(*generate_tasks(client)) delta_time = time.time() - start print("Result: ", all(results)) print(delta_time) def main(): loop = asyncio.get_event_loop() client = AsyncClient( wsdl="http://localhost:8080/say_hello/?WSDL", transport=AsyncTransport(cache=InMemoryCache(timeout=None)), ) loop.run_until_complete(send_messages(client)) loop.run_until_complete(client.transport.aclose()) if __name__ == "__main__": main()
import asyncio import platform import time from zeep import AsyncClient from zeep.cache import InMemoryCache from zeep.transports import AsyncTransport # Spyne SOAP client using Zeep and async transport. Run with python -m examples.test_client # Allow CTRL+C on windows console w/ asyncio if platform.system() == "Windows": import signal signal.signal(signal.SIGINT, signal.SIG_DFL) async def do_call(client, text, number): result = await client.service.say_hello(text=text, number=number) return result == "{} {}".format(text, number) def generate_tasks(client): tasks = [] for m in range(10000): tasks.append(asyncio.ensure_future(do_call(client, "Tester", m))) return tasks async def send_messages(client): start = time.time() results = await asyncio.gather(*generate_tasks(client)) delta_time = time.time() - start print("Result: ", all(results)) print(delta_time) async def main(): client = AsyncClient( wsdl="http://localhost:8080/say_hello/?WSDL", transport=AsyncTransport(cache=InMemoryCache(timeout=None)), ) await send_messages(client) await client.transport.aclose() if __name__ == "__main__": asyncio.run(main())
Use asyncio.run() to run the test client.
Use asyncio.run() to run the test client. This makes for cleaner code.
Python
lgpl-2.1
katajakasa/aiohttp-spyne
--- +++ @@ -36,15 +36,14 @@ print(delta_time) -def main(): - loop = asyncio.get_event_loop() +async def main(): client = AsyncClient( wsdl="http://localhost:8080/say_hello/?WSDL", transport=AsyncTransport(cache=InMemoryCache(timeout=None)), ) - loop.run_until_complete(send_messages(client)) - loop.run_until_complete(client.transport.aclose()) + await send_messages(client) + await client.transport.aclose() if __name__ == "__main__": - main() + asyncio.run(main())
07488d90549db4a47898bdea4ebd8687de638590
forum/models.py
forum/models.py
from django.db import models import django.contrib.auth.models as auth class User(auth.User): """Model for representing users. It has few fields that aren't in the standard authentication user table, and are needed for the forum to work, like footers. """ display_name = models.CharField(max_length=30, null=True) class Thread(models.Model): """Model for representing threads.""" title = models.CharField(max_length=100) views = models.PositiveIntegerField(default=0) sticky = models.BooleanField() closed = models.BooleanField()
from django.db import models import django.contrib.auth.models as auth class User(auth.User): """Model for representing users. It has few fields that aren't in the standard authentication user table, and are needed for the forum to work, like footers. """ display_name = models.CharField(max_length=30, null=True) footer = models.TextField(null=True) class Thread(models.Model): """Model for representing threads.""" title = models.CharField(max_length=100) views = models.PositiveIntegerField(default=0) sticky = models.BooleanField() closed = models.BooleanField()
Add footers the comment discusses.
Add footers the comment discusses.
Python
mit
xfix/NextBoard
--- +++ @@ -8,6 +8,7 @@ table, and are needed for the forum to work, like footers. """ display_name = models.CharField(max_length=30, null=True) + footer = models.TextField(null=True) class Thread(models.Model):
22b92437c1ae672297bed8567b335ef7da100103
dotfiles/utils.py
dotfiles/utils.py
""" Misc utility functions. """ import os.path from dotfiles.compat import islink, realpath def compare_path(path1, path2): return (realpath_expanduser(path1) == realpath_expanduser(path2)) def realpath_expanduser(path): return realpath(os.path.expanduser(path)) def is_link_to(path, target): def normalize(path): return os.path.normcase(os.path.normpath(path)) return islink(path) and \ normalize(realpath(path)) == normalize(target)
""" Misc utility functions. """ import os.path from dotfiles.compat import islink, realpath def compare_path(path1, path2): return (realpath_expanduser(path1) == realpath_expanduser(path2)) def realpath_expanduser(path): return realpath(os.path.expanduser(path)) def is_link_to(path, target): def normalize(path): return os.path.normcase(os.path.normpath(path)) return islink(path) and \ normalize(realpath(path)) == normalize(realpath(target))
Fix link detection when target is itself a symlink
Fix link detection when target is itself a symlink This shows up on OSX where /tmp is actually a symlink to /private/tmp.
Python
isc
aparente/Dotfiles,nilehmann/dotfiles-1,aparente/Dotfiles,aparente/Dotfiles,aparente/Dotfiles,Bklyn/dotfiles
--- +++ @@ -19,5 +19,4 @@ def normalize(path): return os.path.normcase(os.path.normpath(path)) return islink(path) and \ - normalize(realpath(path)) == normalize(target) - + normalize(realpath(path)) == normalize(realpath(target))
1fa7237f47096bc9574ffdf649e6231bf2a670e9
features/stadt/views.py
features/stadt/views.py
import django import utils from features import gestalten, groups class Entity(django.views.generic.View): def get(self, request, *args, **kwargs): try: entity = groups.models.Group.objects.get(slug=kwargs.get('entity_slug')) view = groups.views.Group() except groups.models.Group.DoesNotExist: entity = django.shortcuts.get_object_or_404( gestalten.models.Gestalt, user__username=kwargs.get('entity_slug')) view = gestalten.views.Detail() view.request = request view.kwargs = kwargs view.object = entity return view.get(request, *args, **kwargs) class Imprint(utils.views.PageMixin, django.views.generic.TemplateView): permission_required = 'entities.view_imprint' template_name = 'entities/imprint.html' title = 'Impressum' class Privacy(utils.views.PageMixin, django.views.generic.TemplateView): permission_required = 'entities.view_imprint' template_name = 'entities/privacy.html' title = 'Datenschutz'
import django import core import utils from features import gestalten, groups class Entity(core.views.PermissionMixin, django.views.generic.View): def get(self, request, *args, **kwargs): return self.view.get(request, *args, **kwargs) def get_view(self): entity_slug = self.kwargs.get('entity_slug') try: entity = groups.models.Group.objects.get(slug=entity_slug) view = groups.views.Group() view.related_object = entity except groups.models.Group.DoesNotExist: entity = django.shortcuts.get_object_or_404( gestalten.models.Gestalt, user__username=entity_slug) view = gestalten.views.Detail() view.object = entity return view def has_permission(self): self.view = self.get_view() self.view.request = self.request self.view.kwargs = self.kwargs return self.view.has_permission() class Imprint(utils.views.PageMixin, django.views.generic.TemplateView): permission_required = 'entities.view_imprint' template_name = 'entities/imprint.html' title = 'Impressum' class Privacy(utils.views.PageMixin, django.views.generic.TemplateView): permission_required = 'entities.view_imprint' template_name = 'entities/privacy.html' title = 'Datenschutz'
Fix permission checking for entity proxy view
Fix permission checking for entity proxy view
Python
agpl-3.0
stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten
--- +++ @@ -1,22 +1,32 @@ import django +import core import utils from features import gestalten, groups -class Entity(django.views.generic.View): +class Entity(core.views.PermissionMixin, django.views.generic.View): def get(self, request, *args, **kwargs): + return self.view.get(request, *args, **kwargs) + + def get_view(self): + entity_slug = self.kwargs.get('entity_slug') try: - entity = groups.models.Group.objects.get(slug=kwargs.get('entity_slug')) + entity = groups.models.Group.objects.get(slug=entity_slug) view = groups.views.Group() + view.related_object = entity except groups.models.Group.DoesNotExist: entity = django.shortcuts.get_object_or_404( - gestalten.models.Gestalt, user__username=kwargs.get('entity_slug')) + gestalten.models.Gestalt, user__username=entity_slug) view = gestalten.views.Detail() - view.request = request - view.kwargs = kwargs - view.object = entity - return view.get(request, *args, **kwargs) + view.object = entity + return view + + def has_permission(self): + self.view = self.get_view() + self.view.request = self.request + self.view.kwargs = self.kwargs + return self.view.has_permission() class Imprint(utils.views.PageMixin, django.views.generic.TemplateView):
7ffdd38b500b38d6bd48ca7f1bf88fb92c88e1d5
prime-factors/prime_factors.py
prime-factors/prime_factors.py
def prime_factors(n): factors = [] factor = 2 while n != 1: while n % factor == 0: factors += [factor] n //= factor factor += 1 return factors
def prime_factors(n): factors = [] while n % 2 == 0: factors += [2] n //= 2 factor = 3 while n != 1: while n % factor == 0: factors += [factor] n //= factor factor += 2 return factors
Make solution more efficient by only testing odd numbers
Make solution more efficient by only testing odd numbers
Python
agpl-3.0
CubicComet/exercism-python-solutions
--- +++ @@ -1,9 +1,12 @@ def prime_factors(n): factors = [] - factor = 2 + while n % 2 == 0: + factors += [2] + n //= 2 + factor = 3 while n != 1: while n % factor == 0: factors += [factor] n //= factor - factor += 1 + factor += 2 return factors
6b7fe344827ddf49c40d165d6e0ff09013ee5716
edxval/migrations/0002_data__default_profiles.py
edxval/migrations/0002_data__default_profiles.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models DEFAULT_PROFILES = [ "desktop_mp4", "desktop_webm", "mobile_high", "mobile_low", "youtube", ] def create_default_profiles(apps, schema_editor): """ Add default profiles """ Profile = apps.get_model("edxval", "Profile") db_alias = schema_editor.connection.alias for profile in DEFAULT_PROFILES: Profile.objects.using(db_alias).get_or_create(profile_name=profile) def delete_default_profiles(apps, schema_editor): """ Remove default profiles """ Profile = apps.get_model("edxval", "Profile") db_alias = schema_editor.connection.alias Profile.objects.using(db_alias).filter(profile_name__in=DEFAULT_PROFILES).delete() class Migration(migrations.Migration): dependencies = [ ('edxval', '0001_initial'), ] operations = [ migrations.RunPython(create_default_profiles, delete_default_profiles), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models DEFAULT_PROFILES = [ "desktop_mp4", "desktop_webm", "mobile_high", "mobile_low", "youtube", ] def create_default_profiles(apps, schema_editor): """ Add default profiles """ Profile = apps.get_model("edxval", "Profile") for profile in DEFAULT_PROFILES: Profile.objects.get_or_create(profile_name=profile) def delete_default_profiles(apps, schema_editor): """ Remove default profiles """ Profile = apps.get_model("edxval", "Profile") Profile.objects.filter(profile_name__in=DEFAULT_PROFILES).delete() class Migration(migrations.Migration): dependencies = [ ('edxval', '0001_initial'), ] operations = [ migrations.RunPython(create_default_profiles, delete_default_profiles), ]
Remove uses of using() from migrations
Remove uses of using() from migrations This hardcoded the db_alias fetched from schema_editor and forces django to try and migrate any second database you use, rather than routing to the default database. In testing a build from scratch, these do not appear needed. Using using() prevents us from using multiple databases behind edxapp.
Python
agpl-3.0
edx/edx-val
--- +++ @@ -16,16 +16,14 @@ def create_default_profiles(apps, schema_editor): """ Add default profiles """ Profile = apps.get_model("edxval", "Profile") - db_alias = schema_editor.connection.alias for profile in DEFAULT_PROFILES: - Profile.objects.using(db_alias).get_or_create(profile_name=profile) + Profile.objects.get_or_create(profile_name=profile) def delete_default_profiles(apps, schema_editor): """ Remove default profiles """ Profile = apps.get_model("edxval", "Profile") - db_alias = schema_editor.connection.alias - Profile.objects.using(db_alias).filter(profile_name__in=DEFAULT_PROFILES).delete() + Profile.objects.filter(profile_name__in=DEFAULT_PROFILES).delete() class Migration(migrations.Migration):
78031ca1077a224d37c4f549cd8dac55edd4ed5f
fragdenstaat_de/urls.py
fragdenstaat_de/urls.py
from django.conf.urls.defaults import patterns urlpatterns = patterns('fragdenstaat_de.views', (r'^presse/(?P<slug>[-\w]+)/$', 'show_press', {}, 'fds-show_press'), )
from django.conf.urls import patterns, url from django.http import HttpResponseRedirect urlpatterns = patterns('fragdenstaat_de.views', (r'^presse/(?P<slug>[-\w]+)/$', 'show_press', {}, 'fds-show_press'), url(r'^nordrhein-westfalen/', lambda request: HttpResponseRedirect('/nrw/'), name="jurisdiction-nrw-redirect") )
Add custom NRW redirect url
Add custom NRW redirect url
Python
mit
okfse/fragastaten_se,catcosmo/fragdenstaat_de,okfse/fragdenstaat_de,okfse/fragastaten_se,catcosmo/fragdenstaat_de,okfse/fragdenstaat_de
--- +++ @@ -1,6 +1,9 @@ -from django.conf.urls.defaults import patterns +from django.conf.urls import patterns, url +from django.http import HttpResponseRedirect urlpatterns = patterns('fragdenstaat_de.views', (r'^presse/(?P<slug>[-\w]+)/$', 'show_press', {}, 'fds-show_press'), + url(r'^nordrhein-westfalen/', lambda request: HttpResponseRedirect('/nrw/'), + name="jurisdiction-nrw-redirect") )
185571932f518760bb3045347578caa98ef820f5
froide/foiidea/views.py
froide/foiidea/views.py
from django.shortcuts import render from foiidea.models import Article def index(request): return render(request, 'foiidea/index.html', { 'object_list': Article.objects.all().select_related('public_bodies', 'foirequests') })
from django.shortcuts import render from foiidea.models import Article def index(request): return render(request, 'foiidea/index.html', { 'object_list': Article.objects.get_ordered() })
Use manager method for view articles
Use manager method for view articles
Python
mit
fin/froide,LilithWittmann/froide,stefanw/froide,CodeforHawaii/froide,CodeforHawaii/froide,ryankanno/froide,LilithWittmann/froide,stefanw/froide,okfse/froide,okfse/froide,ryankanno/froide,ryankanno/froide,ryankanno/froide,LilithWittmann/froide,stefanw/froide,fin/froide,CodeforHawaii/froide,catcosmo/froide,CodeforHawaii/froide,okfse/froide,LilithWittmann/froide,catcosmo/froide,stefanw/froide,LilithWittmann/froide,ryankanno/froide,catcosmo/froide,okfse/froide,fin/froide,catcosmo/froide,fin/froide,stefanw/froide,okfse/froide,CodeforHawaii/froide,catcosmo/froide
--- +++ @@ -5,5 +5,5 @@ def index(request): return render(request, 'foiidea/index.html', { - 'object_list': Article.objects.all().select_related('public_bodies', 'foirequests') + 'object_list': Article.objects.get_ordered() })
52e15ab96718a491f805eee6f7130d4f02530940
alfred/helpers.py
alfred/helpers.py
from alfred_db.models import User from flask import current_app from github import Github from requests_oauth2 import OAuth2 from .database import db def get_shell(): try: from IPython.frontend.terminal.embed import InteractiveShellEmbed except ImportError: import code return lambda **context: code.interact('', local=context) else: ipython = InteractiveShellEmbed(banner1='') return lambda **context: ipython(global_ns={}, local_ns=context) def get_oauth2_handler(): GITHUB = current_app.config['GITHUB'] return OAuth2( GITHUB['client_id'], GITHUB['client_secret'], GITHUB['auth_url'], '', GITHUB['authorize_url'], GITHUB['token_url'] ) def get_user_by_token(access_token): api = Github(access_token) github_user = api.get_user() user = db.session.query(User).filter_by(github_id=github_user.id).first() if user is None: user = User( github_access_token=access_token, github_id=github_user.id, name=github_user.name, email=github_user.email, login=github_user.login, ) else: user.github_access_token = access_token user.login = github_user.login db.session.add(user) db.session.commit() return user
from alfred_db.models import User from flask import current_app from github import Github from requests_oauth2 import OAuth2 from .database import db def get_shell(): try: from IPython.frontend.terminal.embed import InteractiveShellEmbed except ImportError: import code return lambda **context: code.interact('', local=context) else: ipython = InteractiveShellEmbed(banner1='') return lambda **context: ipython(global_ns={}, local_ns=context) def get_oauth2_handler(): GITHUB = current_app.config['GITHUB'] return OAuth2( GITHUB['client_id'], GITHUB['client_secret'], GITHUB['auth_url'], '', GITHUB['authorize_url'], GITHUB['token_url'] ) def get_user_by_token(access_token): api = Github(access_token) github_user = api.get_user() user = db.session.query(User).filter_by(github_id=github_user.id).first() if user is None: user = User( github_access_token=access_token, github_id=github_user.id, name=github_user.name, email=github_user.email, login=github_user.login, ) db.session.add(user) else: user.github_access_token = access_token user.login = github_user.login db.session.commit() return user
Add user to db.session only when it has been created
Add user to db.session only when it has been created
Python
isc
alfredhq/alfred,alfredhq/alfred
--- +++ @@ -37,9 +37,9 @@ email=github_user.email, login=github_user.login, ) + db.session.add(user) else: user.github_access_token = access_token user.login = github_user.login - db.session.add(user) db.session.commit() return user
8dba7306f73479fb3c0a102550f843e2fb9ea1c1
serfnode/handler/docker_utils.py
serfnode/handler/docker_utils.py
import os import subprocess def env(image): """Return environment of image. """ out = docker('inspect', '-f', '{{.Config.Env}}', image) return dict(map(lambda x: x.split('='), out.strip()[1:-1].split())) def path(p): """Build the corresponding path `p` inside the container. """ return os.path.normpath(os.path.join( os.environ.get('HOST_PREFIX', '/host'), './{}'.format(p))) def docker(*args): """Execute a docker command inside the container. """ docker_binary = DOCKER docker_socket = DOCKER_SOCKET cmd = ('{docker_binary} -H unix://{docker_socket}' .format(**locals()).split()) cmd.extend(args) return subprocess.check_output(cmd).strip() def fig(*args): docker_path = os.path.dirname( path(os.environ.get('DOCKER_BINARY', '/usr/bin/docker'))) docker_socket = path(os.environ.get('DOCKER_SOCKET', '/run/docker.sock')) arg_list = ' '.join(args) cmd = ('DOCKER_HOST=unix://{docker_socket} PATH={docker_path}:$PATH ' 'fig {arg_list}' .format(**locals())) return subprocess.check_output(cmd, shell=True).strip() DOCKER = '/usr/bin/docker' DOCKER_SOCKET = 'unix://{}'.format( path(os.environ.get('DOCKER_SOCKET', '/run/docker.sock'))) DOCKER_RUN = os.environ.get('DOCKER_RUN')
import os import subprocess def env(image): """Return environment of image. """ out = docker('inspect', '-f', '{{.Config.Env}}', image) return dict(map(lambda x: x.split('='), out.strip()[1:-1].split())) def path(p): """Build the corresponding path `p` inside the container. """ return os.path.normpath(os.path.join( os.environ.get('HOST_PREFIX', '/host'), './{}'.format(p))) def docker(*args): """Execute a docker command inside the container. """ docker_binary = DOCKER docker_socket = DOCKER_SOCKET cmd = ('{docker_binary} -H {docker_socket}' .format(**locals()).split()) cmd.extend(args) return subprocess.check_output(cmd).strip() def fig(*args): docker_path = os.path.dirname( path(os.environ.get('DOCKER_BINARY', '/usr/bin/docker'))) docker_socket = path(os.environ.get('DOCKER_SOCKET', '/run/docker.sock')) arg_list = ' '.join(args) cmd = ('DOCKER_HOST=unix://{docker_socket} PATH={docker_path}:$PATH ' 'fig {arg_list}' .format(**locals())) return subprocess.check_output(cmd, shell=True).strip() DOCKER = '/usr/bin/docker' DOCKER_SOCKET = 'unix://{}'.format( path(os.environ.get('DOCKER_SOCKET', '/run/docker.sock'))) DOCKER_RUN = os.environ.get('DOCKER_RUN')
Fix template for docker command line
Fix template for docker command line
Python
mit
waltermoreira/serfnode,waltermoreira/serfnode,waltermoreira/serfnode
--- +++ @@ -21,7 +21,7 @@ docker_binary = DOCKER docker_socket = DOCKER_SOCKET - cmd = ('{docker_binary} -H unix://{docker_socket}' + cmd = ('{docker_binary} -H {docker_socket}' .format(**locals()).split()) cmd.extend(args) return subprocess.check_output(cmd).strip()
81e8fb8dd4f9f3d3648e13e8509208710619c615
IMU_program/PythonServer.py
IMU_program/PythonServer.py
import socket import serial.tools.list_ports import serial ports = list(serial.tools.list_ports.comports()) arduino_port = next((port for port in ports if "Arduino" in port.description), None) arduino = serial.Serial(arduino_port[0], 9600) # print("Connecting on " + arduino_port[0]) PORT = 4242 HOST = 'localhost' server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((HOST, PORT)) server_socket.listen(5) while True: connection, address = server_socket.accept() # print("Client connected") while True: try: incoming = arduino.readline() connection.send(incoming) except: # print("Client disconnected") break
#!/usr/bin/env python3 import socket import serial.tools.list_ports import serial ports = list(serial.tools.list_ports.comports()) arduino_port = next((port for port in ports if "Arduino" in port.description), None) arduino = serial.Serial(arduino_port[0], 9600) # print("Connecting on " + arduino_port[0]) PORT = 4242 HOST = 'localhost' server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((HOST, PORT)) server_socket.listen(5) while True: connection, address = server_socket.accept() # print("Client connected") while True: try: incoming = arduino.readline() connection.send(incoming) except: # print("Client disconnected") break
Add shebang to python server
Add shebang to python server
Python
apache-2.0
dmweis/DynamixelServo,dmweis/DynamixelServo,dmweis/DynamixelServo,dmweis/DynamixelServo
--- +++ @@ -1,7 +1,8 @@ +#!/usr/bin/env python3 + import socket import serial.tools.list_ports import serial - ports = list(serial.tools.list_ports.comports()) arduino_port = next((port for port in ports if "Arduino" in port.description), None)
3fa9a7c62aeae10a191b3782e32df107618c19b3
boris/reporting/forms.py
boris/reporting/forms.py
''' Created on 3.12.2011 @author: xaralis ''' from django import forms from django.utils.translation import ugettext_lazy as _ from boris.utils.widgets import SelectYearWidget class MonthlyStatsForm(forms.Form): year = forms.IntegerField(widget=SelectYearWidget(history=10), label=_(u'Rok')) class ServiceForm(forms.Form): date_from = forms.DateField(label=_(u'Od')) date_to = forms.DateField(label=_(u'Do'))
''' Created on 3.12.2011 @author: xaralis ''' from django import forms from django.utils.translation import ugettext_lazy as _ from boris.utils.widgets import SelectYearWidget class MonthlyStatsForm(forms.Form): year = forms.IntegerField(widget=SelectYearWidget(history=10), label=_(u'Rok')) class ServiceForm(forms.Form): date_from = forms.DateField(label=_(u'Od'), required=False) date_to = forms.DateField(label=_(u'Do'), required=False)
Make dates in the ServiceForm optional.
Make dates in the ServiceForm optional.
Python
mit
fragaria/BorIS,fragaria/BorIS,fragaria/BorIS
--- +++ @@ -12,5 +12,5 @@ year = forms.IntegerField(widget=SelectYearWidget(history=10), label=_(u'Rok')) class ServiceForm(forms.Form): - date_from = forms.DateField(label=_(u'Od')) - date_to = forms.DateField(label=_(u'Do')) + date_from = forms.DateField(label=_(u'Od'), required=False) + date_to = forms.DateField(label=_(u'Do'), required=False)
70a004f1455448aca08754084502d4d13b9cc9cd
indra/tests/test_rlimsp.py
indra/tests/test_rlimsp.py
from indra.sources import rlimsp def test_simple_usage(): rp = rlimsp.process_pmc('PMC3717945') stmts = rp.statements assert len(stmts) == 6, len(stmts) for s in stmts: assert len(s.evidence) == 1, "Wrong amount of evidence." ev = s.evidence[0] assert ev.annotations, "Missing annotations." assert 'agents' in ev.annotations.keys() assert 'trigger' in ev.annotations.keys() def test_ungrounded_usage(): rp = rlimsp.process_pmc('PMC3717945', with_grounding=False) assert len(rp.statements) == 33, len(rp.statements)
from indra.sources import rlimsp def test_simple_usage(): rp = rlimsp.process_from_webservice('PMC3717945') stmts = rp.statements assert len(stmts) == 6, len(stmts) for s in stmts: assert len(s.evidence) == 1, "Wrong amount of evidence." ev = s.evidence[0] assert ev.annotations, "Missing annotations." assert 'agents' in ev.annotations.keys() assert 'trigger' in ev.annotations.keys() def test_ungrounded_usage(): rp = rlimsp.process_from_webservice('PMC3717945', with_grounding=False) assert len(rp.statements) == 33, len(rp.statements) def test_grounded_endpoint_with_pmids(): pmid_list = ['16403219', '22258404', '16961925', '22096607'] for pmid in pmid_list: rp = rlimsp.process_from_webservice(pmid, id_type='pmid', with_grounding=False) assert len(rp.statements) > 10, len(rp.statements)
Add a test for pmids and update to new api.
Add a test for pmids and update to new api.
Python
bsd-2-clause
johnbachman/indra,bgyori/indra,pvtodorov/indra,sorgerlab/belpy,johnbachman/belpy,sorgerlab/belpy,johnbachman/belpy,sorgerlab/indra,pvtodorov/indra,sorgerlab/indra,johnbachman/belpy,johnbachman/indra,johnbachman/indra,pvtodorov/indra,bgyori/indra,sorgerlab/belpy,pvtodorov/indra,bgyori/indra,sorgerlab/indra
--- +++ @@ -2,7 +2,7 @@ def test_simple_usage(): - rp = rlimsp.process_pmc('PMC3717945') + rp = rlimsp.process_from_webservice('PMC3717945') stmts = rp.statements assert len(stmts) == 6, len(stmts) for s in stmts: @@ -14,5 +14,13 @@ def test_ungrounded_usage(): - rp = rlimsp.process_pmc('PMC3717945', with_grounding=False) + rp = rlimsp.process_from_webservice('PMC3717945', with_grounding=False) assert len(rp.statements) == 33, len(rp.statements) + + +def test_grounded_endpoint_with_pmids(): + pmid_list = ['16403219', '22258404', '16961925', '22096607'] + for pmid in pmid_list: + rp = rlimsp.process_from_webservice(pmid, id_type='pmid', + with_grounding=False) + assert len(rp.statements) > 10, len(rp.statements)
4a6fe04a93e0d500b9e2fa7ed9951bcb497045df
sphinxcontrib/dd/__init__.py
sphinxcontrib/dd/__init__.py
from docutils.nodes import SkipNode from . import data_dictionary from . import database_diagram def skip(self, node): _ = self _ = node raise SkipNode def setup(app): app.setup_extension('sphinx.ext.graphviz') app.add_directive('data-dictionary', data_dictionary.Directive) app.add_config_value('database_diagram_graph_fontname', '', 'env') app.add_config_value('database_diagram_graph_fontsize', '', 'env') app.add_config_value('database_diagram_graph_label', '', 'env') app.add_config_value('database_diagram_node_fontname', '', 'env') app.add_config_value('database_diagram_node_fontsize', '', 'env') app.add_node( database_diagram.Node, html=(database_diagram.visit_html, skip), latex=(database_diagram.visit_latex, skip), text=(skip, skip), man=(skip, skip), texinfo=(skip, skip), ) app.add_directive('database-diagram', database_diagram.Directive)
from docutils.nodes import SkipNode from . import data_dictionary from . import database_diagram def skip(self, node): _ = self _ = node raise SkipNode def setup(app): app.setup_extension('sphinx.ext.graphviz') app.add_directive('data-dictionary', data_dictionary.Directive) for option in database_diagram.Directive.option_spec: config = 'database_diagram_{0}'.format(option.replace('-', '_')) app.add_config_value(config, None, 'env') app.add_node( database_diagram.Node, html=(database_diagram.visit_html, skip), latex=(database_diagram.visit_latex, skip), text=(skip, skip), man=(skip, skip), texinfo=(skip, skip), ) app.add_directive('database-diagram', database_diagram.Directive)
Replace dash to underscore for config
Replace dash to underscore for config
Python
mit
julot/sphinxcontrib-dd
--- +++ @@ -15,12 +15,9 @@ app.add_directive('data-dictionary', data_dictionary.Directive) - app.add_config_value('database_diagram_graph_fontname', '', 'env') - app.add_config_value('database_diagram_graph_fontsize', '', 'env') - app.add_config_value('database_diagram_graph_label', '', 'env') - - app.add_config_value('database_diagram_node_fontname', '', 'env') - app.add_config_value('database_diagram_node_fontsize', '', 'env') + for option in database_diagram.Directive.option_spec: + config = 'database_diagram_{0}'.format(option.replace('-', '_')) + app.add_config_value(config, None, 'env') app.add_node( database_diagram.Node,
9201e9c433930da8fd0bfb13eadbc249469e4d84
fireplace/cards/tourney/mage.py
fireplace/cards/tourney/mage.py
from ..utils import * ## # Secrets # Effigy class AT_002: events = Death(FRIENDLY + MINION).on( lambda self, minion: Summon(self.controller, RandomMinion(cost=minion.cost)) )
from ..utils import * ## # Minions # Dalaran Aspirant class AT_006: inspire = Buff(SELF, "AT_006e") # Spellslinger class AT_007: play = Give(ALL_PLAYERS, RandomSpell()) # Rhonin class AT_009: deathrattle = Give(CONTROLLER, "EX1_277") * 3 ## # Spells # Flame Lance class AT_001: play = Hit(TARGET, 8) # Arcane Blast class AT_004: play = Hit(TARGET, 2) # Polymorph: Boar class AT_005: play = Morph(TARGET, "AT_005t") ## # Secrets # Effigy class AT_002: events = Death(FRIENDLY + MINION).on( lambda self, minion: Summon(self.controller, RandomMinion(cost=minion.cost)) )
Implement Mage cards for The Grand Tournament
Implement Mage cards for The Grand Tournament
Python
agpl-3.0
Meerkov/fireplace,amw2104/fireplace,liujimj/fireplace,Ragowit/fireplace,smallnamespace/fireplace,jleclanche/fireplace,Ragowit/fireplace,oftc-ftw/fireplace,beheh/fireplace,smallnamespace/fireplace,NightKev/fireplace,liujimj/fireplace,Meerkov/fireplace,amw2104/fireplace,oftc-ftw/fireplace
--- +++ @@ -1,4 +1,40 @@ from ..utils import * + + +## +# Minions + +# Dalaran Aspirant +class AT_006: + inspire = Buff(SELF, "AT_006e") + + +# Spellslinger +class AT_007: + play = Give(ALL_PLAYERS, RandomSpell()) + + +# Rhonin +class AT_009: + deathrattle = Give(CONTROLLER, "EX1_277") * 3 + + +## +# Spells + +# Flame Lance +class AT_001: + play = Hit(TARGET, 8) + + +# Arcane Blast +class AT_004: + play = Hit(TARGET, 2) + + +# Polymorph: Boar +class AT_005: + play = Morph(TARGET, "AT_005t") ##
52a9d0701f7ccc6e5ab12bf2c83473d878b80ee0
src/file_types.py
src/file_types.py
import build_inputs from path import Path class SourceFile(build_inputs.File): def __init__(self, name, source=Path.srcdir, lang=None): build_inputs.File.__init__(self, name, source=source) self.lang = lang class HeaderFile(build_inputs.File): install_kind = 'data' install_root = Path.includedir class HeaderDirectory(build_inputs.Directory): install_root = Path.includedir class ObjectFile(build_inputs.File): def __init__(self, name, source=Path.builddir, lang=None): build_inputs.File.__init__(self, name, source) self.lang = lang class Binary(build_inputs.File): install_kind = 'program' class Executable(Binary): install_root = Path.bindir class Library(Binary): install_root = Path.libdir def __init__(self, lib_name, name, source=Path.builddir): Binary.__init__(self, name, source) self.lib_name = lib_name class StaticLibrary(Library): pass class SharedLibrary(Library): pass # Used for Windows DLL files, which aren't linked to directly. class DynamicLibrary(Library): pass class ExternalLibrary(Library): def __init__(self, name): # TODO: Handle import libraries specifically? Library.__init__(self, name, name)
import build_inputs from path import Path class SourceFile(build_inputs.File): def __init__(self, name, source=Path.srcdir, lang=None): build_inputs.File.__init__(self, name, source=source) self.lang = lang class HeaderFile(build_inputs.File): install_kind = 'data' install_root = Path.includedir class HeaderDirectory(build_inputs.Directory): install_root = Path.includedir class ObjectFile(build_inputs.File): def __init__(self, name, source=Path.builddir, lang=None): build_inputs.File.__init__(self, name, source) self.lang = lang class Binary(build_inputs.File): install_kind = 'program' class Executable(Binary): install_root = Path.bindir class Library(Binary): install_root = Path.libdir def __init__(self, lib_name, name, source=Path.builddir): Binary.__init__(self, name, source) self.lib_name = lib_name class StaticLibrary(Library): pass class SharedLibrary(Library): pass # Used for Windows DLL files, which aren't linked to directly. Import libraries # are handled via SharedLibrary above. class DynamicLibrary(Library): pass class ExternalLibrary(Library): def __init__(self, name): # TODO: Keep track of the external lib's actual location on the # filesystem? Library.__init__(self, name, name)
Update comments on the built-in file types
Update comments on the built-in file types
Python
bsd-3-clause
jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000
--- +++ @@ -37,11 +37,13 @@ class SharedLibrary(Library): pass -# Used for Windows DLL files, which aren't linked to directly. +# Used for Windows DLL files, which aren't linked to directly. Import libraries +# are handled via SharedLibrary above. class DynamicLibrary(Library): pass class ExternalLibrary(Library): def __init__(self, name): - # TODO: Handle import libraries specifically? + # TODO: Keep track of the external lib's actual location on the + # filesystem? Library.__init__(self, name, name)
2145ee5961cc35d36013e2333c636c7390b6c039
gooey/gui/util/taskkill.py
gooey/gui/util/taskkill.py
import sys import os import signal if sys.platform.startswith("win"): def taskkill(pid): os.system('taskkill /F /PID {:d} /T >NUL 2>NUL'.format(pid)) else: # POSIX def taskkill(pid): os.kill(pid, signal.SIGTERM)
import sys import os import signal if sys.platform.startswith("win"): def taskkill(pid): os.system('taskkill /F /PID {:d} /T >NUL 2>NUL'.format(pid)) else: # POSIX import psutil def taskkill(pid): parent = psutil.Process(pid) for child in parent.children(recursive=True): child.kill() parent.kill()
Kill child processes as well as shell process
Kill child processes as well as shell process
Python
mit
jschultz/Gooey,partrita/Gooey,chriskiehl/Gooey,codingsnippets/Gooey
--- +++ @@ -7,5 +7,9 @@ def taskkill(pid): os.system('taskkill /F /PID {:d} /T >NUL 2>NUL'.format(pid)) else: # POSIX + import psutil def taskkill(pid): - os.kill(pid, signal.SIGTERM) + parent = psutil.Process(pid) + for child in parent.children(recursive=True): + child.kill() + parent.kill()
2204fa211f09dda25830d9f3f84a0e748e6aa02c
freeze.py
freeze.py
from flask_site import freezer, config if __name__ == '__main__': freezer.run(debug=config.get('debug')) # build and serve from build directory
from flask_site import freezer, flask_config if __name__ == '__main__': freezer.run(debug=flask_config.get('DEBUG')) # build and serve from build directory
Fix freezing debug or not
Fix freezing debug or not
Python
apache-2.0
wcpr740/wcpr.org,wcpr740/wcpr.org,wcpr740/wcpr.org
--- +++ @@ -1,4 +1,4 @@ -from flask_site import freezer, config +from flask_site import freezer, flask_config if __name__ == '__main__': - freezer.run(debug=config.get('debug')) # build and serve from build directory + freezer.run(debug=flask_config.get('DEBUG')) # build and serve from build directory
229ea6b0f373aa2d37c40f794c4c17bfff231e01
mox3/fixture.py
mox3/fixture.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Hewlett-Packard Development Company, L.P. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import fixtures from mox3 import mox from mox3 import stubout class MoxStubout(fixtures.Fixture): """Deal with code around mox and stubout as a fixture.""" def setUp(self): super(MoxStubout, self).setUp() self.mox = mox.Mox() self.stubs = stubout.StubOutForTesting() self.addCleanup(self.mox.UnsetStubs) self.addCleanup(self.stubs.UnsetAll) self.addCleanup(self.stubs.SmartUnsetAll) self.addCleanup(self.mox.VerifyAll)
# Copyright 2013 Hewlett-Packard Development Company, L.P. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import fixtures from mox3 import mox from mox3 import stubout class MoxStubout(fixtures.Fixture): """Deal with code around mox and stubout as a fixture.""" def setUp(self): super(MoxStubout, self).setUp() self.mox = mox.Mox() self.stubs = stubout.StubOutForTesting() self.addCleanup(self.mox.UnsetStubs) self.addCleanup(self.stubs.UnsetAll) self.addCleanup(self.stubs.SmartUnsetAll) self.addCleanup(self.mox.VerifyAll)
Remove vim header from source files
Remove vim header from source files Change-Id: I67a1ee4e894841bee620b1012257ad72f5e31765
Python
apache-2.0
openstack/mox3
--- +++ @@ -1,5 +1,3 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - # Copyright 2013 Hewlett-Packard Development Company, L.P. # All Rights Reserved. #
788ac45c702109036a4ebd0868919d5b42c040ef
this_app/forms.py
this_app/forms.py
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, TextAreaField from wtforms.validators import DataRequired, Length, Email class SignupForm(FlaskForm): """Render and validate the signup form""" email = StringField("Email", validators=[DataRequired(), Email(message="Invalid email format"), Length(max=32)]) username = StringField("Username", validators=[DataRequired(), Length(2, 32)]) password = PasswordField("Password", validators=[DataRequired(), Length(min=4, max=32)]) class LoginForm(FlaskForm): """Form to let users login""" email = StringField("Email", validators=[DataRequired(), Email(message="Invalid email format"), Length(max=32)]) password = PasswordField("Password", validators=[DataRequired(), Length(4, 32)]) remember = BooleanField("Remember Me") class BucketlistForm(FlaskForm): """Form to CRUd a bucketlist""" name = StringField("Name", validators=[DataRequired()]) description = TextAreaField("Description", validators=[DataRequired()]) class BucketlistItemForm(FlaskForm): """Form to CRUd a bucketlist item""" title = StringField("Title", validators=[DataRequired()]) description = TextAreaField("Description", validators=[DataRequired()]) status = BooleanField("Status")
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, TextAreaField from wtforms.validators import DataRequired, Length, Email class SignupForm(FlaskForm): """Render and validate the signup form""" email = StringField("Email", validators=[DataRequired(), Email(message="Invalid email format"), Length(max=32)]) username = StringField("Username", validators=[DataRequired(), Length(2, 32)]) password = PasswordField("Password", validators=[DataRequired(), Length(min=4, max=32)]) class LoginForm(FlaskForm): """Form to let users login""" email = StringField("Email", validators=[DataRequired(), Email(message="Invalid email format"), Length(max=32)]) password = PasswordField("Password", validators=[DataRequired(), Length(4, 32)]) remember = BooleanField("Remember Me") class BucketlistForm(FlaskForm): """Form to CRUd a bucketlist""" name = StringField("Name", validators=[DataRequired()]) description = TextAreaField("Description", validators=[DataRequired()]) class ActivityForm(FlaskForm): """Form to CRUd a bucketlist item""" title = StringField("Title", validators=[DataRequired()]) description = TextAreaField("Description", validators=[DataRequired()]) status = BooleanField("Status")
Rename form BucketlistItem to Activity
Rename form BucketlistItem to Activity
Python
mit
borenho/flask-bucketlist,borenho/flask-bucketlist
--- +++ @@ -23,7 +23,7 @@ description = TextAreaField("Description", validators=[DataRequired()]) -class BucketlistItemForm(FlaskForm): +class ActivityForm(FlaskForm): """Form to CRUd a bucketlist item""" title = StringField("Title", validators=[DataRequired()]) description = TextAreaField("Description", validators=[DataRequired()])
dddef6b793bc7c45d1f70f133a608d017ad4b341
tests/manage_tests.py
tests/manage_tests.py
import os import unittest from application.default_settings import _basedir from application import app, db class ManagerTestCase(unittest.TestCase): """ setup and teardown for the testing database """ def setUp(self): create_db_dir = _basedir + '/db' if not os.path.exists(create_db_dir): os.mkdir(create_db_dir, 0755) app.config['TESTING'] = True app.config['SQLALCHEMY_DATABASE_URI'] = ('sqlite:///' + os.path.join(_basedir, 'db/tests.db')) self.app = app.test_client() db.create_all() def tearDown(self): db.session.remove() db.drop_all() class OriginalRoutes(ManagerTestCase): """ test suite for the original in app routes """ def route_username(self, username): return self.app.get('/hello/%s' % (username), follow_redirects=True) def test_username(self): rv = self.route_username('alberto') assert "Hello, alberto" in rv.data def test_index(self): rv = self.app.get('/') assert 'hi' in rv.data
import os import unittest from application.default_settings import _basedir from application import app, db class ManagerTestCase(unittest.TestCase): """ setup and teardown for the testing database """ def setUp(self): create_db_dir = _basedir + '/db' if not os.path.exists(create_db_dir): os.mkdir(create_db_dir, 0755) app.config['TESTING'] = True app.config['SQLALCHEMY_DATABASE_URI'] = ('sqlite:///' + os.path.join(_basedir, 'db/tests.db')) self.app = app.test_client() db.create_all() def tearDown(self): db.session.remove() db.drop_all() class OriginalRoutes(ManagerTestCase): """ test suite for the original in app routes """ def route_username(self, username): return self.app.get('/hello/%s' % (username), follow_redirects=True) def test_username(self): rv = self.route_username('alberto') assert "Hello, alberto" in rv.data def test_index(self): rv = self.app.get('/') assert 'Flask bootstrap project' in rv.data assert 'Flask-bootstrap' in rv.data assert 'Read the wiki' in rv.data
Fix tests for new index.
Fix tests for new index.
Python
bsd-3-clause
san-bil/astan,san-bil/astan,fert89/prueba-3-heroku-flask,albertogg/flask-bootstrap-skel,Agreste/MobUrbRoteiro,fert89/prueba-3-heroku-flask,san-bil/astan,scwu/stress-relief,san-bil/astan,scwu/stress-relief,Agreste/MobUrbRoteiro,Agreste/MobUrbRoteiro,akhilaryan/clickcounter
--- +++ @@ -34,4 +34,6 @@ def test_index(self): rv = self.app.get('/') - assert 'hi' in rv.data + assert 'Flask bootstrap project' in rv.data + assert 'Flask-bootstrap' in rv.data + assert 'Read the wiki' in rv.data
c32eb5f0a09f0a43172ed257ce21ab9545b6e03e
lazy_helpers.py
lazy_helpers.py
# Lazy objects, for the serializer to find them we put them here class LazyDriver(object): _driver = None @classmethod def get(cls): import os if cls._driver is None: from pyvirtualdisplay import Display display = Display(visible=0, size=(800, 600)) display.start() from selenium import webdriver # Configure headless mode chrome_options = webdriver.ChromeOptions() #Oops chrome_options.add_argument('--verbose') chrome_options.add_argument('--ignore-certificate-errors') log_path = "/tmp/chromelogpanda{0}".format(os.getpid()) if not os.path.exists(log_path): os.mkdir(log_path) chrome_options.add_argument("--log-path {0}/log.txt".format(log_path)) chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-setuid-sandbox") cls._driver = webdriver.Chrome(chrome_options=chrome_options) return cls._driver class LazyPool(object): _pool = None @classmethod def get(cls): if cls._pool is None: import urllib3 cls._pool = urllib3.PoolManager() return cls._pool
# Lazy objects, for the serializer to find them we put them here class LazyDriver(object): _driver = None @classmethod def get(cls): import os if cls._driver is None: from pyvirtualdisplay import Display cls._display = display display = Display(visible=0, size=(1024, 768)) display.start() from selenium import webdriver # Configure headless mode chrome_options = webdriver.ChromeOptions() #Oops chrome_options.add_argument('--verbose') chrome_options.add_argument('--ignore-certificate-errors') log_path = "/tmp/chromelogpanda{0}".format(os.getpid()) if not os.path.exists(log_path): os.mkdir(log_path) chrome_options.add_argument("--log-path {0}/log.txt".format(log_path)) chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-setuid-sandbox") cls._driver = webdriver.Chrome(chrome_options=chrome_options) return cls._driver @classmethod def reset(cls): cls._display.stop() cls._driver.Dispose() class LazyPool(object): _pool = None @classmethod def get(cls): if cls._pool is None: import urllib3 cls._pool = urllib3.PoolManager() return cls._pool
Update lazy helper to support the idea of a reset on bad state.
Update lazy helper to support the idea of a reset on bad state.
Python
apache-2.0
holdenk/diversity-analytics,holdenk/diversity-analytics
--- +++ @@ -8,7 +8,8 @@ import os if cls._driver is None: from pyvirtualdisplay import Display - display = Display(visible=0, size=(800, 600)) + cls._display = display + display = Display(visible=0, size=(1024, 768)) display.start() from selenium import webdriver # Configure headless mode @@ -24,6 +25,11 @@ cls._driver = webdriver.Chrome(chrome_options=chrome_options) return cls._driver + @classmethod + def reset(cls): + cls._display.stop() + cls._driver.Dispose() + class LazyPool(object): _pool = None
2f4ed65bcddf9494134f279046fde75b0772b07d
utils/database.py
utils/database.py
import ConfigParser import os import yaml class Database(object): """ Generic class for handling database-related tasks. """ def select_config_for_environment(self): """ Read the value of env variable and load the property database configuration based on the value of DB_ENV. Takes no input and returns a string like 'production' or 'testing'.""" return os.getenv('DB_ENV', 'development') def load_config(self): """ Pull the configuration off disk and parse the yml. Returns a dict containing a subset of the yml from the 'database' section. """ environment = self.select_config_for_environment() config_src = ("%s/config/cmdb.%s.yml" % ( (os.path.join(os.path.dirname(__file__), '..')), environment)) config = open(config_src) try: return yaml.load(config)['database'] except: print ("Ensure config/cmdb.%s.yml exists" % config_src) return None
import ConfigParser import os import yaml class Database(object): """ Generic class for handling database-related tasks. """ def select_config_for_environment(self): """ Read the value of env variable and load the property database configuration based on the value of DB_ENV. Takes no input and returns a string like 'production' or 'testing'.""" return os.getenv('DB_ENV', 'development') def load_config(self): """ Pull the configuration off disk and parse the yml. Returns a dict containing a subset of the yml from the 'database' section. """ environment = self.select_config_for_environment() config_src = ("%s/config/cmdb.%s.yml" % ( (os.path.join(os.path.dirname(__file__), '..')), environment)) config = open(config_src) try: return yaml.load(config)['database'] except: print ("Ensure config/cmdb.%s.yml exists" % environment) return None
Fix mistake in path in warning when config file is missing
Fix mistake in path in warning when config file is missing
Python
apache-2.0
ProjectFlorida/outrider
--- +++ @@ -24,5 +24,5 @@ try: return yaml.load(config)['database'] except: - print ("Ensure config/cmdb.%s.yml exists" % config_src) + print ("Ensure config/cmdb.%s.yml exists" % environment) return None
5dacd62d8d27f6d0d94313ec1bd39857ee314d2f
scrubadub/filth/named_entity.py
scrubadub/filth/named_entity.py
from .base import Filth class NamedEntityFilth(Filth): """ Named entity filth. Upon initialisation provide a label for named entity (e.g. name, org) """ type = 'named_entity' def __init__(self, *args, label: str, **kwargs): super(NamedEntityFilth, self).__init__(*args, **kwargs) self.label = label.lower()
from .base import Filth class NamedEntityFilth(Filth): """ Named entity filth. Upon initialisation provide a label for named entity (e.g. name, org) """ type = 'named_entity' def __init__(self, *args, label: str, **kwargs): super(NamedEntityFilth, self).__init__(*args, **kwargs) self.label = label.lower() self.replacement_string = "{}_{}".format(self.type, self.label)
Change replacement string of named entity filth
Change replacement string of named entity filth
Python
mit
deanmalmgren/scrubadub,datascopeanalytics/scrubadub,deanmalmgren/scrubadub,datascopeanalytics/scrubadub
--- +++ @@ -10,3 +10,4 @@ def __init__(self, *args, label: str, **kwargs): super(NamedEntityFilth, self).__init__(*args, **kwargs) self.label = label.lower() + self.replacement_string = "{}_{}".format(self.type, self.label)
0e34fce69b01ab9b8f3ec00be633bc2581df26d5
bibliopixel/animation/mixer.py
bibliopixel/animation/mixer.py
import copy from . import parallel from .. util import color_list class Mixer(parallel.Parallel): def __init__(self, *args, levels=None, master=1, **kwds): self.master = master super().__init__(*args, **kwds) self.mixer = color_list.Mixer( self.color_list, [a.color_list for a in self.animations], levels) self.levels = self.mixer.levels def step(self, amt=1): super().step(amt) self.mixer.clear() self.mixer.mix(self.master)
import copy from . import parallel from .. util import color_list class Mixer(parallel.Parallel): def __init__(self, *args, levels=None, master=1, **kwds): self.master = master super().__init__(*args, **kwds) self.mixer = color_list.Mixer( self.color_list, [a.color_list for a in self.animations], levels) @property def levels(self): return self.mixer.levels @levels.setter def levels(self, levels): self.mixer.levels[:] = levels def step(self, amt=1): super().step(amt) self.mixer.clear() self.mixer.mix(self.master)
Handle getting and setting the Mixer levels correctly
Handle getting and setting the Mixer levels correctly
Python
mit
rec/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel
--- +++ @@ -12,7 +12,14 @@ self.color_list, [a.color_list for a in self.animations], levels) - self.levels = self.mixer.levels + + @property + def levels(self): + return self.mixer.levels + + @levels.setter + def levels(self, levels): + self.mixer.levels[:] = levels def step(self, amt=1): super().step(amt)
a41e07ff20d9dc44288a57f76a83e86b4944049a
nlppln/commands/frog_to_saf.py
nlppln/commands/frog_to_saf.py
#!/usr/bin/env python import click import os import codecs import json from xtas.tasks._frog import parse_frog, frog_to_saf @click.command() @click.argument('input_files', nargs=-1, type=click.Path(exists=True)) @click.argument('output_dir', nargs=1, type=click.Path()) def frog2saf(input_files, output_dir): if not os.path.exists(output_dir): os.makedirs(output_dir) for fi in input_files: with codecs.open(fi) as f: lines = f.readlines() lines = [line.strip() for line in lines] saf_data = frog_to_saf(parse_frog(lines)) head, tail = os.path.split(fi) fname = tail.replace(os.path.splitext(tail)[1], '') out_file = os.path.join(output_dir, '{}.json'.format(fname)) with codecs.open(out_file, 'wb', encoding='utf-8') as f: json.dump(saf_data, f, indent=4) if __name__ == '__main__': frog2saf()
#!/usr/bin/env python import click import os import codecs import json from xtas.tasks._frog import parse_frog, frog_to_saf from nlppln.utils import create_dirs, out_file_name @click.command() @click.argument('input_files', nargs=-1, type=click.Path(exists=True)) @click.argument('output_dir', nargs=1, type=click.Path()) def frog2saf(input_files, output_dir): create_dirs(output_dir) for fi in input_files: with codecs.open(fi) as f: lines = f.readlines() lines = [line.strip() for line in lines] saf_data = frog_to_saf(parse_frog(lines)) head, tail = os.path.split(fi) fname = tail.replace(os.path.splitext(tail)[1], '') out_file = os.path.join(output_dir, out_file_name(output_dir, fname, 'json')) with codecs.open(out_file, 'wb', encoding='utf-8') as f: json.dump(saf_data, f, indent=4) if __name__ == '__main__': frog2saf()
Update command to use nlppln utils
Update command to use nlppln utils - fixes the double extension of output files
Python
apache-2.0
WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln
--- +++ @@ -6,13 +6,14 @@ from xtas.tasks._frog import parse_frog, frog_to_saf +from nlppln.utils import create_dirs, out_file_name + @click.command() @click.argument('input_files', nargs=-1, type=click.Path(exists=True)) @click.argument('output_dir', nargs=1, type=click.Path()) def frog2saf(input_files, output_dir): - if not os.path.exists(output_dir): - os.makedirs(output_dir) + create_dirs(output_dir) for fi in input_files: with codecs.open(fi) as f: @@ -23,7 +24,8 @@ head, tail = os.path.split(fi) fname = tail.replace(os.path.splitext(tail)[1], '') - out_file = os.path.join(output_dir, '{}.json'.format(fname)) + out_file = os.path.join(output_dir, out_file_name(output_dir, fname, + 'json')) with codecs.open(out_file, 'wb', encoding='utf-8') as f: json.dump(saf_data, f, indent=4)
8ad7e25d024e8549609119906fa09668dbb3e952
pywikibot/families/wikivoyage_family.py
pywikibot/families/wikivoyage_family.py
"""Family module for Wikivoyage.""" # # (C) Pywikibot team, 2012-2020 # # Distributed under the terms of the MIT license. # # The new Wikivoyage family that is hosted at Wikimedia from pywikibot import family class Family(family.SubdomainFamily, family.WikimediaFamily): """Family class for Wikivoyage.""" name = 'wikivoyage' languages_by_size = [ 'en', 'de', 'pl', 'it', 'fa', 'fr', 'ru', 'zh', 'nl', 'pt', 'es', 'he', 'vi', 'fi', 'sv', 'el', 'uk', 'ro', 'bn', 'eo', 'ps', 'ja', 'hi', ] category_redirect_templates = { '_default': (), 'bn': ('বিষয়শ্রেণী পুনর্নির্দেশ',), 'zh': ('分类重定向',), } # Global bot allowed languages on # https://meta.wikimedia.org/wiki/BPI#Current_implementation # & https://meta.wikimedia.org/wiki/Special:WikiSets/2 cross_allowed = [ 'bn', 'el', 'en', 'es', 'fa', 'fi', 'hi', 'ps', 'ru', ]
"""Family module for Wikivoyage.""" # # (C) Pywikibot team, 2012-2020 # # Distributed under the terms of the MIT license. # # The new Wikivoyage family that is hosted at Wikimedia from pywikibot import family class Family(family.SubdomainFamily, family.WikimediaFamily): """Family class for Wikivoyage.""" name = 'wikivoyage' languages_by_size = [ 'en', 'de', 'pl', 'it', 'fa', 'fr', 'ru', 'zh', 'nl', 'pt', 'es', 'he', 'vi', 'fi', 'sv', 'el', 'uk', 'ro', 'bn', 'eo', 'ps', 'ja', 'hi', 'tr', ] category_redirect_templates = { '_default': (), 'bn': ('বিষয়শ্রেণী পুনর্নির্দেশ',), 'zh': ('分类重定向',), } # Global bot allowed languages on # https://meta.wikimedia.org/wiki/BPI#Current_implementation # & https://meta.wikimedia.org/wiki/Special:WikiSets/2 cross_allowed = [ 'bn', 'el', 'en', 'es', 'fa', 'fi', 'hi', 'ps', 'ru', ]
Add support for trwikivoyage to Pywikibot
Add support for trwikivoyage to Pywikibot Bug: T271263 Change-Id: I96597f57522147d26e9b0a86f89c67ca8959c5a2
Python
mit
wikimedia/pywikibot-core,wikimedia/pywikibot-core
--- +++ @@ -16,7 +16,7 @@ languages_by_size = [ 'en', 'de', 'pl', 'it', 'fa', 'fr', 'ru', 'zh', 'nl', 'pt', 'es', 'he', - 'vi', 'fi', 'sv', 'el', 'uk', 'ro', 'bn', 'eo', 'ps', 'ja', 'hi', + 'vi', 'fi', 'sv', 'el', 'uk', 'ro', 'bn', 'eo', 'ps', 'ja', 'hi', 'tr', ] category_redirect_templates = {
5b66a57257807adf527fcb1de4c750013e532f25
newsletter/utils.py
newsletter/utils.py
import logging logger = logging.getLogger(__name__) import random from django.utils.hashcompat import sha_constructor from django.contrib.sites.models import Site from datetime import datetime # Conditional import of 'now' # Django 1.4 should use timezone.now, Django 1.3 datetime.now try: from django.utils.timezone import now except ImportError: logger.warn('Timezone support not enabled.') now = datetime.now # Generic helper functions def make_activation_code(): """ Generate a unique activation code. """ random_string = str(random.random()) random_digest = sha_constructor(random_string).hexdigest()[:5] time_string = str(datetime.now().microsecond) combined_string = random_digest + time_string return sha_constructor(combined_string).hexdigest() def get_default_sites(): """ Get a list of id's for all sites; the default for newsletters. """ return [site.id for site in Site.objects.all()]
import logging logger = logging.getLogger(__name__) import random try: from hashlib import sha1 except ImportError: from django.utils.hashcompat import sha_constructor as sha1 from django.contrib.sites.models import Site from datetime import datetime # Conditional import of 'now' # Django 1.4 should use timezone.now, Django 1.3 datetime.now try: from django.utils.timezone import now except ImportError: logger.warn('Timezone support not enabled.') now = datetime.now # Generic helper functions def make_activation_code(): """ Generate a unique activation code. """ random_string = str(random.random()) random_digest = sha1(random_string).hexdigest()[:5] time_string = str(datetime.now().microsecond) combined_string = random_digest + time_string return sha1(combined_string).hexdigest() def get_default_sites(): """ Get a list of id's for all sites; the default for newsletters. """ return [site.id for site in Site.objects.all()]
Fix deprecation warnings with Django 1.5
Fix deprecation warnings with Django 1.5 django/utils/hashcompat.py:9: DeprecationWarning: django.utils.hashcompat is deprecated; use hashlib instead
Python
agpl-3.0
dsanders11/django-newsletter,dsanders11/django-newsletter,ctxis/django-newsletter,ctxis/django-newsletter,viaregio/django-newsletter,dsanders11/django-newsletter,ctxis/django-newsletter,viaregio/django-newsletter
--- +++ @@ -3,7 +3,11 @@ import random -from django.utils.hashcompat import sha_constructor +try: + from hashlib import sha1 +except ImportError: + from django.utils.hashcompat import sha_constructor as sha1 + from django.contrib.sites.models import Site from datetime import datetime @@ -21,12 +25,12 @@ def make_activation_code(): """ Generate a unique activation code. """ random_string = str(random.random()) - random_digest = sha_constructor(random_string).hexdigest()[:5] + random_digest = sha1(random_string).hexdigest()[:5] time_string = str(datetime.now().microsecond) combined_string = random_digest + time_string - return sha_constructor(combined_string).hexdigest() + return sha1(combined_string).hexdigest() def get_default_sites():
45f30b4b1da110e79787b85c054796a671718910
tests/__main__.py
tests/__main__.py
import unittest import os.path if __name__ == '__main__': HERE = os.path.dirname(__file__) loader = unittest.loader.TestLoader() suite = loader.discover(HERE) result = unittest.result.TestResult() suite.run(result) print('Ran {} tests.'.format(result.testsRun)) print('{} errors, {} failed, {} skipped'.format( len(result.errors), len(result.failures), len(result.skipped), )) if not result.wasSuccessful(): for module, traceback in result.errors: print('[{}]\n{}\n\n'.format(module, traceback))
import unittest import os.path if __name__ == '__main__': HERE = os.path.dirname(__file__) loader = unittest.loader.TestLoader() suite = loader.discover(HERE) result = unittest.result.TestResult() suite.run(result) print('Ran {} tests.'.format(result.testsRun)) print('{} errors, {} failed, {} skipped'.format( len(result.errors), len(result.failures), len(result.skipped), )) if not result.wasSuccessful(): if result.errors: print('\nErrors:') for module, traceback in result.errors: print('[{}]\n{}\n\n'.format(module, traceback)) if result.failures: print('\nFailures:') for module, traceback in result.failures: print('[{}]\n{}\n\n'.format(module, traceback))
Print failures and errors in test run
Print failures and errors in test run
Python
mit
funkybob/antfarm
--- +++ @@ -18,5 +18,11 @@ len(result.skipped), )) if not result.wasSuccessful(): - for module, traceback in result.errors: - print('[{}]\n{}\n\n'.format(module, traceback)) + if result.errors: + print('\nErrors:') + for module, traceback in result.errors: + print('[{}]\n{}\n\n'.format(module, traceback)) + if result.failures: + print('\nFailures:') + for module, traceback in result.failures: + print('[{}]\n{}\n\n'.format(module, traceback))
5990374409ca2c5f35c602cb6d2276eb536d979a
tests/test_lib.py
tests/test_lib.py
""" Unit tests for One Codex """ from onecodex.lib.auth import check_version from onecodex.version import __version__ SERVER = 'https://app.onecodex.com/' def test_check_version(): # TODO: Remove Internet dependency here -- need a version response mock should_upgrade, msg = check_version(__version__, SERVER, 'gui') assert not should_upgrade assert msg is None or msg.startswith('Please upgrade your client to the latest version')
""" Unit tests for One Codex """ from onecodex.lib.auth import check_version from onecodex.version import __version__ SERVER = 'https://app.onecodex.com/' def test_check_version_integration(): # TODO: Remove Internet dependency here -- need a version response mock should_upgrade, msg = check_version(__version__, SERVER, 'cli') assert not should_upgrade assert msg is None or msg.startswith('Please upgrade your client to the latest version')
Update verison check test, note it's an integration test
Update verison check test, note it's an integration test
Python
mit
refgenomics/onecodex,refgenomics/onecodex,onecodex/onecodex,onecodex/onecodex
--- +++ @@ -8,9 +8,9 @@ SERVER = 'https://app.onecodex.com/' -def test_check_version(): +def test_check_version_integration(): # TODO: Remove Internet dependency here -- need a version response mock - should_upgrade, msg = check_version(__version__, SERVER, 'gui') + should_upgrade, msg = check_version(__version__, SERVER, 'cli') assert not should_upgrade assert msg is None or msg.startswith('Please upgrade your client to the latest version')
f2af046da299686515e4eaf2d9ae58a62108cc21
games/urls/installers.py
games/urls/installers.py
# pylint: disable=C0103 from __future__ import absolute_import from django.conf.urls import url from games.views import installers as views urlpatterns = [ url(r'revisions/(?P<pk>[\d]+)$', views.InstallerRevisionDetailView.as_view(), name="api_installer_revision_detail"), url(r'(?P<pk>[\d]+)/revisions$', views.InstallerRevisionListView.as_view(), name="api_installer_revision_list"), url(r'game/(?P<slug>[\w\-]+)$', views.GameInstallerList.as_view(), name='api_game_installer_list'), url(r'game/(?P<slug>[\w\-]+)/revisions$', views.GameRevisionListView.as_view(), name='api_game_revisions_list'), url(r'(?P<pk>[\d]+)$', views.InstallerDetailView.as_view(), name='api_installer_detail'), url(r'^$', views.InstallerListView.as_view(), name='api_installer_list'), ]
# pylint: disable=C0103 from __future__ import absolute_import from django.conf.urls import url from games.views import installers as views urlpatterns = [ url(r'game/(?P<slug>[\w\-]+)$', views.GameInstallerList.as_view(), name='api_game_installer_list'), url(r'game/(?P<slug>[\w\-]+)/revisions$', views.GameRevisionListView.as_view(), name='api_game_revisions_list'), url(r'(?P<pk>[\d]+)/revisions$', views.InstallerRevisionListView.as_view(), name="api_installer_revision_list"), url(r'revisions/(?P<pk>[\d]+)$', views.InstallerRevisionDetailView.as_view(), name="api_installer_revision_detail"), url(r'(?P<pk>[\d]+)$', views.InstallerDetailView.as_view(), name='api_installer_detail'), url(r'^$', views.InstallerListView.as_view(), name='api_installer_list'), ]
Fix order for installer API routes
Fix order for installer API routes
Python
agpl-3.0
lutris/website,lutris/website,Turupawn/website,Turupawn/website,lutris/website,Turupawn/website,Turupawn/website,lutris/website
--- +++ @@ -5,19 +5,19 @@ urlpatterns = [ - url(r'revisions/(?P<pk>[\d]+)$', - views.InstallerRevisionDetailView.as_view(), - name="api_installer_revision_detail"), - url(r'(?P<pk>[\d]+)/revisions$', - views.InstallerRevisionListView.as_view(), - name="api_installer_revision_list"), - url(r'game/(?P<slug>[\w\-]+)$', views.GameInstallerList.as_view(), name='api_game_installer_list'), url(r'game/(?P<slug>[\w\-]+)/revisions$', views.GameRevisionListView.as_view(), name='api_game_revisions_list'), + + url(r'(?P<pk>[\d]+)/revisions$', + views.InstallerRevisionListView.as_view(), + name="api_installer_revision_list"), + url(r'revisions/(?P<pk>[\d]+)$', + views.InstallerRevisionDetailView.as_view(), + name="api_installer_revision_detail"), url(r'(?P<pk>[\d]+)$', views.InstallerDetailView.as_view(),
3f1aeba98cd4bc2f326f9c18c34e66c396be99cf
scikits/statsmodels/tools/tests/test_data.py
scikits/statsmodels/tools/tests/test_data.py
import pandas import numpy as np from scikits.statsmodels.tools import data def test_missing_data_pandas(): """ Fixes GH: #144 """ X = np.random.random((10,5)) X[1,2] = np.nan df = pandas.DataFrame(X) vals, cnames, rnames = data.interpret_data(df) np.testing.assert_equal(rnames, [0,2,3,4,5,6,7,8,9])
import pandas import numpy as np from scikits.statsmodels.tools import data def test_missing_data_pandas(): """ Fixes GH: #144 """ X = np.random.random((10,5)) X[1,2] = np.nan df = pandas.DataFrame(X) vals, cnames, rnames = data.interpret_data(df) np.testing.assert_equal(rnames, [0,2,3,4,5,6,7,8,9]) def test_structarray(): X = np.random.random((10,)).astype([('var1', 'f8'), ('var2', 'f8'), ('var3', 'f8')]) vals, cnames, rnames = data.interpret_data(X) np.testing.assert_equal(cnames, X.dtype.names) np.testing.assert_equal(vals, X.view((float,3))) np.testing.assert_equal(rnames, None) def test_recarray(): X = np.random.random((10,)).astype([('var1', 'f8'), ('var2', 'f8'), ('var3', 'f8')]) vals, cnames, rnames = data.interpret_data(X.view(np.recarray)) np.testing.assert_equal(cnames, X.dtype.names) np.testing.assert_equal(vals, X.view((float,3))) np.testing.assert_equal(rnames, None) def test_dataframe(): X = np.random.random((10,5)) df = pandas.DataFrame(X) vals, cnames, rnames = data.interpret_data(df) np.testing.assert_equal(vals, df.values) np.testing.assert_equal(rnames, df.index) np.testing.assert_equal(cnames, df.columns)
Add some tests for unused function
TST: Add some tests for unused function
Python
bsd-3-clause
Averroes/statsmodels,saketkc/statsmodels,wwf5067/statsmodels,phobson/statsmodels,musically-ut/statsmodels,hlin117/statsmodels,cbmoore/statsmodels,ChadFulton/statsmodels,pprett/statsmodels,statsmodels/statsmodels,gef756/statsmodels,rgommers/statsmodels,alekz112/statsmodels,jstoxrocky/statsmodels,kiyoto/statsmodels,musically-ut/statsmodels,Averroes/statsmodels,jstoxrocky/statsmodels,gef756/statsmodels,phobson/statsmodels,edhuckle/statsmodels,kiyoto/statsmodels,josef-pkt/statsmodels,Averroes/statsmodels,yl565/statsmodels,bert9bert/statsmodels,huongttlan/statsmodels,jstoxrocky/statsmodels,alekz112/statsmodels,alekz112/statsmodels,wzbozon/statsmodels,wzbozon/statsmodels,wkfwkf/statsmodels,wwf5067/statsmodels,Averroes/statsmodels,wwf5067/statsmodels,yl565/statsmodels,rgommers/statsmodels,bavardage/statsmodels,hlin117/statsmodels,cbmoore/statsmodels,adammenges/statsmodels,ChadFulton/statsmodels,adammenges/statsmodels,statsmodels/statsmodels,phobson/statsmodels,yarikoptic/pystatsmodels,bsipocz/statsmodels,edhuckle/statsmodels,astocko/statsmodels,yarikoptic/pystatsmodels,DonBeo/statsmodels,alekz112/statsmodels,YihaoLu/statsmodels,nvoron23/statsmodels,cbmoore/statsmodels,bsipocz/statsmodels,DonBeo/statsmodels,waynenilsen/statsmodels,kiyoto/statsmodels,nvoron23/statsmodels,waynenilsen/statsmodels,jseabold/statsmodels,detrout/debian-statsmodels,wkfwkf/statsmodels,rgommers/statsmodels,josef-pkt/statsmodels,astocko/statsmodels,bzero/statsmodels,jseabold/statsmodels,bavardage/statsmodels,pprett/statsmodels,bzero/statsmodels,YihaoLu/statsmodels,bashtage/statsmodels,bashtage/statsmodels,bert9bert/statsmodels,detrout/debian-statsmodels,wdurhamh/statsmodels,kiyoto/statsmodels,rgommers/statsmodels,yl565/statsmodels,nguyentu1602/statsmodels,wzbozon/statsmodels,DonBeo/statsmodels,ChadFulton/statsmodels,pprett/statsmodels,hainm/statsmodels,bashtage/statsmodels,wdurhamh/statsmodels,saketkc/statsmodels,bert9bert/statsmodels,wdurhamh/statsmodels,statsmodels/statsmodels,gef756/statsmodels,hainm/statsmodels,rgommers/statsmodels,bashtage/statsmodels,YihaoLu/statsmodels,statsmodels/statsmodels,cbmoore/statsmodels,wdurhamh/statsmodels,musically-ut/statsmodels,phobson/statsmodels,kiyoto/statsmodels,wkfwkf/statsmodels,wdurhamh/statsmodels,YihaoLu/statsmodels,huongttlan/statsmodels,bert9bert/statsmodels,josef-pkt/statsmodels,detrout/debian-statsmodels,waynenilsen/statsmodels,bashtage/statsmodels,hainm/statsmodels,bsipocz/statsmodels,edhuckle/statsmodels,bavardage/statsmodels,DonBeo/statsmodels,bzero/statsmodels,jseabold/statsmodels,bashtage/statsmodels,statsmodels/statsmodels,gef756/statsmodels,hlin117/statsmodels,waynenilsen/statsmodels,jseabold/statsmodels,astocko/statsmodels,bavardage/statsmodels,jseabold/statsmodels,wkfwkf/statsmodels,pprett/statsmodels,yarikoptic/pystatsmodels,wkfwkf/statsmodels,nvoron23/statsmodels,ChadFulton/statsmodels,saketkc/statsmodels,nguyentu1602/statsmodels,musically-ut/statsmodels,cbmoore/statsmodels,bsipocz/statsmodels,saketkc/statsmodels,gef756/statsmodels,nguyentu1602/statsmodels,astocko/statsmodels,bzero/statsmodels,bzero/statsmodels,nvoron23/statsmodels,nvoron23/statsmodels,ChadFulton/statsmodels,josef-pkt/statsmodels,statsmodels/statsmodels,jstoxrocky/statsmodels,phobson/statsmodels,adammenges/statsmodels,wwf5067/statsmodels,ChadFulton/statsmodels,edhuckle/statsmodels,huongttlan/statsmodels,bert9bert/statsmodels,hainm/statsmodels,bavardage/statsmodels,YihaoLu/statsmodels,DonBeo/statsmodels,detrout/debian-statsmodels,josef-pkt/statsmodels,adammenges/statsmodels,huongttlan/statsmodels,josef-pkt/statsmodels,wzbozon/statsmodels,hlin117/statsmodels,yl565/statsmodels,wzbozon/statsmodels,saketkc/statsmodels,nguyentu1602/statsmodels,edhuckle/statsmodels,yl565/statsmodels
--- +++ @@ -12,3 +12,30 @@ df = pandas.DataFrame(X) vals, cnames, rnames = data.interpret_data(df) np.testing.assert_equal(rnames, [0,2,3,4,5,6,7,8,9]) + +def test_structarray(): + X = np.random.random((10,)).astype([('var1', 'f8'), + ('var2', 'f8'), + ('var3', 'f8')]) + vals, cnames, rnames = data.interpret_data(X) + np.testing.assert_equal(cnames, X.dtype.names) + np.testing.assert_equal(vals, X.view((float,3))) + np.testing.assert_equal(rnames, None) + +def test_recarray(): + X = np.random.random((10,)).astype([('var1', 'f8'), + ('var2', 'f8'), + ('var3', 'f8')]) + vals, cnames, rnames = data.interpret_data(X.view(np.recarray)) + np.testing.assert_equal(cnames, X.dtype.names) + np.testing.assert_equal(vals, X.view((float,3))) + np.testing.assert_equal(rnames, None) + + +def test_dataframe(): + X = np.random.random((10,5)) + df = pandas.DataFrame(X) + vals, cnames, rnames = data.interpret_data(df) + np.testing.assert_equal(vals, df.values) + np.testing.assert_equal(rnames, df.index) + np.testing.assert_equal(cnames, df.columns)
98dd2759a184ba1066e8fd49cd09ff4194d2da0f
docweb/tests/__init__.py
docweb/tests/__init__.py
import os, sys from django.conf import settings # -- Setup Django configuration appropriately TESTDIR = os.path.abspath(os.path.dirname(__file__)) settings.MODULE_DIR = TESTDIR settings.PULL_SCRIPT = os.path.join(TESTDIR, 'pull-test.sh') # The CSRF middleware prevents the Django test client from working, so # disable it. settings.MIDDLEWARE_CLASSES = list(settings.MIDDLEWARE_CLASSES) try: settings.MIDDLEWARE_CLASSES.remove( 'django.contrib.csrf.middleware.CsrfMiddleware') except IndexError: pass # -- Test cases from test_functional import * from test_docstring import * from test_toctreecache import * # -- Allow Django test command to find the script tests test_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'scripts', 'tests') sys.path.append(test_dir) from test_pydoc_tool import *
import os, sys from django.conf import settings # -- Setup Django configuration appropriately TESTDIR = os.path.abspath(os.path.dirname(__file__)) settings.MODULE_DIR = TESTDIR settings.PULL_SCRIPT = os.path.join(TESTDIR, 'pull-test.sh') settings.SITE_ID = 1 # The CSRF middleware prevents the Django test client from working, so # disable it. settings.MIDDLEWARE_CLASSES = list(settings.MIDDLEWARE_CLASSES) try: settings.MIDDLEWARE_CLASSES.remove( 'django.contrib.csrf.middleware.CsrfMiddleware') except IndexError: pass # -- Test cases from test_functional import * from test_docstring import * from test_toctreecache import * # -- Allow Django test command to find the script tests test_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'scripts', 'tests') sys.path.append(test_dir) from test_pydoc_tool import *
Set SITE_ID=1 in tests (corresponds to that in the test fixtures)
Set SITE_ID=1 in tests (corresponds to that in the test fixtures)
Python
bsd-3-clause
pv/pydocweb,pv/pydocweb
--- +++ @@ -6,6 +6,7 @@ TESTDIR = os.path.abspath(os.path.dirname(__file__)) settings.MODULE_DIR = TESTDIR settings.PULL_SCRIPT = os.path.join(TESTDIR, 'pull-test.sh') +settings.SITE_ID = 1 # The CSRF middleware prevents the Django test client from working, so # disable it.
85748e4b18dffca6436c5439a3e40ac773611c37
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jon Surrell # Copyright (c) 2013 Jon Surrell # # License: MIT # """This module exports the Ghc plugin class.""" from SublimeLinter.lint import Linter, util class Ghc(Linter): """Provides an interface to ghc.""" syntax = ('haskell', 'haskell-sublimehaskell') cmd = ('ghc', '-fno-code', '-Wall', '-Wwarn', '-fno-helpful-errors') regex = r'^.+:(?P<line>\d+):(?P<col>\d+):\s+(?P<warning>Warning:\s+)?(?P<message>.+)$' multiline = True # No stdin tempfile_suffix = 'hs' # ghc writes errors to STDERR error_stream = util.STREAM_STDERR # @todo allow some settings defaults = {} inline_settings = None inline_overrides = None comment_re = None
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jon Surrell # Copyright (c) 2013 Jon Surrell # # License: MIT # """This module exports the Ghc plugin class.""" from SublimeLinter.lint import Linter, util class Ghc(Linter): """Provides an interface to ghc.""" syntax = ('haskell', 'haskell-sublimehaskell') cmd = ('ghc', '-fno-code', '-Wall', '-Wwarn', '-fno-helpful-errors') regex = r'^.+:(?P<line>\d+):(?P<col>\d+):\s+(?P<warning>Warning:\s+)?(?P<message>.+)$' multiline = True # No stdin tempfile_suffix = 'hs' # ghc writes errors to STDERR error_stream = util.STREAM_STDERR defaults = {} inline_settings = None inline_overrides = None comment_re = None
Remove todo comment, no settings support
Remove todo comment, no settings support
Python
mit
alexbiehl/SublimeLinter-stack-ghc,SublimeLinter/SublimeLinter-ghc
--- +++ @@ -28,7 +28,6 @@ # ghc writes errors to STDERR error_stream = util.STREAM_STDERR - # @todo allow some settings defaults = {} inline_settings = None inline_overrides = None
23d8664a80a51c489615db6dbcde8a7e76265f15
warehouse/defaults.py
warehouse/defaults.py
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals # The URI for our PostgreSQL database. SQLALCHEMY_DATABASE_URI = "postgres:///warehouse" # The base domain name for this installation. Used to control linking to # sub-domains. SERVER_NAME = "warehouse.local" # The type of Storage to use. Can be either Filesystem or S3. STORAGE = "Filesystem" # The hash to use in computing filenames. # Allowed values: md5, sha1, sha224, sha256, sha384, sha512, None STORAGE_HASH = "md5" # Base directory for storage when using the Filesystem. STORAGE_DIRECTORY = "data" # The name of the bucket that files will be stored in when using S3. # STORAGE_BUCKET = "<storage bucket>" # The S3 Key used to access S3 when using S3 Storage # S3_KEY = "<S3 Key>" # The S3 Secret used to access S# when using S3 Storage # S3_SECRET = "<S3 Secret>"
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals # The base domain name for this installation. Used to control linking to # sub-domains. SERVER_NAME = "warehouse.local" # The URI for our PostgreSQL database. SQLALCHEMY_DATABASE_URI = "postgres:///warehouse" # The type of Storage to use. Can be either Filesystem or S3. STORAGE = "Filesystem" # The hash to use in computing filenames. # Allowed values: md5, sha1, sha224, sha256, sha384, sha512, None STORAGE_HASH = "md5" # Base directory for storage when using the Filesystem. STORAGE_DIRECTORY = "data" # The name of the bucket that files will be stored in when using S3. # STORAGE_BUCKET = "<storage bucket>" # The S3 Key used to access S3 when using S3 Storage # S3_KEY = "<S3 Key>" # The S3 Secret used to access S# when using S3 Storage # S3_SECRET = "<S3 Secret>"
Move the SERVER_NAME to the start of the default config
Move the SERVER_NAME to the start of the default config Minor nit but the SERVER_NAME is one of the more important settings on a per app basis.
Python
bsd-2-clause
davidfischer/warehouse
--- +++ @@ -2,12 +2,12 @@ from __future__ import division from __future__ import unicode_literals -# The URI for our PostgreSQL database. -SQLALCHEMY_DATABASE_URI = "postgres:///warehouse" - # The base domain name for this installation. Used to control linking to # sub-domains. SERVER_NAME = "warehouse.local" + +# The URI for our PostgreSQL database. +SQLALCHEMY_DATABASE_URI = "postgres:///warehouse" # The type of Storage to use. Can be either Filesystem or S3. STORAGE = "Filesystem"
71ec798d6a85a2aa0e4b80e6095d4da67612db70
apps/article/serializers.py
apps/article/serializers.py
from rest_framework import serializers from apps.article.models import Article, Tag from apps.authentication.serializers import UserSerializer class ArticleSerializer(serializers.ModelSerializer): author = UserSerializer(source='created_by') # serializers.StringRelatedField(source='created_by') absolute_url = serializers.CharField(source='get_absolute_url', read_only=True) class Meta: model = Article fields = ( 'absolute_url', 'additional_authors', 'author', 'changed_date', 'content', 'created_date', 'featured', 'heading', 'id', # 'image_article_front_featured', 'image_article_front_small', 'image_article_full', 'image_article_main', 'image_article_related', 'ingress', 'ingress_short', 'photographers', 'published_date', 'slug', 'video', 'images', 'article_tags', ) class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('name', 'short_name')
from rest_framework import serializers from apps.article.models import Article, Tag from apps.authentication.serializers import UserSerializer class ArticleSerializer(serializers.ModelSerializer): author = UserSerializer(source='created_by') absolute_url = serializers.CharField(source='get_absolute_url', read_only=True) class Meta: model = Article fields = ( 'absolute_url', 'additional_authors', 'author', 'changed_date', 'content', 'created_date', 'featured', 'heading', 'id', 'ingress', 'ingress_short', 'photographers', 'published_date', 'slug', 'video', 'images', 'article_tags', ) class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('name', 'short_name')
Clean up article serializer a bit
Clean up article serializer a bit
Python
mit
dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4
--- +++ @@ -5,7 +5,7 @@ class ArticleSerializer(serializers.ModelSerializer): - author = UserSerializer(source='created_by') # serializers.StringRelatedField(source='created_by') + author = UserSerializer(source='created_by') absolute_url = serializers.CharField(source='get_absolute_url', read_only=True) class Meta: @@ -13,7 +13,6 @@ fields = ( 'absolute_url', 'additional_authors', 'author', 'changed_date', 'content', 'created_date', 'featured', 'heading', 'id', - # 'image_article_front_featured', 'image_article_front_small', 'image_article_full', 'image_article_main', 'image_article_related', 'ingress', 'ingress_short', 'photographers', 'published_date', 'slug', 'video', 'images', 'article_tags', )
3fca658f3db21a0b3b8de626e6a7faf07da6ddab
restalchemy/dm/models.py
restalchemy/dm/models.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2014 Eugene Frolov <eugene@frolov.net.ru> # # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import abc import uuid from restalchemy.dm import properties from restalchemy.dm import types class Model(properties.PropertyBasedObject): __metaclass__ = abc.ABCMeta def __init__(self, **kwargs): super(Model, self).__init__(properties.AbstractProperty, **kwargs) @classmethod def restore(cls, **kwargs): return super(Model, cls).restore(properties.AbstractProperty, **kwargs) @abc.abstractmethod def get_id(self): pass class ModelWithUUID(Model): uuid = properties.property(types.UUID, read_only=True, default=lambda: str(uuid.uuid4())) def get_id(self): return self.uuid
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2014 Eugene Frolov <eugene@frolov.net.ru> # # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import abc import uuid from restalchemy.dm import properties from restalchemy.dm import types class Model(properties.PropertyBasedObject): __metaclass__ = abc.ABCMeta def __init__(self, **kwargs): super(Model, self).__init__(properties.AbstractProperty, **kwargs) @classmethod def restore(cls, **kwargs): return super(Model, cls).restore(properties.AbstractProperty, **kwargs) @abc.abstractmethod def get_id(self): pass class ModelWithUUID(Model): uuid = properties.property(types.UUID, read_only=True, default=lambda: str(uuid.uuid4())) def get_id(self): return self.uuid def __eq__(self, other): if isinstance(other, type(self)): return self.get_id() == other.get_id() return False
Add equal method to model with uuid
Add equal method to model with uuid Change-Id: Iefa05d50f2f591399d5423debd699f88074a574e
Python
apache-2.0
phantomii/restalchemy
--- +++ @@ -44,3 +44,8 @@ def get_id(self): return self.uuid + + def __eq__(self, other): + if isinstance(other, type(self)): + return self.get_id() == other.get_id() + return False
2f34954716c3164b6fd65e997a6d0b02a4be6a03
pyblox/api/http.py
pyblox/api/http.py
# # http.py # pyblox # # By Sanjay-B(Sanjay Bhadra) # Copyright © 2017 Sanjay-B(Sanjay Bhadra). All rights reserved. # import json import requests class Http: def sendRequest(url): payload = requests.get(str(url)) statusCode = payload.status_code header = payload.headers content = payload.content if statusCode == 403: return print("[Roblox][GET] Something went wrong. Error: 403") return content def postRequest(url,param1,param2): payload = requests.post(str(url), data = {str(param1):str(param2)}) statusCode = payload.status_code header = payload.headers content = payload.content if statusCode == 403: return print("[Roblox][POST] Something went wrong. Error: 403") return content
# # http.py # pyblox # # By Sanjay-B(Sanjay Bhadra) # Copyright © 2017 Sanjay-B(Sanjay Bhadra). All rights reserved. # import json import requests class Http: def sendRequest(url): payload = requests.get(str(url)) statusCode = payload.status_code header = payload.headers content = payload.content if statusCode is not 200: return print("[Roblox][GET] Something went wrong. Error: "+statusCode) return content def postRequest(url,param1,param2): payload = requests.post(str(url), data = {str(param1):str(param2)}) statusCode = payload.status_code header = payload.headers content = payload.content if statusCode is not 200: return print("[Roblox][POST] Something went wrong. Error: "+statusCode) return content
Check this commits description for more information
[Http] Check this commits description for more information - sendRequest() and postRequest now have better error handling and display the error via console - No longer toggles error on 403, instead it toggles everything but 200
Python
mit
Sanjay-B/Pyblox
--- +++ @@ -16,8 +16,8 @@ statusCode = payload.status_code header = payload.headers content = payload.content - if statusCode == 403: - return print("[Roblox][GET] Something went wrong. Error: 403") + if statusCode is not 200: + return print("[Roblox][GET] Something went wrong. Error: "+statusCode) return content def postRequest(url,param1,param2): @@ -25,6 +25,6 @@ statusCode = payload.status_code header = payload.headers content = payload.content - if statusCode == 403: - return print("[Roblox][POST] Something went wrong. Error: 403") + if statusCode is not 200: + return print("[Roblox][POST] Something went wrong. Error: "+statusCode) return content
8e755e7dc94b6966e73af5434d382fa1ecd15572
manage.py
manage.py
# TODO: migrate to Flask CLI instead of Flask-Script '''This module enables command line interface for randompeople app.''' from flask_script import Manager from app import create_app, db from app.models import Room, Member manager = Manager(create_app) @manager.shell def make_shell_context(): '''''' return dict(app=manager.app, db=db, Room=Room, Member=Member) if __name__ == '__main__': manager.run()
# TODO: migrate to Flask CLI instead of Flask-Script '''This module enables command line interface for randompeople app.''' from flask_script import Manager from app import create_app, db from app.models import Room, Member app = create_app() manager = Manager(app) @manager.shell def make_shell_context(): '''''' return dict(app=app, db=db, Room=Room, Member=Member) if __name__ == '__main__': manager.run()
Add Flask app variable to use with gunicorn
Add Flask app variable to use with gunicorn
Python
mit
chetotam/randompeople,chetotam/randompeople,chetotam/randompeople
--- +++ @@ -4,12 +4,13 @@ from app import create_app, db from app.models import Room, Member -manager = Manager(create_app) +app = create_app() +manager = Manager(app) @manager.shell def make_shell_context(): '''''' - return dict(app=manager.app, db=db, Room=Room, Member=Member) + return dict(app=app, db=db, Room=Room, Member=Member) if __name__ == '__main__': manager.run()
2958e793ea30d879afe265bb511183e4512fc049
webstr/core/config.py
webstr/core/config.py
""" Central configuration module of webstr selenium tests. This module provides configuration options along with default values and function to redefine values. """ # Copyright 2016 Red Hat # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import sys SELENIUM_LOG_LEVEL = logging.INFO SCHEME = 'https' PORT = 443 BROWSER = 'Firefox' BROWSER_VERSION = '' BROWSER_PLATFORM = 'ANY' SELENIUM_SERVER = 'selenium-grid.example.com' SELENIUM_PORT = 4444 BROWSER_WIDTH = 1280 BROWSER_HEIGHT = 1024 def update_value(key_name, value, force=False): """ Update single value of this config module. """ this_module = sys.modules[__name__] key_name = key_name.upper() # raise AttributeError if we try to define new value (unless force is used) if not force: getattr(this_module, key_name) setattr(this_module, key_name, value)
""" Central configuration module of webstr selenium tests. This module provides configuration options along with default values and function to redefine values. """ # Copyright 2016 Red Hat # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import sys SELENIUM_LOG_LEVEL = logging.INFO SCHEME = 'https' PORT = 443 BROWSER = 'Firefox' BROWSER_VERSION = '' BROWSER_PLATFORM = 'ANY' SELENIUM_SERVER = None SELENIUM_PORT = 4444 BROWSER_WIDTH = 1280 BROWSER_HEIGHT = 1024 def update_value(key_name, value, force=False): """ Update single value of this config module. """ this_module = sys.modules[__name__] key_name = key_name.upper() # raise AttributeError if we try to define new value (unless force is used) if not force: getattr(this_module, key_name) setattr(this_module, key_name, value)
Change the default value for SELENIUM_SERVER
Change the default value for SELENIUM_SERVER with this change it is possible to use webstr on localhost without any action Change-Id: Ife533552d7a746401df01c03af0b2d1caf0702b5 Signed-off-by: ltrilety <b0b91364d2d251c1396ffbe2df56e3ab774d4d4b@redhat.com>
Python
apache-2.0
Webstr-framework/webstr
--- +++ @@ -30,7 +30,7 @@ BROWSER = 'Firefox' BROWSER_VERSION = '' BROWSER_PLATFORM = 'ANY' -SELENIUM_SERVER = 'selenium-grid.example.com' +SELENIUM_SERVER = None SELENIUM_PORT = 4444 BROWSER_WIDTH = 1280 BROWSER_HEIGHT = 1024
d6d15743f6bac48a051798df0638190e1241ffb1
parliament/politicians/twit.py
parliament/politicians/twit.py
import email import datetime import re from django.conf import settings import twitter from parliament.core.models import Politician, PoliticianInfo from parliament.activity import utils as activity def save_tweets(): twitter_to_pol = dict([(i.value.lower(), i.politician) for i in PoliticianInfo.objects.filter(schema='twitter').select_related('politician')]) twit = twitter.Twitter() statuses = twit.openparlca.lists.mps.statuses(per_page=200) statuses.reverse() for status in statuses: pol = twitter_to_pol[status['user']['screen_name'].lower()] date = datetime.date.fromtimestamp( email.utils.mktime_tz( email.utils.parsedate_tz(status['created_at']) ) ) # fuck you, time formats guid = 'twit_%s' % status['id'] # Twitter apparently escapes < > but not & " # so I'm clunkily unescaping lt and gt then reescaping in the template text = status['text'].replace('&lt;', '<').replace('&gt;', '>') activity.save_activity({'text': status['text']}, politician=pol, date=date, guid=guid, variety='twitter')
import email import datetime import re from django.conf import settings import twitter from parliament.core.models import Politician, PoliticianInfo from parliament.activity import utils as activity def save_tweets(): twitter_to_pol = dict([(i.value.lower(), i.politician) for i in PoliticianInfo.objects.filter(schema='twitter').select_related('politician')]) twit = twitter.Twitter(domain='api.twitter.com/1') statuses = twit.openparlca.lists.mps.statuses(per_page=200) statuses.reverse() for status in statuses: pol = twitter_to_pol[status['user']['screen_name'].lower()] date = datetime.date.fromtimestamp( email.utils.mktime_tz( email.utils.parsedate_tz(status['created_at']) ) ) # fuck you, time formats guid = 'twit_%s' % status['id'] # Twitter apparently escapes < > but not & " # so I'm clunkily unescaping lt and gt then reescaping in the template text = status['text'].replace('&lt;', '<').replace('&gt;', '>') activity.save_activity({'text': status['text']}, politician=pol, date=date, guid=guid, variety='twitter')
Change the base URL for the Twitter API
Change the base URL for the Twitter API
Python
agpl-3.0
rhymeswithcycle/openparliament,litui/openparliament,rhymeswithcycle/openparliament,litui/openparliament,twhyte/openparliament,rhymeswithcycle/openparliament,twhyte/openparliament,litui/openparliament,twhyte/openparliament
--- +++ @@ -11,7 +11,7 @@ def save_tweets(): twitter_to_pol = dict([(i.value.lower(), i.politician) for i in PoliticianInfo.objects.filter(schema='twitter').select_related('politician')]) - twit = twitter.Twitter() + twit = twitter.Twitter(domain='api.twitter.com/1') statuses = twit.openparlca.lists.mps.statuses(per_page=200) statuses.reverse() for status in statuses:
add6013c8484e56545ed2f11c8c6e042c1384429
swf/exceptions.py
swf/exceptions.py
# -*- coding: utf-8 -*- # Copyright (c) 2013, Theo Crevon # Copyright (c) 2013, Greg Leclercq # # See the file LICENSE for copying permission. class PollTimeout(Exception): pass class InvalidCredentialsError(Exception): pass class ResponseError(Exception): pass class DoesNotExistError(Exception): pass class AlreadyExistsError(Exception): pass class InvalidKeywordArgumentError(Exception): pass
# -*- coding: utf-8 -*- # Copyright (c) 2013, Theo Crevon # Copyright (c) 2013, Greg Leclercq # # See the file LICENSE for copying permission. class SWFError(Exception): def __init__(self, message, raw_error, *args): Exception.__init__(self, message, *args) self.kind, self.details = raw_error.split(':') def __repr__(self): msg = self.message if self.kind and self.details: msg += '\nReason: {}, {}'.format(self.kind, self.details) return msg def __str__(self): msg = self.message if self.kind and self.details: msg += '\nReason: {}, {}'.format(self.kind, self.details) return msg class PollTimeout(SWFError): pass class InvalidCredentialsError(SWFError): pass class ResponseError(SWFError): pass class DoesNotExistError(SWFError): pass class AlreadyExistsError(SWFError): pass class InvalidKeywordArgumentError(SWFError): pass
Enhance swf errors wrapping via an exception helper
Enhance swf errors wrapping via an exception helper
Python
mit
botify-labs/python-simple-workflow,botify-labs/python-simple-workflow
--- +++ @@ -5,26 +5,47 @@ # # See the file LICENSE for copying permission. +class SWFError(Exception): + def __init__(self, message, raw_error, *args): + Exception.__init__(self, message, *args) + self.kind, self.details = raw_error.split(':') -class PollTimeout(Exception): + def __repr__(self): + msg = self.message + + if self.kind and self.details: + msg += '\nReason: {}, {}'.format(self.kind, self.details) + + return msg + + def __str__(self): + msg = self.message + + if self.kind and self.details: + msg += '\nReason: {}, {}'.format(self.kind, self.details) + + return msg + + +class PollTimeout(SWFError): pass -class InvalidCredentialsError(Exception): +class InvalidCredentialsError(SWFError): pass -class ResponseError(Exception): +class ResponseError(SWFError): pass -class DoesNotExistError(Exception): +class DoesNotExistError(SWFError): pass -class AlreadyExistsError(Exception): +class AlreadyExistsError(SWFError): pass -class InvalidKeywordArgumentError(Exception): +class InvalidKeywordArgumentError(SWFError): pass
5397cb0d10f680bc4bf4ab30deb77e9fbff4761d
tapes/__init__.py
tapes/__init__.py
from datetime import datetime __version__ = '0.2.dev{}'.format(datetime.now().strftime('%Y%m%d%H%M%S')) try: # we need __version__ for setup.py, sphinx stuff, just to generally be nice, etc., # but at the point of invocation in setup.py the dependencies imported in .registry are not installed # yet, so we do this from .registry import Registry _global_registry = Registry() meter = _global_registry.meter timer = _global_registry.timer gauge = _global_registry.gauge counter = _global_registry.counter histogram = _global_registry.histogram get_stats = _global_registry.get_stats except ImportError: pass
from datetime import datetime __version__ = '0.3.dev{}'.format(datetime.now().strftime('%Y%m%d%H%M%S')) try: # we need __version__ for setup.py, sphinx stuff, just to generally be nice, etc., # but at the point of invocation in setup.py the dependencies imported in .registry are not installed # yet, so we do this from .registry import Registry _global_registry = Registry() meter = _global_registry.meter timer = _global_registry.timer gauge = _global_registry.gauge counter = _global_registry.counter histogram = _global_registry.histogram get_stats = _global_registry.get_stats except ImportError: pass
Bump version for future dev
Bump version for future dev
Python
apache-2.0
emilssolmanis/tapes,emilssolmanis/tapes,emilssolmanis/tapes
--- +++ @@ -1,5 +1,5 @@ from datetime import datetime -__version__ = '0.2.dev{}'.format(datetime.now().strftime('%Y%m%d%H%M%S')) +__version__ = '0.3.dev{}'.format(datetime.now().strftime('%Y%m%d%H%M%S')) try: # we need __version__ for setup.py, sphinx stuff, just to generally be nice, etc.,
5f6fb9dc79982331a36debdeb33212357def2b11
bayohwoolph.py
bayohwoolph.py
#!/usr/bin/python3 import asyncio import configparser import discord import os import logging from discord.ext import commands logging.basicConfig(level=logging.INFO) # Parse the config and stick in global "config" var config = configparser.ConfigParser() for inifile in [os.path.expanduser('~')+'/.bayohwoolph.ini','bayohwoolph.local.ini','bayohwoolph.ini']: if os.path.isfile(inifile): config.read(inifile) break # First config file wins MAIN = config['MAIN'] description = '''Dark Echo's barkeep''' bot = commands.Bot(command_prefix='$', description=description) @bot.event @asyncio.coroutine def on_ready(): print('Logged in as') print(bot.user.name) print(bot.user.id) print('------') bot.run(MAIN.get('login_token'))
#!/usr/bin/python3 import asyncio import configparser import discord import os import logging from discord.ext import commands logging.basicConfig(level=logging.INFO) # Parse the config and stick in global "config" var config = configparser.ConfigParser() for inifile in [os.path.expanduser('~')+'/.bayohwoolph.ini','bayohwoolph.local.ini','bayohwoolph.ini']: if os.path.isfile(inifile): config.read(inifile) break # First config file wins MAIN = config['MAIN'] description = '''Dark Echo's barkeep''' bot = commands.Bot(command_prefix=commands.when_mentioned_or('$'), description=description) @bot.event @asyncio.coroutine def on_ready(): print('Logged in as') print(bot.user.name) print(bot.user.id) print('------') bot.run(MAIN.get('login_token'))
Make bot respond to mentions.
Make bot respond to mentions.
Python
agpl-3.0
dark-echo/Bay-Oh-Woolph,freiheit/Bay-Oh-Woolph
--- +++ @@ -17,7 +17,7 @@ MAIN = config['MAIN'] description = '''Dark Echo's barkeep''' -bot = commands.Bot(command_prefix='$', description=description) +bot = commands.Bot(command_prefix=commands.when_mentioned_or('$'), description=description) @bot.event @asyncio.coroutine
bfc16a9010a664d18d01f0fc4684353adbab7a47
{{cookiecutter.project_name}}/{{cookiecutter.module_name}}.py
{{cookiecutter.project_name}}/{{cookiecutter.module_name}}.py
#!/usr/bin/env python """{{ cookiecutter.description }}""" # Copyright (C) {{cookiecutter.year}} {{cookiecutter.author_name}}. See LICENSE for terms of use. import sys import logging import click from click import echo __version__ = '{{ cookiecutter.version }}' @click.command() @click.help_option('--help', '-h') @click.version_option(version=__version__) @click.option('--debug', is_flag=True, help='enable debug logging') def main(debug): """{{ cookiecutter.description }}""" logging.basicConfig(level=logging.WARNING) logger = logging.getLogger(__name__) if debug: logger.setLevel(logging.DEBUG) logger.debug("Enabled debug output") if __name__ == "__main__": sys.exit(main())
#!/usr/bin/env python """{{ cookiecutter.description }}""" # Copyright (C) {{cookiecutter.year}} {{cookiecutter.author_name}}. See LICENSE for terms of use. import sys import logging import click from click import echo __version__ = '{{ cookiecutter.version }}' @click.command() @click.help_option('--help', '-h') @click.version_option(version=__version__) @click.option('--debug', is_flag=True, help='enable debug logging') def main(debug): """{{ cookiecutter.description }}""" logging.basicConfig(level=logging.WARNING) logger = logging.getLogger(__name__) if debug: logger.setLevel(logging.DEBUG) logger.debug("Enabled debug output")
Remove ability to run module directly
Remove ability to run module directly
Python
mit
goerz/cookiecutter-pyscript
--- +++ @@ -23,6 +23,3 @@ logger.setLevel(logging.DEBUG) logger.debug("Enabled debug output") - -if __name__ == "__main__": - sys.exit(main())
faf8f70128d70696707f073181f9ce8d08629fd2
teknologr/members/lookups.py
teknologr/members/lookups.py
from ajax_select import register, LookupChannel from members.models import * from django.utils.html import escape @register('member') class MemberLookup(LookupChannel): model = Member def get_query(self, q, request): from django.db.models import Q args = [] for word in q.split(): args.append(Q(given_names__icontains=word) | Q(surname__icontains=word)) if not args: return [] # No words in query (only spaces?) return Member.objects.filter(*args).order_by('surname', 'given_names')[:10] def get_result(self, obj): """ result is the simple text that is the completion of what the person typed """ return obj._get_full_name() def format_match(self, obj): """ (HTML) formatted item for display in the dropdown """ return obj._get_full_name() def format_item_display(self, obj): """ (HTML) formatted item for displaying item in the selected deck area """ return obj._get_full_name() def check_auth(self, request): # TODO: Actual authentication? # The whole request can be denied earlier, this just limits the AJAX lookup channel? Not sure tough return True
from ajax_select import register, LookupChannel from members.models import * from django.utils.html import escape @register('member') class MemberLookup(LookupChannel): model = Member def get_query(self, q, request): from django.db.models import Q args = [] for word in q.split(): args.append(Q(given_names__icontains=word) | Q(surname__icontains=word)) if not args: return [] # No words in query (only spaces?) return Member.objects.filter(*args).order_by('surname', 'given_names')[:10] def get_result(self, obj): """ result is the simple text that is the completion of what the person typed """ return obj._get_full_name() def format_match(self, obj): """ (HTML) formatted item for display in the dropdown """ return obj._get_full_name() def format_item_display(self, obj): """ (HTML) formatted item for displaying item in the selected deck area """ return obj._get_full_name() def check_auth(self, request): # TODO: Actual authentication? # The whole request can be denied earlier, this just limits the AJAX lookup channel? Not sure tough return True
Remove too many newlines (pep8 E303)
Remove too many newlines (pep8 E303)
Python
mit
Teknologforeningen/teknologr.io,Teknologforeningen/teknologr.io,Teknologforeningen/teknologr.io,Teknologforeningen/teknologr.io
--- +++ @@ -19,7 +19,6 @@ if not args: return [] # No words in query (only spaces?) - return Member.objects.filter(*args).order_by('surname', 'given_names')[:10] def get_result(self, obj):
01ca6c2c71b8558e119ae4448e02c2c84a5ef6f9
mailviews/tests/urls.py
mailviews/tests/urls.py
from mailviews.utils import is_django_version_greater from django.conf.urls import include, url from mailviews.previews import autodiscover, site autodiscover() urlpatterns = [ url(regex=r'', view=site.urls) ]
from django.conf.urls import include, url from mailviews.previews import autodiscover, site autodiscover() urlpatterns = [ url(regex=r'', view=site.urls) ]
Remove unused import on test url's
Remove unused import on test url's
Python
apache-2.0
disqus/django-mailviews,disqus/django-mailviews
--- +++ @@ -1,5 +1,3 @@ -from mailviews.utils import is_django_version_greater - from django.conf.urls import include, url
6d48f5fb6be6045d89948729c6e28ed1f1a305ab
pywal/reload.py
pywal/reload.py
""" Reload programs. """ import shutil import subprocess from pywal.settings import CACHE_DIR from pywal import util def reload_i3(): """Reload i3 colors.""" if shutil.which("i3-msg"): util.disown("i3-msg", "reload") def reload_xrdb(): """Merge the colors into the X db so new terminals use them.""" if shutil.which("xrdb"): subprocess.call(["xrdb", "-merge", CACHE_DIR / "colors.Xresources"]) def reload_env(): """Reload environment programs.""" reload_i3() reload_xrdb() print("reload: Reloaded environment.")
""" Reload programs. """ import shutil import subprocess from pywal.settings import CACHE_DIR from pywal import util def reload_xrdb(): """Merge the colors into the X db so new terminals use them.""" if shutil.which("xrdb"): subprocess.call(["xrdb", "-merge", CACHE_DIR / "colors.Xresources"]) def reload_i3(): """Reload i3 colors.""" if shutil.which("i3-msg"): util.disown("i3-msg", "reload") def reload_env(): """Reload environment programs.""" reload_xrdb() reload_i3() print("reload: Reloaded environment.")
Fix bug with i3 titlebars not being the right color.
colors: Fix bug with i3 titlebars not being the right color.
Python
mit
dylanaraps/pywal,dylanaraps/pywal,dylanaraps/pywal
--- +++ @@ -8,20 +8,20 @@ from pywal import util +def reload_xrdb(): + """Merge the colors into the X db so new terminals use them.""" + if shutil.which("xrdb"): + subprocess.call(["xrdb", "-merge", CACHE_DIR / "colors.Xresources"]) + + def reload_i3(): """Reload i3 colors.""" if shutil.which("i3-msg"): util.disown("i3-msg", "reload") -def reload_xrdb(): - """Merge the colors into the X db so new terminals use them.""" - if shutil.which("xrdb"): - subprocess.call(["xrdb", "-merge", CACHE_DIR / "colors.Xresources"]) - - def reload_env(): """Reload environment programs.""" + reload_xrdb() reload_i3() - reload_xrdb() print("reload: Reloaded environment.")