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
d1cc22a5ab94b6df503679cc8b6a19948f4049c9
maildump/web_realtime.py
maildump/web_realtime.py
from flask import current_app from gevent.queue import Queue clients = set() def broadcast(event, data=None): for q in clients: q.put((event, data)) def handle_sse_request(): return current_app.response_class(_gen(), mimetype='text/event-stream') def _gen(): yield _sse('connected') q = Queue() clients.add(q) while True: msg = q.get() try: yield _sse(*msg) except GeneratorExit: clients.remove(q) raise def _sse(event, data=None): parts = [f'event: {event}', f'data: {data or ""}'] return ('\r\n'.join(parts) + '\r\n\r\n').encode()
from flask import current_app from gevent.queue import Empty, Queue clients = set() def broadcast(event, data=None): for q in clients: q.put((event, data)) def handle_sse_request(): return current_app.response_class(_gen(), mimetype='text/event-stream') def _gen(): yield _sse('connected') q = Queue() clients.add(q) while True: try: msg = q.get(timeout=60) except Empty: yield _sse('ping') continue try: yield _sse(*msg) except GeneratorExit: clients.remove(q) raise def _sse(event, data=None): parts = [f'event: {event}', f'data: {data or ""}'] return ('\r\n'.join(parts) + '\r\n\r\n').encode()
Send regular ping on SSE channel
Send regular ping on SSE channel Otherwise dead clients stay around for a very long time (they are only detected and removed when sending data fails, and that used to depend on new emails arriving).
Python
mit
ThiefMaster/maildump,ThiefMaster/maildump,ThiefMaster/maildump,ThiefMaster/maildump
--- +++ @@ -1,5 +1,5 @@ from flask import current_app -from gevent.queue import Queue +from gevent.queue import Empty, Queue clients = set() @@ -18,7 +18,11 @@ q = Queue() clients.add(q) while True: - msg = q.get() + try: + msg = q.get(timeout=60) + except Empty: + yield _sse('ping') + continue try: yield _sse(*msg) except GeneratorExit:
332a9086e1481697389774648cfcfefa332ff3e2
adb-enhanced/setup.py
adb-enhanced/setup.py
from setuptools import setup, find_packages import sys, os with open('version.txt', 'r') as fh: version = fh.read().strip() with open('README.md', 'r') as fh: long_description = fh.read() setup(name='adb-enhanced', version=version, description='Swiss-army knife for Android testing and development', long_description=long_description, long_description_content_type='text/markdown', classifiers=['Intended Audience :: Developers'], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='Android ADB developer', author='Ashish Bhatia', author_email='ashishb@ashishb.net', url='https://github.com/ashishb/adb-enhanced', license='Apache', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=True, install_requires=[ # -*- Extra requirements: -*- 'docopt', 'future', ], entry_points={ # -*- Entry points: -*- 'console_scripts': [ 'adbe=adbe:main', ], } )
from setuptools import setup, find_packages import sys, os _DIR_OF_THIS_SCRIPT = os.path.split(__file__)[0] _VERSION_FILE_NAME = 'version.txt' _VERSION_FILE_PATH = os.path.join(_DIR_OF_THIS_SCRIPT, _VERSION_FILE_NAME) with open(_VERSION_FILE_PATH, 'r') as fh: version = fh.read().strip() with open('README.md', 'r') as fh: long_description = fh.read() setup(name='adb-enhanced', version=version, description='Swiss-army knife for Android testing and development', long_description=long_description, long_description_content_type='text/markdown', classifiers=['Intended Audience :: Developers'], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='Android ADB developer', author='Ashish Bhatia', author_email='ashishb@ashishb.net', url='https://github.com/ashishb/adb-enhanced', license='Apache', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=True, install_requires=[ # -*- Extra requirements: -*- 'docopt', 'future', ], entry_points={ # -*- Entry points: -*- 'console_scripts': [ 'adbe=adbe:main', ], } )
Make path to version file relative
Make path to version file relative
Python
apache-2.0
ashishb/adb-enhanced
--- +++ @@ -1,7 +1,11 @@ from setuptools import setup, find_packages import sys, os -with open('version.txt', 'r') as fh: +_DIR_OF_THIS_SCRIPT = os.path.split(__file__)[0] +_VERSION_FILE_NAME = 'version.txt' +_VERSION_FILE_PATH = os.path.join(_DIR_OF_THIS_SCRIPT, _VERSION_FILE_NAME) + +with open(_VERSION_FILE_PATH, 'r') as fh: version = fh.read().strip() with open('README.md', 'r') as fh:
be67ff47938be435f1eb713ed1c9b08f3f98bc5b
number_to_words.py
number_to_words.py
class NumberToWords(object): """ Class for converting positive integer values to a textual representation of the submitted number for value of 0 up to 999999999. """ MAX = 999999999 SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] TENS = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] LARGE_NUMBERS = ['', 'thousand', 'million'] EXCEPTION_STRING = "This method expects positive integer values between " \ + "0 and {0}".format(MAX) def convert(self, number): """ Take an integer and return it converted to a textual representation. Args: number (int): The number to be converted. Returns: sentence (string): The textual representation of `number`. Raises: ValueError: If `number` is not a positive integer or is greater than `MAX`. """ if not isinstance(number, (int, long)): raise ValueError(self.EXCEPTION_STRING)
class NumberToWords(object): """ Class for converting positive integer values to a textual representation of the submitted number for value of 0 up to 999999999. """ MAX = 999999999 SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] TENS = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] LARGE_NUMBERS = ['', 'thousand', 'million'] EXCEPTION_STRING = "This method expects positive integer values between " \ + "0 and {0}".format(MAX) def convert(self, number): """ Take an integer and return it converted to a textual representation. Args: number (int): The number to be converted. Returns: sentence (string): The textual representation of `number`. Raises: ValueError: If `number` is not a positive integer or is greater than `MAX`. """ if not isinstance(number, (int, long)): raise ValueError(self.EXCEPTION_STRING) sentence = "" if number is 0: sentence = "zero" return sentence
Add condition to handle the case when `number` is 0
Add condition to handle the case when `number` is 0
Python
mit
ianfieldhouse/number_to_words
--- +++ @@ -32,3 +32,7 @@ if not isinstance(number, (int, long)): raise ValueError(self.EXCEPTION_STRING) + sentence = "" + if number is 0: + sentence = "zero" + return sentence
ab3d830ca682805180710bf1aeb79519c826a7f0
frontend.py
frontend.py
from flask import Flask from flask import render_template import requests import json app = Flask(__name__) @app.route('/') def index(): r = requests.get("http://127.0.0.1:5000/playlist") playlist = json.loads(r.text) return render_template('index.html', playlist=playlist) @app.route('/settings') def settings(): return render_template('settings.html') @app.route('/player') def player(): return render_template('player.html') if __name__ == '__main__': app.run(port=5001)
from flask import Flask from flask import render_template import requests import json app = Flask(__name__) @app.route('/') def index(): r = requests.get("http://127.0.0.1:5000/playlist") playlist = json.loads(r.text) return render_template('index.html', playlist=playlist) @app.route('/settings') def settings(): return render_template('settings.html') @app.route('/player') def player(): return render_template('player.html') @app.route('/search/<name>') def search(name): params = { "render": "json", "locale": "fr-FR", "call": name, "query": name, "c": "stations" } r = requests.get("https://opml.radiotime.com/Search.ashx", params=params) return r.text
Add tunein search and use flask new run
Add tunein search and use flask new run
Python
mit
MCG-Radio/frontend,MCG-Radio/frontend,MCG-Radio/frontend
--- +++ @@ -23,5 +23,14 @@ return render_template('player.html') -if __name__ == '__main__': - app.run(port=5001) +@app.route('/search/<name>') +def search(name): + params = { + "render": "json", + "locale": "fr-FR", + "call": name, + "query": name, + "c": "stations" + } + r = requests.get("https://opml.radiotime.com/Search.ashx", params=params) + return r.text
d791577e797bdcdabe68ef4999e39d2b2d99a291
sugar/activity/__init__.py
sugar/activity/__init__.py
import gtk from sugar.graphics.grid import Grid settings = gtk.settings_get_default() grid = Grid() sizes = 'gtk-large-toolbar=%d, %d' % (grid.dimension(1), grid.dimension(1)) settings.set_string_property('gtk-icon-sizes', sizes, '') def get_default_type(activity_type): """Get the activity default type. It's the type of the main network service which tracks presence and provides info about the activity, for example the title.""" splitted_id = activity_type.split('.') splitted_id.reverse() return '_' + '_'.join(splitted_id) + '._udp'
import gtk from sugar.graphics.grid import Grid settings = gtk.settings_get_default() grid = Grid() sizes = 'gtk-large-toolbar=%d, %d' % (grid.dimension(1), grid.dimension(1)) settings.set_string_property('gtk-icon-sizes', sizes, '') settings.set_string_property('gtk-font-name', 'Sans 14', '') def get_default_type(activity_type): """Get the activity default type. It's the type of the main network service which tracks presence and provides info about the activity, for example the title.""" splitted_id = activity_type.split('.') splitted_id.reverse() return '_' + '_'.join(splitted_id) + '._udp'
Set default font size to 14
Set default font size to 14
Python
lgpl-2.1
i5o/sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,manuq/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit,tchx84/debian-pkg-sugar-toolkit,quozl/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit,Daksh/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit,godiard/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit,manuq/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit,gusDuarte/sugar-toolkit-gtk3,Daksh/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit,tchx84/debian-pkg-sugar-toolkit-gtk3,godiard/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit,gusDuarte/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit-gtk3,puneetgkaur/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit-gtk3,godiard/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit,sugarlabs/sugar-toolkit,samdroid-apps/sugar-toolkit-gtk3,samdroid-apps/sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,puneetgkaur/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit-gtk3,manuq/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,puneetgkaur/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit,ceibal-tatu/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit-gtk3,samdroid-apps/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,samdroid-apps/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit,sugarlabs/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit,Daksh/sugar-toolkit-gtk3
--- +++ @@ -8,6 +8,8 @@ sizes = 'gtk-large-toolbar=%d, %d' % (grid.dimension(1), grid.dimension(1)) settings.set_string_property('gtk-icon-sizes', sizes, '') +settings.set_string_property('gtk-font-name', 'Sans 14', '') + def get_default_type(activity_type): """Get the activity default type.
f735e813d1babba1c488f8ea761ffd1295103451
systemofrecord/__init__.py
systemofrecord/__init__.py
import os import logging from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from raven.contrib.flask import Sentry app = Flask(__name__) app.config.from_object(os.environ.get('SETTINGS')) db = SQLAlchemy(app) def configure_logging(obj): logger = logging.getLogger(obj.__class__.__name__) logger.addHandler(logging.StreamHandler()) if app.config['DEBUG']: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) return logger # Sentry exception reporting if 'SENTRY_DSN' in os.environ: sentry = Sentry(app, dsn=os.environ['SENTRY_DSN']) if not app.debug: app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.INFO) app.logger.debug("\nConfiguration\n%s\n" % app.config) def configure_health(): from systemofrecord.health import Health from systemofrecord.repository import blockchain_object_repository from systemofrecord.services import ingest_queue, chain_queue Health(app, checks=[blockchain_object_repository.health, ingest_queue.health, chain_queue.health ]) configure_health()
import os import logging from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from raven.contrib.flask import Sentry app = Flask(__name__) app.config.from_object(os.environ.get('SETTINGS')) from werkzeug.contrib.fixers import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app) db = SQLAlchemy(app) def configure_logging(obj): logger = logging.getLogger(obj.__class__.__name__) logger.addHandler(logging.StreamHandler()) if app.config['DEBUG']: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) return logger # Sentry exception reporting if 'SENTRY_DSN' in os.environ: sentry = Sentry(app, dsn=os.environ['SENTRY_DSN']) if not app.debug: app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.INFO) app.logger.debug("\nConfiguration\n%s\n" % app.config) def configure_health(): from systemofrecord.health import Health from systemofrecord.repository import blockchain_object_repository from systemofrecord.services import ingest_queue, chain_queue Health(app, checks=[blockchain_object_repository.health, ingest_queue.health, chain_queue.health ]) configure_health()
Add proxy fix as in lr this will run with reverse proxy
Add proxy fix as in lr this will run with reverse proxy
Python
mit
LandRegistry/system-of-record-alpha,LandRegistry/system-of-record-alpha,LandRegistry/system-of-record-alpha
--- +++ @@ -6,8 +6,11 @@ app = Flask(__name__) app.config.from_object(os.environ.get('SETTINGS')) + +from werkzeug.contrib.fixers import ProxyFix +app.wsgi_app = ProxyFix(app.wsgi_app) + db = SQLAlchemy(app) - def configure_logging(obj): logger = logging.getLogger(obj.__class__.__name__)
937db1a685da31a9b00d7652835f2fafc7493fc7
applebot/botmodule.py
applebot/botmodule.py
import logging import discord from applebot.utils import caller_attr log = logging.getLogger(__name__) class BotModule(object): def __init__(self, client=None): self.__name__ = None self.client = client or caller_attr('client', levels=3) or discord.Client() self.__register_handlers() def __register_handlers(self): for method in [getattr(self, m) for m in dir(self) if '__' not in m]: if callable(method): commands = method.__dict__.get('command_names') event = method.__dict__.get('event_name') if commands: for command in commands: log.debug('Adding command \'{}\' in {}'.format(commands, self.__class__.__name__)) self.client.commands.add(str(command), method) if event: log.debug('Registering event \'{}\' from {}'.format(event, self.__class__.__name__)) self.client.events.add(event, method) @staticmethod def event(event): def inner_decorator(method): method.event_name = str(event) return method return inner_decorator @staticmethod def command(*commands): def inner_decorator(method): method.command_names = commands return method return inner_decorator
import logging import discord from applebot.utils import caller_attr log = logging.getLogger(__name__) class BotModule(object): def __init__(self, client=None): self.__name__ = None self.client = client or caller_attr('client', levels=3) or discord.Client() self.__register_handlers() def __register_handlers(self): for method in [getattr(self, m) for m in dir(self) if '__' not in m]: if callable(method): commands = method.__dict__.get('command_names', ()) for command in commands: log.debug('Adding command \'{}\' in {}'.format(commands, self.__class__.__name__)) self.client.commands.add(str(command), method) events = method.__dict__.get('event_names', ()) for event in events: log.debug('Registering event \'{}\' from {}'.format(event, self.__class__.__name__)) self.client.events.add(event, method) @staticmethod def event(*events): def inner_decorator(method): method.event_names = events return method return inner_decorator @staticmethod def command(*commands): def inner_decorator(method): method.command_names = commands return method return inner_decorator
Allow for multiple events with the @BotModule.event decorator.
Allow for multiple events with the @BotModule.event decorator.
Python
mit
appul/applebot
--- +++ @@ -16,20 +16,20 @@ def __register_handlers(self): for method in [getattr(self, m) for m in dir(self) if '__' not in m]: if callable(method): - commands = method.__dict__.get('command_names') - event = method.__dict__.get('event_name') - if commands: - for command in commands: - log.debug('Adding command \'{}\' in {}'.format(commands, self.__class__.__name__)) - self.client.commands.add(str(command), method) - if event: + commands = method.__dict__.get('command_names', ()) + for command in commands: + log.debug('Adding command \'{}\' in {}'.format(commands, self.__class__.__name__)) + self.client.commands.add(str(command), method) + + events = method.__dict__.get('event_names', ()) + for event in events: log.debug('Registering event \'{}\' from {}'.format(event, self.__class__.__name__)) self.client.events.add(event, method) @staticmethod - def event(event): + def event(*events): def inner_decorator(method): - method.event_name = str(event) + method.event_names = events return method return inner_decorator
d7454240f4f888309a63bba07526a821962c9670
masters/master.chromium.webrtc.fyi/master_source_cfg.py
masters/master.chromium.webrtc.fyi/master_source_cfg.py
# Copyright (c) 2012 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 master import gitiles_poller def Update(config, c): webrtc_repo_url = config.Master.git_server_url + '/external/webrtc/' webrtc_poller = gitiles_poller.GitilesPoller(webrtc_repo_url, project='webrtc') c['change_source'].append(webrtc_poller) samples_poller = gitiles_poller.GitilesPoller( config.Master.git_server_url + '/external/webrtc-samples', project='webrtc-samples', comparator=webrtc_poller.comparator) c['change_source'].append(samples_poller)
# Copyright (c) 2012 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 master import gitiles_poller def Update(config, c): webrtc_repo_url = config.Master.git_server_url + '/external/webrtc/' webrtc_poller = gitiles_poller.GitilesPoller(webrtc_repo_url, project='webrtc') c['change_source'].append(webrtc_poller)
Remove poller for webrtc-samples repo.
WebRTC: Remove poller for webrtc-samples repo. Having multiple GittilesPollers produces blamelists with hashes from different repos, but more importantly perf dashboard links that are not valid, since the from-hash can be from the Chromium repo and the to-hash from the webrtc-samples repo. Since breakages by changes in the webrtc-samples are rare, we should just remove the poller of that repo for simplicity. What has changed reasonably recently is that we download a prebuilt AppRTC which is pinned to specific revision and rolled manually, so if there are changes in AppRTC that are breaking Chromium, we still wouldn't detect them anymore. This solves one of the problems in crbug.com/491520 but more work is needed. TBR=phoglund@webrtc.org BUG=491520 Review URL: https://codereview.chromium.org/1754243003 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@299053 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
--- +++ @@ -10,9 +10,3 @@ webrtc_poller = gitiles_poller.GitilesPoller(webrtc_repo_url, project='webrtc') c['change_source'].append(webrtc_poller) - - samples_poller = gitiles_poller.GitilesPoller( - config.Master.git_server_url + '/external/webrtc-samples', - project='webrtc-samples', - comparator=webrtc_poller.comparator) - c['change_source'].append(samples_poller)
f46e91ae286dbc1dd86180d2920017d3222a48e2
btdjango/__init__.py
btdjango/__init__.py
#!/usr/bin/env python """ Braintree Django Python Module """ import braintree from django.conf import settings VERSION = "1.0" if not hasattr(braintree.Configuration, "merchant_id"): braintree.Configuration.configure( getattr(settings, "BRAINTREE_ENV", braintree.Environment.Sandbox), getattr(settings, "BRAINTREE_MERCHANT", ""), getattr(settings, "BRAINTREE_PUBLIC_KEY", ""), getattr(settings, "BRAINTREE_PRIVATE_KEY", ""), ) if getattr(settings, "BRAINTREE_UNSAFE", False): braintree.Configuration.use_unsafe_ssl = True
#!/usr/bin/env python """ Braintree Django Python Module """ import braintree from django.conf import settings VERSION = "1.1" if not hasattr(braintree.Configuration, "merchant_id"): braintree.Configuration.configure( getattr(settings, "BRAINTREE_ENV", braintree.Environment.Sandbox), getattr(settings, "BRAINTREE_MERCHANT", ""), getattr(settings, "BRAINTREE_PUBLIC_KEY", ""), getattr(settings, "BRAINTREE_PRIVATE_KEY", ""), ) if getattr(settings, "BRAINTREE_UNSAFE_SSL", False): braintree.Configuration.use_unsafe_ssl = True
Fix small typo to make unsafe SSL really work, minor version bump
Fix small typo to make unsafe SSL really work, minor version bump
Python
mit
danielgtaylor/braintree_django
--- +++ @@ -8,7 +8,7 @@ from django.conf import settings -VERSION = "1.0" +VERSION = "1.1" if not hasattr(braintree.Configuration, "merchant_id"): braintree.Configuration.configure( @@ -18,6 +18,6 @@ getattr(settings, "BRAINTREE_PRIVATE_KEY", ""), ) - if getattr(settings, "BRAINTREE_UNSAFE", False): + if getattr(settings, "BRAINTREE_UNSAFE_SSL", False): braintree.Configuration.use_unsafe_ssl = True
57d4e10636b9593ef650f0f62410f0b0d7effdf2
test/test_e2e.py
test/test_e2e.py
import h2o import socket import threading import unittest import urllib.request SIMPLE_PATH = b'/simple' SIMPLE_BODY = b'<h1>It works!</h1>' class E2eTest(unittest.TestCase): def setUp(self): config = h2o.Config() host = config.add_host(b'default', 65535) host.add_path(SIMPLE_PATH).add_handler(lambda: SIMPLE_BODY) self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) self.sock.bind(('127.0.0.1', 0)) self.sock.listen() self.url_prefix = b'http://127.0.0.1:%d' % self.sock.getsockname()[1] self.loop = h2o.Loop() self.loop.start_accept(self.sock.fileno(), config) threading.Thread(target=self.run_loop, daemon=True).start() def run_loop(self): while self.loop.run() == 0: pass def get(self, path): return urllib.request.urlopen((self.url_prefix + path).decode()).read() def test_simple(self): self.assertEqual(self.get(SIMPLE_PATH), SIMPLE_BODY) if __name__ == '__main__': unittest.main()
import h2o import socket import threading import unittest import urllib.request SIMPLE_PATH = b'/simple' SIMPLE_BODY = b'<h1>It works!</h1>' class E2eTest(unittest.TestCase): def setUp(self): config = h2o.Config() host = config.add_host(b'default', 65535) host.add_path(SIMPLE_PATH).add_handler(lambda: SIMPLE_BODY) self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) self.sock.bind(('127.0.0.1', 0)) self.sock.listen(0) self.url_prefix = ( 'http://127.0.0.1:{}'.format(self.sock.getsockname()[1]).encode()) self.loop = h2o.Loop() self.loop.start_accept(self.sock.fileno(), config) threading.Thread(target=self.run_loop, daemon=True).start() def run_loop(self): while self.loop.run() == 0: pass def get(self, path): return urllib.request.urlopen((self.url_prefix + path).decode()).read() def test_simple(self): self.assertEqual(self.get(SIMPLE_PATH), SIMPLE_BODY) if __name__ == '__main__': unittest.main()
Fix test under python 3.4
Fix test under python 3.4
Python
mit
iceb0y/pyh2o,iceb0y/pyh2o
--- +++ @@ -17,13 +17,14 @@ self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) self.sock.bind(('127.0.0.1', 0)) - self.sock.listen() - self.url_prefix = b'http://127.0.0.1:%d' % self.sock.getsockname()[1] + self.sock.listen(0) + self.url_prefix = ( + 'http://127.0.0.1:{}'.format(self.sock.getsockname()[1]).encode()) self.loop = h2o.Loop() self.loop.start_accept(self.sock.fileno(), config) threading.Thread(target=self.run_loop, daemon=True).start() - + def run_loop(self): while self.loop.run() == 0: pass
89b164781ba433c9209f306889463e189006778c
board.py
board.py
""" Board represents a four in a row game board. Author: Isaac Arvestad """ class Board: """ Initializes the game with a certain number of rows and columns. """ def __init(self, rows, columns): self.rows = rows self.columns = columns
import numpy """ Board represents a four in a row game board. Author: Isaac Arvestad """ class Board: """ Initializes the game with a certain number of rows and columns. """ def __init(self, rows, columns): self.rows = rows self.columns = columns self.boardMatrix = numpy.zeros((rows, columns)) """ Attempts to add a piece to a certain column. If the column is full the move is illegal and false is returned, otherwise true is returned. """ def addPiece(self, column, value): "Check if column is full." if self.boardMatrix.item(0,column) != 0: return false "Place piece." for y in range(self.rows): currentValue = self.boardMatrix.item(y, column) if currentValue == 0: if y == rows - 1: self.boardMatrix.itemset((y, column), value) else: continue return true
Add matrix and addPiece function.
Add matrix and addPiece function.
Python
mit
isaacarvestad/four-in-a-row
--- +++ @@ -1,3 +1,5 @@ +import numpy + """ Board represents a four in a row game board. @@ -11,3 +13,26 @@ def __init(self, rows, columns): self.rows = rows self.columns = columns + self.boardMatrix = numpy.zeros((rows, columns)) + + """ + Attempts to add a piece to a certain column. If the column is + full the move is illegal and false is returned, otherwise true + is returned. + """ + def addPiece(self, column, value): + "Check if column is full." + if self.boardMatrix.item(0,column) != 0: + return false + + "Place piece." + for y in range(self.rows): + currentValue = self.boardMatrix.item(y, column) + + if currentValue == 0: + if y == rows - 1: + self.boardMatrix.itemset((y, column), value) + else: + continue + return true +
e53da7173bfa63ea4acbe5a1884d41ed295e978f
TUI/Scripts/TSpec/Focus.py
TUI/Scripts/TSpec/Focus.py
"""Take a series of exposures at different focus positions to estimate best focus. """ import TUI.Base.BaseFocusScript # make script reload also reload BaseFocusScript reload(TUI.Base.BaseFocusScript) SlitviewerFocusScript = TUI.Base.BaseFocusScript.SlitviewerFocusScript Debug = False # run in debug-only mode (which doesn't DO anything, it just pretends)? HelpURL = "Scripts/BuiltInScripts/InstFocus.html" class ScriptClass(SlitviewerFocusScript): def __init__(self, sr): """The setup script; run once when the script runner window is created. """ SlitviewerFocusScript.__init__(self, sr = sr, gcamActor = "tcam", instName = "TSpec", imageViewerTLName = "Guide.TSpec Slitviewer", defBoreXY = [None, -5.0], doWindow = False, helpURL = HelpURL, debug = Debug, )
"""Take a series of exposures at different focus positions to estimate best focus. History: 2008-03-25 ROwen First version 2008-04-03 ROwen Changed doWindow to True because the TripleSpec slitviewer can now window """ import TUI.Base.BaseFocusScript # make script reload also reload BaseFocusScript reload(TUI.Base.BaseFocusScript) SlitviewerFocusScript = TUI.Base.BaseFocusScript.SlitviewerFocusScript Debug = False # run in debug-only mode (which doesn't DO anything, it just pretends)? HelpURL = "Scripts/BuiltInScripts/InstFocus.html" class ScriptClass(SlitviewerFocusScript): def __init__(self, sr): """The setup script; run once when the script runner window is created. """ SlitviewerFocusScript.__init__(self, sr = sr, gcamActor = "tcam", instName = "TSpec", imageViewerTLName = "Guide.TSpec Slitviewer", defBoreXY = [None, -5.0], doWindow = True, helpURL = HelpURL, debug = Debug, )
Change TSpec focus script to use windowing (now that it is supported).
Change TSpec focus script to use windowing (now that it is supported). git-svn-id: a38512e6531051f4ba6aaa1c8358347ddeca2e1b@117751 b00c9580-4927-0410-8824-811d448ea4c7
Python
bsd-3-clause
r-owen/stui,r-owen/stui
--- +++ @@ -1,4 +1,8 @@ """Take a series of exposures at different focus positions to estimate best focus. + +History: +2008-03-25 ROwen First version +2008-04-03 ROwen Changed doWindow to True because the TripleSpec slitviewer can now window """ import TUI.Base.BaseFocusScript # make script reload also reload BaseFocusScript @@ -19,7 +23,7 @@ instName = "TSpec", imageViewerTLName = "Guide.TSpec Slitviewer", defBoreXY = [None, -5.0], - doWindow = False, + doWindow = True, helpURL = HelpURL, debug = Debug, )
56da6b0b39fc3b4b9fa5c19ed0738ff526bf5072
src/sugar/__init__.py
src/sugar/__init__.py
# Copyright (C) 2006-2007, Red Hat, Inc. # Copyright (C) 2007, One Laptop Per Child # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA.
# Copyright (C) 2006-2007, Red Hat, Inc. # Copyright (C) 2007-2008, One Laptop Per Child # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. import os import gettext if os.environ.has_key('SUGAR_PREFIX'): prefix = os.environ['SUGAR_PREFIX'] else: prefix = '/usr' locale_path = os.path.join(prefix, 'share', 'locale') gettext.bindtextdomain('sugar', locale_path)
Use the right gettext domain.
Use the right gettext domain.
Python
lgpl-2.1
tchx84/debian-pkg-sugar-base,ceibal-tatu/sugar-base,ceibal-tatu/sugar-base,sugarlabs/sugar-base,ceibal-tatu/sugar-base,tchx84/debian-pkg-sugar-base,sugarlabs/sugar-base,sugarlabs/sugar-base,tchx84/debian-pkg-sugar-base
--- +++ @@ -1,5 +1,5 @@ # Copyright (C) 2006-2007, Red Hat, Inc. -# Copyright (C) 2007, One Laptop Per Child +# Copyright (C) 2007-2008, One Laptop Per Child # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public @@ -16,3 +16,15 @@ # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. +import os +import gettext + +if os.environ.has_key('SUGAR_PREFIX'): + prefix = os.environ['SUGAR_PREFIX'] +else: + prefix = '/usr' + +locale_path = os.path.join(prefix, 'share', 'locale') + +gettext.bindtextdomain('sugar', locale_path) +
e94d40af916fa51e7e8737fd151d8cfc8a94891a
cmsplugin_iframe/models.py
cmsplugin_iframe/models.py
from cms.models import CMSPlugin from django.db import models class IframePlugin(CMSPlugin): src = models.URLField()
from cms.models import CMSPlugin from django.db import models class IframePlugin(CMSPlugin): src = models.URLField(max_length=400)
Increase urlfield size from 200 to 500 to deal with large embed urls for google calendar and other embeds
Increase urlfield size from 200 to 500 to deal with large embed urls for google calendar and other embeds
Python
mit
jonasmcarson/cmsplugin-iframe,jonasmcarson/cmsplugin-iframe
--- +++ @@ -3,4 +3,4 @@ class IframePlugin(CMSPlugin): - src = models.URLField() + src = models.URLField(max_length=400)
116e76557d239edab69bab47c96cb5835618c31f
tilenol/xcb/keysymparse.py
tilenol/xcb/keysymparse.py
import re keysym_re = re.compile(r"^#define\s+(XF86)?XK_(\w+)\s+(\S+)") class Keysyms(object): __slots__ = ('name_to_code', 'code_to_name', '__dict__') def __init__(self): self.name_to_code = {} self.code_to_name = {} def add_from_file(self, filename): with open(filename, 'rt') as f: for line in f: m = keysym_re.match(line) if not m: continue name = (m.group(1) or '') + m.group(2) code = int(m.group(3), 0) self.__dict__[name] = code self.name_to_code[name] = code self.code_to_name[code] = name def load_default(self): self.add_from_file('/usr/include/X11/keysymdef.h') self.add_from_file('/usr/include/X11/XF86keysym.h')
import os import re keysym_re = re.compile(r"^#define\s+(XF86)?XK_(\w+)\s+(\S+)") class Keysyms(object): __slots__ = ('name_to_code', 'code_to_name', '__dict__') def __init__(self): self.name_to_code = {} self.code_to_name = {} def add_from_file(self, filename): with open(filename, 'rt') as f: for line in f: m = keysym_re.match(line) if not m: continue name = (m.group(1) or '') + m.group(2) code = int(m.group(3), 0) self.__dict__[name] = code self.name_to_code[name] = code self.code_to_name[code] = name def load_default(self): xproto_dir = os.environ.get("XPROTO_DIR", "/usr/include/X11") self.add_from_file(xproto_dir + '/keysymdef.h') self.add_from_file(xproto_dir + '/XF86keysym.h')
Allow to override include dir of xproto
Allow to override include dir of xproto
Python
mit
tailhook/tilenol,tailhook/tilenol
--- +++ @@ -1,3 +1,4 @@ +import os import re keysym_re = re.compile(r"^#define\s+(XF86)?XK_(\w+)\s+(\S+)") @@ -23,6 +24,7 @@ self.code_to_name[code] = name def load_default(self): - self.add_from_file('/usr/include/X11/keysymdef.h') - self.add_from_file('/usr/include/X11/XF86keysym.h') + xproto_dir = os.environ.get("XPROTO_DIR", "/usr/include/X11") + self.add_from_file(xproto_dir + '/keysymdef.h') + self.add_from_file(xproto_dir + '/XF86keysym.h')
6f9a2ef636c8ac5272de15ddfeb7c80b3bd00246
test/test_arena.py
test/test_arena.py
from support import lib,ffi from qcgc_test import QCGCTest class ArenaTestCase(QCGCTest): def test_size_calculations(self): exp = lib.QCGC_ARENA_SIZE_EXP size = 2**exp bitmap = size / 128 cells = (size - 2 * bitmap) / 16 self.assertEqual(size, lib.qcgc_arena_size) self.assertEqual(bitmap, lib.qcgc_arena_bitmap_size) self.assertEqual(cells, lib.qcgc_arena_cells_count)
from support import lib,ffi from qcgc_test import QCGCTest class ArenaTestCase(QCGCTest): def test_size_calculations(self): exp = lib.QCGC_ARENA_SIZE_EXP size = 2**exp bitmap = size / 128 cells = size / 16 self.assertEqual(size, lib.qcgc_arena_size) self.assertEqual(bitmap, lib.qcgc_arena_bitmap_size) self.assertEqual(cells, lib.qcgc_arena_cells_count)
Fix wrong cell count calculation
Fix wrong cell count calculation
Python
mit
ntruessel/qcgc,ntruessel/qcgc,ntruessel/qcgc
--- +++ @@ -6,7 +6,7 @@ exp = lib.QCGC_ARENA_SIZE_EXP size = 2**exp bitmap = size / 128 - cells = (size - 2 * bitmap) / 16 + cells = size / 16 self.assertEqual(size, lib.qcgc_arena_size) self.assertEqual(bitmap, lib.qcgc_arena_bitmap_size) self.assertEqual(cells, lib.qcgc_arena_cells_count)
5fd3bed281018a556cfd6305670317bf5acb2a16
tests/test_auth.py
tests/test_auth.py
import random import unittest from .config import * from tweepy import API, OAuthHandler class TweepyAuthTests(unittest.TestCase): def testoauth(self): auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret) # test getting access token auth_url = auth.get_authorization_url() print('Please authorize: ' + auth_url) verifier = input('PIN: ').strip() self.assertTrue(len(verifier) > 0) access_token = auth.get_access_token(verifier) self.assertTrue(access_token is not None) # build api object test using oauth api = API(auth) s = api.update_status(f'test {random.randint(0, 1000)}') api.destroy_status(s.id) def testaccesstype(self): auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret) auth_url = auth.get_authorization_url(access_type='read') print('Please open: ' + auth_url) answer = input('Did Twitter only request read permissions? (y/n) ') self.assertEqual('y', answer.lower())
import random import unittest from .config import * from tweepy import API, OAuthHandler class TweepyAuthTests(unittest.TestCase): def testoauth(self): auth = OAuthHandler(consumer_key, consumer_secret) # test getting access token auth_url = auth.get_authorization_url() print('Please authorize: ' + auth_url) verifier = input('PIN: ').strip() self.assertTrue(len(verifier) > 0) access_token = auth.get_access_token(verifier) self.assertTrue(access_token is not None) # build api object test using oauth api = API(auth) s = api.update_status(f'test {random.randint(0, 1000)}') api.destroy_status(s.id) def testaccesstype(self): auth = OAuthHandler(consumer_key, consumer_secret) auth_url = auth.get_authorization_url(access_type='read') print('Please open: ' + auth_url) answer = input('Did Twitter only request read permissions? (y/n) ') self.assertEqual('y', answer.lower())
Update consumer key and secret usage in auth tests
Update consumer key and secret usage in auth tests
Python
mit
svven/tweepy,tweepy/tweepy
--- +++ @@ -8,7 +8,7 @@ class TweepyAuthTests(unittest.TestCase): def testoauth(self): - auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret) + auth = OAuthHandler(consumer_key, consumer_secret) # test getting access token auth_url = auth.get_authorization_url() @@ -24,7 +24,7 @@ api.destroy_status(s.id) def testaccesstype(self): - auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret) + auth = OAuthHandler(consumer_key, consumer_secret) auth_url = auth.get_authorization_url(access_type='read') print('Please open: ' + auth_url) answer = input('Did Twitter only request read permissions? (y/n) ')
fc08fb4086b3438cbe84042903b855c6fb55c30e
sshuttle/assembler.py
sshuttle/assembler.py
import sys import zlib import imp z = zlib.decompressobj() while 1: name = sys.stdin.readline().strip() if name: name = name.decode("ASCII") nbytes = int(sys.stdin.readline()) if verbosity >= 2: sys.stderr.write('server: assembling %r (%d bytes)\n' % (name, nbytes)) content = z.decompress(sys.stdin.read(nbytes)) module = imp.new_module(name) parents = name.rsplit(".", 1) if len(parents) == 2: parent, parent_name = parents setattr(sys.modules[parent], parent_name, module) code = compile(content, name, "exec") exec(code, module.__dict__) # nosec sys.modules[name] = module else: break sys.stderr.flush() sys.stdout.flush() import sshuttle.helpers sshuttle.helpers.verbose = verbosity import sshuttle.cmdline_options as options from sshuttle.server import main main(options.latency_control, options.auto_hosts, options.to_nameserver)
import sys import zlib import imp z = zlib.decompressobj() while 1: global verbosity name = sys.stdin.readline().strip() if name: name = name.decode("ASCII") nbytes = int(sys.stdin.readline()) if verbosity >= 2: sys.stderr.write('server: assembling %r (%d bytes)\n' % (name, nbytes)) content = z.decompress(sys.stdin.read(nbytes)) module = imp.new_module(name) parents = name.rsplit(".", 1) if len(parents) == 2: parent, parent_name = parents setattr(sys.modules[parent], parent_name, module) code = compile(content, name, "exec") exec(code, module.__dict__) # nosec sys.modules[name] = module else: break sys.stderr.flush() sys.stdout.flush() import sshuttle.helpers sshuttle.helpers.verbose = verbosity import sshuttle.cmdline_options as options from sshuttle.server import main main(options.latency_control, options.auto_hosts, options.to_nameserver)
Declare 'verbosity' as global variable to placate linters
Declare 'verbosity' as global variable to placate linters
Python
lgpl-2.1
sshuttle/sshuttle,sshuttle/sshuttle
--- +++ @@ -4,6 +4,7 @@ z = zlib.decompressobj() while 1: + global verbosity name = sys.stdin.readline().strip() if name: name = name.decode("ASCII")
964da81ef5a90130a47ff726839798a7a7b716ef
buildcert.py
buildcert.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime from subprocess import call from ca import app, db, mail from ca.models import Request from flask import Flask, render_template from flask_mail import Message def mail_certificate(id, email): msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email]) msg.body = render_template('mail.txt') with app.open_resource("/etc/openvpn/clients/freifunk_{}.tgz".format(id)) as fp: msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read()) mail.send(msg) for request in Request.query.filter(Request.generation_date == None).all(): # noqa prompt = "Do you want to generate a certificate for {}, {} ?" print(prompt.format(request.id, request.email)) print("Type y to continue") confirm = input('>') if confirm in ['Y', 'y']: print('generating certificate') call([app.config['COMMAND_BUILD'], request.id, request.email]) #call([app.config['COMMAND_MAIL'], request.id, request.email]) mail_certificate(request.id, request.email) request.generation_date = datetime.date.today() db.session.commit() print() else: print('skipping generation \n')
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime from subprocess import call from ca import app, db, mail from ca.models import Request from flask import Flask, render_template from flask_mail import Message def mail_certificate(id, email): with app.app_context(): msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email]) msg.body = render_template('mail.txt') with app.open_resource("/etc/openvpn/clients/freifunk_{}.tgz".format(id)) as fp: msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read()) mail.send(msg) for request in Request.query.filter(Request.generation_date == None).all(): # noqa prompt = "Do you want to generate a certificate for {}, {} ?" print(prompt.format(request.id, request.email)) print("Type y to continue") confirm = input('>') if confirm in ['Y', 'y']: print('generating certificate') call([app.config['COMMAND_BUILD'], request.id, request.email]) #call([app.config['COMMAND_MAIL'], request.id, request.email]) mail_certificate(request.id, request.email) request.generation_date = datetime.date.today() db.session.commit() print() else: print('skipping generation \n')
Add app.context() to populate context for render_template
Add app.context() to populate context for render_template
Python
mit
freifunk-berlin/ca.berlin.freifunk.net,freifunk-berlin/ca.berlin.freifunk.net,freifunk-berlin/ca.berlin.freifunk.net
--- +++ @@ -12,11 +12,12 @@ def mail_certificate(id, email): - msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email]) - msg.body = render_template('mail.txt') - with app.open_resource("/etc/openvpn/clients/freifunk_{}.tgz".format(id)) as fp: - msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read()) - mail.send(msg) + with app.app_context(): + msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email]) + msg.body = render_template('mail.txt') + with app.open_resource("/etc/openvpn/clients/freifunk_{}.tgz".format(id)) as fp: + msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read()) + mail.send(msg) for request in Request.query.filter(Request.generation_date == None).all(): # noqa prompt = "Do you want to generate a certificate for {}, {} ?"
d95eda2f88a8b493e40cd6628c7e532a1f510610
src/dashboard/src/main/urls.py
src/dashboard/src/main/urls.py
from django.conf.urls.defaults import * from django.conf import settings from django.views.generic.simple import direct_to_template, redirect_to UUID_REGEX = '[\w]{8}(-[\w]{4}){3}-[\w]{12}' urlpatterns = patterns('dashboard.main.views', # Ingest url(r'ingest/$', direct_to_template, {'template': 'main/ingest.html', 'extra_context': {'polling_interval': settings.POLLING_INTERVAL, 'microservices_help': settings.MICROSERVICES_HELP}}, 'ingest'), (r'ingest/go/$', 'ingest'), (r'ingest/go/(?P<uuid>' + UUID_REGEX + ')$', 'ingest'), (r'jobs/(?P<uuid>' + UUID_REGEX + ')/explore/$', 'explore'), (r'tasks/(?P<uuid>' + UUID_REGEX + ')/$', 'tasks'), # Preservatin planning (r'preservation-planning/$', 'preservation_planning'), # Index (r'', redirect_to, {'url': '/ingest/'}), )
from django.conf.urls.defaults import * from django.conf import settings from django.views.generic.simple import direct_to_template, redirect_to UUID_REGEX = '[\w]{8}(-[\w]{4}){3}-[\w]{12}' urlpatterns = patterns('dashboard.main.views', # Index (r'^$', redirect_to, {'url': '/ingest/'}), # Ingest url(r'ingest/$', direct_to_template, {'template': 'main/ingest.html', 'extra_context': {'polling_interval': settings.POLLING_INTERVAL, 'microservices_help': settings.MICROSERVICES_HELP}}, 'ingest'), (r'ingest/go/$', 'ingest'), (r'ingest/go/(?P<uuid>' + UUID_REGEX + ')$', 'ingest'), (r'jobs/(?P<uuid>' + UUID_REGEX + ')/explore/$', 'explore'), (r'jobs/(?P<uuid>' + UUID_REGEX + ')/list-objects/$', 'list_objects'), (r'tasks/(?P<uuid>' + UUID_REGEX + ')/$', 'tasks'), # Preservatin planning (r'preservation-planning/$', 'preservation_planning'), )
Remove default route because it is not the desired behavior.
Remove default route because it is not the desired behavior. Autoconverted from SVN (revision:1409)
Python
agpl-3.0
artefactual/archivematica-history,artefactual/archivematica-history,artefactual/archivematica-history,artefactual/archivematica-history
--- +++ @@ -6,17 +6,18 @@ urlpatterns = patterns('dashboard.main.views', + # Index + (r'^$', redirect_to, {'url': '/ingest/'}), + # Ingest url(r'ingest/$', direct_to_template, {'template': 'main/ingest.html', 'extra_context': {'polling_interval': settings.POLLING_INTERVAL, 'microservices_help': settings.MICROSERVICES_HELP}}, 'ingest'), (r'ingest/go/$', 'ingest'), (r'ingest/go/(?P<uuid>' + UUID_REGEX + ')$', 'ingest'), (r'jobs/(?P<uuid>' + UUID_REGEX + ')/explore/$', 'explore'), + (r'jobs/(?P<uuid>' + UUID_REGEX + ')/list-objects/$', 'list_objects'), (r'tasks/(?P<uuid>' + UUID_REGEX + ')/$', 'tasks'), # Preservatin planning (r'preservation-planning/$', 'preservation_planning'), - # Index - (r'', redirect_to, {'url': '/ingest/'}), - )
1a35294baac296bbd665dc55e35cd2b383ae7116
alembic/versions/87acbbe5887b_add_freeform_profile_for_user.py
alembic/versions/87acbbe5887b_add_freeform_profile_for_user.py
"""Add freeform profile for user Revision ID: 87acbbe5887b Revises: f2a71c7b93b6 Create Date: 2016-09-11 21:39:20.753000 """ # revision identifiers, used by Alembic. revision = '87acbbe5887b' down_revision = 'f2a71c7b93b6' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('user', sa.Column('profile_data', sa.Text(), nullable=False)) def downgrade(): op.drop_column('user', 'profile_data')
"""Add freeform profile for user Revision ID: 87acbbe5887b Revises: f2a71c7b93b6 Create Date: 2016-09-11 21:39:20.753000 """ # revision identifiers, used by Alembic. revision = '87acbbe5887b' down_revision = 'f2a71c7b93b6' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('user', sa.Column('profile_data', sa.Text(), nullable=False, server_default=u'{}')) def downgrade(): op.drop_column('user', 'profile_data')
Set default value for user profile data
Set default value for user profile data
Python
mit
katajakasa/aetherguild2,katajakasa/aetherguild2
--- +++ @@ -17,7 +17,7 @@ def upgrade(): - op.add_column('user', sa.Column('profile_data', sa.Text(), nullable=False)) + op.add_column('user', sa.Column('profile_data', sa.Text(), nullable=False, server_default=u'{}')) def downgrade():
12a9ef54d82d9508852e5596dbb9df321986e067
tests/test_heroku.py
tests/test_heroku.py
"""Tests for the Wallace API.""" import subprocess import re import requests class TestHeroku(object): """The Heroku test class.""" def test_sandbox(self): """Launch the experiment on Heroku.""" sandbox_output = subprocess.check_output( "cd examples/bartlett1932; wallace sandbox --verbose", shell=True) id = re.search( 'Running as experiment (.*)...', sandbox_output).group(1) r = requests.get("http://{}.herokuapp.com/summary".format(id)) assert r.json()['status'] == [] subprocess.call( "heroku apps:destroy --app {} --confirm {}".format(id), shell=True)
"""Tests for the Wallace API.""" import subprocess import re import os import requests class TestHeroku(object): """The Heroku test class.""" sandbox_output = subprocess.check_output( "cd examples/bartlett1932; wallace sandbox --verbose", shell=True) os.environ['app_id'] = re.search( 'Running as experiment (.*)...', sandbox_output).group(1) @classmethod def teardown_class(cls): """Remove the app from Heroku.""" app_id = os.environ['app_id'] subprocess.call( "heroku apps:destroy --app {} --confirm {}".format(app_id, app_id), shell=True) def test_summary(self): """Launch the experiment on Heroku.""" app_id = os.environ['app_id'] r = requests.get("http://{}.herokuapp.com/summary".format(app_id)) assert r.json()['status'] == []
Refactor Heroku tests to have shared setup
Refactor Heroku tests to have shared setup
Python
mit
Dallinger/Dallinger,berkeley-cocosci/Wallace,jcpeterson/Dallinger,jcpeterson/Dallinger,suchow/Wallace,berkeley-cocosci/Wallace,Dallinger/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,berkeley-cocosci/Wallace,Dallinger/Dallinger,jcpeterson/Dallinger,suchow/Wallace,suchow/Wallace,jcpeterson/Dallinger,Dallinger/Dallinger
--- +++ @@ -2,6 +2,7 @@ import subprocess import re +import os import requests @@ -9,18 +10,22 @@ """The Heroku test class.""" - def test_sandbox(self): + sandbox_output = subprocess.check_output( + "cd examples/bartlett1932; wallace sandbox --verbose", shell=True) + + os.environ['app_id'] = re.search( + 'Running as experiment (.*)...', sandbox_output).group(1) + + @classmethod + def teardown_class(cls): + """Remove the app from Heroku.""" + app_id = os.environ['app_id'] + subprocess.call( + "heroku apps:destroy --app {} --confirm {}".format(app_id, app_id), + shell=True) + + def test_summary(self): """Launch the experiment on Heroku.""" - sandbox_output = subprocess.check_output( - "cd examples/bartlett1932; wallace sandbox --verbose", shell=True) - - id = re.search( - 'Running as experiment (.*)...', sandbox_output).group(1) - - r = requests.get("http://{}.herokuapp.com/summary".format(id)) - + app_id = os.environ['app_id'] + r = requests.get("http://{}.herokuapp.com/summary".format(app_id)) assert r.json()['status'] == [] - - subprocess.call( - "heroku apps:destroy --app {} --confirm {}".format(id), - shell=True)
3c66efc142d53a4c8f9f88fb33d942c6840bd343
tests/test_trivia.py
tests/test_trivia.py
import unittest from units.trivia import check_answer class TestCheckAnswer(unittest.TestCase): def test_correct_answer(self): self.assertTrue(check_answer("correct", "correct")) def test_incorrect_answer(self): self.assertFalse(check_answer("correct", "incorrect")) def test_parentheses_with_article_prefix(self): self.assertTrue( check_answer( "the ISS (the International Space Station)", "International Space Station" ) ) self.assertTrue( check_answer("Holland (The Netherlands)", "Netherlands") ) def test_wrong_encoding(self): self.assertTrue(check_answer("a résumé", "resume")) self.assertTrue(check_answer("Tenochtitlán", "Tenochtitlan")) if __name__ == "__main__": unittest.main()
import unittest from units.trivia import check_answer class TestCheckAnswer(unittest.TestCase): def test_correct_answer(self): self.assertTrue(check_answer("correct", "correct")) def test_incorrect_answer(self): self.assertFalse(check_answer("correct", "incorrect")) def test_large_number(self): self.assertFalse( check_answer( "33 1/3", "128347192834719283561293847129384719238471234" ) ) def test_parentheses_with_article_prefix(self): self.assertTrue( check_answer( "the ISS (the International Space Station)", "International Space Station" ) ) self.assertTrue( check_answer("Holland (The Netherlands)", "Netherlands") ) def test_wrong_encoding(self): self.assertTrue(check_answer("a résumé", "resume")) self.assertTrue(check_answer("Tenochtitlán", "Tenochtitlan")) if __name__ == "__main__": unittest.main()
Test large number as response for check_answer
[Tests] Test large number as response for check_answer
Python
mit
Harmon758/Harmonbot,Harmon758/Harmonbot
--- +++ @@ -11,6 +11,14 @@ def test_incorrect_answer(self): self.assertFalse(check_answer("correct", "incorrect")) + + def test_large_number(self): + self.assertFalse( + check_answer( + "33 1/3", + "128347192834719283561293847129384719238471234" + ) + ) def test_parentheses_with_article_prefix(self): self.assertTrue(
46807ee4923a5799ec371cd8094c36f0b672f4b4
common/highlights.py
common/highlights.py
import common.time SPREADSHEET = "1yrf6d7dPyTiWksFkhISqEc-JR71dxZMkUoYrX4BR40Y" def format_row(title, description, video, timestamp, nick): if '_id' in video: url = "https://www.twitch.tv/loadingreadyrun/manager/%s/highlight" % video['_id'] else: url = video['url'] return [ ("SHOW", title), ("QUOTE or MOMENT", description), ("YOUTUBE VIDEO LINK", url), ("ROUGH TIME THEREIN", "before " + common.time.nice_duration(timestamp, 0)), ("NOTES", "from chat user '%s'" % nick), ]
import common.time SPREADSHEET = "1yrf6d7dPyTiWksFkhISqEc-JR71dxZMkUoYrX4BR40Y" def format_row(title, description, video, timestamp, nick): if '_id' in video: # Allow roughly 15 seconds for chat delay, 10 seconds for chat reaction time, # 20 seconds for how long the actual event is... linkts = timestamp - 45 linkts = "%02dh%02dm%02ds" % (linkts//3600, linkts//60 % 60, linkts % 60) url = "https://www.twitch.tv/loadingreadyrun/manager/%s/highlight?t=%s" % (video['_id'], linkts) else: url = video['url'] return [ ("SHOW", title), ("QUOTE or MOMENT", description), ("YOUTUBE VIDEO LINK", url), ("ROUGH TIME THEREIN", "before " + common.time.nice_duration(timestamp, 0)), ("NOTES", "from chat user '%s'" % nick), ]
Add timestamp to link too
Add timestamp to link too
Python
apache-2.0
andreasots/lrrbot,mrphlip/lrrbot,mrphlip/lrrbot,andreasots/lrrbot,mrphlip/lrrbot,andreasots/lrrbot
--- +++ @@ -4,7 +4,11 @@ def format_row(title, description, video, timestamp, nick): if '_id' in video: - url = "https://www.twitch.tv/loadingreadyrun/manager/%s/highlight" % video['_id'] + # Allow roughly 15 seconds for chat delay, 10 seconds for chat reaction time, + # 20 seconds for how long the actual event is... + linkts = timestamp - 45 + linkts = "%02dh%02dm%02ds" % (linkts//3600, linkts//60 % 60, linkts % 60) + url = "https://www.twitch.tv/loadingreadyrun/manager/%s/highlight?t=%s" % (video['_id'], linkts) else: url = video['url'] return [
b06f0e17541f7d424e73fd200ae10db0722b1a5a
organizer/views.py
organizer/views.py
from django.shortcuts import ( get_object_or_404, render) from .forms import TagForm from .models import Startup, Tag def startup_detail(request, slug): startup = get_object_or_404( Startup, slug__iexact=slug) return render( request, 'organizer/startup_detail.html', {'startup': startup}) def startup_list(request): return render( request, 'organizer/startup_list.html', {'startup_list': Startup.objects.all()}) def tag_create(request): if request.method == 'POST': form = TagForm(request.POST) if form.is_valid(): # create new object from data # show webpage for new object pass else: # empty data or invalid data # show bound HTML form (with errors) pass else: # request.method != 'POST' # show unbound HTML form pass def tag_detail(request, slug): tag = get_object_or_404( Tag, slug__iexact=slug) return render( request, 'organizer/tag_detail.html', {'tag': tag}) def tag_list(request): return render( request, 'organizer/tag_list.html', {'tag_list': Tag.objects.all()})
from django.shortcuts import ( get_object_or_404, redirect, render) from .forms import TagForm from .models import Startup, Tag def startup_detail(request, slug): startup = get_object_or_404( Startup, slug__iexact=slug) return render( request, 'organizer/startup_detail.html', {'startup': startup}) def startup_list(request): return render( request, 'organizer/startup_list.html', {'startup_list': Startup.objects.all()}) def tag_create(request): if request.method == 'POST': form = TagForm(request.POST) if form.is_valid(): new_tag = form.save() return redirect(new_tag) else: # empty data or invalid data # show bound HTML form (with errors) pass else: # request.method != 'POST' # show unbound HTML form pass def tag_detail(request, slug): tag = get_object_or_404( Tag, slug__iexact=slug) return render( request, 'organizer/tag_detail.html', {'tag': tag}) def tag_list(request): return render( request, 'organizer/tag_list.html', {'tag_list': Tag.objects.all()})
Create and redirect to Tag in tag_create().
Ch09: Create and redirect to Tag in tag_create().
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
--- +++ @@ -1,5 +1,5 @@ from django.shortcuts import ( - get_object_or_404, render) + get_object_or_404, redirect, render) from .forms import TagForm from .models import Startup, Tag @@ -25,9 +25,8 @@ if request.method == 'POST': form = TagForm(request.POST) if form.is_valid(): - # create new object from data - # show webpage for new object - pass + new_tag = form.save() + return redirect(new_tag) else: # empty data or invalid data # show bound HTML form (with errors) pass
5553dd2aba90749fdedda55067c2010cf1522f54
mesobox/boxes.py
mesobox/boxes.py
from django.conf import settings import importlib # Merge two lots of mesobox-compatible context additions def merge_context_additions(additions): context = {} boxes = {} for c in additions: try: context.update(c.get("context")) except TypeError: pass try: for k, v in c.get("boxes").items(): if k in boxes: boxes[k].append(v) else: boxes[k] = v except TypeError: pass except AttributeError: pass return {"context": context, "boxes": boxes} def context_processor(request): additions = {} # Get the boxes and accompanying context additions from all the installed apps. for app in settings.INSTALLED_APPS: print(app) try: module = importlib.import_module(app+".boxes") except ImportError: continue # Run each function now. for b in module.BOX_INCLUDES: b_func = getattr(module, b) if not b_func: raise Exception("Method %s not implemented in module %s" % (b, app)) additions = merge_context_additions([additions, b_func(request)]) # Merge boxes down to being part of the context additions dict now they have all been assembled result = additions['context'] result['boxes'] = additions['boxes'] return result
from django.conf import settings import importlib # Merge two lots of mesobox-compatible context additions def merge_context_additions(additions): context = {} boxes = {} for c in additions: try: context.update(c.get("context")) except TypeError: pass try: for k, v in c.get("boxes").items(): if k in boxes: boxes[k].append(v) else: boxes[k] = v except TypeError: pass except AttributeError: pass return {"context": context, "boxes": boxes} def context_processor(request): additions = {} # Get the boxes and accompanying context additions from all the installed apps. for app in settings.INSTALLED_APPS: try: module = importlib.import_module(app+".boxes") except ImportError: continue # Run each function now. for b in module.BOX_INCLUDES: b_func = getattr(module, b) if not b_func: raise Exception("Method %s not implemented in module %s" % (b, app)) additions = merge_context_additions([additions, b_func(request)]) # Merge boxes down to being part of the context additions dict now they have all been assembled result = additions['context'] result['boxes'] = additions['boxes'] return result
Remove a debugging print that should never have been left there anyway.
Remove a debugging print that should never have been left there anyway.
Python
mit
grundleborg/mesosphere
--- +++ @@ -28,7 +28,6 @@ # Get the boxes and accompanying context additions from all the installed apps. for app in settings.INSTALLED_APPS: - print(app) try: module = importlib.import_module(app+".boxes") except ImportError:
bde51dc314bd920dafd5f72fbc4ccae099f5be59
tsune/settings/ci.py
tsune/settings/ci.py
from .base import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', #'NAME': 'db.sqlite3', } } INSTALLED_APPS += ('django_jenkins',) PROJECT_APPS = { 'cardbox', }
from .base import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', #'NAME': 'db.sqlite3', } } INSTALLED_APPS += ('django_jenkins',) PROJECT_APPS = { 'cardbox', 'deckglue', 'memorize', }
Add deckglue and memorize to django_jenkins
Add deckglue and memorize to django_jenkins
Python
mit
DummyDivision/Tsune,DummyDivision/Tsune,DummyDivision/Tsune
--- +++ @@ -11,4 +11,7 @@ PROJECT_APPS = { 'cardbox', + 'deckglue', + 'memorize', } +
2492803223060ecf92f8c60a2aa07db8f450e7b1
get_dev_id.py
get_dev_id.py
from gmusicapi import Mobileclient # Try to print out some valid device IDs. if __name__ == '__main__': api = Mobileclient() email = input('Enter your email: ') password = input('Enter your password: ') if not api.login(email, password, Mobileclient.FROM_MAC_ADDRESS): print('Login failed, verify your email and password:' 'enter any key to exit.') quit() devices = api.get_registered_devices() i = 1 for device in devices: print('%d: %s' % ( i, device['id'][2:] if device['id'].startswith('0x') else device['id'])) i += 1
import getpass from gmusicapi import Mobileclient # Try to print out some valid device IDs. if __name__ == '__main__': api = Mobileclient() email = input('Enter your email: ').strip() assert '@' in email, 'Please enter a valid email.' password = getpass.getpass('Enter password for {}: '.format(email)) if not api.login(email, password, Mobileclient.FROM_MAC_ADDRESS): print('Login failed, verify your email and password: ' 'enter any key to exit.') quit() for i, device in enumerate(api.get_registered_devices()): d_id = device['id'] print('%d: %s' % (i + 1, d_id[2:] if d_id.startswith('0x') else d_id))
Secure with getpass(), Simplify with enumerate()
Secure with getpass(), Simplify with enumerate()
Python
mit
christopher-dG/pmcli,christopher-dG/pmcli
--- +++ @@ -1,20 +1,19 @@ +import getpass from gmusicapi import Mobileclient + # Try to print out some valid device IDs. if __name__ == '__main__': api = Mobileclient() - email = input('Enter your email: ') - password = input('Enter your password: ') + email = input('Enter your email: ').strip() + assert '@' in email, 'Please enter a valid email.' + password = getpass.getpass('Enter password for {}: '.format(email)) if not api.login(email, password, Mobileclient.FROM_MAC_ADDRESS): - print('Login failed, verify your email and password:' + print('Login failed, verify your email and password: ' 'enter any key to exit.') quit() - devices = api.get_registered_devices() - i = 1 - for device in devices: - print('%d: %s' % ( - i, device['id'][2:] if device['id'].startswith('0x') - else device['id'])) - i += 1 + for i, device in enumerate(api.get_registered_devices()): + d_id = device['id'] + print('%d: %s' % (i + 1, d_id[2:] if d_id.startswith('0x') else d_id))
443172dd4f8717f55da8f8a4af1397044f66ccf0
yunity/users/api.py
yunity/users/api.py
from django.contrib.auth import get_user_model from rest_framework import filters from rest_framework import viewsets from yunity.users.serializers import UserSerializer class UserViewSet(viewsets.ModelViewSet): queryset = get_user_model().objects.all() serializer_class = UserSerializer filter_backends = (filters.SearchFilter,) search_fields = ('display_name', 'first_name', 'last_name')
from django.contrib.auth import get_user_model from rest_framework import filters from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated, AllowAny, BasePermission from yunity.users.serializers import UserSerializer class IsRequestUser(BasePermission): message = 'You can modify only your own user data.' def has_object_permission(self, request, view, obj): return request.user == obj class UserViewSet(viewsets.ModelViewSet): queryset = get_user_model().objects.all() serializer_class = UserSerializer filter_backends = (filters.SearchFilter,) search_fields = ('display_name', 'first_name', 'last_name') def get_permissions(self): if self.action == 'create': self.permission_classes = (AllowAny,) elif self.action in ('list', 'retrieve'): self.permission_classes = (IsAuthenticated,) else: self.permission_classes = (IsRequestUser,) return super().get_permissions()
Extend Users API to conform to tests
Extend Users API to conform to tests
Python
agpl-3.0
yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend
--- +++ @@ -1,7 +1,16 @@ from django.contrib.auth import get_user_model from rest_framework import filters from rest_framework import viewsets +from rest_framework.permissions import IsAuthenticated, AllowAny, BasePermission + from yunity.users.serializers import UserSerializer + + +class IsRequestUser(BasePermission): + message = 'You can modify only your own user data.' + + def has_object_permission(self, request, view, obj): + return request.user == obj class UserViewSet(viewsets.ModelViewSet): @@ -9,3 +18,13 @@ serializer_class = UserSerializer filter_backends = (filters.SearchFilter,) search_fields = ('display_name', 'first_name', 'last_name') + + def get_permissions(self): + if self.action == 'create': + self.permission_classes = (AllowAny,) + elif self.action in ('list', 'retrieve'): + self.permission_classes = (IsAuthenticated,) + else: + self.permission_classes = (IsRequestUser,) + + return super().get_permissions()
20a938892492defb1063a63b12e1aeb5b47c5508
web/core/models.py
web/core/models.py
from __future__ import unicode_literals from django.db import models from django.conf import settings import django.db.models.signals import django.dispatch.dispatcher import web.core import re import os import uuid class File(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) slug = models.CharField(max_length=64, default=web.core.random_slug_default_length, editable=False) author = models.ForeignKey(settings.AUTH_USER_MODEL) file = models.FileField(upload_to=web.core.get_file_path) created = models.DateTimeField(auto_now_add=True) expiry = models.DateTimeField(default=web.core.default_expiry, blank=True) def delete_file(self): return self.file.delete() def __unicode__(self): return self.file.name @django.dispatch.dispatcher.receiver(django.db.models.signals.post_delete, sender=File) def file_delete(sender, instance, **kwargs): instance.delete_file()
from __future__ import unicode_literals from django.db import models from django.conf import settings import django.db.models.signals import django.dispatch.dispatcher import web.core import re import os import uuid class File(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) slug = models.CharField(max_length=64, default=web.core.random_slug_default_length, editable=False) author = models.ForeignKey(settings.AUTH_USER_MODEL) file = models.FileField(upload_to=web.core.get_file_path) created = models.DateTimeField(auto_now_add=True) expiry = models.DateTimeField(default=web.core.default_expiry, blank=True) def delete_file(self): base_path = os.path.dirname(self.file.name) os.unlink(self.file.name) os.rmdir(base_path) def __unicode__(self): return self.file.name @django.dispatch.dispatcher.receiver(django.db.models.signals.post_delete, sender=File) def file_delete(sender, instance, **kwargs): instance.delete_file()
Remove directories when deleting files
Remove directories when deleting files
Python
bsd-3-clause
ambientsound/rsync,ambientsound/rsync,ambientsound/rsync,ambientsound/rsync
--- +++ @@ -21,7 +21,9 @@ expiry = models.DateTimeField(default=web.core.default_expiry, blank=True) def delete_file(self): - return self.file.delete() + base_path = os.path.dirname(self.file.name) + os.unlink(self.file.name) + os.rmdir(base_path) def __unicode__(self): return self.file.name
d7d9fcb260b85a3f785852239acaea6ccda1725a
what_meta/views.py
what_meta/views.py
from django.core import serializers from django.http.response import HttpResponse from what_meta.models import WhatTorrentGroup def search_torrent_groups(request, query): return HttpResponse( serializers.serialize('json', WhatTorrentGroup.objects.filter(name__icontains=query)), content_type='text/plain', )
from django.core import serializers from django.http.response import HttpResponse from what_meta.models import WhatTorrentGroup def search_torrent_groups(request, query): response = HttpResponse( serializers.serialize('json', WhatTorrentGroup.objects.filter(name__icontains=query)), content_type='text/json', ) response['Access-Control-Allow-Origin'] = '*' return response
Support for super simple player.
Support for super simple player.
Python
mit
grandmasterchef/WhatManager2,davols/WhatManager2,MADindustries/WhatManager2,MADindustries/WhatManager2,davols/WhatManager2,karamanolev/WhatManager2,MADindustries/WhatManager2,davols/WhatManager2,grandmasterchef/WhatManager2,grandmasterchef/WhatManager2,grandmasterchef/WhatManager2,karamanolev/WhatManager2,karamanolev/WhatManager2,karamanolev/WhatManager2,MADindustries/WhatManager2
--- +++ @@ -5,7 +5,9 @@ def search_torrent_groups(request, query): - return HttpResponse( + response = HttpResponse( serializers.serialize('json', WhatTorrentGroup.objects.filter(name__icontains=query)), - content_type='text/plain', + content_type='text/json', ) + response['Access-Control-Allow-Origin'] = '*' + return response
9312a291d09df1314497e8d438f388d8eb37cc7b
shuup/front/apps/carousel/migrations/0003_add_shops.py
shuup/front/apps/carousel/migrations/0003_add_shops.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-05-09 01:13 from __future__ import unicode_literals from django.db import migrations, models def add_shop_for_carousels(apps, schema_editor): Shop = apps.get_model("shuup", "Shop") Carousel = apps.get_model("carousel", "Carousel") shop = Shop.objects.first() for carousel in Carousel.objects.all(): carousel.shops.set([shop]) class Migration(migrations.Migration): dependencies = [ ('carousel', '0002_alter_names'), ] operations = [ migrations.AddField( model_name='carousel', name='shops', field=models.ManyToManyField(help_text='Select which shops you would like the carousel to be visible in.', related_name='carousels', to='shuup.Shop', verbose_name='shops'), ), migrations.RunPython(add_shop_for_carousels, migrations.RunPython.noop) ]
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-05-09 01:13 from __future__ import unicode_literals from django.db import migrations, models def add_shop_for_carousels(apps, schema_editor): Shop = apps.get_model("shuup", "Shop") Carousel = apps.get_model("carousel", "Carousel") shop = Shop.objects.first() for carousel in Carousel.objects.all(): carousel.shops = [shop] class Migration(migrations.Migration): dependencies = [ ('carousel', '0002_alter_names'), ] operations = [ migrations.AddField( model_name='carousel', name='shops', field=models.ManyToManyField(help_text='Select which shops you would like the carousel to be visible in.', related_name='carousels', to='shuup.Shop', verbose_name='shops'), ), migrations.RunPython(add_shop_for_carousels, migrations.RunPython.noop) ]
Fix migration issue with Django 1.8
Fix migration issue with Django 1.8
Python
agpl-3.0
shoopio/shoop,shoopio/shoop,shoopio/shoop
--- +++ @@ -10,7 +10,7 @@ Carousel = apps.get_model("carousel", "Carousel") shop = Shop.objects.first() for carousel in Carousel.objects.all(): - carousel.shops.set([shop]) + carousel.shops = [shop] class Migration(migrations.Migration):
68211b703e15309b1a384f46d7bd70a8657decde
piper/process.py
piper/process.py
import logbook import sh from piper.logging import SEPARATOR class Process: """ Helper class for running processes """ def __init__(self, config, cmd, parent_key): self.config = config self.cmd = cmd self.sh = None self.success = None self.log = logbook.Logger(parent_key + SEPARATOR + self.cmd) def setup(self): """ Setup the Popen object used in execution """ self.log.debug('Spawning process handler') cmd, *args = self.cmd.split() self.sh = sh.Command(cmd)(args, _iter=True) def run(self): self.log.debug('Executing') try: for line in self.sh: self.log.info(line) except sh.ErrorReturnCode: self.log.error(self.sh.stderr) finally: exit = self.sh.exit_code self.success = exit == 0 self.log.debug('Exitcode {0}'.format(exit))
import logbook import sh from piper.logging import SEPARATOR class Process: """ Helper class for running processes """ def __init__(self, config, cmd, parent_key): self.config = config self.cmd = cmd self.sh = None self.success = None self.log = logbook.Logger(parent_key + SEPARATOR + self.cmd) def setup(self): """ Setup the Popen object used in execution """ self.log.debug('Spawning process handler') cmd, *args = self.cmd.split() self.sh = sh.Command(cmd)(args, _iter=True) def run(self): self.log.debug('Executing') try: for line in self.sh: self.log.info(line.strip()) except sh.ErrorReturnCode: self.log.error(self.sh.stderr) finally: exit = self.sh.exit_code self.success = exit == 0 self.log.debug('Exitcode {0}'.format(exit))
Fix output with trailing newlines from sh.
Fix output with trailing newlines from sh. Closes #39
Python
mit
thiderman/piper
--- +++ @@ -34,7 +34,7 @@ try: for line in self.sh: - self.log.info(line) + self.log.info(line.strip()) except sh.ErrorReturnCode: self.log.error(self.sh.stderr) finally:
fd516d3b80e63c6883d5eec47a8bf9ff6042509b
pandoc-figref.py
pandoc-figref.py
#! /usr/bin/env python3 """Pandoc filter that replaces labels of format {#?:???}, where ? is a single lower case character defining the type and ??? is an alphanumeric label, with numbers. Different types are counted separately. """ from pandocfilters import toJSONFilter, Str import re REF_PAT = re.compile('\{#([a-z]):(\w*)\}(.*)') known_labels = {} def figref(key, val, fmt, meta): if key == 'Str' and REF_PAT.match(val): kind, label, end = REF_PAT.match(val).groups() if kind in known_labels: if label not in known_labels[kind]: known_labels[kind][label] = str(len(known_labels[kind])\ + 1) else: known_labels[kind] = {} known_labels[kind][label] = "1" return [Str(known_labels[kind][label])] + [Str(end)] if __name__ == '__main__': toJSONFilter(figref)
#! /usr/bin/env python3 """Pandoc filter that replaces labels of format {#?:???}, where ? is a single lower case character defining the type and ??? is an alphanumeric label, with numbers. Different types are counted separately. """ from pandocfilters import toJSONFilter, Str import re REF_PAT = re.compile('(.*)\{#([a-z]):(\w*)\}(.*)') known_labels = {} def figref(key, val, fmt, meta): if key == 'Str' and REF_PAT.match(val): start, kind, label, end = REF_PAT.match(val).groups() if kind in known_labels: if label not in known_labels[kind]: known_labels[kind][label] = str(len(known_labels[kind])\ + 1) else: known_labels[kind] = {} known_labels[kind][label] = "1" return [Str(start)] + [Str(known_labels[kind][label])] + \ [Str(end)] if __name__ == '__main__': toJSONFilter(figref)
Fix error with no space before tag
Fix error with no space before tag
Python
mit
scotthartley/pandoc-figref
--- +++ @@ -8,13 +8,13 @@ from pandocfilters import toJSONFilter, Str import re -REF_PAT = re.compile('\{#([a-z]):(\w*)\}(.*)') +REF_PAT = re.compile('(.*)\{#([a-z]):(\w*)\}(.*)') known_labels = {} def figref(key, val, fmt, meta): if key == 'Str' and REF_PAT.match(val): - kind, label, end = REF_PAT.match(val).groups() + start, kind, label, end = REF_PAT.match(val).groups() if kind in known_labels: if label not in known_labels[kind]: known_labels[kind][label] = str(len(known_labels[kind])\ @@ -22,7 +22,8 @@ else: known_labels[kind] = {} known_labels[kind][label] = "1" - return [Str(known_labels[kind][label])] + [Str(end)] + return [Str(start)] + [Str(known_labels[kind][label])] + \ + [Str(end)] if __name__ == '__main__': toJSONFilter(figref)
7642359c1ecf2b5dc38f70924e7c9885739a79c8
jungle/emr.py
jungle/emr.py
# -*- coding: utf-8 -*- import boto3 import click @click.group() def cli(): """EMR CLI group""" pass @cli.command(help='List EMR clusters') @click.argument('name', default='*') def ls(name): """List EMR instances""" client = boto3.client('emr', region_name='us-east-1') results = client.list_clusters( ClusterStates=['RUNNING', 'STARTING', 'BOOTSTRAPPING', 'WAITING'] ) for cluster in results['Clusters']: click.echo(cluster['Id'])
# -*- coding: utf-8 -*- import subprocess import boto3 import click @click.group() def cli(): """EMR CLI group""" pass @cli.command(help='List EMR clusters') @click.argument('name', default='*') def ls(name): """List EMR instances""" client = boto3.client('emr') results = client.list_clusters( ClusterStates=['RUNNING', 'STARTING', 'BOOTSTRAPPING', 'WAITING'] ) for cluster in results['Clusters']: click.echo("{}\t{}\t{}".format(cluster['Id'], cluster['Name'], cluster['Status']['State'])) @cli.command(help='List EMR clusters') @click.option('--cluster-id', '-i', required=True, help='EMR cluster id') @click.option('--key-file', '-k', required=True, help='SSH Key file path', type=click.Path()) def ssh(cluster_id, key_file): """List EMR instances""" client = boto3.client('emr') result = client.describe_cluster(ClusterId=cluster_id) target_dns = result['Cluster']['MasterPublicDnsName'] ssh_options = '-o StrictHostKeyChecking=no -o ServerAliveInterval=10' cmd = 'ssh {ssh_options} -i {key_file} hadoop@{target_dns}'.format( ssh_options=ssh_options, key_file=key_file, target_dns=target_dns) subprocess.call(cmd, shell=True)
Add ssh subcommand for EMR
Add ssh subcommand for EMR
Python
mit
achiku/jungle
--- +++ @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*- +import subprocess + import boto3 import click @@ -13,9 +15,23 @@ @click.argument('name', default='*') def ls(name): """List EMR instances""" - client = boto3.client('emr', region_name='us-east-1') + client = boto3.client('emr') results = client.list_clusters( ClusterStates=['RUNNING', 'STARTING', 'BOOTSTRAPPING', 'WAITING'] ) for cluster in results['Clusters']: - click.echo(cluster['Id']) + click.echo("{}\t{}\t{}".format(cluster['Id'], cluster['Name'], cluster['Status']['State'])) + + +@cli.command(help='List EMR clusters') +@click.option('--cluster-id', '-i', required=True, help='EMR cluster id') +@click.option('--key-file', '-k', required=True, help='SSH Key file path', type=click.Path()) +def ssh(cluster_id, key_file): + """List EMR instances""" + client = boto3.client('emr') + result = client.describe_cluster(ClusterId=cluster_id) + target_dns = result['Cluster']['MasterPublicDnsName'] + ssh_options = '-o StrictHostKeyChecking=no -o ServerAliveInterval=10' + cmd = 'ssh {ssh_options} -i {key_file} hadoop@{target_dns}'.format( + ssh_options=ssh_options, key_file=key_file, target_dns=target_dns) + subprocess.call(cmd, shell=True)
9168abf53be960d1630ec6ecb01c6d8f55d21739
promotions_app/models.py
promotions_app/models.py
from django.db import models from authentication_app.models import Account ''' @name : Promotion @desc : The promotion model. ''' class Promotion(models.Model): account = models.ForeignKey(Account) name = models.CharField(max_length=50, unique=True) desc = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) expire_date = models.DateTimeField(auto_now=True) image = models.ImageField(upload_to='promotions') def _unicode_(self): return self.name def get_short_promotion(self): return ' '.join([self.name, self.expire_date]) def get_promotion(self): return ' '.join([self.name, self.desc, self.expire_date])
from django.db import models from authentication_app.models import Account ''' @name : PromotionManager. @desc : The PromotionManager is responsible to create, delete and update the promotions. ''' class PromotionManager(models.Manager): def create_promotion(self, name, desc, expire_date, image): promotion = self.create(name=name, desc=desc, expire_date=expire_date, image=image) promotion.save() return promotion def delete_promotion(self, name): promotion = super(PromotionManager, self).get_queryset().filter(name=name) promotion.delete() def update_promotion(self, name, expire_date): promotion = super(PromotionManager, self).get_queryset().filter(name=name) promotion.set_expire_date(expire_date) return promotion ''' @name : Promotion. @desc : The promotion model. ''' class Promotion(models.Model): account = models.ForeignKey(Account) name = models.CharField(max_length=50, unique=True) desc = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) expire_date = models.DateTimeField(auto_now=True) image = models.ImageField(upload_to='promotions') objects = PromotionManager() def _unicode_(self): return self.name def get_short_promotion(self): return ' '.join([self.name, self.expire_date]) def get_promotion(self): return ' '.join([self.name, self.desc, self.expire_date])
Add the promotion manager to the promotions app.
Add the promotion manager to the promotions app.
Python
mit
mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app
--- +++ @@ -3,7 +3,27 @@ from authentication_app.models import Account ''' - @name : Promotion + @name : PromotionManager. + @desc : The PromotionManager is responsible to create, delete and update the promotions. +''' +class PromotionManager(models.Manager): + + def create_promotion(self, name, desc, expire_date, image): + promotion = self.create(name=name, desc=desc, expire_date=expire_date, image=image) + promotion.save() + return promotion + + def delete_promotion(self, name): + promotion = super(PromotionManager, self).get_queryset().filter(name=name) + promotion.delete() + + def update_promotion(self, name, expire_date): + promotion = super(PromotionManager, self).get_queryset().filter(name=name) + promotion.set_expire_date(expire_date) + return promotion + +''' + @name : Promotion. @desc : The promotion model. ''' class Promotion(models.Model): @@ -18,6 +38,8 @@ image = models.ImageField(upload_to='promotions') + objects = PromotionManager() + def _unicode_(self): return self.name
657d2d7e5aaefd2ee3b543ab9eb03f4a91d26d37
Lib/xml/__init__.py
Lib/xml/__init__.py
"""Core XML support for Python. This package contains three sub-packages: dom -- The W3C Document Object Model. This supports DOM Level 1 + Namespaces. parser -- Python wrappers for XML parsers (currently only supports Expat). sax -- The Simple API for XML, developed by XML-Dev, led by David Megginson and ported to Python by Lars Marius Garshol. This supports the SAX 2 API. """
"""Core XML support for Python. This package contains three sub-packages: dom -- The W3C Document Object Model. This supports DOM Level 1 + Namespaces. parsers -- Python wrappers for XML parsers (currently only supports Expat). sax -- The Simple API for XML, developed by XML-Dev, led by David Megginson and ported to Python by Lars Marius Garshol. This supports the SAX 2 API. """ if __name__ == "xml": try: import _xmlplus except ImportError: pass else: import sys sys.modules[__name__] = _xmlplus
Add magic to replace the xml package with _xmlplus at import time. Update docstring to reflect change of name for the parsers subpackage.
Add magic to replace the xml package with _xmlplus at import time. Update docstring to reflect change of name for the parsers subpackage.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
--- +++ @@ -5,9 +5,19 @@ dom -- The W3C Document Object Model. This supports DOM Level 1 + Namespaces. -parser -- Python wrappers for XML parsers (currently only supports Expat). +parsers -- Python wrappers for XML parsers (currently only supports Expat). sax -- The Simple API for XML, developed by XML-Dev, led by David Megginson and ported to Python by Lars Marius Garshol. This supports the SAX 2 API. """ + + +if __name__ == "xml": + try: + import _xmlplus + except ImportError: + pass + else: + import sys + sys.modules[__name__] = _xmlplus
61f4d269e745a24209e1719049f25dab3e3171a0
preconditions.py
preconditions.py
class PreconditionError (TypeError): pass def preconditions(*precs): pass # stub.
class PreconditionError (TypeError): pass def preconditions(*precs): def decorate(f): def g(*a, **kw): return f(*a, **kw) return g return decorate
Implement a stub decorator factory.
Implement a stub decorator factory.
Python
mit
nejucomo/preconditions
--- +++ @@ -3,4 +3,8 @@ def preconditions(*precs): - pass # stub. + def decorate(f): + def g(*a, **kw): + return f(*a, **kw) + return g + return decorate
5e1ffdab41c322a9bcd466b34aabaa37ef08a6e2
profiling_run.py
profiling_run.py
# -*- coding: utf-8 -*- """ Created on Wed Sep 23 15:23:58 2015 @author: jensv """ import skin_core_scanner_simple as scss reload(scss) import equil_solver as es reload(es) import newcomb_simple as new reload(new) (lambda_a_mesh, k_a_mesh, stability_maps) = scss.scan_lambda_k_space([0.01, 3.0, 25.], [0.01, 1.5, 25], epsilon=0.11, core_radius_norm=0.9, transition_width_norm=0.033, skin_width_norm=0.034, method='lsoda', max_step=1E-2, nsteps=1000)
# -*- coding: utf-8 -*- """ Created on Wed Sep 23 15:23:58 2015 @author: jensv """ import skin_core_scanner_simple as scss reload(scss) import equil_solver as es reload(es) import newcomb_simple as new reload(new) (lambda_a_mesh, k_a_mesh, stability_maps) = scss.scan_lambda_k_space([0.01, 3.0, 25.], [0.01, 1.5, 25], epsilon=0.11, core_radius_norm=0.9, transition_width_norm=0.033, skin_width_norm=0.034, method='lsoda', max_step=1E-2, nsteps=1000, use_jac=True)
Make jacobian use more explicit.
Make jacobian use more explicit.
Python
mit
jensv/fluxtubestability,jensv/fluxtubestability
--- +++ @@ -18,4 +18,4 @@ transition_width_norm=0.033, skin_width_norm=0.034, method='lsoda', - max_step=1E-2, nsteps=1000) + max_step=1E-2, nsteps=1000, use_jac=True)
653e40e15bfbf5c24c990ecdf90c0e6deb6d5636
test/macro_tests/test_macros.py
test/macro_tests/test_macros.py
#!/usr/bin/env python import unittest import os.path from macropolo import MacroTestCase, JSONTestCaseLoader from macropolo.environments import SheerEnvironment class CFGovTestCase(SheerEnvironment, MacroTestCase): """ A MacroTestCase subclass for cfgov-refresh. """ def search_root(self): """ Return the root of the search path for templates. """ # Get the cfgov-refresh root dir, ../../../ # PLEASE NOTE: This presumes that the file containing the test always # lives three levels above the cfgov-refresh root. templates = os.path.abspath(os.path.join( os.path.dirname(__file__), os.pardir, os.pardir, 'cfgov/v1/jinja2/v1')) return templates def search_exceptions(self): """ Return a list of subdirectory names that should not be searched for templates. """ templates = 'cfgov/v1/jinja2/v1' return [ templates + '/_defaults', templates + '/_lib', templates + '/_queries', templates + '/_settings', 'test', 'config' ] # Create CFGovTestCase subclasses for all JSON tests. tests_path = os.path.abspath(os.path.join(os.path.dirname( __file__ ), 'tests')) JSONTestCaseLoader(tests_path, CFGovTestCase, globals()) # Run the tests if we're executed if __name__ == '__main__': unittest.main()
#!/usr/bin/env python import unittest import os.path from macropolo import MacroTestCase, JSONTestCaseLoader from macropolo.environments import SheerEnvironment class CFGovTestCase(SheerEnvironment, MacroTestCase): """ A MacroTestCase subclass for cfgov-refresh. """ def search_root(self): """ Return the root of the search path for templates. """ # Get the cfgov-refresh root dir, ../../../ # PLEASE NOTE: This presumes that the file containing the test always # lives three levels above the cfgov-refresh root. templates = os.path.abspath(os.path.join( os.path.dirname(__file__), os.pardir, os.pardir, 'cfgov/jinja2/v1')) return templates def search_exceptions(self): """ Return a list of subdirectory names that should not be searched for templates. """ templates = 'cfgov/jinja2/v1' return [ templates + '/_defaults', templates + '/_lib', templates + '/_queries', templates + '/_settings', 'test', 'config' ] # Create CFGovTestCase subclasses for all JSON tests. tests_path = os.path.abspath(os.path.join(os.path.dirname( __file__ ), 'tests')) JSONTestCaseLoader(tests_path, CFGovTestCase, globals()) # Run the tests if we're executed if __name__ == '__main__': unittest.main()
Adjust macro tests to new template location
Adjust macro tests to new template location
Python
cc0-1.0
kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh
--- +++ @@ -23,7 +23,7 @@ os.path.dirname(__file__), os.pardir, os.pardir, - 'cfgov/v1/jinja2/v1')) + 'cfgov/jinja2/v1')) return templates @@ -33,7 +33,7 @@ Return a list of subdirectory names that should not be searched for templates. """ - templates = 'cfgov/v1/jinja2/v1' + templates = 'cfgov/jinja2/v1' return [ templates + '/_defaults', templates + '/_lib',
845b9b9be9c5a7f0f4e214215854d2d3c05a11f3
bfg9000/shell/__init__.py
bfg9000/shell/__init__.py
import os import subprocess from ..platform_name import platform_name if platform_name() == 'windows': from .windows import * else: from .posix import * class shell_list(list): """A special subclass of list used to mark that this command line uses special shell characters.""" pass def execute(args, shell=False, env=None, quiet=False): stderr = None if quiet: stderr = open(os.devnull, 'wb') try: return subprocess.check_output( args, universal_newlines=True, shell=shell, env=env, stderr=stderr ) except: if quiet: stderr.close() raise
import os import subprocess from ..platform_name import platform_name if platform_name() == 'windows': from .windows import * else: from .posix import * class shell_list(list): """A special subclass of list used to mark that this command line uses special shell characters.""" pass def execute(args, shell=False, env=None, quiet=False): stderr = None if quiet: stderr = open(os.devnull, 'wb') try: result = subprocess.check_output( args, universal_newlines=True, shell=shell, env=env, stderr=stderr ) finally: if quiet: stderr.close() return result
Fix closing /dev/null when executing in quiet mode
Fix closing /dev/null when executing in quiet mode
Python
bsd-3-clause
jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000
--- +++ @@ -20,10 +20,10 @@ if quiet: stderr = open(os.devnull, 'wb') try: - return subprocess.check_output( + result = subprocess.check_output( args, universal_newlines=True, shell=shell, env=env, stderr=stderr ) - except: + finally: if quiet: stderr.close() - raise + return result
daaf58639148b220d6dcce13e054374a68f9b01a
testfixtures/tests/test_docs.py
testfixtures/tests/test_docs.py
# Copyright (c) 2009 Simplistix Ltd # # See license.txt for more details. import unittest from glob import glob from os.path import dirname,join,pardir from doctest import DocFileSuite,REPORT_NDIFF,ELLIPSIS options = REPORT_NDIFF|ELLIPSIS def test_suite(): return unittest.TestSuite(( DocFileSuite( *glob(join(dirname(__file__),pardir,'docs','*.txt')), module_relative=False, optionflags=options ), ))
# Copyright (c) 2009 Simplistix Ltd # # See license.txt for more details. from glob import glob from manuel import doctest,codeblock from manuel.testing import TestSuite from os.path import dirname,join,pardir from doctest import REPORT_NDIFF,ELLIPSIS def test_suite(): m = doctest.Manuel(optionflags=REPORT_NDIFF|ELLIPSIS) m += codeblock.Manuel() return TestSuite( m, *glob(join(dirname(__file__),pardir,pardir,'docs','*.txt')) )
Use Manuel instead of doctest.
Use Manuel instead of doctest.
Python
mit
nebulans/testfixtures,Simplistix/testfixtures
--- +++ @@ -2,19 +2,16 @@ # # See license.txt for more details. -import unittest - from glob import glob +from manuel import doctest,codeblock +from manuel.testing import TestSuite from os.path import dirname,join,pardir -from doctest import DocFileSuite,REPORT_NDIFF,ELLIPSIS - -options = REPORT_NDIFF|ELLIPSIS +from doctest import REPORT_NDIFF,ELLIPSIS def test_suite(): - return unittest.TestSuite(( - DocFileSuite( - *glob(join(dirname(__file__),pardir,'docs','*.txt')), - module_relative=False, - optionflags=options - ), - )) + m = doctest.Manuel(optionflags=REPORT_NDIFF|ELLIPSIS) + m += codeblock.Manuel() + return TestSuite( + m, + *glob(join(dirname(__file__),pardir,pardir,'docs','*.txt')) + )
a8726f9acf3d2a1b0287046d0ffb5236892c6535
tests/django_test_app/models.py
tests/django_test_app/models.py
# -*- coding: utf-8 -*- # Copyright (c) 2012-2013 Raphaël Barrois from django.db import models from semantic_version import django_fields as semver_fields class VersionModel(models.Model): version = semver_fields.VersionField(verbose_name='my version') spec = semver_fields.SpecField(verbose_name='my spec') class PartialVersionModel(models.Model): partial = semver_fields.VersionField(partial=True, verbose_name='partial version') optional = semver_fields.VersionField(verbose_name='optional version', blank=True, null=True) optional_spec = semver_fields.SpecField(verbose_name='optional spec', blank=True, null=True) class CoerceVersionModel(models.Model): version = semver_fields.VersionField(verbose_name='my version', coerce=True) partial = semver_fields.VersionField(verbose_name='partial version', coerce=True, partial=True)
# -*- coding: utf-8 -*- # Copyright (c) 2012-2013 Raphaël Barrois try: from django.db import models django_loaded = True except ImportError: django_loaded = False if django_loaded: from semantic_version import django_fields as semver_fields class VersionModel(models.Model): version = semver_fields.VersionField(verbose_name='my version') spec = semver_fields.SpecField(verbose_name='my spec') class PartialVersionModel(models.Model): partial = semver_fields.VersionField(partial=True, verbose_name='partial version') optional = semver_fields.VersionField(verbose_name='optional version', blank=True, null=True) optional_spec = semver_fields.SpecField(verbose_name='optional spec', blank=True, null=True) class CoerceVersionModel(models.Model): version = semver_fields.VersionField(verbose_name='my version', coerce=True) partial = semver_fields.VersionField(verbose_name='partial version', coerce=True, partial=True)
Fix test running when Django isn't available.
tests: Fix test running when Django isn't available.
Python
bsd-2-clause
rbarrois/python-semanticversion,marcelometal/python-semanticversion,mhrivnak/python-semanticversion,pombredanne/python-semanticversion
--- +++ @@ -1,21 +1,28 @@ # -*- coding: utf-8 -*- # Copyright (c) 2012-2013 Raphaël Barrois -from django.db import models -from semantic_version import django_fields as semver_fields +try: + from django.db import models + django_loaded = True +except ImportError: + django_loaded = False -class VersionModel(models.Model): - version = semver_fields.VersionField(verbose_name='my version') - spec = semver_fields.SpecField(verbose_name='my spec') +if django_loaded: + from semantic_version import django_fields as semver_fields -class PartialVersionModel(models.Model): - partial = semver_fields.VersionField(partial=True, verbose_name='partial version') - optional = semver_fields.VersionField(verbose_name='optional version', blank=True, null=True) - optional_spec = semver_fields.SpecField(verbose_name='optional spec', blank=True, null=True) + class VersionModel(models.Model): + version = semver_fields.VersionField(verbose_name='my version') + spec = semver_fields.SpecField(verbose_name='my spec') -class CoerceVersionModel(models.Model): - version = semver_fields.VersionField(verbose_name='my version', coerce=True) - partial = semver_fields.VersionField(verbose_name='partial version', coerce=True, partial=True) + class PartialVersionModel(models.Model): + partial = semver_fields.VersionField(partial=True, verbose_name='partial version') + optional = semver_fields.VersionField(verbose_name='optional version', blank=True, null=True) + optional_spec = semver_fields.SpecField(verbose_name='optional spec', blank=True, null=True) + + + class CoerceVersionModel(models.Model): + version = semver_fields.VersionField(verbose_name='my version', coerce=True) + partial = semver_fields.VersionField(verbose_name='partial version', coerce=True, partial=True)
2a867ea42e5ebe978ed41ef166893cb4a0e86de2
tests/multi_memory_mgmt_test.py
tests/multi_memory_mgmt_test.py
#! /usr/bin/env python # -*- coding: utf-8 -*- # vi:ts=4:et import pycurl import unittest import gc debug = False class MultiMemoryMgmtTest(unittest.TestCase): def test_opensocketfunction_collection(self): self.check_callback(pycurl.M_SOCKETFUNCTION) def test_seekfunction_collection(self): self.check_callback(pycurl.M_TIMERFUNCTION) def check_callback(self, callback): # Note: extracting a context manager seems to result in # everything being garbage collected even if the C code # does not clear the callback object_count = 0 gc.collect() # gc.collect() can create new objects... running it again here # settles tracked object count for the actual test below gc.collect() object_count = len(gc.get_objects()) c = pycurl.CurlMulti() c.setopt(callback, lambda x: True) del c gc.collect() new_object_count = len(gc.get_objects()) # it seems that GC sometimes collects something that existed # before this test ran, GH issues #273/#274 self.assertTrue(new_object_count in (object_count, object_count-1))
#! /usr/bin/env python # -*- coding: utf-8 -*- # vi:ts=4:et import pycurl import unittest import gc import flaky debug = False @flaky.flaky(max_runs=3) class MultiMemoryMgmtTest(unittest.TestCase): def test_opensocketfunction_collection(self): self.check_callback(pycurl.M_SOCKETFUNCTION) def test_seekfunction_collection(self): self.check_callback(pycurl.M_TIMERFUNCTION) def check_callback(self, callback): # Note: extracting a context manager seems to result in # everything being garbage collected even if the C code # does not clear the callback object_count = 0 gc.collect() # gc.collect() can create new objects... running it again here # settles tracked object count for the actual test below gc.collect() object_count = len(gc.get_objects()) c = pycurl.CurlMulti() c.setopt(callback, lambda x: True) del c gc.collect() new_object_count = len(gc.get_objects()) # it seems that GC sometimes collects something that existed # before this test ran, GH issues #273/#274 self.assertTrue(new_object_count in (object_count, object_count-1))
Mark multi memory management test flaky
Mark multi memory management test flaky
Python
lgpl-2.1
pycurl/pycurl,pycurl/pycurl,pycurl/pycurl
--- +++ @@ -5,9 +5,11 @@ import pycurl import unittest import gc +import flaky debug = False +@flaky.flaky(max_runs=3) class MultiMemoryMgmtTest(unittest.TestCase): def test_opensocketfunction_collection(self): self.check_callback(pycurl.M_SOCKETFUNCTION)
b8c4d7aabcd07fcba443558a02cdcb38d32009df
pages/tests.py
pages/tests.py
from django.test import TestCase from pages.models import * from django.test.client import Client class PagesTestCase(TestCase): fixtures = ['tests.json'] def test_01_add_page(self): """ Test that the add admin page could be displayed via the admin """ c = Client() c.login(username= 'batiste', password='b') response = c.get('/admin/pages/page/add/') assert(response.status_code == 200) def test_02_create_page(self): """ Test that a page can be created via the admin """ c = Client() c.login(username= 'batiste', password='b') page_data = {'title':'test page', 'slug':'test-page', 'language':'en', 'sites':[1], 'status':1} response = c.post('/admin/pages/page/add/', page_data) self.assertRedirects(response, '/admin/pages/page/')
from django.test import TestCase import settings from pages.models import * from django.test.client import Client page_data = {'title':'test page', 'slug':'test-page', 'language':'en', 'sites':[1], 'status':1} class PagesTestCase(TestCase): fixtures = ['tests.json'] def test_01_add_page(self): """ Test that the add admin page could be displayed via the admin """ c = Client() c.login(username= 'batiste', password='b') response = c.get('/admin/pages/page/add/') assert(response.status_code == 200) def test_02_create_page(self): """ Test that a page can be created via the admin """ c = Client() c.login(username= 'batiste', password='b') response = c.post('/admin/pages/page/add/', page_data) self.assertRedirects(response, '/admin/pages/page/') slug_content = Content.objects.get_page_slug(page_data['slug']) assert(slug_content is not None) page = slug_content.page assert(page.title() == page_data['title']) assert(page.slug() == page_data['slug']) def test_03_slug_collision(self): """ Test a slug collision """ c = Client() c.login(username= 'batiste', password='b') response = c.post('/admin/pages/page/add/', page_data) self.assertRedirects(response, '/admin/pages/page/') page1 = Content.objects.get_page_slug(page_data['slug']).page response = c.post('/admin/pages/page/add/', page_data) assert(response.status_code == 200) settings.PAGE_UNIQUE_SLUG_REQUIRED = False response = c.post('/admin/pages/page/add/', page_data) self.assertRedirects(response, '/admin/pages/page/') page2 = Content.objects.get_page_slug(page_data['slug']).page assert(page1.id != page2.id)
Add a test for slug collision
Add a test for slug collision git-svn-id: 54fea250f97f2a4e12c6f7a610b8f07cb4c107b4@320 439a9e5f-3f3e-0410-bc46-71226ad0111b
Python
bsd-3-clause
pombredanne/django-page-cms-1,remik/django-page-cms,pombredanne/django-page-cms-1,oliciv/django-page-cms,oliciv/django-page-cms,pombredanne/django-page-cms-1,remik/django-page-cms,oliciv/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,remik/django-page-cms,batiste/django-page-cms,batiste/django-page-cms,remik/django-page-cms,akaihola/django-page-cms,akaihola/django-page-cms
--- +++ @@ -1,10 +1,13 @@ from django.test import TestCase - +import settings from pages.models import * from django.test.client import Client +page_data = {'title':'test page', 'slug':'test-page', 'language':'en', 'sites':[1], 'status':1} + class PagesTestCase(TestCase): fixtures = ['tests.json'] + def test_01_add_page(self): """ @@ -22,6 +25,31 @@ """ c = Client() c.login(username= 'batiste', password='b') - page_data = {'title':'test page', 'slug':'test-page', 'language':'en', 'sites':[1], 'status':1} response = c.post('/admin/pages/page/add/', page_data) self.assertRedirects(response, '/admin/pages/page/') + slug_content = Content.objects.get_page_slug(page_data['slug']) + assert(slug_content is not None) + page = slug_content.page + assert(page.title() == page_data['title']) + assert(page.slug() == page_data['slug']) + + def test_03_slug_collision(self): + """ + Test a slug collision + """ + c = Client() + c.login(username= 'batiste', password='b') + response = c.post('/admin/pages/page/add/', page_data) + self.assertRedirects(response, '/admin/pages/page/') + page1 = Content.objects.get_page_slug(page_data['slug']).page + + response = c.post('/admin/pages/page/add/', page_data) + assert(response.status_code == 200) + + settings.PAGE_UNIQUE_SLUG_REQUIRED = False + response = c.post('/admin/pages/page/add/', page_data) + self.assertRedirects(response, '/admin/pages/page/') + page2 = Content.objects.get_page_slug(page_data['slug']).page + assert(page1.id != page2.id) + +
89c906fc0ff6490de07543292c6e1e738652e2ef
pelicanconf.py
pelicanconf.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals AUTHOR = u'Leonardo Zhou' SITENAME = u'\u4e91\u7ffc\u56fe\u5357' SITEURL = '' TIMEZONE = 'Asia/Shanghai' DEFAULT_LANG = u'zh' # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None # Blogroll LINKS = (('Pelican', 'http://getpelican.com/'), ('Python.org', 'http://python.org/'), ('Jinja2', 'http://jinja.pocoo.org/'), ('You can modify those links in your config file', '#'),) # Social widget SOCIAL = (('You can add links in your config file', '#'), ('Another social link', '#'),) DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing RELATIVE_URLS = True STATIC_PATHS = ['images', 'extra/CNAME'] EXTRA_PATH_METADATA = {'extra/CNAME': {'path': 'CNAME'},}
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals AUTHOR = u'Leonardo Zhou' SITENAME = u'\u4e91\u7ffc\u56fe\u5357' SITEURL = '' TIMEZONE = 'Asia/Shanghai' DEFAULT_LANG = u'zh' # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None # Blogroll LINKS = (('Pelican', 'http://getpelican.com/'), ('Python.org', 'http://python.org/'), ('Jinja2', 'http://jinja.pocoo.org/'), ('You can modify those links in your config file', '#'),) # Social widget SOCIAL = (('You can add links in your config file', '#'), ('Another social link', '#'),) DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing RELATIVE_URLS = True STATIC_PATHS = ['images', 'extra/CNAME'] EXTRA_PATH_METADATA = {'extra/CNAME': {'path': 'CNAME'},} THEME = 'themes/BT3-Flat-4zha' ARTICLE_URL = '{slug}/' ARTICLE_SAVE_AS = '{slug}/index.html'
Change custom theme settings and url pattern
Change custom theme settings and url pattern
Python
cc0-1.0
glasslion/zha,glasslion/zha-beta,glasslion/zha,glasslion/zha-beta,glasslion/zha-beta,glasslion/zha
--- +++ @@ -32,3 +32,8 @@ STATIC_PATHS = ['images', 'extra/CNAME'] EXTRA_PATH_METADATA = {'extra/CNAME': {'path': 'CNAME'},} + +THEME = 'themes/BT3-Flat-4zha' + +ARTICLE_URL = '{slug}/' +ARTICLE_SAVE_AS = '{slug}/index.html'
0ac40dd99823ccff795361c9e0f49409d9d4d95e
bpython/test/test_keys.py
bpython/test/test_keys.py
#!/usr/bin/env python import unittest import bpython.keys as keys class TestKeys(unittest.TestCase): def test_keymap_map(self): """Verify KeyMap.map being a dictionary with the correct length.""" self.assertEqual(len(keys.key_dispatch.map), 43) def test_keymap_setitem(self): """Verify keys.KeyMap correctly setting items.""" keys.key_dispatch['simon'] = 'awesome'; self.assertEqual(keys.key_dispatch['simon'], 'awesome') def test_keymap_delitem(self): """Verify keys.KeyMap correctly removing items.""" keys.key_dispatch['simon'] = 'awesome' del keys.key_dispatch['simon'] if 'simon' in keys.key_dispatch.map: raise Exception('Key still exists in dictionary') def test_keymap_getitem(self): """Verify keys.KeyMap correctly looking up items.""" self.assertEqual(keys.key_dispatch['C-['], (chr(27), '^[')) self.assertEqual(keys.key_dispatch['F11'], ('KEY_F(11)',)) self.assertEqual(keys.key_dispatch['C-a'], ('\x01', '^A')) def test_keymap_keyerror(self): """Verify keys.KeyMap raising KeyError when getting undefined key""" def raiser(): keys.key_dispatch['C-asdf'] keys.key_dispatch['C-qwerty'] self.assertRaises(KeyError, raiser); if __name__ == '__main__': unittest.main()
#!/usr/bin/env python import unittest import bpython.keys as keys class TestKeys(unittest.TestCase): def test_keymap_getitem(self): """Verify keys.KeyMap correctly looking up items.""" self.assertEqual(keys.key_dispatch['C-['], (chr(27), '^[')) self.assertEqual(keys.key_dispatch['F11'], ('KEY_F(11)',)) self.assertEqual(keys.key_dispatch['C-a'], ('\x01', '^A')) def test_keymap_keyerror(self): """Verify keys.KeyMap raising KeyError when getting undefined key""" def raiser(): keys.key_dispatch['C-asdf'] keys.key_dispatch['C-qwerty'] self.assertRaises(KeyError, raiser); if __name__ == '__main__': unittest.main()
Add __delitem__, and dict length checking to tests for keys
Add __delitem__, and dict length checking to tests for keys
Python
mit
myint-archive/bpython,hirochachacha/apython,thomasballinger/old-bpython-with-hy-support
--- +++ @@ -3,22 +3,6 @@ import bpython.keys as keys class TestKeys(unittest.TestCase): - def test_keymap_map(self): - """Verify KeyMap.map being a dictionary with the correct length.""" - self.assertEqual(len(keys.key_dispatch.map), 43) - - def test_keymap_setitem(self): - """Verify keys.KeyMap correctly setting items.""" - keys.key_dispatch['simon'] = 'awesome'; - self.assertEqual(keys.key_dispatch['simon'], 'awesome') - - def test_keymap_delitem(self): - """Verify keys.KeyMap correctly removing items.""" - keys.key_dispatch['simon'] = 'awesome' - del keys.key_dispatch['simon'] - if 'simon' in keys.key_dispatch.map: - raise Exception('Key still exists in dictionary') - def test_keymap_getitem(self): """Verify keys.KeyMap correctly looking up items.""" self.assertEqual(keys.key_dispatch['C-['], (chr(27), '^['))
aedd144895d6ff6da0766d935cd0221985fccca8
kaf2html.py
kaf2html.py
"""Script to generate an HTML page from a KAF file that shows the text contents including line numbers. """ from bs4 import BeautifulSoup with open('data/minnenijd.kaf') as f: xml_doc = BeautifulSoup(f) output_html = ['<html><head>', '<meta http-equiv="Content-Type" content="text/html; ' 'charset=utf-8">', '</head>', '<body>', '<p>'] current_para = None new_para = False current_sent = None for token in xml_doc('wf'): if token['para'] != current_para: current_para = token['para'] output_html.append('</p><p>') new_para = True if token['sent'] != current_sent: current_sent = token['sent'] if not new_para: output_html.append('<br>') output_html.append(str(current_sent)) output_html.append(': ') new_para = False # exctract text from cdata (waarom is dat nou weer zo!) output_html.append(token.text) output_html.append('</p>') html = BeautifulSoup(' '.join(output_html)) print html.prettify().encode('utf-8')
"""Script to generate an HTML page from a KAF file that shows the text contents including line numbers. """ from bs4 import BeautifulSoup import sys xml_doc = None if len(sys.argv) < 2: print 'Please provide a kaf input file.' print 'Usage: python kaf2html.py <kaf input>' sys.exit(1) else: with open(sys.argv[1]) as f: xml_doc = BeautifulSoup(f) output_html = ['<html><head>', '<meta http-equiv="Content-Type" content="text/html; ' 'charset=utf-8">', '</head>', '<body>', '<p>'] current_para = None new_para = False current_sent = None for token in xml_doc('wf'): if token['para'] != current_para: current_para = token['para'] output_html.append('</p><p>') new_para = True if token['sent'] != current_sent: current_sent = token['sent'] if not new_para: output_html.append('<br>') output_html.append(str(current_sent)) output_html.append(': ') new_para = False # exctract text from cdata (waarom is dat nou weer zo!) output_html.append(token.text) output_html.append('</p>') html = BeautifulSoup(' '.join(output_html)) print html.prettify().encode('utf-8')
Read kaf input from command line argument
Read kaf input from command line argument The kaf input file used in the script is read from the command line.
Python
apache-2.0
NLeSC/embodied-emotions-scripts,NLeSC/embodied-emotions-scripts
--- +++ @@ -2,10 +2,18 @@ including line numbers. """ from bs4 import BeautifulSoup +import sys -with open('data/minnenijd.kaf') as f: - xml_doc = BeautifulSoup(f) +xml_doc = None + +if len(sys.argv) < 2: + print 'Please provide a kaf input file.' + print 'Usage: python kaf2html.py <kaf input>' + sys.exit(1) +else: + with open(sys.argv[1]) as f: + xml_doc = BeautifulSoup(f) output_html = ['<html><head>', '<meta http-equiv="Content-Type" content="text/html; '
6661c7afe060e21b29483cb01d30473211cef830
timepiece/urls.py
timepiece/urls.py
from django.core.urlresolvers import reverse from django.http import HttpResponsePermanentRedirect from django.conf.urls import patterns, include, url urlpatterns = patterns('', # Redirect the base URL to the dashboard. url(r'^$', lambda r: HttpResponsePermanentRedirect(reverse('dashboard'))), url('', include('timepiece.crm.urls')), url('', include('timepiece.contracts.urls')), url('', include('timepiece.entries.urls')), url('', include('timepiece.reports.urls')), )
from django.conf.urls import patterns, include, url from django.core.urlresolvers import reverse_lazy from django.views.generic import RedirectView urlpatterns = patterns('', # Redirect the base URL to the dashboard. url(r'^$', RedirectView.as_view(url=reverse_lazy('dashboard')), url('', include('timepiece.crm.urls')), url('', include('timepiece.contracts.urls')), url('', include('timepiece.entries.urls')), url('', include('timepiece.reports.urls')), )
Use generic RedirectView rather than lambda function
Use generic RedirectView rather than lambda function
Python
mit
dannybrowne86/django-timepiece,caktus/django-timepiece,josesanch/django-timepiece,caktus/django-timepiece,dannybrowne86/django-timepiece,gaga3966/django-timepiece,arbitrahj/django-timepiece,arbitrahj/django-timepiece,gaga3966/django-timepiece,josesanch/django-timepiece,arbitrahj/django-timepiece,BocuStudio/django-timepiece,caktus/django-timepiece,gaga3966/django-timepiece,BocuStudio/django-timepiece,dannybrowne86/django-timepiece,BocuStudio/django-timepiece,josesanch/django-timepiece
--- +++ @@ -1,12 +1,11 @@ -from django.core.urlresolvers import reverse -from django.http import HttpResponsePermanentRedirect - from django.conf.urls import patterns, include, url +from django.core.urlresolvers import reverse_lazy +from django.views.generic import RedirectView urlpatterns = patterns('', # Redirect the base URL to the dashboard. - url(r'^$', lambda r: HttpResponsePermanentRedirect(reverse('dashboard'))), + url(r'^$', RedirectView.as_view(url=reverse_lazy('dashboard')), url('', include('timepiece.crm.urls')), url('', include('timepiece.contracts.urls')),
995d0067dd1bd1823e3a7cb4fbc8e4ad1bf8208c
registration/__init__.py
registration/__init__.py
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
from django.conf import settings from django.core.exceptions import ImproperlyConfigured # TODO: When Python 2.7 is released this becomes a try/except falling # back to Django's implementation. from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
Add reminder to myself to to importlib fallback.
Add reminder to myself to to importlib fallback.
Python
bsd-3-clause
bruth/django-registration2,ogirardot/django-registration,wuyuntao/django-registration,danielsokolowski/django-registration,andresdouglas/django-registration,stefankoegl/django-registration-couchdb,stefankoegl/django-couchdb-utils,schmidsi/django-registration,wuyuntao/django-registration,stefankoegl/django-registration-couchdb,stefankoegl/django-couchdb-utils,ratio/django-registration,stefankoegl/django-registration-couchdb,stefankoegl/django-couchdb-utils,danielsokolowski/django-registration,ogirardot/django-registration
--- +++ @@ -1,5 +1,8 @@ from django.conf import settings from django.core.exceptions import ImproperlyConfigured + +# TODO: When Python 2.7 is released this becomes a try/except falling +# back to Django's implementation. from django.utils.importlib import import_module def get_backend():
6eacc0a0736edc410c011003986831b5f58da03e
tests/command_test.py
tests/command_test.py
import os, sys import unittest class SqliteTest(unittest.TestCase): TESTING_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), 'testing_dir')) def test_command(self): command = 'diary generate sqlite %s/log.sqlite3' % self.TESTING_DIR os.system(command) self.assertTrue(os.path.exists(os.path.join(self.TESTING_DIR, 'log.sqlite3'))) def test_command_no_path_given(self): command = 'diary generate sqlite' os.system(command) target_path = os.path.join(os.getcwd(), 'log.sqlite3') self.assertTrue(os.path.exists(target_path)) os.remove(target_path) def test_command_specific_name_given(self): command = 'diary generate sqlite mylog.sqlite3' os.system(command) target_path = os.path.join(os.getcwd(), 'mylog.sqlite3') self.assertTrue(os.path.exists(target_path)) os.remove(target_path) if __name__ == '__main__': unittest.main()
import os, sys import unittest class SqliteTest(unittest.TestCase): TESTING_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), 'testing_dir')) def test_command(self): command = 'diary generate sqlite %s/log.sqlite3' % self.TESTING_DIR os.system(command) self.assertTrue(os.path.exists(os.path.join(self.TESTING_DIR, 'log.sqlite3'))) def test_command_no_path_given(self): command = 'diary generate sqlite' os.system(command) target_path = os.path.join(os.getcwd(), 'log.sqlite3') self.assertTrue(os.path.exists(target_path)) os.remove(target_path) def test_command_specific_name_given(self): command = 'diary generate sqlite mylog.sqlite3' os.system(command) target_path = os.path.join(os.getcwd(), 'mylog.sqlite3') self.assertTrue(os.path.exists(target_path)) os.remove(target_path) def test_command_weird_extension(self): command = 'diary generate sqlite mylog.diary.log' os.system(command) target_path = os.path.join(os.getcwd(), 'mylog.diary.log') self.assertTrue(os.path.exists(target_path)) os.remove(target_path) if __name__ == '__main__': unittest.main()
Add test for odd extension to diary command
Add test for odd extension to diary command
Python
mit
GreenVars/diary
--- +++ @@ -25,6 +25,12 @@ self.assertTrue(os.path.exists(target_path)) os.remove(target_path) + def test_command_weird_extension(self): + command = 'diary generate sqlite mylog.diary.log' + os.system(command) + target_path = os.path.join(os.getcwd(), 'mylog.diary.log') + self.assertTrue(os.path.exists(target_path)) + os.remove(target_path) if __name__ == '__main__': unittest.main()
abef969505fc5cb30367a4c16c7daf1205c1c2aa
tests/test_twisted.py
tests/test_twisted.py
from __future__ import absolute_import, unicode_literals from unittest import skipUnless from prometheus_client import Counter from prometheus_client import CollectorRegistry, generate_latest try: from prometheus_client.twisted import MetricsResource from twisted.trial.unittest import TestCase from twisted.web.server import Site from twisted.web.resource import Resource from twisted.internet import reactor from twisted.web.client import Agent from twisted.web.client import readBody HAVE_TWISTED = True except ImportError: from unittest import TestCase HAVE_TWISTED = False class MetricsResourceTest(TestCase): @skipUnless(HAVE_TWISTED, "Don't have twisted installed.") def setUp(self): self.registry = CollectorRegistry() def test_reports_metrics(self): """ ``MetricsResource`` serves the metrics from the provided registry. """ c = Counter('cc', 'A counter', registry=self.registry) c.inc() root = Resource() root.putChild(b'metrics', MetricsResource(registry=self.registry)) server = reactor.listenTCP(0, Site(root)) self.addCleanup(server.stopListening) agent = Agent(reactor) port = server.getHost().port url = u"http://localhost:{port}/metrics".format(port=port) d = agent.request(b"GET", url.encode("ascii")) d.addCallback(readBody) d.addCallback(self.assertEqual, generate_latest(self.registry)) return d
from __future__ import absolute_import, unicode_literals from unittest import skipUnless from prometheus_client import Counter from prometheus_client import CollectorRegistry, generate_latest try: from prometheus_client.twisted import MetricsResource from twisted.trial.unittest import TestCase from twisted.web.server import Site from twisted.web.resource import Resource from twisted.internet import reactor from twisted.web.client import Agent from twisted.web.client import readBody HAVE_TWISTED = True except ImportError: from unittest import TestCase HAVE_TWISTED = False class MetricsResourceTest(TestCase): @skipUnless(HAVE_TWISTED, "Don't have twisted installed.") def setUp(self): self.registry = CollectorRegistry() def test_reports_metrics(self): """ ``MetricsResource`` serves the metrics from the provided registry. """ c = Counter('cc', 'A counter', registry=self.registry) c.inc() root = Resource() root.putChild(b'metrics', MetricsResource(registry=self.registry)) server = reactor.listenTCP(0, Site(root)) self.addCleanup(server.stopListening) agent = Agent(reactor) port = server.getHost().port url = "http://localhost:{port}/metrics".format(port=port) d = agent.request(b"GET", url.encode("ascii")) d.addCallback(readBody) d.addCallback(self.assertEqual, generate_latest(self.registry)) return d
Make tests pass on python3
Make tests pass on python3
Python
apache-2.0
thomaso-mirodin/client_python,prometheus/client_python
--- +++ @@ -39,7 +39,7 @@ agent = Agent(reactor) port = server.getHost().port - url = u"http://localhost:{port}/metrics".format(port=port) + url = "http://localhost:{port}/metrics".format(port=port) d = agent.request(b"GET", url.encode("ascii")) d.addCallback(readBody)
55a6d1204543b9fea3b955f39722779d153c3752
update_checker_app/__init__.py
update_checker_app/__init__.py
#!/usr/bin/env python from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy __version__ = '0.1' DB_URI = 'postgresql://@/updatechecker' APP = Flask(__name__) APP.config['SQLALCHEMY_DATABASE_URI'] = DB_URI APP.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(APP) # Delay these imports until db is defined from .controllers import * from .helpers import configure_logging configure_logging(APP) def main(): db.create_all() APP.run('', 65429, processes=4)
#!/usr/bin/env python from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from os import getenv __version__ = '0.1' DB_URI = 'postgresql://@/updatechecker' APP = Flask(__name__) APP.config['SQLALCHEMY_DATABASE_URI'] = DB_URI APP.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False APP.debug = getenv('DEBUG') db = SQLAlchemy(APP) # Delay these imports until db is defined from .controllers import * from .helpers import configure_logging configure_logging(APP) def main(): db.create_all() APP.run('', 65429, processes=4)
Enable debugging based on environment variable.
Enable debugging based on environment variable.
Python
bsd-2-clause
bboe/update_checker_app
--- +++ @@ -1,6 +1,7 @@ #!/usr/bin/env python from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy +from os import getenv __version__ = '0.1' @@ -9,6 +10,7 @@ APP = Flask(__name__) APP.config['SQLALCHEMY_DATABASE_URI'] = DB_URI APP.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False +APP.debug = getenv('DEBUG') db = SQLAlchemy(APP) # Delay these imports until db is defined
f2ecbe9020746a00c9f68918697a45b7f68e23fa
utils/tests/test_math_utils.py
utils/tests/test_math_utils.py
import numpy as np from nose2 import tools import utils @tools.params(((1000, 25), 10, 0), ((1000, 25), 10, 1), ((1000, 25), 77, 0) ) def test_online_statistics(shape, batch_size, axis): online_stats = utils.OnlineStatistics(axis=axis) X = np.random.random(shape) data_size = X.shape[axis] curr_ind = 0 while curr_ind < data_size: slices = [] for i in range(X.ndim): if i == axis: slices.append(slice(curr_ind, min(curr_ind + batch_size, data_size))) else: slices.append(slice(None)) batch_data = X[slices] online_stats.add_data(batch_data) curr_ind += batch_size mean = X.mean(axis=axis) std = X.std(axis=axis) assert np.allclose(mean, online_stats.mean) assert np.allclose(std, online_stats.std)
import numpy as np from nose2 import tools import utils @tools.params(((1000, 25), 10, 0), ((1000, 25), 10, 1), ((1000, 25), 77, 0), ((1000, 1, 2, 3), 10, (0, 3)) ) def test_online_statistics(shape, batch_size, axis): online_stats = utils.OnlineStatistics(axis=axis) X = np.random.random(shape) if isinstance(axis, (list, tuple)): data_size = np.prod([X.shape[ax] for ax in axis]) else: data_size = X.shape[axis] curr_ind = 0 while curr_ind < data_size: slices = [] for i in range(X.ndim): if i == axis: slices.append(slice(curr_ind, min(curr_ind + batch_size, data_size))) else: slices.append(slice(None)) batch_data = X[slices] online_stats.add_data(batch_data) curr_ind += batch_size mean = X.mean(axis=axis) std = X.std(axis=axis) assert np.allclose(mean, online_stats.mean) assert np.allclose(std, online_stats.std)
Add test case for OnlineStatistics where axis is a tuple
Add test case for OnlineStatistics where axis is a tuple
Python
mit
alexlee-gk/visual_dynamics
--- +++ @@ -5,12 +5,16 @@ @tools.params(((1000, 25), 10, 0), ((1000, 25), 10, 1), - ((1000, 25), 77, 0) + ((1000, 25), 77, 0), + ((1000, 1, 2, 3), 10, (0, 3)) ) def test_online_statistics(shape, batch_size, axis): online_stats = utils.OnlineStatistics(axis=axis) X = np.random.random(shape) - data_size = X.shape[axis] + if isinstance(axis, (list, tuple)): + data_size = np.prod([X.shape[ax] for ax in axis]) + else: + data_size = X.shape[axis] curr_ind = 0 while curr_ind < data_size: slices = []
3814a07c44c7d97a2ca4aa0f2741a913149d4acd
support/update-converity-branch.py
support/update-converity-branch.py
#!/usr/bin/env python # Update the coverity branch from the master branch. # It is not done automatically because Coverity Scan limits # the number of submissions per day. from __future__ import print_function import shutil, tempfile from subprocess import check_call class Git: def __init__(self, dir): self.dir = dir def __call__(self, *args): check_call(['git'] + list(args), cwd=self.dir) dir = tempfile.mkdtemp() try: git = Git(dir) git('clone', '-b', 'coverity', 'git@github.com:cppformat/cppformat.git', dir) git('merge', '-X', 'theirs', '--no-commit', 'origin/master') git('reset', 'HEAD', '.travis.yml') git('checkout', '--', '.travis.yml') git('commit', '-m', 'Update coverity branch') git('push') finally: shutil.rmtree(dir)
#!/usr/bin/env python # Update the coverity branch from the master branch. # It is not done automatically because Coverity Scan limits # the number of submissions per day. from __future__ import print_function import shutil, tempfile from subprocess import check_output, STDOUT class Git: def __init__(self, dir): self.dir = dir def __call__(self, *args): output = check_output(['git'] + list(args), cwd=self.dir, stderr=STDOUT) print(output) return output dir = tempfile.mkdtemp() try: git = Git(dir) git('clone', '-b', 'coverity', 'git@github.com:cppformat/cppformat.git', dir) output = git('merge', '-X', 'theirs', '--no-commit', 'origin/master') if 'Fast-forward' not in output: git('reset', 'HEAD', '.travis.yml') git('checkout', '--', '.travis.yml') git('commit', '-m', 'Update coverity branch') git('push') finally: shutil.rmtree(dir)
Handle fast forward in update-coverity-branch.py
Handle fast forward in update-coverity-branch.py
Python
bsd-2-clause
lightslife/cppformat,alabuzhev/fmt,mojoBrendan/fmt,dean0x7d/cppformat,Jopie64/cppformat,alabuzhev/fmt,cppformat/cppformat,alabuzhev/fmt,mojoBrendan/fmt,cppformat/cppformat,lightslife/cppformat,cppformat/cppformat,dean0x7d/cppformat,lightslife/cppformat,dean0x7d/cppformat,mojoBrendan/fmt,Jopie64/cppformat,Jopie64/cppformat
--- +++ @@ -5,23 +5,26 @@ from __future__ import print_function import shutil, tempfile -from subprocess import check_call +from subprocess import check_output, STDOUT class Git: def __init__(self, dir): self.dir = dir def __call__(self, *args): - check_call(['git'] + list(args), cwd=self.dir) + output = check_output(['git'] + list(args), cwd=self.dir, stderr=STDOUT) + print(output) + return output dir = tempfile.mkdtemp() try: git = Git(dir) git('clone', '-b', 'coverity', 'git@github.com:cppformat/cppformat.git', dir) - git('merge', '-X', 'theirs', '--no-commit', 'origin/master') - git('reset', 'HEAD', '.travis.yml') - git('checkout', '--', '.travis.yml') - git('commit', '-m', 'Update coverity branch') + output = git('merge', '-X', 'theirs', '--no-commit', 'origin/master') + if 'Fast-forward' not in output: + git('reset', 'HEAD', '.travis.yml') + git('checkout', '--', '.travis.yml') + git('commit', '-m', 'Update coverity branch') git('push') finally: shutil.rmtree(dir)
1c5cd470002b256677f9dc0a7c25c141880cd916
leonardo/widgets/__init__.py
leonardo/widgets/__init__.py
from leonardo.module.nav.mixins import NavigationWidgetMixin from leonardo.module.nav.models import NavigationWidget from leonardo.module.web.models import ListWidget, Widget from leonardo.module.web.widgets.mixins import (AuthContentProxyWidgetMixin, ContentProxyWidgetMixin, JSONContentMixin, ListWidgetMixin) __all__ = ('Widget', 'ListWidgetMixin', 'ContentProxyWidgetMixin', 'JSONContentMixin', 'AuthContentProxyWidgetMixin', 'ListWidget', 'NavigationWidgetMixin', 'NavigationWidget')
from leonardo.module.nav.mixins import NavigationWidgetMixin from leonardo.module.nav.models import NavigationWidget from leonardo.module.web.models import ListWidget, Widget from leonardo.module.web.widgets.mixins import (AuthContentProxyWidgetMixin, ContentProxyWidgetMixin, JSONContentMixin, ListWidgetMixin) from leonardo.utils.widgets import get_htmltext_widget __all__ = ('Widget', 'ListWidgetMixin', 'ContentProxyWidgetMixin', 'JSONContentMixin', 'AuthContentProxyWidgetMixin', 'ListWidget', 'NavigationWidgetMixin', 'NavigationWidget', 'get_htmltext_widget')
Include get htmltext widget in widgets module.
Include get htmltext widget in widgets module.
Python
bsd-3-clause
django-leonardo/django-leonardo,django-leonardo/django-leonardo,django-leonardo/django-leonardo,django-leonardo/django-leonardo
--- +++ @@ -7,6 +7,9 @@ JSONContentMixin, ListWidgetMixin) +from leonardo.utils.widgets import get_htmltext_widget + __all__ = ('Widget', 'ListWidgetMixin', 'ContentProxyWidgetMixin', 'JSONContentMixin', 'AuthContentProxyWidgetMixin', - 'ListWidget', 'NavigationWidgetMixin', 'NavigationWidget') + 'ListWidget', 'NavigationWidgetMixin', 'NavigationWidget', + 'get_htmltext_widget')
ffff57041cf8d2a13a941a8f0e39d92fe082f28a
welt2000/__init__.py
welt2000/__init__.py
from flask import Flask, request, session from flask.ext.babel import Babel from welt2000.__about__ import ( __title__, __summary__, __uri__, __version__, __author__, __email__, __license__, ) # noqa app = Flask(__name__) app.secret_key = '1234567890' babel = Babel(app) translations = ['en'] translations.extend(map(str, babel.list_translations())) @app.template_global() @babel.localeselector def get_locale(): lang = session.get('lang') if lang and lang in translations: return lang return request.accept_languages.best_match(translations) from welt2000 import views # noqa
from flask import Flask, request, session from flask.ext.babel import Babel from babel.core import negotiate_locale from welt2000.__about__ import ( __title__, __summary__, __uri__, __version__, __author__, __email__, __license__, ) # noqa app = Flask(__name__) app.secret_key = '1234567890' babel = Babel(app) translations = ['en'] translations.extend(map(str, babel.list_translations())) @app.template_global() @babel.localeselector def get_locale(): lang = session.get('lang') if lang and lang in translations: return lang preferred = map(lambda l: l[0], request.accept_languages) return negotiate_locale(preferred, translations) from welt2000 import views # noqa
Use babel.negotiate_locale() instead of best_match()
app: Use babel.negotiate_locale() instead of best_match() The babel version takes care of handling territory codes etc.
Python
mit
Turbo87/welt2000,Turbo87/welt2000
--- +++ @@ -1,5 +1,6 @@ from flask import Flask, request, session from flask.ext.babel import Babel +from babel.core import negotiate_locale from welt2000.__about__ import ( __title__, __summary__, __uri__, __version__, __author__, __email__, @@ -23,7 +24,8 @@ if lang and lang in translations: return lang - return request.accept_languages.best_match(translations) + preferred = map(lambda l: l[0], request.accept_languages) + return negotiate_locale(preferred, translations) from welt2000 import views # noqa
ef91f18f7fce637643ad58351b96e13c37eb8925
traits/qt/__init__.py
traits/qt/__init__.py
#------------------------------------------------------------------------------ # Copyright (c) 2010, Enthought Inc # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # # Author: Enthought Inc # Description: Qt API selector. Can be used to switch between pyQt and PySide #------------------------------------------------------------------------------ import os qt_api = os.environ.get('QT_API') if qt_api is None: try: import PySide qt_api = 'pyside' except ImportError: try: import PyQt4 qt_api = 'pyqt' except ImportError: raise ImportError('Cannot import PySide or PyQt4') if qt_api == 'pyqt': # Set PySide compatible APIs. import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) elif qt_api != 'pyside': raise RuntimeError('Invalid Qt API %r, valid values are: pyqt or pyside')
#------------------------------------------------------------------------------ # Copyright (c) 2010, Enthought Inc # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # # Author: Enthought Inc # Description: Qt API selector. Can be used to switch between pyQt and PySide #------------------------------------------------------------------------------ import os def prepare_pyqt4(): # Set PySide compatible APIs. import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) qt_api = os.environ.get('QT_API') if qt_api is None: try: import PySide qt_api = 'pyside' except ImportError: try: prepare_pyqt4() import PyQt4 qt_api = 'pyqt' except ImportError: raise ImportError('Cannot import PySide or PyQt4') elif qt_api == 'pyqt': prepare_pyqt4() elif qt_api != 'pyside': raise RuntimeError('Invalid Qt API %r, valid values are: pyqt or pyside')
Fix bug in the PyQt4 binding selection logic.
Fix bug in the PyQt4 binding selection logic.
Python
bsd-3-clause
burnpanck/traits,burnpanck/traits
--- +++ @@ -11,23 +11,28 @@ import os +def prepare_pyqt4(): + # Set PySide compatible APIs. + import sip + sip.setapi('QString', 2) + sip.setapi('QVariant', 2) + qt_api = os.environ.get('QT_API') + if qt_api is None: try: import PySide qt_api = 'pyside' except ImportError: try: + prepare_pyqt4() import PyQt4 qt_api = 'pyqt' except ImportError: raise ImportError('Cannot import PySide or PyQt4') -if qt_api == 'pyqt': - # Set PySide compatible APIs. - import sip - sip.setapi('QString', 2) - sip.setapi('QVariant', 2) +elif qt_api == 'pyqt': + prepare_pyqt4() elif qt_api != 'pyside': raise RuntimeError('Invalid Qt API %r, valid values are: pyqt or pyside')
9b020b87cede9dc2014c86946b3fa9bfedbd0577
tests/rules_tests/FromSymbolComputeTest.py
tests/rules_tests/FromSymbolComputeTest.py
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from unittest import main, TestCase from grammpy import Rule class FromSymbolComputeTest(TestCase): pass if __name__ == '__main__': main()
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from unittest import main, TestCase from grammpy import Rule class Simple(Rule): fromSymbol = 0 toSymbol = 1 class FromSymbolComputeTest(TestCase): def test_rules_simple(self): r = Simple.rules self.assertIsInstance(r, list) self.assertEqual(len(r), 1) self.assertIsInstance(r[0], tuple) self.assertEqual(r[0][0], [0]) self.assertEqual(r[0][1], [1]) def test_rule_simple(self): r = Simple.rule self.assertIsInstance(r, tuple) self.assertEqual(r[0][0], [0]) self.assertEqual(r[0][1], [1]) def test_leftRight_simple(self): self.assertEqual(Simple.left, [0]) self.assertEqual(Simple.right, [1]) if __name__ == '__main__': main()
Add tests of converting from symbol to rest of rule's property
Add tests of converting from symbol to rest of rule's property
Python
mit
PatrikValkovic/grammpy
--- +++ @@ -11,8 +11,29 @@ from grammpy import Rule +class Simple(Rule): + fromSymbol = 0 + toSymbol = 1 + + class FromSymbolComputeTest(TestCase): - pass + def test_rules_simple(self): + r = Simple.rules + self.assertIsInstance(r, list) + self.assertEqual(len(r), 1) + self.assertIsInstance(r[0], tuple) + self.assertEqual(r[0][0], [0]) + self.assertEqual(r[0][1], [1]) + + def test_rule_simple(self): + r = Simple.rule + self.assertIsInstance(r, tuple) + self.assertEqual(r[0][0], [0]) + self.assertEqual(r[0][1], [1]) + + def test_leftRight_simple(self): + self.assertEqual(Simple.left, [0]) + self.assertEqual(Simple.right, [1]) if __name__ == '__main__':
d44010acc32fcb78570cd34478d0f4e8f1cfa979
utility/dbproc.py
utility/dbproc.py
from discord.ext import commands from utils import * from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from member import Base, Member import discord import asyncio class Baydb: engine = create_engine('sqlite:///bayohwoolph.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() conn = engine.connect()
from discord.ext import commands from utils import * from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from member import Base, Member from config import Config import discord import asyncio class Baydb: engine = create_engine(Config.MAIN['dbpath']) Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() conn = engine.connect()
Move another usage of DB into ini file thing.
Move another usage of DB into ini file thing.
Python
agpl-3.0
dark-echo/Bay-Oh-Woolph,freiheit/Bay-Oh-Woolph
--- +++ @@ -3,13 +3,14 @@ from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from member import Base, Member +from config import Config import discord import asyncio class Baydb: - engine = create_engine('sqlite:///bayohwoolph.db') + engine = create_engine(Config.MAIN['dbpath']) Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession()
bb1722d4ac346823551c65861a8ac58f77dca2d0
setup.py
setup.py
from setuptools import setup import numpy from numpy.distutils.core import Extension import railgun from railgun import __author__, __version__, __license__ setup( name='railgun', version=__version__, packages=['railgun'], description=('ctypes utilities for faster and easier ' 'simulation programming in C and Python'), long_description=railgun.__doc__, author=__author__, author_email='aka.tkf@gmail.com', url='http://bitbucket.org/tkf/railgun/src', keywords='numerical simulation, research, ctypes, numpy, c', license=__license__, classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Science/Research", "Intended Audience :: Developers", "Operating System :: POSIX :: Linux", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Topic :: Scientific/Engineering", ], include_dirs = [numpy.get_include()], ext_modules=[ Extension( 'railgun.cstyle', sources=['src/cstylemodule.c'], extra_compile_args=["-fPIC", "-Wall"], ), ], )
from setuptools import setup import numpy from numpy.distutils.core import Extension import railgun from railgun import __author__, __version__, __license__ setup( name='railgun', version=__version__, packages=['railgun'], description=('ctypes utilities for faster and easier ' 'simulation programming in C and Python'), long_description=railgun.__doc__, author=__author__, author_email='aka.tkf@gmail.com', url='http://bitbucket.org/tkf/railgun/src', keywords='numerical simulation, research, ctypes, numpy, c', license=__license__, classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", "Intended Audience :: Developers", "Operating System :: POSIX :: Linux", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Topic :: Scientific/Engineering", ], include_dirs = [numpy.get_include()], ext_modules=[ Extension( 'railgun.cstyle', sources=['src/cstylemodule.c'], extra_compile_args=["-fPIC", "-Wall"], ), ], )
Change "Development Status" to beta
Change "Development Status" to beta
Python
mit
tkf/railgun,tkf/railgun
--- +++ @@ -17,7 +17,7 @@ keywords='numerical simulation, research, ctypes, numpy, c', license=__license__, classifiers=[ - "Development Status :: 3 - Alpha", + "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", "Intended Audience :: Developers", "Operating System :: POSIX :: Linux",
65e72a7688d6382bd07896cc8c86914277fca422
setup.py
setup.py
import setuptools setuptools.setup( name='mailcap-fix', version='0.1.1', description='A patched mailcap module that conforms to RFC 1524', long_description=open('README.rst', encoding='utf-8').read(), url='https://github.com/michael-lazar/mailcap_fix', author='Michael Lazar', author_email='lazar.michael22@gmail.com', license='UNLICENSE', keywords='mailcap 1524', packages=['mailcap_fix'], )
import setuptools from io import open setuptools.setup( name='mailcap-fix', version='0.1.1', description='A patched mailcap module that conforms to RFC 1524', long_description=open('README.rst', encoding='utf-8').read(), url='https://github.com/michael-lazar/mailcap_fix', author='Michael Lazar', author_email='lazar.michael22@gmail.com', license='UNLICENSE', keywords='mailcap 1524', packages=['mailcap_fix'], )
Use io framework from python 3.0 to fix build on python 2.7
Use io framework from python 3.0 to fix build on python 2.7
Python
unlicense
michael-lazar/mailcap_fix
--- +++ @@ -1,4 +1,5 @@ import setuptools +from io import open setuptools.setup( name='mailcap-fix',
7660b601d068652487cc97a704ae54acc33c6889
setup.py
setup.py
from distutils.core import setup setup(name='hermes-gui', version='0.1', packages=[ 'acme', 'acme.acmelab', 'acme.core', 'acme.core.views', ], package_data={ 'acme.acmelab': ['images/*'], 'acme.core': ['images/*.png'], } )
from distutils.core import setup setup(name='hermes-gui', version='0.1', packages=[ 'acme', 'acme.acmelab', 'acme.core', 'acme.core.views', ], package_data={ 'acme.acmelab': ['images/*'], 'acme.core': ['images/*.png'], }, scripts = ['hermes-gui.py'], )
Install the hermes-gui.py executable too
Install the hermes-gui.py executable too
Python
bsd-3-clause
certik/hermes-gui
--- +++ @@ -10,5 +10,6 @@ package_data={ 'acme.acmelab': ['images/*'], 'acme.core': ['images/*.png'], - } + }, + scripts = ['hermes-gui.py'], )
01d3027e568bcd191e7e25337c6597eb75b82789
setup.py
setup.py
#!/usr/bin/env python3 from setuptools import setup setup( name='todoman', description='A simple CalDav-based todo manager.', author='Hugo Osvaldo Barrera', author_email='hugo@barrera.io', url='https://github.com/pimutils/todoman', license='MIT', packages=['todoman'], entry_points={ 'console_scripts': [ 'todo = todoman.cli:cli', ] }, install_requires=[ open('requirements.txt').readlines() ], long_description=open('README.rst').read(), use_scm_version={ 'version_scheme': 'post-release', 'write_to': 'todoman/version.py', }, setup_requires=['setuptools_scm != 1.12.0', 'pytest-runner'], tests_require=['pytest'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: Console :: Curses', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Topic :: Office/Business :: Scheduling', 'Topic :: Utilities', ] )
#!/usr/bin/env python3 from setuptools import setup setup( name='todoman', description='A simple CalDav-based todo manager.', author='Hugo Osvaldo Barrera', author_email='hugo@barrera.io', url='https://github.com/pimutils/todoman', license='MIT', packages=['todoman'], entry_points={ 'console_scripts': [ 'todo = todoman.cli:cli', ] }, install_requires=[ open('requirements.txt').readlines() ], long_description=open('README.rst').read(), use_scm_version={ 'version_scheme': 'post-release', 'write_to': 'todoman/version.py', }, setup_requires=['setuptools_scm != 1.12.0', 'pytest-runner'], tests_require=['pytest'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: Console :: Curses', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Office/Business :: Scheduling', 'Topic :: Utilities', ] )
Add classifiers for supported python versions
Add classifiers for supported python versions
Python
isc
Sakshisaraswat/todoman,AnubhaAgrawal/todoman,hobarrera/todoman,pimutils/todoman,asalminen/todoman,rimshaakhan/todoman
--- +++ @@ -31,6 +31,11 @@ 'Environment :: Console :: Curses', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.3', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', 'Topic :: Office/Business :: Scheduling', 'Topic :: Utilities', ]
425de8b01ccaef3aa7b6ac988158609fa237e96b
setup.py
setup.py
from setuptools import setup, find_packages setup( version='0.43', name="pydvkbiology", packages=find_packages(), description='Python scripts used in my biology/bioinformatics research', author='DV Klopfenstein', author_email='music_pupil@yahoo.com', scripts=['./pydvkbiology/NCBI/cols.py'], license='BSD', url='http://github.com/dvklopfenstein/biocode', download_url='http://github.com/dvklopfenstein/biocode/tarball/0.1', keywords=['NCBI', 'biology', 'bioinformatics'], classifiers = [ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Topic :: Scientific/Engineering :: Bio-Informatics'], #install_requires=['sys', 're', 'os', 'collections'] # Potential other requires: # Entrez # math # matplotlib # numpy # requests # shutil )
from setuptools import setup, find_packages setup( version='0.44', name="pydvkbiology", packages=find_packages(), description='Python scripts used in my biology/bioinformatics research', author='DV Klopfenstein', author_email='music_pupil@yahoo.com', scripts=['./pydvkbiology/NCBI/cols.py'], license='BSD', url='http://github.com/dvklopfenstein/biocode', download_url='http://github.com/dvklopfenstein/biocode/tarball/0.1', keywords=['NCBI', 'biology', 'bioinformatics'], classifiers = [ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Topic :: Scientific/Engineering :: Bio-Informatics'], #install_requires=['sys', 're', 'os', 'collections'] # Potential other requires: # Entrez # math # matplotlib # numpy # requests # shutil )
Put latest additions in package.
Put latest additions in package.
Python
mit
dvklopfenstein/biocode
--- +++ @@ -1,7 +1,7 @@ from setuptools import setup, find_packages setup( - version='0.43', + version='0.44', name="pydvkbiology", packages=find_packages(), description='Python scripts used in my biology/bioinformatics research',
8e5e2dcd6e2743667cbcfb3284b6b01aa6606220
setup.py
setup.py
from setuptools import setup setup(name='pyramid_uniform', version='0.2', description='Form handling for Pyramid.', long_description='', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Framework :: Pyramid', ], keywords='pyramid forms validation rendering', url='http://github.com/cartlogic/pyramid_uniform', author='Scott Torborg', author_email='scott@cartlogic.com', install_requires=[ 'Pyramid', 'FormEncode', 'webhelpers2', 'six', # These are for tests. 'coverage', 'nose>=1.1', 'nose-cover3', ], license='MIT', packages=['pyramid_uniform'], test_suite='nose.collector', tests_require=['nose'], include_package_data=True, zip_safe=False)
from setuptools import setup, find_packages setup(name='pyramid_uniform', version='0.2', description='Form handling for Pyramid.', long_description='', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Framework :: Pyramid', ], keywords='pyramid forms validation rendering', url='http://github.com/cartlogic/pyramid_uniform', author='Scott Torborg', author_email='scott@cartlogic.com', install_requires=[ 'Pyramid', 'FormEncode', 'webhelpers2', 'six', # These are for tests. 'coverage', 'nose>=1.1', 'nose-cover3', ], license='MIT', packages=find_packages(), test_suite='nose.collector', tests_require=['nose'], include_package_data=True, zip_safe=False)
Use find_packages() instead of manually specifying package name, so that subpackages get included
Use find_packages() instead of manually specifying package name, so that subpackages get included
Python
mit
storborg/pyramid_uniform
--- +++ @@ -1,4 +1,4 @@ -from setuptools import setup +from setuptools import setup, find_packages setup(name='pyramid_uniform', @@ -29,7 +29,7 @@ 'nose-cover3', ], license='MIT', - packages=['pyramid_uniform'], + packages=find_packages(), test_suite='nose.collector', tests_require=['nose'], include_package_data=True,
37f137003d1b6e9f7361db38e0de109e0327fc42
setup.py
setup.py
from setuptools import setup, find_packages __version__ = "0.0.1" description = "A buildout recipe to create .deb packages" setup( name='vdt.recipe.debian', version=__version__, description=description, long_description=description, classifiers=[ "Framework :: Buildout", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Topic :: Software Development :: Libraries :: Python Modules", ], keywords='', author='Martijn Jacobs', author_email='martijn@devopsconsulting.nl', url='https://github.com/devopsconsulting/vdt.recipe.debian', license='', # include all packages in the egg, except the test package. packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), # for avoiding conflict have one namespace for all apc related eggs. namespace_packages=['vdt', 'vdt.recipe'], # include non python files include_package_data=True, zip_safe=False, # specify dependencies install_requires=[ 'setuptools', 'zc.buildout', 'vdt.versionplugin.buildout>=0.0.2' ], # mark test target to require extras. extras_require={ 'test': [ ] }, # generate scripts entry_points={ 'console_scripts': ['debianize = vdt.recipe.debian.debianize:debianize'], # noqs 'zc.buildout': ['default = vdt.recipe.debian.config:CreateConfig'] }, )
from setuptools import setup, find_packages __version__ = "0.0.1" description = "A buildout recipe to create .deb packages" setup( name='vdt.recipe.debian', version=__version__, description=description, long_description=description, classifiers=[ "Framework :: Buildout", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Topic :: Software Development :: Libraries :: Python Modules", ], keywords='', author='Martijn Jacobs', author_email='martijn@devopsconsulting.nl', url='https://github.com/devopsconsulting/vdt.recipe.debian', license='', # include all packages in the egg, except the test package. packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), # for avoiding conflict have one namespace for all apc related eggs. namespace_packages=['vdt', 'vdt.recipe'], # include non python files include_package_data=True, zip_safe=False, # specify dependencies install_requires=[ 'setuptools', 'zc.buildout', ], # mark test target to require extras. extras_require={ 'test': [ ] }, # generate scripts entry_points={ 'console_scripts': ['debianize = vdt.recipe.debian.debianize:debianize'], # noqs 'zc.buildout': ['default = vdt.recipe.debian.config:CreateConfig'] }, )
Remove dependency as plugin is configurable
Remove dependency as plugin is configurable
Python
bsd-3-clause
devopsconsulting/vdt.recipe.version
--- +++ @@ -32,7 +32,6 @@ install_requires=[ 'setuptools', 'zc.buildout', - 'vdt.versionplugin.buildout>=0.0.2' ], # mark test target to require extras. extras_require={
5de287f0b4dbe19ccb46048a4c1b4f792835ec42
setup.py
setup.py
#!/usr/bin/evn python2 from setuptools import setup, find_packages setup(name='pprof', version='0.9.6', packages=find_packages(), install_requires=["SQLAlchemy==1.0.4", "cloud==2.8.5", "plumbum==1.4.2", "regex==2015.5.28", "wheel==0.24.0", "parse==1.6.6", "virtualenv==13.1.0", "sphinxcontrib-napoleon"], author="Andreas Simbuerger", author_email="simbuerg@fim.uni-passau.de", description="This is the experiment driver for the pprof study", license="MIT", entry_points={ 'console_scripts': ['pprof=pprof.driver:main'] })
#!/usr/bin/evn python2 from setuptools import setup, find_packages setup(name='pprof', version='0.9.6', packages=find_packages(), install_requires=["SQLAlchemy==1.0.4", "cloud==2.8.5", "plumbum==1.4.2", "regex==2015.5.28", "wheel==0.24.0", "parse==1.6.6", "virtualenv==13.1.0", "sphinxcontrib-napoleon", "psycopg2"], author="Andreas Simbuerger", author_email="simbuerg@fim.uni-passau.de", description="This is the experiment driver for the pprof study", license="MIT", entry_points={ 'console_scripts': ['pprof=pprof.driver:main'] })
Add pyscopg2 to list of dependencies
Add pyscopg2 to list of dependencies
Python
mit
simbuerg/benchbuild,simbuerg/benchbuild
--- +++ @@ -6,7 +6,8 @@ packages=find_packages(), install_requires=["SQLAlchemy==1.0.4", "cloud==2.8.5", "plumbum==1.4.2", "regex==2015.5.28", "wheel==0.24.0", "parse==1.6.6", - "virtualenv==13.1.0", "sphinxcontrib-napoleon"], + "virtualenv==13.1.0", "sphinxcontrib-napoleon", + "psycopg2"], author="Andreas Simbuerger", author_email="simbuerg@fim.uni-passau.de", description="This is the experiment driver for the pprof study",
247a42a9839f03f01fb3228505798dffc0659ac9
setup.py
setup.py
#!/usr/bin/env python # Generated by jaraco.develop (https://bitbucket.org/jaraco/jaraco.develop) import io import setuptools with io.open('README.txt', encoding='utf-8') as readme: long_description = readme.read() with io.open('CHANGES.txt', encoding='utf-8') as changes: long_description += '\n\n' + changes.read() setup_params = dict( name='jaraco.functools', use_hg_version=True, author="Jason R. Coombs", author_email="jaraco@jaraco.com", description="jaraco.functools", long_description=long_description, url="https://bitbucket.org/jaraco/jaraco.functools", packages=setuptools.find_packages(), namespace_packages=['jaraco'], setup_requires=[ 'hgtools', 'pytest-runner', 'sphinx', ], tests_require=[ 'pytest', ], classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", ], ) if __name__ == '__main__': setuptools.setup(**setup_params)
#!/usr/bin/env python # Generated by jaraco.develop (https://bitbucket.org/jaraco/jaraco.develop) import io import sys import setuptools with io.open('README.txt', encoding='utf-8') as readme: long_description = readme.read() with io.open('CHANGES.txt', encoding='utf-8') as changes: long_description += '\n\n' + changes.read() needs_pytest = {'pytest', 'test'}.intersection(sys.argv) pytest_runner = ['pytest_runner'] if needs_pytest else [] needs_sphinx = {'release', 'build_sphinx', 'upload_docs'}.intersection(sys.argv) sphinx = ['sphinx'] if needs_sphinx else [] setup_params = dict( name='jaraco.functools', use_hg_version=True, author="Jason R. Coombs", author_email="jaraco@jaraco.com", description="jaraco.functools", long_description=long_description, url="https://bitbucket.org/jaraco/jaraco.functools", packages=setuptools.find_packages(), namespace_packages=['jaraco'], setup_requires=[ 'hgtools', ] + pytest_runner + sphinx, tests_require=[ 'pytest', ], classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", ], ) if __name__ == '__main__': setuptools.setup(**setup_params)
Make pytest-runner and sphinx optionlly required.
Make pytest-runner and sphinx optionlly required.
Python
mit
jaraco/jaraco.functools
--- +++ @@ -1,6 +1,7 @@ #!/usr/bin/env python # Generated by jaraco.develop (https://bitbucket.org/jaraco/jaraco.develop) import io +import sys import setuptools @@ -8,6 +9,11 @@ long_description = readme.read() with io.open('CHANGES.txt', encoding='utf-8') as changes: long_description += '\n\n' + changes.read() + +needs_pytest = {'pytest', 'test'}.intersection(sys.argv) +pytest_runner = ['pytest_runner'] if needs_pytest else [] +needs_sphinx = {'release', 'build_sphinx', 'upload_docs'}.intersection(sys.argv) +sphinx = ['sphinx'] if needs_sphinx else [] setup_params = dict( name='jaraco.functools', @@ -21,9 +27,7 @@ namespace_packages=['jaraco'], setup_requires=[ 'hgtools', - 'pytest-runner', - 'sphinx', - ], + ] + pytest_runner + sphinx, tests_require=[ 'pytest', ],
8e194b9598f71a5005601d64b82c563827f14351
setup.py
setup.py
from __future__ import absolute_import from setuptools import setup import json import version_handling version = "v%s.%s.%s" % version_handling.get_version() long_description="""TravisCI results .. image:: https://travis-ci.org/nanonyme/simplecpreprocessor.svg?tag=v%s """ % version setup( name = "simplecpreprocessor", version = version, author = "Seppo Yli-Olli", author_email = "seppo.yli-olli@iki.fi", description = "Simple C preprocessor for usage eg before CFFI", keywords = "python c preprocessor", license = "BSD", url = "https://github.com/nanonyme/simplecpreprocessor", py_modules=["simplecpreprocessor"], long_description=long_description, classifiers=[ "Development Status :: 4 - Beta", "Topic :: Utilities", "License :: OSI Approved :: BSD License", ], )
from __future__ import absolute_import from setuptools import setup import json import version_handling version = "%s.%s.%s" % version_handling.get_version() long_description="""TravisCI results .. image:: https://travis-ci.org/nanonyme/simplecpreprocessor.svg?tag=v%s """ % version setup( name = "simplecpreprocessor", version = version, author = "Seppo Yli-Olli", author_email = "seppo.yli-olli@iki.fi", description = "Simple C preprocessor for usage eg before CFFI", keywords = "python c preprocessor", license = "BSD", url = "https://github.com/nanonyme/simplecpreprocessor", py_modules=["simplecpreprocessor"], long_description=long_description, classifiers=[ "Development Status :: 4 - Beta", "Topic :: Utilities", "License :: OSI Approved :: BSD License", ], )
Remove the leading v from format
Remove the leading v from format
Python
mit
nanonyme/simplecpreprocessor
--- +++ @@ -3,7 +3,7 @@ import json import version_handling -version = "v%s.%s.%s" % version_handling.get_version() +version = "%s.%s.%s" % version_handling.get_version() long_description="""TravisCI results .. image:: https://travis-ci.org/nanonyme/simplecpreprocessor.svg?tag=v%s
68e6cad67a7b18c28377899bca1716f5e64d3d6f
setup.py
setup.py
from setuptools import setup, find_packages setup( name = "countries", version = "0.1.1-1", description = 'Provides models for a "complete" list of countries', author = 'David Danier', author_email = 'david.danier@team23.de', url = 'https://github.com/ddanier/django_countries', long_description=open('README.rst', 'r').read(), packages = [ 'countries', 'countries.management', 'countries.management.commands', 'countries.templatetags', 'countries.utils', ], package_data = { 'countries': ['fixtures/*', 'locale/*/LC_MESSAGES/*'], }, install_requires = [ 'Django >=1.2', ], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], )
from setuptools import setup, find_packages setup( name = "countries", version = "0.1.1-2", description = 'Provides models for a "complete" list of countries', author = 'David Danier', author_email = 'david.danier@team23.de', url = 'https://github.com/ddanier/django_countries', long_description=open('README.rst', 'r').read(), packages = [ 'countries', 'countries.management', 'countries.management.commands', 'countries.templatetags', 'countries.utils', 'countries.migrations', ], package_data = { 'countries': ['fixtures/*', 'locale/*/LC_MESSAGES/*'], }, install_requires = [ 'Django >=1.2', ], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], )
Include migrations in package data
Include migrations in package data
Python
bsd-3-clause
team23/django_countries
--- +++ @@ -2,7 +2,7 @@ setup( name = "countries", - version = "0.1.1-1", + version = "0.1.1-2", description = 'Provides models for a "complete" list of countries', author = 'David Danier', author_email = 'david.danier@team23.de', @@ -14,6 +14,7 @@ 'countries.management.commands', 'countries.templatetags', 'countries.utils', + 'countries.migrations', ], package_data = { 'countries': ['fixtures/*', 'locale/*/LC_MESSAGES/*'],
95af1be2d31685eca899549fe9656b137cedcf96
setup.py
setup.py
from setuptools import setup, find_packages import os version = __import__('cms_themes').__version__ install_requires = [ 'setuptools', 'django', 'django-cms', ] setup( name = "django-cms-themes", version = version, url = 'http://github.com/megamark16/django-cms-themes', license = 'BSD', platforms=['OS Independent'], description = "Load prepackaged themes (templates and accompanying media) into Django CMS projects through the admin", author = "Mark Ransom", author_email = 'megamark16@gmail.com', packages=find_packages(), install_requires = install_requires, include_package_data=True, zip_safe=False, classifiers = [ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], package_dir={ 'cms_themes': 'cms_themes', }, )
#!/usr/bin/env python2 from setuptools import setup, find_packages import os version = __import__('cms_themes').__version__ install_requires = [ 'setuptools', 'django', 'django-cms', ] setup( name = "django-cms-themes", version = version, url = 'http://github.com/megamark16/django-cms-themes', license = 'BSD', platforms=['OS Independent'], description = "Load prepackaged themes (templates and accompanying media) into Django CMS projects through the admin", author = "Mark Ransom", author_email = 'megamark16@gmail.com', packages=find_packages(), install_requires = install_requires, include_package_data=True, zip_safe=False, classifiers = [ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], package_dir={ 'cms_themes': 'cms_themes', }, )
Set python2 explicitly as interpreter
Set python2 explicitly as interpreter
Python
bsd-3-clause
MegaMark16/django-cms-themes
--- +++ @@ -1,3 +1,4 @@ +#!/usr/bin/env python2 from setuptools import setup, find_packages import os
f6cede5524061faee8ae0f4c0f7dd3ef8c05a0a7
setup.py
setup.py
# -*- coding: utf-8 -*- import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = os.path.join(here, 'README.rst') install_requirements = [ 'pybit', 'jsonpickle', 'requests', ] test_requirements = [] # These requirements are specifically for the legacy module. legacy_requirements = [] setup( name='roadrunners', version='1.0', author="Connexions/Rhaptos Team", author_email="info@cnx.org", long_description=open(README).read(), url='https://github.com/connexions/roadrunners', license='AGPL', # See also LICENSE.txt packages=find_packages(), include_package_data=True, install_requires=install_requirements, extras_require={ 'tests': test_requirements, 'legacy': legacy_requirements, }, entry_points = """\ """, )
# -*- coding: utf-8 -*- import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = os.path.join(here, 'README.rst') install_requirements = [ 'requests', # PyBit and dependencies 'pybit', # 'psycopg2', # 'amqplib', 'jsonpickle', ] test_requirements = [] # These requirements are specifically for the legacy module. legacy_requirements = [] setup( name='roadrunners', version='1.0', author="Connexions/Rhaptos Team", author_email="info@cnx.org", long_description=open(README).read(), url='https://github.com/connexions/roadrunners', license='AGPL', # See also LICENSE.txt packages=find_packages(), include_package_data=True, install_requires=install_requirements, extras_require={ 'tests': test_requirements, 'legacy': legacy_requirements, }, entry_points = """\ """, )
Put in the necessary pybit dependenies
Put in the necessary pybit dependenies
Python
agpl-3.0
Connexions/roadrunners,Connexions/roadrunners
--- +++ @@ -6,9 +6,12 @@ README = os.path.join(here, 'README.rst') install_requirements = [ + 'requests', + # PyBit and dependencies 'pybit', + # 'psycopg2', + # 'amqplib', 'jsonpickle', - 'requests', ] test_requirements = [] # These requirements are specifically for the legacy module.
08563ac150e6264ca3f57d720bc204998863fbb1
setup.py
setup.py
import os, sys try: from setuptools import setup except ImportError: from distutils.core import setup def main(): setup( name='stcrestclient', version= '1.8.3', author='Andrew Gillis', author_email='andrew.gillis@spirent.com', url='https://github.com/Spirent/py-stcrestclient', description='stcrestclient: Client modules for STC ReST API', long_description = 'See https://github.com/Spirent/py-stcrestclient#python-stc-rest-api-client-stcrestclient', license='http://www.opensource.org/licenses/mit-license.php', keywords='Spirent TestCenter API', classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS :: MacOS X', 'Topic :: Software Development :: Libraries', 'Topic :: Utilities', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3'], packages=['stcrestclient'], entry_points={ 'console_scripts': [ 'tccsh = stcrestclient.tccsh:main', 'stcinfo = stcrestclient.systeminfo:main'], }, install_requires=['requests>=2.7'], zip_safe=True, ) if __name__ == '__main__': main()
import os, sys try: from setuptools import setup except ImportError: from distutils.core import setup def main(): setup( name='stcrestclient', version= '1.8.3', author='Andrew Gillis', author_email='support@spirent.com', url='https://github.com/Spirent/py-stcrestclient', description='stcrestclient: Client modules for STC ReST API', long_description = 'See https://github.com/Spirent/py-stcrestclient#python-stc-rest-api-client-stcrestclient', license='http://www.opensource.org/licenses/mit-license.php', keywords='Spirent TestCenter API', classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS :: MacOS X', 'Topic :: Software Development :: Libraries', 'Topic :: Utilities', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3'], packages=['stcrestclient'], entry_points={ 'console_scripts': [ 'tccsh = stcrestclient.tccsh:main', 'stcinfo = stcrestclient.systeminfo:main'], }, install_requires=['requests>=2.7'], zip_safe=True, ) if __name__ == '__main__': main()
Update author email to Spirent support.
Update author email to Spirent support.
Python
mit
Spirent/py-stcrestclient
--- +++ @@ -10,7 +10,7 @@ name='stcrestclient', version= '1.8.3', author='Andrew Gillis', - author_email='andrew.gillis@spirent.com', + author_email='support@spirent.com', url='https://github.com/Spirent/py-stcrestclient', description='stcrestclient: Client modules for STC ReST API', long_description = 'See https://github.com/Spirent/py-stcrestclient#python-stc-rest-api-client-stcrestclient',
0d3553c38117d0f410d38a5f34510e8a87db10bd
setup.py
setup.py
#!/usr/bin/env python """A custom GeoKey extension for WeGovNow functionality.""" from os.path import join from setuptools import setup, find_packages name = 'geokey-wegovnow' version = __import__(name.replace('-', '_')).__version__ repository = join('https://github.com/ExCiteS', name) setup( name=name, version=version, description='GeoKey extension for WeGovNow functionality', url=repository, download_url=join(repository, 'tarball', version), author='ExCiteS', author_email='excites@ucl.ac.uk', license='MIT', packages=find_packages(exclude=['*.tests', '*.tests.*', 'tests.*']), include_package_data=True, install_requires=['django-material==0.10.0', 'geokey', 'django-allauth', 'django', 'requests'], )
#!/usr/bin/env python """A custom GeoKey extension for WeGovNow functionality.""" from os.path import join from setuptools import setup, find_packages name = 'geokey-wegovnow' version = __import__(name.replace('-', '_')).__version__ repository = join('https://github.com/ExCiteS', name) setup( name=name, version=version, description='GeoKey extension for WeGovNow functionality', url=repository, download_url=join(repository, 'tarball', version), author='ExCiteS', author_email='excites@ucl.ac.uk', license='MIT', packages=find_packages(exclude=['*.tests', '*.tests.*', 'tests.*']), include_package_data=True, install_requires=['django-material==0.10.0'], )
Remove extra requirements from install.
Remove extra requirements from install.
Python
mit
ExCiteS/geokey-wegovnow,ExCiteS/geokey-wegovnow
--- +++ @@ -21,5 +21,5 @@ license='MIT', packages=find_packages(exclude=['*.tests', '*.tests.*', 'tests.*']), include_package_data=True, - install_requires=['django-material==0.10.0', 'geokey', 'django-allauth', 'django', 'requests'], + install_requires=['django-material==0.10.0'], )
2683d93184b8f7b82ce0651c900f3c8b830af33b
setup.py
setup.py
import sys from setuptools import setup setup_requires = ['setuptools_scm'] if sys.argv[-1] in ('sdist', 'bdist_wheel'): setup_requires.append('setuptools-markdown') setup( name='tldr', author='Felix Yan', author_email='felixonmars@gmail.com', url='https://github.com/tldr-pages/tldr-python-client', description='command line client for tldr', long_description_markdown_filename='README.md', license='MIT', py_modules=['tldr'], scripts=['tldr.py'], install_requires=['six', 'termcolor', 'colorama'], tests_require=[ 'pytest-runner', ], setup_requires=setup_requires, use_scm_version=True, entry_points={ 'console_scripts': ['tldr = tldr:main'] }, classifiers=[ "Development Status :: 4 - Beta", "License :: OSI Approved :: MIT License", "Environment :: Console", "Intended Audience :: End Users/Desktop", "Natural Language :: English", "Operating System :: POSIX :: Linux", "Operating System :: MacOS :: MacOS X", "Operating System :: POSIX :: SunOS/Solaris", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Utilities", "Topic :: System" ] )
import sys from setuptools import setup setup_requires = ['setuptools_scm'] if sys.argv[-1] in ('sdist', 'bdist_wheel'): setup_requires.append('setuptools-markdown') setup( name='tldr', author='Felix Yan', author_email='felixonmars@gmail.com', url='https://github.com/tldr-pages/tldr-python-client', description='command line client for tldr', long_description_markdown_filename='README.md', license='MIT', py_modules=['tldr'], scripts=['tldr.py'], install_requires=['six', 'termcolor', 'colorama'], tests_require=[ 'pytest-runner', ], setup_requires=setup_requires, use_scm_version=True, entry_points={ 'console_scripts': ['tldr = tldr:main'] }, classifiers=[ "Development Status :: 4 - Beta", "License :: OSI Approved :: MIT License", "Environment :: Console", "Intended Audience :: End Users/Desktop", "Natural Language :: English", "Operating System :: POSIX :: Linux", "Operating System :: MacOS :: MacOS X", "Operating System :: POSIX :: SunOS/Solaris", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Topic :: Utilities", "Topic :: System" ] )
Add python 3.6 to support array
Add python 3.6 to support array
Python
mit
tldr-pages/tldr-python-client
--- +++ @@ -37,6 +37,7 @@ "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", + "Programming Language :: Python :: 3.6", "Topic :: Utilities", "Topic :: System" ]
eca14d9db21a6cdfdb47261af1a29f6fc294825a
accounts/backends.py
accounts/backends.py
"""Custom authentication backends""" from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend class SmarterModelBackend(ModelBackend): """Authentication backend that is less moronic that the default Django one""" def authenticate(self, request, username=None, password=None, **kwargs): """Avoids being a complete dick to users by fetching usernames case insensitively""" UserModel = get_user_model() # pylint: disable=invalid-name if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: case_insensitive_username_field = '{}__iexact'.format(UserModel.USERNAME_FIELD) user = UserModel._default_manager.get( # pylint: disable=protected-access **{case_insensitive_username_field: username} ) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a non-existing user (#20760). UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user
"""Custom authentication backends""" import logging from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend LOGGER = logging.getLogger(__name__) class SmarterModelBackend(ModelBackend): """Authentication backend that is less moronic that the default Django one""" def authenticate(self, request, username=None, password=None, **kwargs): """Avoids being a complete dick to users by fetching usernames case insensitively""" UserModel = get_user_model() # pylint: disable=invalid-name if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: case_insensitive_username_field = '{}__iexact'.format(UserModel.USERNAME_FIELD) user = UserModel._default_manager.get( # pylint: disable=protected-access **{case_insensitive_username_field: username} ) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a non-existing user (#20760). UserModel().set_password(password) except UserModel.MultipleObjectsReturned: # Usernames are migrated to be case insensitive but some existing # users will have duplicate usernames when all converted to # lowercase. If that's the case, try logging in the user with a # case sensitive password. return self.case_sensitive_authenticate(username, password) else: if user.check_password(password) and self.user_can_authenticate(user): return user def case_sensitive_authenticate(self, username, password): """Tries to authenticate any user with the username exactly as given This should resolve most issues regarding duplicate usernames. """ LOGGER.error("Duplicate username %s", username) UserModel = get_user_model() # pylint: disable=invalid-name user = UserModel._default_manager.get( # pylint: disable=protected-access username=username ) if user.check_password(password) and self.user_can_authenticate(user): return user
Add a case sensitive login for duplicate usernames
Add a case sensitive login for duplicate usernames
Python
agpl-3.0
lutris/website,lutris/website,lutris/website,lutris/website
--- +++ @@ -1,6 +1,9 @@ """Custom authentication backends""" +import logging from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend + +LOGGER = logging.getLogger(__name__) class SmarterModelBackend(ModelBackend): @@ -20,6 +23,24 @@ # Run the default password hasher once to reduce the timing # difference between an existing and a non-existing user (#20760). UserModel().set_password(password) + except UserModel.MultipleObjectsReturned: + # Usernames are migrated to be case insensitive but some existing + # users will have duplicate usernames when all converted to + # lowercase. If that's the case, try logging in the user with a + # case sensitive password. + return self.case_sensitive_authenticate(username, password) else: if user.check_password(password) and self.user_can_authenticate(user): return user + + def case_sensitive_authenticate(self, username, password): + """Tries to authenticate any user with the username exactly as given + This should resolve most issues regarding duplicate usernames. + """ + LOGGER.error("Duplicate username %s", username) + UserModel = get_user_model() # pylint: disable=invalid-name + user = UserModel._default_manager.get( # pylint: disable=protected-access + username=username + ) + if user.check_password(password) and self.user_can_authenticate(user): + return user
07806b972dd1bc308e1c7b032b78c7dd8db8810b
setup.py
setup.py
# -*- coding: utf-8 -*- import os from setuptools import setup src_dir = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(src_dir, 'README.txt')) as f: long_description = f.read() setup( name='PyENScript', version='0.1.0', description='A Python wrapper for the Evernote ENScript.exe executable', long_description=long_description, url='https://github.com/yglezfdez/pyenscript', author='Yasser Gonzalez Fernandez', author_email='contact@yglezfdez.com', license='Apache License Version 2.0', py_modules=['pyenscript'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
# -*- coding: utf-8 -*- import os import subprocess from setuptools import setup src_dir = os.path.abspath(os.path.dirname(__file__)) try: # Try to get the latest version string dynamically from git: # (latest version, commits since latest release, and commit SHA-1) git_args = ['git', '--work-tree', src_dir, '--git-dir', os.path.join(src_dir, '.git'), 'describe'] with open(os.devnull, 'w') as devnull: version = subprocess.check_output(git_args, stderr=devnull).strip() except subprocess.CalledProcessError: # Set statically if git repo not available version = '0.1.0' with open(os.path.join(src_dir, 'README.txt')) as f: long_description = f.read() setup(name='PyENScript', version=version, description='A Python wrapper for the Evernote ENScript.exe executable', long_description=long_description, url='https://github.com/yglezfdez/pyenscript', author='Yasser Gonzalez Fernandez', author_email='contact@yglezfdez.com', license='Apache License Version 2.0', py_modules=['pyenscript'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], )
Read version number from 'git describe' if available
Read version number from 'git describe' if available
Python
apache-2.0
yasserglez/pyenscript
--- +++ @@ -1,30 +1,42 @@ # -*- coding: utf-8 -*- import os +import subprocess from setuptools import setup src_dir = os.path.abspath(os.path.dirname(__file__)) + +try: + # Try to get the latest version string dynamically from git: + # (latest version, commits since latest release, and commit SHA-1) + git_args = ['git', '--work-tree', src_dir, + '--git-dir', os.path.join(src_dir, '.git'), 'describe'] + with open(os.devnull, 'w') as devnull: + version = subprocess.check_output(git_args, stderr=devnull).strip() +except subprocess.CalledProcessError: + # Set statically if git repo not available + version = '0.1.0' + with open(os.path.join(src_dir, 'README.txt')) as f: long_description = f.read() -setup( - name='PyENScript', - version='0.1.0', - description='A Python wrapper for the Evernote ENScript.exe executable', - long_description=long_description, - url='https://github.com/yglezfdez/pyenscript', - author='Yasser Gonzalez Fernandez', - author_email='contact@yglezfdez.com', - license='Apache License Version 2.0', - py_modules=['pyenscript'], - classifiers=[ - 'Development Status :: 4 - Beta', - 'Intended Audience :: Developers', - 'Topic :: Software Development :: Libraries :: Python Modules', - 'License :: OSI Approved :: Apache Software License', - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 3', - ], +setup(name='PyENScript', + version=version, + description='A Python wrapper for the Evernote ENScript.exe executable', + long_description=long_description, + url='https://github.com/yglezfdez/pyenscript', + author='Yasser Gonzalez Fernandez', + author_email='contact@yglezfdez.com', + license='Apache License Version 2.0', + py_modules=['pyenscript'], + classifiers=[ + 'Development Status :: 4 - Beta', + 'Intended Audience :: Developers', + 'Topic :: Software Development :: Libraries :: Python Modules', + 'License :: OSI Approved :: Apache Software License', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 3', + ], )
8026b40fe57f699b3c49bbc95753ab1c54cb35e8
setup.py
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import codecs from setuptools import setup def read(fname): file_path = os.path.join(os.path.dirname(__file__), fname) return codecs.open(file_path, encoding='utf-8').read() setup( name='pytest-mypy', version='0.2.0', author='Daniel Bader', author_email='mail@dbader.org', maintainer='Daniel Bader', maintainer_email='mail@dbader.org', license='MIT', url='https://github.com/dbader/pytest-mypy', description='Mypy static type checker plugin for Pytest', long_description=read('README.rst'), py_modules=['pytest_mypy'], install_requires=['pytest>=2.9.2', 'mypy-lang>=0.4.5'], classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Pytest', 'Intended Audience :: Developers', 'Topic :: Software Development :: Testing', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', ], entry_points={ 'pytest11': [ 'mypy = pytest_mypy', ], }, )
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import codecs from setuptools import setup def read(fname): file_path = os.path.join(os.path.dirname(__file__), fname) return codecs.open(file_path, encoding='utf-8').read() setup( name='pytest-mypy', version='0.2.0', author='Daniel Bader', author_email='mail@dbader.org', maintainer='Daniel Bader', maintainer_email='mail@dbader.org', license='MIT', url='https://github.com/dbader/pytest-mypy', description='Mypy static type checker plugin for Pytest', long_description=read('README.rst'), py_modules=['pytest_mypy'], install_requires=['pytest>=2.9.2', 'mypy>=0.470'], classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Pytest', 'Intended Audience :: Developers', 'Topic :: Software Development :: Testing', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', ], entry_points={ 'pytest11': [ 'mypy = pytest_mypy', ], }, )
Update dependency from mypy-lang to mypy
Update dependency from mypy-lang to mypy
Python
mit
dbader/pytest-mypy
--- +++ @@ -23,7 +23,7 @@ description='Mypy static type checker plugin for Pytest', long_description=read('README.rst'), py_modules=['pytest_mypy'], - install_requires=['pytest>=2.9.2', 'mypy-lang>=0.4.5'], + install_requires=['pytest>=2.9.2', 'mypy>=0.470'], classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Pytest',
684bf371bca1a7443e0f77a0f22b2f1ab5d5b4b4
setup.py
setup.py
from __future__ import absolute_import import subprocess from setuptools import setup try: pandoc = subprocess.Popen(['pandoc', 'README.md', '--to', 'rst'], stdout=subprocess.PIPE) readme = str(pandoc.communicate()[0]) except OSError: with open('README.md') as f: readme = f.read() setup( name="notedown", version="1.3.1", description="Convert markdown to IPython notebook.", long_description=readme, packages=['notedown'], author="Aaron O'Leary", author_email='dev@aaren.me', license='BSD 2-Clause', url='http://github.com/aaren/notedown', install_requires=['ipython[nbconvert] >= 3.0', 'pandoc-attributes'], entry_points={'console_scripts': ['notedown = notedown:cli', ]}, package_dir={'notedown': 'notedown'}, package_data={'notedown': ['templates/markdown.tpl']}, include_package_data=True, )
from __future__ import absolute_import import subprocess from setuptools import setup try: pandoc = subprocess.Popen(['pandoc', 'README.md', '--to', 'rst'], stdout=subprocess.PIPE) readme = str(pandoc.communicate()[0]) except OSError: with open('README.md') as f: readme = f.read() setup( name="notedown", version="1.3.1", description="Convert markdown to IPython notebook.", long_description=readme, packages=['notedown'], author="Aaron O'Leary", author_email='dev@aaren.me', license='BSD 2-Clause', url='http://github.com/aaren/notedown', install_requires=['ipython[nbconvert] >= 3.0', 'pandoc-attributes', 'six'], entry_points={'console_scripts': ['notedown = notedown:cli', ]}, package_dir={'notedown': 'notedown'}, package_data={'notedown': ['templates/markdown.tpl']}, include_package_data=True, )
Add 'six' to the install requirements
Add 'six' to the install requirements
Python
bsd-2-clause
michhar/notedown,aaren/notedown,michhar/notedown,lgautier/notedown,lgautier/notedown,aaren/notedown
--- +++ @@ -23,7 +23,7 @@ author_email='dev@aaren.me', license='BSD 2-Clause', url='http://github.com/aaren/notedown', - install_requires=['ipython[nbconvert] >= 3.0', 'pandoc-attributes'], + install_requires=['ipython[nbconvert] >= 3.0', 'pandoc-attributes', 'six'], entry_points={'console_scripts': ['notedown = notedown:cli', ]}, package_dir={'notedown': 'notedown'}, package_data={'notedown': ['templates/markdown.tpl']},
6c75574504489ddd26b236db0ce7246c545db14c
setup.py
setup.py
from setuptools import setup setup( name='twitter-text-py', version='1.0.3', description='A library for auto-converting URLs, mentions, hashtags, lists, etc. in Twitter text. Also does tweet validation and search term highlighting.', author='Daniel Ryan', author_email='dryan@dryan.com', url='http://github.com/dryan/twitter-text-py', packages=['twitter_text'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], include_package_data=True, install_requires=['setuptools'], license = "BSD" )
from setuptools import setup, find_packages setup( name='twitter-text-py', version='1.0.3', description='A library for auto-converting URLs, mentions, hashtags, lists, etc. in Twitter text. Also does tweet validation and search term highlighting.', author='Daniel Ryan', author_email='dryan@dryan.com', url='http://github.com/dryan/twitter-text-py', packages=find_packages(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], include_package_data=True, install_requires=['setuptools'], license = "BSD" )
Use find_packages to ensure template library gets installed
Use find_packages to ensure template library gets installed
Python
apache-2.0
joebos/twitter-text-py,joebos/twitter-text-py,joebos/twitter-text-py,joebos/twitter-text-py,joebos/twitter-text-py,joebos/twitter-text-py
--- +++ @@ -1,4 +1,4 @@ -from setuptools import setup +from setuptools import setup, find_packages setup( name='twitter-text-py', @@ -7,7 +7,7 @@ author='Daniel Ryan', author_email='dryan@dryan.com', url='http://github.com/dryan/twitter-text-py', - packages=['twitter_text'], + packages=find_packages(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment',
495a117cd122ce0d22b7c603eaf2bbdef3df0df9
setup.py
setup.py
""" Package configuration file """ from setuptools import setup setup( name='pylint-mccabe', version='0.1.2', author='Infoxchange Australia dev team', author_email='devs@infoxchange.net.au', py_modules=['pylint_mccabe'], url='http://pypi.python.org/pypi/pylint-mccabe/', license='MIT', description='McCabe complexity checker as a PyLint plugin', long_description=open('README.rst').read(), install_requires=[ 'mccabe >= 0.2', 'pep8 >= 1.4.5', 'pylint >= 0.28.0', ], )
""" Package configuration file """ from setuptools import setup setup( name='pylint-mccabe', version='0.1.3', author='Infoxchange Australia dev team', author_email='devs@infoxchange.net.au', py_modules=['pylint_mccabe'], url='http://pypi.python.org/pypi/pylint-mccabe/', license='MIT', description='McCabe complexity checker as a PyLint plugin', long_description=open('README.rst').read(), install_requires=[ 'mccabe >= 0.2', 'pep8 >= 1.4.6', 'pylint >= 0.28.0', ], )
Bump the version, update dependencies
Bump the version, update dependencies
Python
mit
infoxchange/pylint-mccabe
--- +++ @@ -5,7 +5,7 @@ setup( name='pylint-mccabe', - version='0.1.2', + version='0.1.3', author='Infoxchange Australia dev team', author_email='devs@infoxchange.net.au', py_modules=['pylint_mccabe'], @@ -15,7 +15,7 @@ long_description=open('README.rst').read(), install_requires=[ 'mccabe >= 0.2', - 'pep8 >= 1.4.5', + 'pep8 >= 1.4.6', 'pylint >= 0.28.0', ], )
dda39cf93fdbd9e40becfc82bb4e1e49e08c44f3
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup import lithium packages = ['lithium',] core = ['conf', 'views',] apps = ['blog', 'contact',] templatetags = ['blog',] package_data = {} for item in templatetags: packages.append('lithium.%s.templatetags' % item) for item in apps + core + templatetags: packages.append('lithium.%s' % item) for app in apps: package_data['lithium.%s' % app] = [('templates/%s/*.html' % app),] setup( name='lithium', version='%s' % lithium.__version__, description="A set of applications for writing a Django website's, it includes a blog, a forum, and many other useful applications.", author='Kyle Fuller', author_email='inbox@kylefuller.co.uk', url='http://github.com/kylef/lithium/', download_url='http://github.com/kylef/lithium/zipball/%s' % lithium.__version__, packages=packages, package_data=package_data, license='BSD', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', ] )
#!/usr/bin/env python from distutils.core import setup import lithium packages = ['lithium',] core = ['conf', 'views',] apps = ['blog', 'contact',] templatetags = ['blog',] package_data = {} for item in templatetags: packages.append('lithium.%s.templatetags' % item) for item in apps + core + templatetags: packages.append('lithium.%s' % item) for app in apps: package_data['lithium.%s' % app] = ['templates/%s/*.html' % app, 'templates/%s/*.txt' % app] setup( name='lithium', version='%s' % lithium.__version__, description="A set of applications for writing a Django website's, it includes a blog, a forum, and many other useful applications.", author='Kyle Fuller', author_email='inbox@kylefuller.co.uk', url='http://github.com/kylef/lithium/', download_url='http://github.com/kylef/lithium/zipball/%s' % lithium.__version__, packages=packages, package_data=package_data, license='BSD', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', ] )
Include *.txt in package data, since lithium.contact has a txt template
Include *.txt in package data, since lithium.contact has a txt template
Python
bsd-2-clause
kylef/lithium
--- +++ @@ -15,7 +15,7 @@ packages.append('lithium.%s' % item) for app in apps: - package_data['lithium.%s' % app] = [('templates/%s/*.html' % app),] + package_data['lithium.%s' % app] = ['templates/%s/*.html' % app, 'templates/%s/*.txt' % app] setup( name='lithium',
e5c949d33bb40c32d05932e4dfe8fe75f87fbf16
lcp/urls.py
lcp/urls.py
"""lcp URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from rest_framework import routers from planner.views import SchoolViewSet router = routers.DefaultRouter() router.register('schools', SchoolViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^admin/', admin.site.urls), url(r'^api-auth/', include('rest_framework.urls')), ]
"""lcp URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from rest_framework import routers from planner.views import SchoolViewSet router = routers.DefaultRouter(trailing_slash=False) router.register('schools', SchoolViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^admin/', admin.site.urls), url(r'^api-auth/', include('rest_framework.urls')), ]
Make the API not use trailing slashes. This is what Ember expects.
Make the API not use trailing slashes. This is what Ember expects.
Python
bsd-2-clause
mblayman/lcp,mblayman/lcp,mblayman/lcp
--- +++ @@ -19,7 +19,7 @@ from planner.views import SchoolViewSet -router = routers.DefaultRouter() +router = routers.DefaultRouter(trailing_slash=False) router.register('schools', SchoolViewSet) urlpatterns = [
fcc030b960965f9ac462bbefa48f629b73db5c8b
etd_drop_app/validators.py
etd_drop_app/validators.py
from django.core.exceptions import ValidationError import magic class MimetypeValidator(object): def __init__(self, mimetypes): self.mimetypes = mimetypes def __call__(self, value): mime = magic.from_buffer(value.read(1024), mime=True) if not mime in self.mimetypes: raise ValidationError('%s is not an acceptable file type' % value)
from django.core.exceptions import ValidationError import magic class MimetypeValidator(object): def __init__(self, mimetypes): self.mimetypes = mimetypes def __call__(self, value): try: mime = magic.from_buffer(value.read(1024), mime=True) if not mime in self.mimetypes: raise ValidationError('%s is not an acceptable file type' % value) except AttributeError as e: raise ValidationError('This value could not be validated for file type' % value)
Make mimetype validator slightly more robust
Make mimetype validator slightly more robust
Python
bsd-3-clause
MetaArchive/etd-drop,MetaArchive/etd-drop
--- +++ @@ -7,6 +7,9 @@ self.mimetypes = mimetypes def __call__(self, value): - mime = magic.from_buffer(value.read(1024), mime=True) - if not mime in self.mimetypes: - raise ValidationError('%s is not an acceptable file type' % value) + try: + mime = magic.from_buffer(value.read(1024), mime=True) + if not mime in self.mimetypes: + raise ValidationError('%s is not an acceptable file type' % value) + except AttributeError as e: + raise ValidationError('This value could not be validated for file type' % value)
e549c9382e2a75c1607a33925a6532d7859836d7
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup, find_packages exec(open('jira/version.py').read()) setup( name='jira-python', version=__version__, packages=find_packages(), install_requires=['requests>=0.13.6', 'ipython>=0.13', 'python-magic==0.4.2', 'tlslite==0.4.1'], # can't get this working for the moment. # extras_require = { # 'interactive-shell': ['ipython==0.12.1',] # }, entry_points = { 'console_scripts': ['jirashell = tools.jirashell:main'], }, url='http://bitbucket.org/bspeakmon_atlassian/jira-python', license='BSD', description='A library to ease use of the JIRA 5 REST APIs.', author='Ben Speakmon', author_email='bspeakmon@atlassian.com', provides=['jira'], keywords='jira', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', ], )
#!/usr/bin/env python from setuptools import setup, find_packages exec(open('jira/version.py').read()) setup( name='jira-python', version=__version__, packages=find_packages(), install_requires=['requests>=0.13.6', 'ipython>=0.13', 'python-magic==0.4.2', 'tlslite==0.4.1'], # can't get this working for the moment. # extras_require = { # 'interactive-shell': ['ipython==0.12.1',] # }, entry_points = { 'console_scripts': ['jirashell = tools.jirashell:main'], }, url='http://bitbucket.org/bspeakmon/jira-python', license='BSD', description='A library to ease use of the JIRA 5 REST APIs.', author='Ben Speakmon', author_email='ben.speakmon@gmail.com', provides=['jira'], keywords='jira', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', ], )
Update to new address + contact info
Update to new address + contact info
Python
bsd-2-clause
milo-minderbinder/jira,milo-minderbinder/jira,m42e/jira,systemadev/jira-python,jameskeane/jira-python,dwmarshall/pycontribs-jira,kinow/jira,awurster/jira,coddingtonbear/jira,VikingDen/jira,tsarnowski/jira-python,pycontribs/jira,systemadev/jira-python,jameskeane/jira-python,rayyen/jira,awurster/jira,kinow/jira,dbaxa/jira,m42e/jira,pycontribs/jira,stevencarey/jira,akosiaris/jira,dwmarshall/pycontribs-jira,VikingDen/jira,rayyen/jira,dbaxa/jira,akosiaris/jira,stevencarey/jira,coddingtonbear/jira,tsarnowski/jira-python
--- +++ @@ -18,11 +18,11 @@ ['jirashell = tools.jirashell:main'], }, - url='http://bitbucket.org/bspeakmon_atlassian/jira-python', + url='http://bitbucket.org/bspeakmon/jira-python', license='BSD', description='A library to ease use of the JIRA 5 REST APIs.', author='Ben Speakmon', - author_email='bspeakmon@atlassian.com', + author_email='ben.speakmon@gmail.com', provides=['jira'], keywords='jira', classifiers=[
db41d77cbdb42d0bb8326e4585d1c2f73ec8c708
setup.py
setup.py
#!/usr/bin/env python # from distutils.core import setup from setuptools import setup, find_packages from pip.req import parse_requirements import pip import sys try: import multiprocessing except ImportError: pass try: # parse_requirements() returns generator of pip.req.InstallRequirement objects install_reqs = parse_requirements('requirements.txt', session=pip.download.PipSession()) except AttributeError: # compatibility for pip < 1.5.6 install_reqs = parse_requirements('requirements.txt') tests_require = ['nose', 'mock'] # reqs is a list of requirement # e.g. ['django==1.5.1', 'mezzanine==1.4.6'] reqs = [str(ir.req) for ir in install_reqs] if sys.version_info < (2, 7): tests_require.append('unittest2') setup_requires = [] if 'nosetests' in sys.argv[1:]: setup_requires.append('nose') setup( name="keen", version="0.3.13", description="Python Client for Keen IO", author="Keen IO", author_email="team@keen.io", url="https://github.com/keenlabs/KeenClient-Python", packages=["keen"], install_requires=reqs, tests_require=tests_require, test_suite='nose.collector', )
#!/usr/bin/env python from setuptools import setup import os, sys setup_path = os.path.dirname(__file__) reqs_file = open(os.path.join(setup_path, 'requirements.txt'), 'r') reqs = reqs_file.readlines() reqs_file.close() tests_require = ['nose', 'mock'] if sys.version_info < (2, 7): tests_require.append('unittest2') setup_requires = [] if 'nosetests' in sys.argv[1:]: setup_requires.append('nose') setup( name="keen", version="0.3.14", description="Python Client for Keen IO", author="Keen IO", author_email="team@keen.io", url="https://github.com/keenlabs/KeenClient-Python", packages=["keen"], install_requires=reqs, tests_require=tests_require, test_suite='nose.collector', )
Simplify requirements inclusion for compatibility with old pip
Simplify requirements inclusion for compatibility with old pip
Python
mit
isotoma/KeenClient-Python,keenlabs/KeenClient-Python
--- +++ @@ -1,28 +1,14 @@ #!/usr/bin/env python -# from distutils.core import setup -from setuptools import setup, find_packages -from pip.req import parse_requirements -import pip -import sys +from setuptools import setup +import os, sys -try: - import multiprocessing -except ImportError: - pass - -try: - # parse_requirements() returns generator of pip.req.InstallRequirement objects - install_reqs = parse_requirements('requirements.txt', session=pip.download.PipSession()) -except AttributeError: - # compatibility for pip < 1.5.6 - install_reqs = parse_requirements('requirements.txt') +setup_path = os.path.dirname(__file__) +reqs_file = open(os.path.join(setup_path, 'requirements.txt'), 'r') +reqs = reqs_file.readlines() +reqs_file.close() tests_require = ['nose', 'mock'] - -# reqs is a list of requirement -# e.g. ['django==1.5.1', 'mezzanine==1.4.6'] -reqs = [str(ir.req) for ir in install_reqs] if sys.version_info < (2, 7): tests_require.append('unittest2') @@ -33,7 +19,7 @@ setup( name="keen", - version="0.3.13", + version="0.3.14", description="Python Client for Keen IO", author="Keen IO", author_email="team@keen.io",
82597c5bc118ef9a3e53268614cfe398fc848477
setup.py
setup.py
# Copyright (c) 2018 Arista Networks, Inc. # Use of this source code is governed by the Apache License 2.0 # that can be found in the LICENSE file. from setuptools import setup setup( name='switools', version='1.0', description='Tools for handling Arista SWI/X', packages=['switools', 'swixtools'], install_requires=[ 'M2Crypto' ], test_suite="tests", entry_points = { 'console_scripts': [ 'verify-swi=switools.verifyswi:main', 'swi-signature=switools.swisignature:main', 'swix-create=swixtools.create:main' ], }, url='https://github.com/aristanetworks/swi-tools', zip_safe=False, include_package_data=True )
# Copyright (c) 2018 Arista Networks, Inc. # Use of this source code is governed by the Apache License 2.0 # that can be found in the LICENSE file. from setuptools import setup setup( name='switools', version='1.0', description='Tools for handling Arista SWI/X', packages=['switools', 'swixtools'], install_requires=[ 'M2Crypto' ], test_suite="tests", entry_points = { 'console_scripts': [ 'verify-swi=switools.verifyswi:main', 'swi-signature=switools.swisignature:main', 'swix-create=swixtools.create:main', 'swix-signature=switools.swisignature:main', ], }, url='https://github.com/aristanetworks/swi-tools', zip_safe=False, include_package_data=True )
Introduce `swix-signatre` which is handled by switools/swisignature
Introduce `swix-signatre` which is handled by switools/swisignature
Python
apache-2.0
aristanetworks/swi-tools,aristanetworks/swi-tools
--- +++ @@ -13,7 +13,9 @@ entry_points = { 'console_scripts': [ 'verify-swi=switools.verifyswi:main', 'swi-signature=switools.swisignature:main', - 'swix-create=swixtools.create:main' ], + 'swix-create=swixtools.create:main', + 'swix-signature=switools.swisignature:main', + ], }, url='https://github.com/aristanetworks/swi-tools', zip_safe=False,
e15f9e221e81d41f2da3ed06253fd4ff8b5d9199
setup.py
setup.py
import re from distribute_setup import use_setuptools use_setuptools() from setuptools import setup version = None for line in open('./soundcloud/__init__.py'): m = re.search('__version__\s*=\s*(.*)', line) if m: version = m.group(1).strip()[1:-1] # quotes break assert version setup( name='soundcloud', version=version, description='A friendly wrapper library for the Soundcloud API', author='Paul Osman', author_email='osman@soundcloud.com', url='https://github.com/soundcloud/soundcloud-python', license='BSD', packages=['soundcloud'], include_package_data=True, use_2to3=True, package_data={ '': ['README.rst'] }, install_requires=[ 'fudge==1.0.3', 'requests>=0.14.0', 'simplejson>=2.0', ], tests_require=[ 'nose>=1.1.2', ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet', 'Topic :: Multimedia :: Sound/Audio', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
import re from distribute_setup import use_setuptools use_setuptools() from setuptools import setup version = None for line in open('./soundcloud/__init__.py'): m = re.search('__version__\s*=\s*(.*)', line) if m: version = m.group(1).strip()[1:-1] # quotes break assert version setup( name='soundcloud', version=version, description='A friendly wrapper library for the Soundcloud API', author='Paul Osman', author_email='osman@soundcloud.com', url='https://github.com/soundcloud/soundcloud-python', license='BSD', packages=['soundcloud'], include_package_data=True, use_2to3=True, package_data={ '': ['README.rst'] }, install_requires=[ 'fudge>=1.0.3', 'requests>=0.14.0', 'simplejson>=2.0', ], tests_require=[ 'nose>=1.1.2', ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet', 'Topic :: Multimedia :: Sound/Audio', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
Allow never version of fudge (1.0.3 and up)
Allow never version of fudge (1.0.3 and up)
Python
bsd-2-clause
phijor/soundcloud-python,soundcloud/soundcloud-python
--- +++ @@ -27,7 +27,7 @@ '': ['README.rst'] }, install_requires=[ - 'fudge==1.0.3', + 'fudge>=1.0.3', 'requests>=0.14.0', 'simplejson>=2.0', ],
9bec0bfcf8f12dc3f95a04918331c99c77b4914b
exercises/chapter_04/exercise_04_01/exercise_04_01.py
exercises/chapter_04/exercise_04_01/exercise_04_01.py
# 4-1. Pizzas favorite_pizzas = ["Columpus", "Marco Polo", "Amerikana"] for pizza in favorite_pizzas: print(pizza)
# 4-1. Pizzas favorite_pizzas = ["Columpus", "Marco Polo", "Amerikana"] for pizza in favorite_pizzas: print("I like " + pizza + " pizza.")
Add version 2 of exercise 4.1.
Add version 2 of exercise 4.1.
Python
mit
HenrikSamuelsson/python-crash-course
--- +++ @@ -3,4 +3,4 @@ favorite_pizzas = ["Columpus", "Marco Polo", "Amerikana"] for pizza in favorite_pizzas: - print(pizza) + print("I like " + pizza + " pizza.")
5645946d9a99ff86c43c7801053a0ef279dc1382
ynr/apps/candidates/csv_helpers.py
ynr/apps/candidates/csv_helpers.py
from compat import BufferDictWriter from .models import CSV_ROW_FIELDS def _candidate_sort_by_name_key(row): return ( row["name"].split()[-1], row["name"].rsplit(None, 1)[0], not row["election_current"], row["election_date"], row["election"], row["post_label"], ) def _candidate_sort_by_post_key(row): return ( not row["election_current"], row["election_date"], row["election"], row["post_label"], row["name"].split()[-1], row["name"].rsplit(None, 1)[0], ) def list_to_csv(candidates_list, group_by_post=False): from .election_specific import EXTRA_CSV_ROW_FIELDS csv_fields = CSV_ROW_FIELDS + EXTRA_CSV_ROW_FIELDS writer = BufferDictWriter(fieldnames=csv_fields) writer.writeheader() if group_by_post: sorted_rows = sorted(candidates_list, key=_candidate_sort_by_post_key) else: sorted_rows = sorted(candidates_list, key=_candidate_sort_by_name_key) for row in sorted_rows: writer.writerow(row) return writer.output
from collections import defaultdict from compat import BufferDictWriter from django.conf import settings from popolo.models import Membership from candidates.models import PersonRedirect def list_to_csv(membership_list): csv_fields = settings.CSV_ROW_FIELDS writer = BufferDictWriter(fieldnames=csv_fields) writer.writeheader() for row in membership_list: writer.writerow(row) return writer.output def memberships_dicts_for_csv(election_slug=None, post_slug=None): redirects = PersonRedirect.all_redirects_dict() memberships = Membership.objects.joins_for_csv() if election_slug: memberships = memberships.filter( post_election__election__slug=election_slug ) if post_slug: memberships = memberships.filter(post_election__post__slug=post_slug) memberships_by_election = defaultdict(list) elected_by_election = defaultdict(list) for membership in memberships: election_slug = membership.post_election.election.slug line = membership.dict_for_csv(redirects=redirects) memberships_by_election[election_slug].append(line) if membership.elected: elected_by_election[election_slug].append(line) return (memberships_by_election, elected_by_election)
Move to using membership based CSV output
Move to using membership based CSV output
Python
agpl-3.0
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative
--- +++ @@ -1,39 +1,40 @@ +from collections import defaultdict + from compat import BufferDictWriter -from .models import CSV_ROW_FIELDS +from django.conf import settings + +from popolo.models import Membership +from candidates.models import PersonRedirect -def _candidate_sort_by_name_key(row): - return ( - row["name"].split()[-1], - row["name"].rsplit(None, 1)[0], - not row["election_current"], - row["election_date"], - row["election"], - row["post_label"], - ) +def list_to_csv(membership_list): + + csv_fields = settings.CSV_ROW_FIELDS + writer = BufferDictWriter(fieldnames=csv_fields) + writer.writeheader() + for row in membership_list: + writer.writerow(row) + return writer.output -def _candidate_sort_by_post_key(row): - return ( - not row["election_current"], - row["election_date"], - row["election"], - row["post_label"], - row["name"].split()[-1], - row["name"].rsplit(None, 1)[0], - ) +def memberships_dicts_for_csv(election_slug=None, post_slug=None): + redirects = PersonRedirect.all_redirects_dict() + memberships = Membership.objects.joins_for_csv() + if election_slug: + memberships = memberships.filter( + post_election__election__slug=election_slug + ) + if post_slug: + memberships = memberships.filter(post_election__post__slug=post_slug) + memberships_by_election = defaultdict(list) + elected_by_election = defaultdict(list) -def list_to_csv(candidates_list, group_by_post=False): - from .election_specific import EXTRA_CSV_ROW_FIELDS + for membership in memberships: + election_slug = membership.post_election.election.slug + line = membership.dict_for_csv(redirects=redirects) + memberships_by_election[election_slug].append(line) + if membership.elected: + elected_by_election[election_slug].append(line) - csv_fields = CSV_ROW_FIELDS + EXTRA_CSV_ROW_FIELDS - writer = BufferDictWriter(fieldnames=csv_fields) - writer.writeheader() - if group_by_post: - sorted_rows = sorted(candidates_list, key=_candidate_sort_by_post_key) - else: - sorted_rows = sorted(candidates_list, key=_candidate_sort_by_name_key) - for row in sorted_rows: - writer.writerow(row) - return writer.output + return (memberships_by_election, elected_by_election)
0975c706c503d403810ddeba24ea14b5c9bdd133
d1_client_cli/src/setup.py
d1_client_cli/src/setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :mod:`setup` ==================== :Synopsis: Create egg. :Author: DataONE (Pippin) """ from setuptools import setup, find_packages import d1_client_cli setup( name='Python DataONE CLI', version=d1_client_cli.__version__, author='Roger Dahl, and the DataONE Development Team', author_email='developers@dataone.org', url='http://dataone.org', license='Apache License, Version 2.0', description='A DataONE Command-line interface', packages=find_packages(), # Dependencies that are available through PYPI / easy_install. install_requires=[ 'pyxb >= 1.1.3', ], package_data={ # If any package contains *.txt or *.rst files, include them: '': ['*.txt', '*.rst'], } )
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :mod:`setup` ==================== :Synopsis: Create egg. :Author: DataONE (Pippin) """ from setuptools import setup, find_packages import d1_client_cli setup( name='Python DataONE CLI', version=d1_client_cli.__version__, author='Roger Dahl, and the DataONE Development Team', author_email='developers@dataone.org', url='http://dataone.org', license='Apache License, Version 2.0', description='A DataONE Command-line interface', packages = find_packages(), # Dependencies that are available through PYPI / easy_install. install_requires = [ 'pyxb >= 1.1.3', ], dependency_links = [ 'https://repository.dataone.org/software/python_products/d1_cli/Python_DataONE_Common-1.0.0c4-py2.6.egg', 'https://repository.dataone.org/software/python_products/d1_cli/Python_DataONE_Client_Library-1.0.0c4-py2.6.egg', ] package_data = { # If any package contains *.txt or *.rst files, include them: '': ['*.txt', '*.rst'], } )
Add references to common and libclient, which will not be deployed to PyPi.
Add references to common and libclient, which will not be deployed to PyPi.
Python
apache-2.0
DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python
--- +++ @@ -1,5 +1,6 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- + """ :mod:`setup` ==================== @@ -19,14 +20,21 @@ url='http://dataone.org', license='Apache License, Version 2.0', description='A DataONE Command-line interface', - packages=find_packages(), - + packages = find_packages(), + # Dependencies that are available through PYPI / easy_install. - install_requires=[ + install_requires = [ 'pyxb >= 1.1.3', ], - package_data={ + + dependency_links = [ + 'https://repository.dataone.org/software/python_products/d1_cli/Python_DataONE_Common-1.0.0c4-py2.6.egg', + 'https://repository.dataone.org/software/python_products/d1_cli/Python_DataONE_Client_Library-1.0.0c4-py2.6.egg', + ] + + package_data = { # If any package contains *.txt or *.rst files, include them: '': ['*.txt', '*.rst'], } ) +
99b69babaf5ed1517ecb0681a4110a8511876241
catwatch/tests/user/test_tasks.py
catwatch/tests/user/test_tasks.py
from catwatch.extensions import mail from catwatch.blueprints.user.tasks import deliver_password_reset_email from catwatch.blueprints.user.models import User class TestTasks(object): def test_deliver_password_reset_email(self, session, token): """ Deliver a password reset email. """ with mail.record_messages() as outbox: user = User.find_by_identity('admin@localhost.com') deliver_password_reset_email(user.id, token) assert len(outbox) == 1 assert token in outbox[0].body
from catwatch.extensions import mail from catwatch.blueprints.user.tasks import deliver_password_reset_email from catwatch.blueprints.user.models import User class TestTasks(object): def test_deliver_password_reset_email(self, token): """ Deliver a password reset email. """ with mail.record_messages() as outbox: user = User.find_by_identity('admin@localhost.com') deliver_password_reset_email(user.id, token) assert len(outbox) == 1 assert token in outbox[0].body
Remove unnecessary fixture from password reset test
Remove unnecessary fixture from password reset test
Python
mit
nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask
--- +++ @@ -4,7 +4,7 @@ class TestTasks(object): - def test_deliver_password_reset_email(self, session, token): + def test_deliver_password_reset_email(self, token): """ Deliver a password reset email. """ with mail.record_messages() as outbox: user = User.find_by_identity('admin@localhost.com')
39404dfa8ab921977347d4405c525935a0ce234d
cc/license/tests/test_licenses.py
cc/license/tests/test_licenses.py
from nose.tools import assert_true def test_find_sampling_selector(): from zope.interface import implementedBy import cc.license sampling_selector = cc.license.get_selector('recombo')() return sampling_selector def test_find_sampling_licenses(): selector = test_find_sampling_selector() lic = selector.by_code('sampling') assert_true(not lic.libre) assert_true(lic.deprecated) lic = selector.by_code('sampling+') assert_true(not lic.deprecated) def test_find_pd(): from zope.interface import implementedBy import cc.license pd_selector = cc.license.get_selector('publicdomain')() pd = pd_selector.by_code('publicdomain') return pd def test_pd(): pd = test_find_pd() assert_true(pd.libre) assert_true(pd.jurisdiction == 'Your mom') assert_true(not pd.deprecated) assert_true(pd.jurisdiction == 'Your mom') assert_true(pd.license_code == 'publicdomain') assert_true(pd.name() == 'Public Domain' == pd.name('en')) assert_true(pd.name('hr') == u'Javna domena')
from nose.tools import assert_true def test_find_sampling_selector(): from zope.interface import implementedBy import cc.license sampling_selector = cc.license.get_selector('recombo')() return sampling_selector def test_find_standard_selector(): from zope.interface import implementedBy import cc.license standard_selector = cc.license.get_selector('standard')() return standard_selector def test_find_sampling_licenses(): selector = test_find_sampling_selector() lic = selector.by_code('sampling') assert_true(not lic.libre) assert_true(lic.deprecated) lic = selector.by_code('sampling+') assert_true(not lic.deprecated) def test_find_pd(): from zope.interface import implementedBy import cc.license pd_selector = cc.license.get_selector('publicdomain')() pd = pd_selector.by_code('publicdomain') return pd def test_pd(): pd = test_find_pd() assert_true(pd.libre) assert_true(pd.jurisdiction == 'Your mom') assert_true(not pd.deprecated) assert_true(pd.jurisdiction == 'Your mom') assert_true(pd.license_code == 'publicdomain') assert_true(pd.name() == 'Public Domain' == pd.name('en')) assert_true(pd.name('hr') == u'Javna domena')
Add a test for grabbing the standard selector
Add a test for grabbing the standard selector
Python
mit
creativecommons/cc.license,creativecommons/cc.license
--- +++ @@ -6,6 +6,13 @@ sampling_selector = cc.license.get_selector('recombo')() return sampling_selector + +def test_find_standard_selector(): + from zope.interface import implementedBy + import cc.license + + standard_selector = cc.license.get_selector('standard')() + return standard_selector def test_find_sampling_licenses(): selector = test_find_sampling_selector()
5568e84b715ed2de20d325aa1e66e9959e5e8b89
feed/feed.home.loadtest.py
feed/feed.home.loadtest.py
#!/usr/local/bin/python3 -u __author__ = 'Oliver Ratzesberger <https://github.com/fxstein>' __copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger' __license__ = 'Apache License, Version 2.0' # Make sure we have access to SentientHome commons import os, sys sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') # Sentient Home Application from common.shapp import shApp from common.sheventhandler import shEventHandler import logging as log import time # Simple loadtest that 'fires' events as fast as possible with shApp('loadtest') as app: app.run() handler = shEventHandler(app) count = 0 while True: count += 1 event = [{ 'name': 'loadtest', # Time Series Name 'columns': ['count'], # Keys 'points': [[count]] # Data points }] handler.postEvent(event)
#!/usr/local/bin/python3 -u __author__ = 'Oliver Ratzesberger <https://github.com/fxstein>' __copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger' __license__ = 'Apache License, Version 2.0' # Make sure we have access to SentientHome commons import os, sys sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') # Sentient Home Application from common.shapp import shApp from common.sheventhandler import shEventHandler # Simple loadtest that 'fires' events as fast as possible with shApp('loadtest') as app: app.run() handler = shEventHandler(app) count = 0 while True: count += 1 event = [{ 'name': 'loadtest', # Time Series Name 'columns': ['count'], # Keys 'points': [[count]] # Data points }] handler.postEvent(event)
Remove no longer needed python libs
Remove no longer needed python libs
Python
apache-2.0
fxstein/SentientHome
--- +++ @@ -10,9 +10,6 @@ # Sentient Home Application from common.shapp import shApp from common.sheventhandler import shEventHandler - -import logging as log -import time # Simple loadtest that 'fires' events as fast as possible
9c6532aad52f8eb950aeae97dd43f1d921006b6b
tasks.py
tasks.py
from invoke import run, task TESTPYPI = "https://testpypi.python.org/pypi" @task def lint(ctx): """Run flake8 to lint code""" run("flake8") @task(lint) def test(ctx): """Lint, unit test, and check setup.py""" cmd = "{} {}".format( "nosetests", "--with-coverage --cover-erase --cover-package=keysight --cover-html") run(cmd) @task() def release(ctx, deploy=False, test=False, version=''): """Tag release, run Travis-CI, and deploy to PyPI """ if test: run("python setup.py check") run("python setup.py register sdist upload --dry-run") if deploy: run("python setup.py check") if version: run("git checkout master") run("git tag -a v{ver} -m 'v{ver}'".format(ver=version)) run("git push") run("git push origin --tags") else: print("- Have you updated the version?") print("- Have you updated CHANGELOG.md?") print("- Have you fixed any last minute bugs?") print("If you answered yes to all of the above questions,") print("then run `invoke release --deploy -vX.YY.ZZ` to:") print("- Checkout master") print("- Tag the git release with provided vX.YY.ZZ version") print("- Push the master branch and tags to repo") print("- Deploy to PyPi using Travis")
from invoke import run, task TESTPYPI = "https://testpypi.python.org/pypi" @task def lint(ctx): """Run flake8 to lint code""" run("flake8") @task def freeze(ctx): """Freeze the pip requirements""" run("pip freeze -l > requirements.txt") @task(lint) def test(ctx): """Lint, unit test, and check setup.py""" cmd = "{} {}".format( "nosetests", "--with-coverage --cover-erase --cover-package=keysight --cover-html") run(cmd) @task def release(ctx, deploy=False, test=False, version=''): """Tag release, run Travis-CI, and deploy to PyPI """ if test: run("python setup.py check") run("python setup.py register sdist upload --dry-run") if deploy: run("python setup.py check") if version: run("git checkout master") run("git tag -a v{ver} -m 'v{ver}'".format(ver=version)) run("git push") run("git push origin --tags") else: print("- Have you updated the version?") print("- Have you updated CHANGELOG.md?") print("- Have you fixed any last minute bugs?") print("If you answered yes to all of the above questions,") print("then run `invoke release --deploy -vX.YY.ZZ` to:") print("- Checkout master") print("- Tag the git release with provided vX.YY.ZZ version") print("- Push the master branch and tags to repo") print("- Deploy to PyPi using Travis")
Add freeze task to invoke
Add freeze task to invoke
Python
mit
questrail/keysight
--- +++ @@ -9,6 +9,12 @@ run("flake8") +@task +def freeze(ctx): + """Freeze the pip requirements""" + run("pip freeze -l > requirements.txt") + + @task(lint) def test(ctx): """Lint, unit test, and check setup.py""" @@ -18,7 +24,7 @@ run(cmd) -@task() +@task def release(ctx, deploy=False, test=False, version=''): """Tag release, run Travis-CI, and deploy to PyPI """
f75d06702274257215229b83c4ff74de3dc72463
nnpy/tests.py
nnpy/tests.py
from __future__ import print_function import nnpy, unittest class Tests(unittest.TestCase): def test_basic(self): pub = nnpy.Socket(nnpy.AF_SP, nnpy.PUB) pub.bind('inproc://foo') self.assertEqual(pub.getsockopt(nnpy.SOL_SOCKET, nnpy.DOMAIN), 1) sub = nnpy.Socket(nnpy.AF_SP, nnpy.SUB) sub.connect('inproc://foo') sub.setsockopt(nnpy.SUB, nnpy.SUB_SUBSCRIBE, '') pub.send('FLUB') poller = nnpy.PollSet((sub, nnpy.POLLIN)) self.assertEqual(poller.poll(), 1) self.assertEqual(sub.recv(), 'FLUB') self.assertEqual(pub.get_statistic(nnpy.STAT_MESSAGES_SENT), 1) def suite(): return unittest.makeSuite(Tests) if __name__ == '__main__': unittest.main(defaultTest='suite')
from __future__ import print_function import nnpy, unittest class Tests(unittest.TestCase): def test_basic(self): pub = nnpy.Socket(nnpy.AF_SP, nnpy.PUB) pub.setsockopt(nnpy.SOL_SOCKET, nnpy.IPV4ONLY, 0) pub.bind('inproc://foo') self.assertEqual(pub.getsockopt(nnpy.SOL_SOCKET, nnpy.DOMAIN), 1) sub = nnpy.Socket(nnpy.AF_SP, nnpy.SUB) sub_conn = sub.connect('inproc://foo') sub.setsockopt(nnpy.SUB, nnpy.SUB_SUBSCRIBE, '') pub.send('FLUB') poller = nnpy.PollSet((sub, nnpy.POLLIN)) self.assertEqual(poller.poll(), 1) self.assertEqual(sub.recv(), 'FLUB') self.assertEqual(pub.get_statistic(nnpy.STAT_MESSAGES_SENT), 1) pub.close() sub.shutdown(sub_conn) def suite(): return unittest.makeSuite(Tests) if __name__ == '__main__': unittest.main(defaultTest='suite')
Add some more test coverage
Add some more test coverage
Python
mit
nanomsg/nnpy
--- +++ @@ -5,11 +5,12 @@ def test_basic(self): pub = nnpy.Socket(nnpy.AF_SP, nnpy.PUB) + pub.setsockopt(nnpy.SOL_SOCKET, nnpy.IPV4ONLY, 0) pub.bind('inproc://foo') self.assertEqual(pub.getsockopt(nnpy.SOL_SOCKET, nnpy.DOMAIN), 1) sub = nnpy.Socket(nnpy.AF_SP, nnpy.SUB) - sub.connect('inproc://foo') + sub_conn = sub.connect('inproc://foo') sub.setsockopt(nnpy.SUB, nnpy.SUB_SUBSCRIBE, '') pub.send('FLUB') @@ -17,6 +18,8 @@ self.assertEqual(poller.poll(), 1) self.assertEqual(sub.recv(), 'FLUB') self.assertEqual(pub.get_statistic(nnpy.STAT_MESSAGES_SENT), 1) + pub.close() + sub.shutdown(sub_conn) def suite(): return unittest.makeSuite(Tests)
e409e8d77eec8e53978512da56bf52f768d46c1a
create-application.py
create-application.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import subprocess, os, sys, optparse fullpath = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0])) capath = os.path.abspath( os.path.join(fullpath, "qooxdoo", "tool", "bin", "create-application.py") ) skeletonpath = os.path.abspath( os.path.join(fullpath, "unify", "application", "skeleton") ) subprocess.call(["python", capath, "-p", skeletonpath, "-t", "unify"] + sys.argv[1:])
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Create skeleton application for Unify # Copyright (C) 2012 Sebastian Fastner, Mainz, Germany # License: MIT or Apache2 import os, sys, shutil print("Unify create skeleton") print("(C) 2012 Sebastian Fastner, Mainz, Germany") print() if (len(sys.argv) != 2): print("Syntax: %s <namespace>" % os.path.basename(sys.argv[0])) exit(1) NAMESPACE = sys.argv[1] UNIFYPATH = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0])) SKELETONPATH = os.path.abspath( os.path.join(UNIFYPATH, "unify", "application", "skeleton", "unify") ) TARGETPATH = os.path.abspath(os.path.join(os.getcwd(), NAMESPACE)) REPLACEMENTS = { "NAMESPACE" : NAMESPACE, "UNIFYPATH" : os.path.relpath(UNIFYPATH, TARGETPATH) } if os.path.exists(TARGETPATH): print("Path %s exists. Aborting." % TARGETPATH) exit(2) shutil.copytree(SKELETONPATH, TARGETPATH) def patch_line(line): for key in REPLACEMENTS: check = "${" + key + "}" line = line.replace(check, REPLACEMENTS[key]) return line def handle_file(directory, filename): outfile_name = os.path.join(directory, filename.replace(".tmpl", "")) infile_name = os.path.join(directory, filename) with open(outfile_name, "w") as outfile: with open(infile_name) as infile: for line in infile: outfile.write(patch_line(line)) os.remove(infile_name) def handle_dir(directory): shutil.move(directory, directory[:-6] + NAMESPACE) for root, dirs, files in os.walk(TARGETPATH,topdown=False): for file in files: if ".tmpl." in file: handle_file(root, file) if root.endswith("custom"): handle_dir(root) print("Creat application skeleton in %s ... done" % TARGETPATH)
Add variable replacements to create application
Add variable replacements to create application
Python
mit
unify/unify,unify/unify,unify/unify,unify/unify,unify/unify,unify/unify
--- +++ @@ -1,14 +1,63 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- -import subprocess, os, sys, optparse +# Create skeleton application for Unify +# Copyright (C) 2012 Sebastian Fastner, Mainz, Germany +# License: MIT or Apache2 -fullpath = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0])) -capath = os.path.abspath( - os.path.join(fullpath, "qooxdoo", "tool", "bin", "create-application.py") +import os, sys, shutil + +print("Unify create skeleton") +print("(C) 2012 Sebastian Fastner, Mainz, Germany") +print() + +if (len(sys.argv) != 2): + print("Syntax: %s <namespace>" % os.path.basename(sys.argv[0])) + exit(1) + +NAMESPACE = sys.argv[1] + +UNIFYPATH = os.path.join(os.getcwd(), os.path.dirname(sys.argv[0])) +SKELETONPATH = os.path.abspath( + os.path.join(UNIFYPATH, "unify", "application", "skeleton", "unify") ) -skeletonpath = os.path.abspath( - os.path.join(fullpath, "unify", "application", "skeleton") -) +TARGETPATH = os.path.abspath(os.path.join(os.getcwd(), NAMESPACE)) -subprocess.call(["python", capath, "-p", skeletonpath, "-t", "unify"] + sys.argv[1:]) +REPLACEMENTS = { + "NAMESPACE" : NAMESPACE, + "UNIFYPATH" : os.path.relpath(UNIFYPATH, TARGETPATH) +} + +if os.path.exists(TARGETPATH): + print("Path %s exists. Aborting." % TARGETPATH) + exit(2) + +shutil.copytree(SKELETONPATH, TARGETPATH) + +def patch_line(line): + for key in REPLACEMENTS: + check = "${" + key + "}" + line = line.replace(check, REPLACEMENTS[key]) + return line + +def handle_file(directory, filename): + outfile_name = os.path.join(directory, filename.replace(".tmpl", "")) + infile_name = os.path.join(directory, filename) + with open(outfile_name, "w") as outfile: + with open(infile_name) as infile: + for line in infile: + outfile.write(patch_line(line)) + os.remove(infile_name) + +def handle_dir(directory): + shutil.move(directory, directory[:-6] + NAMESPACE) + +for root, dirs, files in os.walk(TARGETPATH,topdown=False): + for file in files: + if ".tmpl." in file: + handle_file(root, file) + + if root.endswith("custom"): + handle_dir(root) + +print("Creat application skeleton in %s ... done" % TARGETPATH)
3d6015649e50a2f55e5dc1ef84406e229607cdaa
test2.py
test2.py
import json #from jsonrpc import ServerProxy, JsonRpc20, TransportTcpIp import jsonrpclib class StanfordNLP: def __init__(self, port_number=8080): self.server = jsonrpclib.Server("http://localhost:%d" % port_number) def parse(self, text): return json.loads(self.server.parse(text)) nlp = StanfordNLP() result = nlp.parse("What is birth date of the wife of the first black president of the United States?") print(result['sentences'][0]['dependencies'])
import json #from jsonrpc import ServerProxy, JsonRpc20, TransportTcpIp import jsonrpclib import fileinput class StanfordNLP: def __init__(self, port_number=8080): self.server = jsonrpclib.Server("http://localhost:%d" % port_number) def parse(self, text): return json.loads(self.server.parse(text)) nlp = StanfordNLP() while(True): line=input("") result = nlp.parse(line) print(result['sentences'][0]['dependencies'])
Add loop, allowing several tests.
Add loop, allowing several tests.
Python
agpl-3.0
ProjetPP/PPP-QuestionParsing-Grammatical,ProjetPP/PPP-QuestionParsing-Grammatical
--- +++ @@ -1,6 +1,7 @@ import json #from jsonrpc import ServerProxy, JsonRpc20, TransportTcpIp import jsonrpclib +import fileinput class StanfordNLP: def __init__(self, port_number=8080): @@ -10,6 +11,8 @@ return json.loads(self.server.parse(text)) nlp = StanfordNLP() -result = nlp.parse("What is birth date of the wife of the first black president of the United States?") -print(result['sentences'][0]['dependencies']) +while(True): + line=input("") + result = nlp.parse(line) + print(result['sentences'][0]['dependencies'])
23dac5f2e5be725eff7d329a6af399f6d80c59de
logintokens/tokens.py
logintokens/tokens.py
"""module containing generator for login tokens """ import base64 from django.core.signing import TimestampSigner, BadSignature from django.contrib.auth import get_user_model class LoginTokenGenerator: """Generator for the timestamp signed tokens used for logging in. """ def __init__(self): self.signer = TimestampSigner( salt='aniauth-tdd.accounts.token.LoginTokenGenerator') def make_token(self, email): """Return a login token for the provided email. """ return base64.urlsafe_b64encode( self.signer.sign(email).encode() ).decode() def consume_token(self, token, max_age=600): """Extract the user provided the token isn't older than max_age. """ try: return self.signer.unsign( base64.urlsafe_b64decode(token.encode()), max_age ) except (BadSignature, base64.binascii.Error): return None
"""module containing generator for login tokens """ import base64 from django.contrib.auth import get_user_model from django.core.signing import TimestampSigner, BadSignature USER = get_user_model() class LoginTokenGenerator: """Generator for the timestamp signed tokens used for logging in. """ def __init__(self): self.signer = TimestampSigner( salt='aniauth-tdd.accounts.token.LoginTokenGenerator') def make_token(self, username): """Return a login token for the provided email. """ try: user = USER.objects.get(username=username) login_timestamp = ('' if user.last_login is None else int(user.last_login.timestamp())) except USER.DoesNotExist: login_timestamp = '' value = str('%s%s%s') % (username, self.signer.sep, login_timestamp) return base64.urlsafe_b64encode( self.signer.sign(value).encode() ).decode() def consume_token(self, token, max_age=600): """Extract the user provided the token isn't older than max_age. """ try: result = self.signer.unsign( base64.urlsafe_b64decode(token.encode()), max_age ) except (BadSignature, base64.binascii.Error): return None username, login_timestamp = result.split(self.signer.sep) try: user = USER.objects.get(username=username) user_login_timestamp = ('' if user.last_login is None else int(user.last_login.timestamp())) if user_login_timestamp == login_timestamp: return username else: return None # The user has logged in since this token was made except USER.DoesNotExist: return username
Use last login of user in signed value
Use last login of user in signed value
Python
mit
randomic/aniauth-tdd,randomic/aniauth-tdd
--- +++ @@ -3,8 +3,11 @@ """ import base64 +from django.contrib.auth import get_user_model from django.core.signing import TimestampSigner, BadSignature -from django.contrib.auth import get_user_model + + +USER = get_user_model() class LoginTokenGenerator: @@ -15,12 +18,20 @@ self.signer = TimestampSigner( salt='aniauth-tdd.accounts.token.LoginTokenGenerator') - def make_token(self, email): + def make_token(self, username): """Return a login token for the provided email. """ + try: + user = USER.objects.get(username=username) + login_timestamp = ('' if user.last_login is None + else int(user.last_login.timestamp())) + except USER.DoesNotExist: + login_timestamp = '' + + value = str('%s%s%s') % (username, self.signer.sep, login_timestamp) return base64.urlsafe_b64encode( - self.signer.sign(email).encode() + self.signer.sign(value).encode() ).decode() def consume_token(self, token, max_age=600): @@ -28,8 +39,20 @@ """ try: - return self.signer.unsign( + result = self.signer.unsign( base64.urlsafe_b64decode(token.encode()), max_age ) except (BadSignature, base64.binascii.Error): return None + + username, login_timestamp = result.split(self.signer.sep) + try: + user = USER.objects.get(username=username) + user_login_timestamp = ('' if user.last_login is None + else int(user.last_login.timestamp())) + if user_login_timestamp == login_timestamp: + return username + else: + return None # The user has logged in since this token was made + except USER.DoesNotExist: + return username