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
48a2eb277d234219dd116d9a0dec5a559b22aff8
app/main/services/process_request_json.py
app/main/services/process_request_json.py
import types from query_builder import FILTER_FIELDS, TEXT_FIELDS from conversions import strip_and_lowercase def process_values_for_matching(request_json, key): values = request_json[key] if isinstance(values, types.ListType): fixed = [] for i in values: fixed.append(strip_and_lowercase(i)) return fixed elif isinstance(values, basestring): return strip_and_lowercase(values) return values def convert_request_json_into_index_json(request_json): filter_fields = [field for field in request_json if field in FILTER_FIELDS] for field in filter_fields: request_json["filter_" + field] = \ process_values_for_matching(request_json, field) if field not in TEXT_FIELDS: del request_json[field] return request_json
from query_builder import FILTER_FIELDS, TEXT_FIELDS from conversions import strip_and_lowercase def process_values_for_matching(request_json, key): values = request_json[key] if isinstance(values, list): return [strip_and_lowercase(value) for value in values] elif isinstance(values, basestring): return strip_and_lowercase(values) return values def convert_request_json_into_index_json(request_json): filter_fields = [field for field in request_json if field in FILTER_FIELDS] for field in filter_fields: request_json["filter_" + field] = \ process_values_for_matching(request_json, field) if field not in TEXT_FIELDS: del request_json[field] return request_json
Refactor argument processing to list comprehension
Refactor argument processing to list comprehension
Python
mit
RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api
--- +++ @@ -1,4 +1,3 @@ -import types from query_builder import FILTER_FIELDS, TEXT_FIELDS from conversions import strip_and_lowercase @@ -6,11 +5,8 @@ def process_values_for_matching(request_json, key): values = request_json[key] - if isinstance(values, types.ListType): - fixed = [] - for i in values: - fixed.append(strip_and_lowercase(i)) - return fixed + if isinstance(values, list): + return [strip_and_lowercase(value) for value in values] elif isinstance(values, basestring): return strip_and_lowercase(values)
33a4f91981373b284e005b245d19fae0000f9201
pontoon/administration/management/commands/update_projects.py
pontoon/administration/management/commands/update_projects.py
import datetime from django.core.management.base import BaseCommand, CommandError from pontoon.administration.utils.files import ( update_from_repository, extract_to_database, ) from pontoon.base.models import Project class Command(BaseCommand): help = 'Update all projects from their repositories and store changes \ to the database' def handle(self, *args, **options): for project in Project.objects.all(): try: update_from_repository(project) extract_to_database(project) now = datetime.datetime.now() self.stdout.write( '[%s]: Successfully updated project "%s"\n' % (now, project)) except Exception as e: now = datetime.datetime.now() raise CommandError( '[%s]: UpdateProjectsFromRepositoryError: %s\n' % (now, unicode(e)))
import datetime from django.core.management.base import BaseCommand, CommandError from pontoon.administration.utils.files import ( update_from_repository, extract_to_database, ) from pontoon.base.models import Project class Command(BaseCommand): args = '<project_id project_id ...>' help = 'Update projects from repositories and store changes to database' def handle(self, *args, **options): projects = Project.objects.all() if args: projects = projects.filter(pk__in=args) for project in projects: try: update_from_repository(project) extract_to_database(project) now = datetime.datetime.now() self.stdout.write( '[%s]: Successfully updated project "%s"\n' % (now, project)) except Exception as e: now = datetime.datetime.now() raise CommandError( '[%s]: UpdateProjectsFromRepositoryError: %s\n' % (now, unicode(e)))
Allow specifying which project to udpate with the management command
Allow specifying which project to udpate with the management command
Python
bsd-3-clause
m8ttyB/pontoon,mozilla/pontoon,mastizada/pontoon,mastizada/pontoon,sudheesh001/pontoon,Jobava/mirror-pontoon,mozilla/pontoon,Osmose/pontoon,sudheesh001/pontoon,yfdyh000/pontoon,mozilla/pontoon,m8ttyB/pontoon,mathjazz/pontoon,participedia/pontoon,mastizada/pontoon,mathjazz/pontoon,sudheesh001/pontoon,Osmose/pontoon,mozilla/pontoon,yfdyh000/pontoon,mathjazz/pontoon,mozilla/pontoon,vivekanand1101/pontoon,m8ttyB/pontoon,participedia/pontoon,yfdyh000/pontoon,vivekanand1101/pontoon,vivekanand1101/pontoon,jotes/pontoon,Osmose/pontoon,mathjazz/pontoon,vivekanand1101/pontoon,jotes/pontoon,participedia/pontoon,Jobava/mirror-pontoon,yfdyh000/pontoon,Jobava/mirror-pontoon,sudheesh001/pontoon,jotes/pontoon,jotes/pontoon,Jobava/mirror-pontoon,participedia/pontoon,mastizada/pontoon,mathjazz/pontoon,m8ttyB/pontoon,Osmose/pontoon
--- +++ @@ -12,11 +12,15 @@ class Command(BaseCommand): - help = 'Update all projects from their repositories and store changes \ - to the database' + args = '<project_id project_id ...>' + help = 'Update projects from repositories and store changes to database' def handle(self, *args, **options): - for project in Project.objects.all(): + projects = Project.objects.all() + if args: + projects = projects.filter(pk__in=args) + + for project in projects: try: update_from_repository(project) extract_to_database(project)
0263189433456f23bdcbb1921d2f710b045cd5ba
bot.py
bot.py
import zirc import ssl import socket import utils import commands debug = False class Bot(zirc.Client): def __init__(self): self.connection = zirc.Socket(family=socket.AF_INET6, wrapper=ssl.wrap_socket) self.config = zirc.IRCConfig(host="chat.freenode.net", port=6697, nickname="zIRCBot2", ident="zirc", realname="A zIRC bot", channels=["##wolfy1339", "##powder-bots"], sasl_user="BigWolfy1339", sasl_pass="") self.connect(self.config) self.start() @staticmethod def on_ctcp(irc, raw): utils.print_(raw, flush=True) @classmethod def on_privmsg(self, event, irc, arguments): if " ".join(arguments).startswith("?"): utils.call_command(self, event, irc, arguments) @classmethod def on_all(self, event, irc): if debug: utils.print_(event.raw, flush=True) @classmethod def on_send(self, event, irc): if debug: utils.print_(event.raw, flush=True) @classmethod def on_nicknameinuse(self, event, irc): irc.nick(bot.config['nickname'] + "_") Bot()
import zirc import ssl import socket import utils import commands debug = False class Bot(zirc.Client): def __init__(self): self.connection = zirc.Socket(family=socket.AF_INET6, wrapper=ssl.wrap_socket) self.config = zirc.IRCConfig(host="chat.freenode.net", port=6697, nickname="zIRCBot2", ident="zirc", realname="A zIRC bot", channels=["##wolfy1339", "##powder-bots"], sasl_user="BigWolfy1339", sasl_pass="") self.connect(self.config) self.start() @staticmethod def on_ctcp(irc, raw): utils.print_(raw, flush=True) @classmethod def on_privmsg(self, event, irc, arguments): if " ".join(arguments).startswith("?"): utils.call_command(self, event, irc, arguments) def on_all(self, event, irc): if debug: utils.print_(event.raw, flush=True) def on_send(self, event, irc): if debug: utils.print_(event.raw, flush=True) def on_nicknameinuse(self, event, irc): irc.nick(self.config['nickname'] + "_") Bot()
Fix error where self.config was undefined
Fix error where self.config was undefined These decorators are harsh
Python
mit
wolfy1339/Python-IRC-Bot
--- +++ @@ -32,18 +32,15 @@ if " ".join(arguments).startswith("?"): utils.call_command(self, event, irc, arguments) - @classmethod def on_all(self, event, irc): if debug: utils.print_(event.raw, flush=True) - @classmethod def on_send(self, event, irc): if debug: utils.print_(event.raw, flush=True) - @classmethod def on_nicknameinuse(self, event, irc): - irc.nick(bot.config['nickname'] + "_") + irc.nick(self.config['nickname'] + "_") Bot()
052de49807dcb9895608e3882b799642b0b08d18
exercises/circular-buffer/circular_buffer.py
exercises/circular-buffer/circular_buffer.py
class BufferFullException(Exception): pass class BufferEmptyException(Exception): pass class CircularBuffer(object): def __init__(self): pass
class BufferFullException(Exception): pass class BufferEmptyException(Exception): pass class CircularBuffer(object): def __init__(self, capacity): pass
Add parameter capacity to circular-buffer example
Add parameter capacity to circular-buffer example Fixes #550
Python
mit
jmluy/xpython,mweb/python,mweb/python,pheanex/xpython,exercism/xpython,jmluy/xpython,exercism/xpython,smalley/python,behrtam/xpython,behrtam/xpython,exercism/python,N-Parsons/exercism-python,exercism/python,N-Parsons/exercism-python,pheanex/xpython,smalley/python
--- +++ @@ -7,5 +7,5 @@ class CircularBuffer(object): - def __init__(self): + def __init__(self, capacity): pass
095f2a78416b12f23b4f59d6415103bd4873a86b
project/tenhou/main.py
project/tenhou/main.py
# -*- coding: utf-8 -*- import logging from tenhou.client import TenhouClient from utils.settings_handler import settings logger = logging.getLogger('tenhou') def connect_and_play(): logger.info('Bot AI enabled: {}'.format(settings.ENABLE_AI)) client = TenhouClient() client.connect() try: was_auth = client.authenticate() if was_auth: client.start_game() else: client.end_game() except KeyboardInterrupt: logger.info('Ending the game...') client.end_game()
# -*- coding: utf-8 -*- import logging from tenhou.client import TenhouClient from utils.settings_handler import settings logger = logging.getLogger('tenhou') def connect_and_play(): logger.info('Bot AI enabled: {}'.format(settings.ENABLE_AI)) client = TenhouClient() client.connect() try: was_auth = client.authenticate() if was_auth: client.start_game() else: client.end_game() except KeyboardInterrupt: logger.info('Ending the game...') client.end_game() except Exception as e: logger.exception('Unexpected exception', exc_info=e) logger.info('Ending the game...') client.end_game(False)
Handle unexpected errors and store stack trace to the log
Handle unexpected errors and store stack trace to the log
Python
mit
MahjongRepository/tenhou-python-bot,huangenyan/Lattish,huangenyan/Lattish,MahjongRepository/tenhou-python-bot
--- +++ @@ -24,3 +24,7 @@ except KeyboardInterrupt: logger.info('Ending the game...') client.end_game() + except Exception as e: + logger.exception('Unexpected exception', exc_info=e) + logger.info('Ending the game...') + client.end_game(False)
1f5ee2f729b947a31ab2b04a72ae8c40616db73a
tests/test_plugin_states.py
tests/test_plugin_states.py
from contextlib import contextmanager from os import path from unittest import TestCase from dictdiffer import diff from jsontest import JsonTest from mock import patch from canaryd_packages import six from canaryd.plugin import get_plugin_by_name class TestPluginRealStates(TestCase): def test_meta_plugin(self): plugin = get_plugin_by_name('meta') plugin.get_state({}) @six.add_metaclass(JsonTest) class TestPluginStates(TestCase): jsontest_files = path.join('tests/plugins') @contextmanager def patch_commands(self, commands): def handle_command(command, *args, **kwargs): command = command[0] if command not in commands: raise ValueError('Broken tests: {0} not in commands: {1}'.format( command, commands.keys(), )) return '\n'.join(commands[command]) check_output_patch = patch( 'canaryd.subprocess.check_output', handle_command, ) check_output_patch.start() yield check_output_patch.stop() def jsontest_function(self, test_name, test_data): plugin = get_plugin_by_name(test_data['plugin']) with self.patch_commands(test_data['commands']): state = plugin.get_state({}) try: self.assertEqual(state, test_data['state']) except AssertionError: print(list(diff(test_data['state'], state))) raise
from contextlib import contextmanager from os import path from unittest import TestCase from dictdiffer import diff from jsontest import JsonTest from mock import patch from canaryd_packages import six from canaryd.plugin import get_plugin_by_name from canaryd.settings import CanarydSettings class TestPluginRealStates(TestCase): def test_meta_plugin(self): plugin = get_plugin_by_name('meta') plugin.get_state({}) @six.add_metaclass(JsonTest) class TestPluginStates(TestCase): jsontest_files = path.join('tests/plugins') test_settings = CanarydSettings() @contextmanager def patch_commands(self, commands): def handle_command(command, *args, **kwargs): command = command[0] if command not in commands: raise ValueError('Broken tests: {0} not in commands: {1}'.format( command, commands.keys(), )) return '\n'.join(commands[command]) check_output_patch = patch( 'canaryd.subprocess.check_output', handle_command, ) check_output_patch.start() yield check_output_patch.stop() def jsontest_function(self, test_name, test_data): plugin = get_plugin_by_name(test_data['plugin']) with self.patch_commands(test_data['commands']): state = plugin.get_state(self.test_settings) try: self.assertEqual(state, test_data['state']) except AssertionError: print(list(diff(test_data['state'], state))) raise
Fix tests by passing default settings object rather than empty dict.
Fix tests by passing default settings object rather than empty dict.
Python
mit
Oxygem/canaryd,Oxygem/canaryd
--- +++ @@ -9,6 +9,7 @@ from canaryd_packages import six from canaryd.plugin import get_plugin_by_name +from canaryd.settings import CanarydSettings class TestPluginRealStates(TestCase): @@ -20,6 +21,7 @@ @six.add_metaclass(JsonTest) class TestPluginStates(TestCase): jsontest_files = path.join('tests/plugins') + test_settings = CanarydSettings() @contextmanager def patch_commands(self, commands): @@ -47,7 +49,7 @@ plugin = get_plugin_by_name(test_data['plugin']) with self.patch_commands(test_data['commands']): - state = plugin.get_state({}) + state = plugin.get_state(self.test_settings) try: self.assertEqual(state, test_data['state'])
19a508aad7c42469923c6f62acef67113e280501
memefarm/imagesearch.py
memefarm/imagesearch.py
import json import os import random import requests from PIL import Image # GLOBALS endpoint = "https://www.googleapis.com/customsearch/v1" searchid = "013060195084513904668:z7-hxk7q35k" # Retrieve my API key from a secret file with open(os.path.join(os.path.dirname(__file__), "API_KEY.txt"), "r") as f: API_KEY = f.read() # API def get_image(search): """ Get a ramdom image URL from the first 10 google images results for a given search term """ r = requests.get(endpoint, params={ "key": API_KEY, "cx": searchid, "searchType": "image", "q": search, }) data = json.loads(r.text) # Load JSON responses results = data["items"] # Find the images returned result = random.choice(results) # Pick a random one return result["link"] # Return its link if __name__ == "__main__": print(get_image("cow"))
import json import os import random import requests from io import BytesIO from PIL import Image # GLOBALS endpoint = "https://www.googleapis.com/customsearch/v1" searchid = "013060195084513904668:z7-hxk7q35k" # Retrieve my API key from a secret file with open(os.path.join(os.path.dirname(__file__), "API_KEY.txt"), "r") as f: API_KEY = f.read() # API def getImageUrl(search): """ Get a ramdom image URL from the first 10 google images results for a given search term """ r = requests.get(endpoint, params={ "key": API_KEY, "cx": searchid, "searchType": "image", "q": search, }) data = json.loads(r.text) # Load JSON responses results = data["items"] # Find the images returned result = random.choice(results) # Pick a random one return result["link"] # Return its link def getImage(search): """ Get a PIL image for a given search term """ url = getImageUrl(search) # Get an image URL req = requests.get(url) # Download image b = BytesIO(req.content) # Load into file-like object return Image.open(b) # Open and return if __name__ == "__main__": getImage("cow").show()
Add method for getting PIL image
Add method for getting PIL image Also change function names to be uniform throughout
Python
mit
The-Penultimate-Defenestrator/memefarm
--- +++ @@ -1,9 +1,9 @@ import json import os import random - import requests +from io import BytesIO from PIL import Image # GLOBALS @@ -18,7 +18,7 @@ # API -def get_image(search): +def getImageUrl(search): """ Get a ramdom image URL from the first 10 google images results for a given search term """ r = requests.get(endpoint, params={ @@ -33,5 +33,14 @@ result = random.choice(results) # Pick a random one return result["link"] # Return its link + +def getImage(search): + """ Get a PIL image for a given search term """ + url = getImageUrl(search) # Get an image URL + req = requests.get(url) # Download image + b = BytesIO(req.content) # Load into file-like object + return Image.open(b) # Open and return + + if __name__ == "__main__": - print(get_image("cow")) + getImage("cow").show()
5f2c7e34bb681fb611f6ba068fc02953d26ab424
pyinfra/facts/pacman.py
pyinfra/facts/pacman.py
from pyinfra.api import FactBase from .util.packaging import parse_packages PACMAN_REGEX = r'^([0-9a-zA-Z\-]+)\s([0-9\._+a-z\-]+)' class PacmanUnpackGroup(FactBase): ''' Returns a list of actual packages belonging to the provided package name, expanding groups or virtual packages. .. code:: python [ 'package_name', [ ''' requires_command = 'pacman' default = list def command(self, name): # Accept failure here (|| true) for invalid/unknown packages return 'pacman -S --print-format "%n" {0} || true'.format(name) def process(self, output): return output class PacmanPackages(FactBase): ''' Returns a dict of installed pacman packages: .. code:: python { 'package_name': ['version'], } ''' command = 'pacman -Q' requires_command = 'pacman' default = dict def process(self, output): return parse_packages(PACMAN_REGEX, output)
from pyinfra.api import FactBase from .util.packaging import parse_packages PACMAN_REGEX = r'^([0-9a-zA-Z\-]+)\s([0-9\._+a-z\-]+)' class PacmanUnpackGroup(FactBase): ''' Returns a list of actual packages belonging to the provided package name, expanding groups or virtual packages. .. code:: python [ 'package_name', ] ''' requires_command = 'pacman' default = list def command(self, name): # Accept failure here (|| true) for invalid/unknown packages return 'pacman -S --print-format "%n" {0} || true'.format(name) def process(self, output): return output class PacmanPackages(FactBase): ''' Returns a dict of installed pacman packages: .. code:: python { 'package_name': ['version'], } ''' command = 'pacman -Q' requires_command = 'pacman' default = dict def process(self, output): return parse_packages(PACMAN_REGEX, output)
Fix docstring in `PacmanUnpackGroup` fact.
Fix docstring in `PacmanUnpackGroup` fact.
Python
mit
Fizzadar/pyinfra,Fizzadar/pyinfra
--- +++ @@ -14,7 +14,7 @@ [ 'package_name', - [ + ] ''' requires_command = 'pacman'
82c4ade1727a044946b0ebf148fe4e015d8dd7af
python/ImageDisplay.py
python/ImageDisplay.py
import numpy as np import cv2 # Load an image in color img = cv2.imread("doge.jpeg", 1) cv2.imshow("image", img) key = cv2.waitKey(0) cv2.destroyAllWindows()
Add read image in color
Add read image in color
Python
mit
maximest-pierre/opencv_example,maximest-pierre/opencv_example
--- +++ @@ -0,0 +1,9 @@ +import numpy as np +import cv2 + +# Load an image in color +img = cv2.imread("doge.jpeg", 1) +cv2.imshow("image", img) +key = cv2.waitKey(0) + +cv2.destroyAllWindows()
f6a65fb602fb13c01ad2d9ee7cf50415df9ffa7e
sparkback/__init__.py
sparkback/__init__.py
# -*- coding: utf-8 -*- from __future__ import division import argparse ticks = ('▁', 'β–‚', 'β–ƒ', 'β–„', 'β–…', 'β–†', 'β–‡', 'β–ˆ') def scale_data(data): m = min(data) n = (max(data) - m) / (len(ticks) - 1) # if every element is the same height return all lower ticks, else compute # the tick height if n == 0: return [ ticks[0] for t in data] else: return [ ticks[int((t - m) / n)] for t in data ] def print_ansi_spark(d): print ''.join(d) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator') args = parser.parse_args() print_ansi_spark(scale_data(args.integers))
# -*- coding: utf-8 -*- from __future__ import division import argparse ticks = ('▁', 'β–‚', 'β–ƒ', 'β–„', 'β–…', 'β–†', 'β–‡', 'β–ˆ') def scale_data(data): m = min(data) n = (max(data) - m) / (len(ticks) - 1) # if every element is the same height return all lower ticks, else compute # the tick height if n == 0: return [ ticks[0] for t in data] else: return [ ticks[int((t - m) / n)] for t in data ] def print_ansi_spark(d): print ''.join(d) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Process numbers') parser.add_argument('numbers', metavar='N', type=float, nargs='+', help='series of data to plot') args = parser.parse_args() print_ansi_spark(scale_data(args.numbers))
Update command line interface to accept floating point input
Update command line interface to accept floating point input
Python
mit
mmichie/sparkback
--- +++ @@ -19,8 +19,8 @@ print ''.join(d) if __name__ == "__main__": - parser = argparse.ArgumentParser(description='Process some integers.') - parser.add_argument('integers', metavar='N', type=int, nargs='+', - help='an integer for the accumulator') + parser = argparse.ArgumentParser(description='Process numbers') + parser.add_argument('numbers', metavar='N', type=float, nargs='+', + help='series of data to plot') args = parser.parse_args() - print_ansi_spark(scale_data(args.integers)) + print_ansi_spark(scale_data(args.numbers))
4bcc8a2f38a010e90eb28f8b4339fc691216ff10
main.py
main.py
import os from flask import Flask from flask import render_template from flask import send_from_directory import zip_codes import weather app = Flask(__name__) app.debug = True @app.route("/") def index(): return render_template('index.html') @app.route("/<zip_code>") def forecast(zip_code): if not zip_codes.is_listed(zip_code): return render_template("wrong_zip.html", zip_code=zip_code),404 city = "/".join(zip_codes.city(zip_code)) txt = weather.forecast_txt(zip_code) forecast = weather.parse(txt) print(forecast) return render_template("forecast.html",city=city,forecast=forecast) @app.errorhandler(404) def page_not_found(error): return render_template('404.html'), 404 @app.errorhandler(500) def server_error(error): return render_template('500.html'), 500 @app.route('/favicon.ico') def favicon(): return send_from_directory(os.path.join(app.root_path, 'static/img'), 'favicon.ico', mimetype='image/vnd.microsoft.icon') if __name__ == "__main__": app.run(debug=True)
import os from flask import Flask from flask import render_template from flask import send_from_directory import zip_codes import weather app = Flask(__name__) @app.route("/") def index(): return render_template('index.html') @app.route("/<zip_code>") def forecast(zip_code): if not zip_codes.is_listed(zip_code): return render_template("wrong_zip.html", zip_code=zip_code),404 city = "/".join(zip_codes.city(zip_code)) txt = weather.forecast_txt(zip_code) forecast = weather.parse(txt) print(forecast) return render_template("forecast.html",city=city,forecast=forecast) @app.errorhandler(404) def page_not_found(error): return render_template('404.html'), 404 @app.errorhandler(500) def server_error(error): return render_template('500.html'), 500 @app.route('/favicon.ico') def favicon(): return send_from_directory(os.path.join(app.root_path, 'static/img'), 'favicon.ico', mimetype='image/vnd.microsoft.icon') if __name__ == "__main__": app.run(debug=False)
Debug flags back to false. Can't use it on prod D:
Debug flags back to false. Can't use it on prod D: This reverts commit 4bf055370da89b13fbe4d1076562183d661904ce.
Python
agpl-3.0
joliv/wordy-weather,joliv/wordy-weather
--- +++ @@ -5,7 +5,6 @@ import zip_codes import weather app = Flask(__name__) -app.debug = True @app.route("/") def index(): @@ -35,4 +34,4 @@ 'favicon.ico', mimetype='image/vnd.microsoft.icon') if __name__ == "__main__": - app.run(debug=True) + app.run(debug=False)
9742935bf5dbc58ffa7fa0ab4d23a920aec60837
main.py
main.py
#!/usr/bin/python3.5 # -*- coding: utf-8 -*- import sys def check_dependencies(): deps = ["PyQt5", "unicorn", "capstone", "keystone", "pygments"] for d in deps: try: __import__(d) except ImportError: print("[-] Missing required dependency '%s'" % d) sys.exit(1) return if __name__ == '__main__': from cemu.core import Cemu check_dependencies() Cemu()
#!/usr/bin/env python3.5 # -*- coding: utf-8 -*- import sys def check_dependencies(): deps = ["PyQt5", "unicorn", "capstone", "keystone", "pygments"] for d in deps: try: __import__(d) except ImportError: print("[-] Missing required dependency '%s'" % d) sys.exit(1) return if __name__ == '__main__': from cemu.core import Cemu check_dependencies() Cemu()
Add support for executing in a virtual env
Add support for executing in a virtual env
Python
mit
hugsy/cemu,hugsy/cemu,hugsy/cemu
--- +++ @@ -1,4 +1,4 @@ -#!/usr/bin/python3.5 +#!/usr/bin/env python3.5 # -*- coding: utf-8 -*- import sys
f5c1255739fa50218af066f2bf690cc46424a38d
main.py
main.py
from crawlers.one337x import One337x if __name__ == '__main__': crawler = One337x() torrents = list(crawler.fetch_torrents('arrow'))
from crawlers.one337x import One337x from flask import Flask, request, Response from jsonpickle import encode app = Flask(__name__) app.secret_key = '\xb0\xf6\x86K\x0c d\x15\xfc\xdd\x96\xf5\t\xa5\xba\xfb6\x1am@\xb2r\x82\xc1' @app.route('/') def index(): data = {"message": 'Welcome to osprey'} json_str = encode(data, unpicklable=False) return Response(json_str, mimetype='application/json') @app.route('/search/<search_term>', methods=['GET']) def search(search_term): crawler = One337x() torrents = list(crawler.fetch_torrents(search_term)) json_str = encode(torrents, unpicklable=False) return Response(json_str, mimetype="application/json") if __name__ == '__main__': crawler = One337x() torrents = list(crawler.fetch_torrents('designated')) json_string = encode(torrents[:2], unpicklable=False) print(json_string)
Add API layer using Flask :dancers:
Add API layer using Flask :dancers:
Python
mit
fayimora/osprey,fayimora/osprey,fayimora/osprey
--- +++ @@ -1,6 +1,27 @@ from crawlers.one337x import One337x +from flask import Flask, request, Response +from jsonpickle import encode +app = Flask(__name__) +app.secret_key = '\xb0\xf6\x86K\x0c d\x15\xfc\xdd\x96\xf5\t\xa5\xba\xfb6\x1am@\xb2r\x82\xc1' + + +@app.route('/') +def index(): + data = {"message": 'Welcome to osprey'} + json_str = encode(data, unpicklable=False) + return Response(json_str, mimetype='application/json') + + +@app.route('/search/<search_term>', methods=['GET']) +def search(search_term): + crawler = One337x() + torrents = list(crawler.fetch_torrents(search_term)) + json_str = encode(torrents, unpicklable=False) + return Response(json_str, mimetype="application/json") if __name__ == '__main__': crawler = One337x() - torrents = list(crawler.fetch_torrents('arrow')) + torrents = list(crawler.fetch_torrents('designated')) + json_string = encode(torrents[:2], unpicklable=False) + print(json_string)
b2ef5ac911a850ac90208ff4f6b40670f998b2ec
main.py
main.py
#!/usr/bin/env python from glob import glob import os.path import re import bottle @bottle.route('/') @bottle.view('index') def index(): return dict(debug=bottle.request.GET.get('debug')) @bottle.route('/static/<path:re:.*>') def static(path): return bottle.static_file(path, root=os.path.join(os.path.dirname(__file__), 'static')) @bottle.route('/tests') @bottle.view('tests/index') def test_index(): tests = dict((re.match(r'\b(\w+)_test.html', os.path.basename(filename)).group(1), filename) for filename in glob(os.path.join(os.path.dirname(__file__), 'static', 'tests', '*_test.html'))) return dict(tests=tests) @bottle.route('/webglmaps') @bottle.view('webglmaps/index') def webglmaps_index(): return dict(debug=bottle.request.GET.get('debug')) if __name__ == '__main__': bottle.DEBUG = True bottle.run(reloader=True, server='tornado')
#!/usr/bin/env python from glob import glob import os.path import re import bottle @bottle.route('/') @bottle.view('index') def index(): return dict(debug=bottle.request.GET.get('debug')) @bottle.route('/static/<path:re:.*>') def static(path): return bottle.static_file(path, root=os.path.join(os.path.dirname(__file__), 'static')) @bottle.route('/tests') @bottle.view('tests/index') def test_index(): tests = dict((re.match(r'\b(\w+)_test.html', os.path.basename(filename)).group(1), filename) for filename in glob(os.path.join(os.path.dirname(__file__), 'static', 'tests', '*_test.html'))) return dict(tests=tests) @bottle.route('/webglmaps') @bottle.view('webglmaps/index') def webglmaps_index(): return dict(debug=bottle.request.GET.get('debug')) if __name__ == '__main__': bottle.debug(True) bottle.run(reloader=True, server='tornado')
Use new Bottle debug API
Use new Bottle debug API
Python
agpl-3.0
twpayne/webglmaps,twpayne/webglmaps
--- +++ @@ -32,5 +32,5 @@ if __name__ == '__main__': - bottle.DEBUG = True + bottle.debug(True) bottle.run(reloader=True, server='tornado')
062c46ca8b83dd7791cfed1305c2ba58872601af
go/api/views.py
go/api/views.py
from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_http_methods from django.views.decorators.csrf import csrf_exempt from go.api.go_api import client import logging logger = logging.getLogger(__name__) @login_required @csrf_exempt @require_http_methods(['GET', 'POST']) def go_api_proxy(request): response = client.request( request.session.session_key, data=request.body, method=request.method) return HttpResponse( response.content, status=response.status_code, content_type=response.headers['content-type'])
from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_http_methods from django.views.decorators.csrf import csrf_exempt from go.api.go_api import client import logging logger = logging.getLogger(__name__) @login_required @csrf_exempt @require_http_methods(['GET', 'POST']) def go_api_proxy(request): """ Proxies client requests to the go api worker. NOTE: This is a straight passthrough to the api, no extra behaviour should be added. NOTE: This proxy is a fallback for dev purposes only. A more sensible proxying solution should be used in production (eg. haproxy). """ response = client.request( request.session.session_key, data=request.body, method=request.method) return HttpResponse( response.content, status=response.status_code, content_type=response.headers['content-type'])
Add explanatory docstring for the purpose of the go api proxy view
Add explanatory docstring for the purpose of the go api proxy view
Python
bsd-3-clause
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
--- +++ @@ -14,6 +14,15 @@ @csrf_exempt @require_http_methods(['GET', 'POST']) def go_api_proxy(request): + """ + Proxies client requests to the go api worker. + + NOTE: This is a straight passthrough to the api, no extra behaviour should + be added. + + NOTE: This proxy is a fallback for dev purposes only. A more sensible + proxying solution should be used in production (eg. haproxy). + """ response = client.request( request.session.session_key, data=request.body,
fa2ac624bc33add0e88f158c525885eef8bf555b
user_management/models/tests/factories.py
user_management/models/tests/factories.py
import factory from django.contrib.auth import get_user_model class UserFactory(factory.DjangoModelFactory): FACTORY_FOR = get_user_model() name = factory.Sequence(lambda i: 'Test User {}'.format(i)) email = factory.Sequence(lambda i: 'email{}@example.com'.format(i))
import factory from django.contrib.auth import get_user_model class UserFactory(factory.DjangoModelFactory): FACTORY_FOR = get_user_model() name = factory.Sequence(lambda i: 'Test User {}'.format(i)) email = factory.Sequence(lambda i: 'email{}@example.com'.format(i)) @classmethod def _prepare(cls, create, **kwargs): password = kwargs.pop('password', None) user = super(UserFactory, cls)._prepare(create=False, **kwargs) user.set_password(password) user.raw_password = password if create: user.save() return user
Improve password handling in UserFactory.
Improve password handling in UserFactory.
Python
bsd-2-clause
incuna/django-user-management,incuna/django-user-management
--- +++ @@ -7,3 +7,13 @@ FACTORY_FOR = get_user_model() name = factory.Sequence(lambda i: 'Test User {}'.format(i)) email = factory.Sequence(lambda i: 'email{}@example.com'.format(i)) + + @classmethod + def _prepare(cls, create, **kwargs): + password = kwargs.pop('password', None) + user = super(UserFactory, cls)._prepare(create=False, **kwargs) + user.set_password(password) + user.raw_password = password + if create: + user.save() + return user
4de18ece5ac2f563c6d8a6a247a77cdc8a45881e
hydromet/anomaly.py
hydromet/anomaly.py
def get_monthly_anomaly(ts, start, end): """ Get monthly anomaly. Monthly anomalies calculated from the mean of the data between the specified start and end dates. :param ts: Pandas timeseries, will be converted to monthly. :type ts: pandas.TimeSeries :param start: Start date to calculated mean from. :type start: datetime.datetime :param end: End date to calculated mean from. :type end: datetime.datetime :returns: pandas.TimeSeries -- Monthly anomalies. """ monthly = ts.asfreq('M') base = monthly.ix[start:end] mean = base.groupby(base.index.month).mean() for month in range(1,13): monthly.ix[monthly.index.month == month] -= mean.ix[mean.index == month].values[0] return monthly def get_annual_anomaly(ts, start, end): """ Get annual anomaly. Annual anomalies calculated from the mean of the data between the specified start and end dates. :param ts: Pandas timeseries, will be converted to annual. :type ts: pandas.TimeSeries :param start: Start date to calculated mean from. :type start: datetime.datetime :param end: End date to calculated mean from. :type end: datetime.datetime :returns: pandas.TimeSeries -- Annual anomalies. """ annual = ts.asfreq('A') base = annual.ix[start:end] mean = base.groupby(base.index.year).mean().mean() annual -= mean return annual
def get_monthly_anomaly(ts, start, end): """ Get monthly anomaly. Monthly anomalies calculated from the mean of the data between the specified start and end dates. :param ts: Pandas timeseries, will be converted to monthly. :type ts: pandas.TimeSeries :param start: Start date to calculated mean from. :type start: datetime.datetime :param end: End date to calculated mean from. :type end: datetime.datetime :returns: pandas.TimeSeries -- Monthly anomalies. """ monthly = ts.resample('MS') base = monthly.ix[start:end] mean = base.groupby(base.index.month).mean() for month in range(1,13): monthly.ix[monthly.index.month == month] -= mean.ix[mean.index == month].values[0] return monthly def get_annual_anomaly(ts, start, end): """ Get annual anomaly. Annual anomalies calculated from the mean of the data between the specified start and end dates. :param ts: Pandas timeseries, will be converted to annual. :type ts: pandas.TimeSeries :param start: Start date to calculated mean from. :type start: datetime.datetime :param end: End date to calculated mean from. :type end: datetime.datetime :returns: pandas.TimeSeries -- Annual anomalies. """ annual = ts.resample('AS') base = annual.ix[start:end] mean = base.groupby(base.index.year).mean().mean() annual -= mean return annual
Use start of month/year dates instead of end.
Use start of month/year dates instead of end.
Python
bsd-3-clause
amacd31/hydromet-toolkit,amacd31/hydromet-toolkit
--- +++ @@ -13,7 +13,7 @@ :returns: pandas.TimeSeries -- Monthly anomalies. """ - monthly = ts.asfreq('M') + monthly = ts.resample('MS') base = monthly.ix[start:end] mean = base.groupby(base.index.month).mean() @@ -37,7 +37,7 @@ :returns: pandas.TimeSeries -- Annual anomalies. """ - annual = ts.asfreq('A') + annual = ts.resample('AS') base = annual.ix[start:end] mean = base.groupby(base.index.year).mean().mean()
86197635800e6b19a6b95e9be932999c79042720
dipy/utils/arrfuncs.py
dipy/utils/arrfuncs.py
""" Utilities to manipulate numpy arrays """ import sys import numpy as np from nibabel.volumeutils import endian_codes, native_code, swapped_code def as_native_array(arr): """ Return `arr` as native byteordered array If arr is already native byte ordered, return unchanged. If it is opposite endian, then make a native byte ordered copy and return that Parameters ---------- arr : ndarray Returns ------- native_arr : ndarray If `arr` was native order, this is just `arr`. Otherwise it's a new array such that ``np.all(native_arr == arr)``, with native byte ordering. """ if endian_codes[arr.dtype.byteorder] == native_code: return arr return arr.byteswap().newbyteorder()
""" Utilities to manipulate numpy arrays """ import sys import numpy as np from nibabel.volumeutils import endian_codes, native_code, swapped_code def as_native_array(arr): """ Return `arr` as native byteordered array If arr is already native byte ordered, return unchanged. If it is opposite endian, then make a native byte ordered copy and return that Parameters ---------- arr : ndarray Returns ------- native_arr : ndarray If `arr` was native order, this is just `arr`. Otherwise it's a new array such that ``np.all(native_arr == arr)``, with native byte ordering. """ if endian_codes[arr.dtype.byteorder] == native_code: return arr return arr.byteswap().newbyteorder() def pinv_vec(a, rcond=1e-15): """Vectorized version of numpy.linalg.pinv""" a = np.asarray(a) swap = np.arange(a.ndim) swap[[-2, -1]] = swap[[-1, -2]] u, s, v = np.linalg.svd(a, full_matrices=False) cutoff = np.maximum.reduce(s, axis=-1, keepdims=True) * rcond mask = s > cutoff s[mask] = 1. / s[mask] s[~mask] = 0 return np.einsum('...ij,...jk', np.transpose(v, swap) * s[..., None, :], np.transpose(u, swap))
Add vectorized version of np.linalg.pinv
Add vectorized version of np.linalg.pinv
Python
bsd-3-clause
matthieudumont/dipy,JohnGriffiths/dipy,FrancoisRheaultUS/dipy,matthieudumont/dipy,StongeEtienne/dipy,villalonreina/dipy,FrancoisRheaultUS/dipy,JohnGriffiths/dipy,nilgoyyou/dipy,villalonreina/dipy,nilgoyyou/dipy,StongeEtienne/dipy
--- +++ @@ -28,3 +28,18 @@ return arr return arr.byteswap().newbyteorder() + +def pinv_vec(a, rcond=1e-15): + """Vectorized version of numpy.linalg.pinv""" + + a = np.asarray(a) + swap = np.arange(a.ndim) + swap[[-2, -1]] = swap[[-1, -2]] + u, s, v = np.linalg.svd(a, full_matrices=False) + cutoff = np.maximum.reduce(s, axis=-1, keepdims=True) * rcond + mask = s > cutoff + s[mask] = 1. / s[mask] + s[~mask] = 0 + return np.einsum('...ij,...jk', + np.transpose(v, swap) * s[..., None, :], + np.transpose(u, swap))
f0deb22062930918e497d494aa5e76224f88b5ea
pylxd/containerState.py
pylxd/containerState.py
# Copyright (c) 2016 Canonical Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class ContainerState(): def __init__(self, **kwargs): for key, value in kwargs.iteritems(): setattr(self, key, value)
# Copyright (c) 2016 Canonical Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class ContainerState(): def __init__(self, **kwargs): for key, value in kwargs.iteritems(): setattr(self, key, value)
Fix formatting file for travis
Fix formatting file for travis
Python
apache-2.0
lxc/pylxd,lxc/pylxd
--- +++ @@ -12,6 +12,7 @@ # License for the specific language governing permissions and limitations # under the License. + class ContainerState(): def __init__(self, **kwargs):
49a182c2b6b7c5e5a7be8452d1ccc262b0d45782
delphi/urls.py
delphi/urls.py
"""delphi URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/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. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), ]
"""delphi URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/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. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), ] #serving static urlpatterns += staticfiles_urlpatterns()
Add url for static files
Add url for static files [development]
Python
mit
VulcanoAhab/delphi,VulcanoAhab/delphi,VulcanoAhab/delphi
--- +++ @@ -12,9 +12,14 @@ Including another URLconf 1. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ +from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), ] + +#serving static +urlpatterns += staticfiles_urlpatterns() +
612a411d0d4b2323bcbb3c3bdd41df945a075f53
tree.py
tree.py
import verify class Tree: def __init__(self, elements): self._elements = elements def count(self): return len(self._elements) def elements(self): result = [] for element in self._elements: if element.__class__ == Tree: result += [element.elements()] else: result += [element] return result def to_string(self): # return ' '.join( list comprehension blah blah blah with_parentheses = verify.sexp_to_string(self._elements) return with_parentheses[1:(len(with_parentheses)-1)] def read_expression(scanner): while True: tok = scanner.get_tok() if tok == None: return None if tok == '(': result = [] while 1: subsexp = read_expression(scanner) if subsexp == ')': break elif subsexp == None: raise SyntaxError('eof inside sexp') result.append(subsexp) return result else: return tok def parse(stream): scanner = verify.Scanner(stream) tokens = [] while True: expression = read_expression(scanner) if expression == None: break tokens += [expression] return Tree(tokens)
import verify import tokenizer class Tree: def __init__(self, elements): self._elements = elements def count(self): return len(self._elements) def elements(self): result = [] for element in self._elements: if element.__class__ == Tree: result += [element.elements()] else: result += [element] return result def to_string(self): # return ' '.join( list comprehension blah blah blah with_parentheses = verify.sexp_to_string(self._elements) return with_parentheses[1:(len(with_parentheses)-1)] def read_expression(tokenizer1): while True: token = tokenizer1.next_token() if token == None: return None if token.isspace() or token.startswith("#"): continue if token == '(': result = [] while True: subsexp = read_expression(tokenizer1) if subsexp == ')': break elif subsexp == None: raise SyntaxError('eof inside sexp') result.append(subsexp) return result else: return token def parse(stream): tokenizer1 = tokenizer.Tokenizer(stream) tokens = [] while True: expression = read_expression(tokenizer1) if expression == None: break tokens += [expression] return Tree(tokens)
Switch from scanner to tokenizer.
Switch from scanner to tokenizer.
Python
apache-2.0
jkingdon/jh2gh
--- +++ @@ -1,4 +1,5 @@ import verify +import tokenizer class Tree: def __init__(self, elements): @@ -21,15 +22,17 @@ with_parentheses = verify.sexp_to_string(self._elements) return with_parentheses[1:(len(with_parentheses)-1)] -def read_expression(scanner): +def read_expression(tokenizer1): while True: - tok = scanner.get_tok() - if tok == None: + token = tokenizer1.next_token() + if token == None: return None - if tok == '(': + if token.isspace() or token.startswith("#"): + continue + if token == '(': result = [] - while 1: - subsexp = read_expression(scanner) + while True: + subsexp = read_expression(tokenizer1) if subsexp == ')': break elif subsexp == None: @@ -37,13 +40,13 @@ result.append(subsexp) return result else: - return tok + return token def parse(stream): - scanner = verify.Scanner(stream) + tokenizer1 = tokenizer.Tokenizer(stream) tokens = [] while True: - expression = read_expression(scanner) + expression = read_expression(tokenizer1) if expression == None: break tokens += [expression]
1c60efdf0b0e2c1b49024ab14b8c012a1acaa71d
saw/filters/__init__.py
saw/filters/__init__.py
import os import glob import inspect import saw.items curr_path = os.path.dirname(__file__) __all__ = [ os.path.basename(f)[:-3] for f in glob.glob(curr_path + "/*.py")] class Filter: _filters = dict() @classmethod def _load_filters(self): module_names = [ name.lower() for name in __all__ if name != '__init__' ] filters = __import__('saw.filters', globals(), locals(), module_names, -1) for module_name in module_names: _filter = getattr(filters, module_name) for obj_name, obj in inspect.getmembers(_filter): if (obj_name.lower() == module_name) and inspect.isclass(obj): self._filters[ module_name ] = obj break @classmethod def exists(self, name): return name in self._filters @classmethod def get(self, name, item): if not(self.exists(name)): raise Exception("Filter not found!") filter_class = self._filters[ name ]() if isinstance(item, saw.items.Items): func = filter_class.items else: func = filter_class.item def _call(*args, **kw): return func(item, *args, **kw) return _call Filter._load_filters()
import os import glob import inspect curr_path = os.path.dirname(__file__) __all__ = [ os.path.basename(f)[:-3] for f in glob.glob(curr_path + "/*.py")] class Filter: _filters = dict() @classmethod def _load_filters(self): module_names = [ name.lower() for name in __all__ if name != '__init__' ] filters = __import__('saw.filters', globals(), locals(), module_names, -1) for module_name in module_names: _filter = getattr(filters, module_name) for obj_name, obj in inspect.getmembers(_filter): if (obj_name.lower() == module_name) and inspect.isclass(obj): self._filters[ module_name ] = obj break @classmethod def exists(self, name): return name in self._filters @classmethod def get(self, name, item): if not(self.exists(name)): raise Exception("Filter not found!") func_name = item.__class__.__name__.lower() func = getattr( self._filters[ name ](), func_name) if not(func): raise Exception("Filter's method '%s' not found!" % func_name) def _call(*args, **kw): return func(item, *args, **kw) return _call Filter._load_filters()
Add support another classes for filters, not only Item and Items
Add support another classes for filters, not only Item and Items
Python
mit
diNard/Saw
--- +++ @@ -1,7 +1,6 @@ import os import glob import inspect -import saw.items curr_path = os.path.dirname(__file__) __all__ = [ os.path.basename(f)[:-3] for f in glob.glob(curr_path + "/*.py")] @@ -30,12 +29,10 @@ def get(self, name, item): if not(self.exists(name)): raise Exception("Filter not found!") - - filter_class = self._filters[ name ]() - if isinstance(item, saw.items.Items): - func = filter_class.items - else: - func = filter_class.item + func_name = item.__class__.__name__.lower() + func = getattr( self._filters[ name ](), func_name) + if not(func): + raise Exception("Filter's method '%s' not found!" % func_name) def _call(*args, **kw): return func(item, *args, **kw)
2bde683bcfbdc7149a114abd609a3c91c19cac0f
tagcache/lock.py
tagcache/lock.py
# -*- encoding: utf-8 -*- import os import fcntl class FileLock(object): def __init__(self, fd): # the fd is borrowed, so do not close it self.fd = fd def acquire(self, write=False, block=False): try: lock_flags = fcntl.LOCK_EX if write else fcntl.LOCK_SH if not block: lock_flags |= fcntl.LOCK_NB fcntl.flock(self.fd, lock_flags) return True except IOError: return False def release(self): fcntl.flock(self.fd, fcntl.LOCK_UN)
# -*- encoding: utf-8 -*- import os import fcntl class FileLock(object): def __init__(self, fd): # the fd is borrowed, so do not close it self.fd = fd def acquire(self, ex=False, nb=True): """ Acquire a lock on the fd. :param ex (optional): default False, acquire a exclusive lock if True :param nb (optional): default True, non blocking if True :return: True if acquired """ try: lock_flags = fcntl.LOCK_EX if ex else fcntl.LOCK_SH if nb: lock_flags |= fcntl.LOCK_NB fcntl.flock(self.fd, lock_flags) return True except IOError: return False def release(self): """ Release lock on the fd. """ fcntl.flock(self.fd, fcntl.LOCK_UN)
Change parameter names in acquire. Add some doc.
Change parameter names in acquire. Add some doc.
Python
mit
huangjunwen/tagcache
--- +++ @@ -11,13 +11,21 @@ # the fd is borrowed, so do not close it self.fd = fd - def acquire(self, write=False, block=False): + def acquire(self, ex=False, nb=True): + """ + Acquire a lock on the fd. + + :param ex (optional): default False, acquire a exclusive lock if True + :param nb (optional): default True, non blocking if True + :return: True if acquired + + """ try: - lock_flags = fcntl.LOCK_EX if write else fcntl.LOCK_SH + lock_flags = fcntl.LOCK_EX if ex else fcntl.LOCK_SH - if not block: + if nb: lock_flags |= fcntl.LOCK_NB @@ -30,6 +38,10 @@ return False def release(self): + """ + Release lock on the fd. + + """ fcntl.flock(self.fd, fcntl.LOCK_UN)
49e38383430f778aaa0952d542675e1cca290167
product_supplier_pricelist/__openerp__.py
product_supplier_pricelist/__openerp__.py
# -*- coding: utf-8 -*- { 'name': 'Product Supplier Pricelist', 'version': '1.0', 'category': 'Product', 'sequence': 14, 'summary': '', 'description': """ Product Supplier Pricelist ========================== Add sql constraint to restrict: 1. That you can only add one supplier to a product per company 2. That you can add olny one record of same quantity for a supplier pricelist It also adds to more menus (and add some related fields) on purchase/product. """, 'author': 'Ingenieria ADHOC', 'website': 'www.ingadhoc.com', 'images': [ ], 'depends': [ 'purchase', ], 'data': [ 'product_view.xml', ], 'demo': [ ], 'test': [ ], 'installable': True, 'auto_install': False, 'application': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# -*- coding: utf-8 -*- { 'name': 'Product Supplier Pricelist', 'version': '1.0', 'category': 'Product', 'sequence': 14, 'summary': '', 'description': """ Product Supplier Pricelist ========================== Add sql constraint to restrict: 1. That you can only add one supplier to a product per company 2. That you can add olny one record of same quantity for a supplier pricelist It also adds to more menus (and add some related fields) on purchase/product. """, 'author': 'Ingenieria ADHOC', 'website': 'www.ingadhoc.com', 'images': [ ], 'depends': [ 'purchase', ], 'data': [ 'product_view.xml', ], 'demo': [ ], 'test': [ ], # TODO fix this module and make installable 'installable': False, 'auto_install': False, 'application': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
FIX disable product supplier pricelist
FIX disable product supplier pricelist
Python
agpl-3.0
csrocha/account_check,csrocha/account_check
--- +++ @@ -30,7 +30,8 @@ ], 'test': [ ], - 'installable': True, + # TODO fix this module and make installable + 'installable': False, 'auto_install': False, 'application': False, }
ca5877d66698179a3c26d12938dfac10cd19d932
paci/commands/search.py
paci/commands/search.py
"""The search command.""" from paci.helpers import display_helper, cache_helper from .base import Base class Search(Base): """Searches for a package!""" def run(self): pkg_name = self.options["<package>"] result = cache_helper.find_pkg(pkg_name, self.settings["paci"]["registry"], self.repo_cache) if result: display_helper.print_list(["Name", "Version", "Description", "Registry"], result) else: print("Package not found.")
"""The search command.""" from paci.helpers import display_helper, cache_helper, std_helper from termcolor import colored from .base import Base class Search(Base): """Searches for a package!""" def run(self): pkg_name = self.options["<package>"] result = cache_helper.find_pkg(pkg_name, self.settings["paci"]["registry"], self.repo_cache) if result: print(colored("Showing all search results for \"{}\"...\n".format(std_helper.stringify(pkg_name)), 'yellow', attrs=['bold'])) display_helper.print_list(["Name", "Version", "Description", "Registry"], result) else: print("Package not found.")
Add a description of what the output represents
Add a description of what the output represents
Python
mit
tradebyte/paci,tradebyte/paci
--- +++ @@ -1,6 +1,7 @@ """The search command.""" -from paci.helpers import display_helper, cache_helper +from paci.helpers import display_helper, cache_helper, std_helper +from termcolor import colored from .base import Base @@ -11,6 +12,7 @@ pkg_name = self.options["<package>"] result = cache_helper.find_pkg(pkg_name, self.settings["paci"]["registry"], self.repo_cache) if result: + print(colored("Showing all search results for \"{}\"...\n".format(std_helper.stringify(pkg_name)), 'yellow', attrs=['bold'])) display_helper.print_list(["Name", "Version", "Description", "Registry"], result) else: print("Package not found.")
78c100ac31c00f4b1c90eb897df2fd5062bf4b0f
tenant/models.py
tenant/models.py
from django.db import models from django.conf import settings from tenant.utils import parse_connection_string from tenant.utils import connect_tenant_provider, disconnect_tenant_provider from tenant import settings as tenant_settings class Tenant(models.Model): name = models.CharField(max_length=256, unique=True, db_index=True) public_name = models.CharField(max_length=256) @property def ident(self): return self.name @property def settings(self): return settings.DATABASES[tenant_settings.MULTITENANT_TENANT_DATABASE].copy() def __unicode__(self): return self.public_name from django.db.models.signals import pre_save, post_save, post_init, post_delete from signals import generate_public_name, syncdb, migrate pre_save.connect(generate_public_name, sender=Tenant) #if tenant_settings.MULTITENANT_SYNCDB_ONCREATE: # post_save.connect(syncdb, sender=Tenant) # #if tenant_settings.MULTITENANT_MIGRATE_ONCREATE: # post_save.connect(migrate, sender=Tenant)
from django.db import models from django.conf import settings from tenant.utils import parse_connection_string from tenant.utils import connect_tenant_provider, disconnect_tenant_provider from tenant import settings as tenant_settings class Tenant(models.Model): created = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) name = models.CharField(max_length=256, unique=True, db_index=True) public_name = models.CharField(max_length=256) @property def ident(self): return self.name @property def settings(self): return settings.DATABASES[tenant_settings.MULTITENANT_TENANT_DATABASE].copy() def __unicode__(self): return self.public_name from django.db.models.signals import pre_save, post_save, post_init, post_delete from signals import generate_public_name, syncdb, migrate pre_save.connect(generate_public_name, sender=Tenant) #if tenant_settings.MULTITENANT_SYNCDB_ONCREATE: # post_save.connect(syncdb, sender=Tenant) # #if tenant_settings.MULTITENANT_MIGRATE_ONCREATE: # post_save.connect(migrate, sender=Tenant)
Add created and is_active field to match appschema model
Add created and is_active field to match appschema model
Python
bsd-3-clause
allanlei/django-multitenant
--- +++ @@ -7,6 +7,8 @@ class Tenant(models.Model): + created = models.DateTimeField(auto_now_add=True) + is_active = models.BooleanField(default=True) name = models.CharField(max_length=256, unique=True, db_index=True) public_name = models.CharField(max_length=256)
402e9c8f5d25ac4f9011176d3714193e6fe92c77
linkcheck/management/commands/unignore_links.py
linkcheck/management/commands/unignore_links.py
from django.core.management.base import BaseCommand from linkcheck.utils import unignore class Command(BaseCommand): help = "Goes through all models registered with Linkcheck and records any links found" def execute(self, *args, **options): print("Unignoring all links") unignore()
from django.core.management.base import BaseCommand from linkcheck.utils import unignore class Command(BaseCommand): help = "Updates the `ignore` status of all links to `False`" def execute(self, *args, **options): print("Unignoring all links") unignore()
Fix help text of unignore command
Fix help text of unignore command
Python
bsd-3-clause
DjangoAdminHackers/django-linkcheck,DjangoAdminHackers/django-linkcheck
--- +++ @@ -5,7 +5,7 @@ class Command(BaseCommand): - help = "Goes through all models registered with Linkcheck and records any links found" + help = "Updates the `ignore` status of all links to `False`" def execute(self, *args, **options): print("Unignoring all links")
b618912444a1f30423432347c1ae970f28799bea
astroquery/dace/tests/test_dace_remote.py
astroquery/dace/tests/test_dace_remote.py
import unittest from astropy.tests.helper import remote_data from astroquery.dace import Dace HARPS_PUBLICATION = '2009A&A...493..639M' @remote_data class TestDaceClass(unittest.TestCase): def test_should_get_radial_velocities(self): radial_velocities_table = Dace.query_radial_velocities('HD40307') assert radial_velocities_table is not None and 'rv' in radial_velocities_table.colnames assert 'HARPS' in radial_velocities_table['ins_name'] assert HARPS_PUBLICATION in radial_velocities_table['pub_bibcode'] public_harps_data = [row for row in radial_velocities_table['pub_bibcode'] if HARPS_PUBLICATION in row] assert len(public_harps_data) > 100 if __name__ == "__main__": unittest.main()
import unittest from astropy.tests.helper import remote_data from astroquery.dace import Dace HARPS_PUBLICATION = '2009A&A...493..639M' @remote_data class TestDaceClass(unittest.TestCase): def test_should_get_radial_velocities(self): radial_velocities_table = Dace.query_radial_velocities('HD40307') assert radial_velocities_table is not None and 'rv' in radial_velocities_table.colnames # HARPS is a spectrograph and has to be present for this target because HD40307 has been observed and # processed by this instrument assert 'HARPS' in radial_velocities_table['ins_name'] assert HARPS_PUBLICATION in radial_velocities_table['pub_bibcode'] public_harps_data = [row for row in radial_velocities_table['pub_bibcode'] if HARPS_PUBLICATION in row] assert len(public_harps_data) > 100 if __name__ == "__main__": unittest.main()
Add comment to explain the test with HARPS instrument
Add comment to explain the test with HARPS instrument
Python
bsd-3-clause
imbasimba/astroquery,ceb8/astroquery,imbasimba/astroquery,ceb8/astroquery
--- +++ @@ -11,6 +11,8 @@ def test_should_get_radial_velocities(self): radial_velocities_table = Dace.query_radial_velocities('HD40307') assert radial_velocities_table is not None and 'rv' in radial_velocities_table.colnames + # HARPS is a spectrograph and has to be present for this target because HD40307 has been observed and + # processed by this instrument assert 'HARPS' in radial_velocities_table['ins_name'] assert HARPS_PUBLICATION in radial_velocities_table['pub_bibcode'] public_harps_data = [row for row in radial_velocities_table['pub_bibcode'] if HARPS_PUBLICATION in row]
99b6e39a333801dc1cfc73665dde24459d244ae4
labtoolkit/Utils.py
labtoolkit/Utils.py
""".""" class AmplitudeLimiter(object): """.""" def __init__(self, f, *args, **kwargs): """If thereareno decorator args the function tobe decorated is passed to the constructor.""" # print(f) # print(*args) # print(**kwargs) # print("Inside __init__()") self.f = f def __call__(self, f, *args, **kwargs): """The __call__ method is not called until the decorated function is called.""" # print(f) print(*args) # print(**kwargs) # print("Inside __call__()") setpoint = float(*args) if setpoint > f.amplimit: f.log.warn( "Amplimit ({}) reached with setpoint ({}) on {}" .format(f.amplimit, setpoint, f.instrument)) else: self.f(f, *args) # print("After self.f(*args)")
""".""" class AmplitudeLimiter(object): """.""" def __init__(self, f, *args, **kwargs): """If thereareno decorator args the function tobe decorated is passed to the constructor.""" # print(f) # print(*args) # print(**kwargs) # print("Inside __init__()") self.f = f def __call__(self, f, *args, **kwargs): """The __call__ method is not called until the decorated function is called.""" # print(f) print(*args) # print(**kwargs) # print("Inside __call__()") setpoint = float(*args) if setpoint >= f.amplimit: f.log.warn( "Amplimit ({}) reached with setpoint ({}) on {}" .format(f.amplimit, setpoint, f.instrument)) else: self.f(f, *args) # print("After self.f(*args)")
Fix AmplitudeLimiter > to >= for expected behavour
Fix AmplitudeLimiter > to >= for expected behavour
Python
mit
DavidLutton/EngineeringProject
--- +++ @@ -19,7 +19,7 @@ # print(**kwargs) # print("Inside __call__()") setpoint = float(*args) - if setpoint > f.amplimit: + if setpoint >= f.amplimit: f.log.warn( "Amplimit ({}) reached with setpoint ({}) on {}" .format(f.amplimit, setpoint, f.instrument))
41eb6c371bb334acac25f5b89be1bb3312d77cc1
examples/img_client.py
examples/img_client.py
#!/usr/bin/env python """ This example demonstrates a client fetching images from a server running img_server.py. The first packet contains the number of chunks to expect, and then that number of chunks is read. Lost packets are not handled in any way. """ from nuts import UDPAuthChannel channel = UDPAuthChannel('secret', timeout=4) with channel.connect( ('10.0.0.1', 8001) ) as session: session.send('Take pic!') msg = session.receive() num_chunks = int(msg) with open('latest_img.jpg', 'wb') as img_fh: for i in range(num_chunks): chunk = session.receive() print('got chunk %d of %d' % (i + 1, num_chunks)) img_fh.write(chunk)
#!/usr/bin/env python """ This example demonstrates a client fetching images from a server running img_server.py. The first packet contains the number of chunks to expect, and then that number of chunks is read. Lost packets are not handled in any way. """ from nuts import UDPAuthChannel channel = UDPAuthChannel('secret', timeout=4) with channel.connect( ('10.0.0.1', 8001) ) as session: session.send('Take pic!') msg = session.receive() num_chunks = int(msg) with open('latest_img.jpg', 'wb') as img_fh: for i in range(num_chunks): chunk = session.receive() print('got chunk %d of %d' % (i + 1, num_chunks)) # Preferably, the msg received would support the buffer interface # and be writable directly, but it isn't img_fh.write(chunk.msg)
Write .msg of chunk to file
Write .msg of chunk to file
Python
mit
thusoy/nuts-auth,thusoy/nuts-auth
--- +++ @@ -18,4 +18,6 @@ for i in range(num_chunks): chunk = session.receive() print('got chunk %d of %d' % (i + 1, num_chunks)) - img_fh.write(chunk) + # Preferably, the msg received would support the buffer interface + # and be writable directly, but it isn't + img_fh.write(chunk.msg)
3156cfcfb4bd642fe742bb36909e7b9b87e15963
jesusmtnez/python/koans/koans/triangle.py
jesusmtnez/python/koans/koans/triangle.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Triangle Project Code. # Triangle analyzes the lengths of the sides of a triangle # (represented by a, b and c) and returns the type of triangle. # # It returns: # 'equilateral' if all sides are equal # 'isosceles' if exactly 2 sides are equal # 'scalene' if no sides are equal # # The tests for this method can be found in # about_triangle_project.py # and # about_triangle_project_2.py # def triangle(a, b, c): # DELETE 'PASS' AND WRITE THIS CODE # pass if a == b == c: return 'equilateral' elif a == b or a == c or b == c: return 'isosceles' else: return 'scalene' # Error class used in part 2. No need to change this code. class TriangleError(Exception): pass
#!/usr/bin/env python # -*- coding: utf-8 -*- # Triangle Project Code. # Triangle analyzes the lengths of the sides of a triangle # (represented by a, b and c) and returns the type of triangle. # # It returns: # 'equilateral' if all sides are equal # 'isosceles' if exactly 2 sides are equal # 'scalene' if no sides are equal # # The tests for this method can be found in # about_triangle_project.py # and # about_triangle_project_2.py # def triangle(a, b, c): # Check input if a <= 0 or b <= 0 or c <= 0: raise TriangleError(AttributeError("Negative values")) if a + b + c <= 2 * max(a, b, c): raise TriangleError(AttributeError("Imposible triangle")) if a == b == c: return 'equilateral' elif a == b or a == c or b == c: return 'isosceles' else: return 'scalene' # Error class used in part 2. No need to change this code. class TriangleError(Exception): pass
Complete 'About Triangle Project 2' koans
[Python] Complete 'About Triangle Project 2' koans
Python
mit
JesusMtnez/devexperto-challenge,JesusMtnez/devexperto-challenge
--- +++ @@ -17,8 +17,12 @@ # about_triangle_project_2.py # def triangle(a, b, c): - # DELETE 'PASS' AND WRITE THIS CODE - # pass + # Check input + if a <= 0 or b <= 0 or c <= 0: + raise TriangleError(AttributeError("Negative values")) + if a + b + c <= 2 * max(a, b, c): + raise TriangleError(AttributeError("Imposible triangle")) + if a == b == c: return 'equilateral' elif a == b or a == c or b == c:
2261a15132a0b98821cb3e5614c044f1b41fbc73
smsgateway/__init__.py
smsgateway/__init__.py
__version__ = '2.0.0' def get_account(using=None): from django.conf import settings accounts = settings.SMSGATEWAY_ACCOUNTS if using is not None: return accounts[using] else: return accounts[accounts['__default__']] def send(to, msg, signature, using=None, reliable=False): """ Send an SMS message immediately. * 'to' is a semicolon separated list of phone numbers with an international prefix (+32... etc). * 'msg' is the message itself as a unicode object (max 160 characters). * 'signature' is where the message comes from. Depends on the backend in use. * 'using' is an optional parameter where you can specify a specific account to send messages from. """ from smsgateway.backends import get_backend from smsgateway.sms import SMSRequest account_dict = get_account(using) backend = get_backend(account_dict['backend']) sms_request = SMSRequest(to, msg, signature, reliable=reliable) return backend.send(sms_request, account_dict) def send_queued(to, msg, signature, using=None, reliable=False): """ Place SMS message in queue to be sent. """ from smsgateway.models import QueuedSMS QueuedSMS.objects.create( to=to, content=msg, signature=signature, using=using if using is not None else '__none__', reliable=reliable )
__version__ = '2.0.0' def get_account(using=None): from django.conf import settings accounts = settings.SMSGATEWAY_ACCOUNTS if using is not None: return accounts[using] else: return accounts[accounts['__default__']] def send(to, msg, signature, using=None, reliable=False): """ Send an SMS message immediately. * 'to' is a semicolon separated list of phone numbers with an international prefix (+32... etc). * 'msg' is the message itself as a unicode object (max 160 characters). * 'signature' is where the message comes from. Depends on the backend in use. * 'using' is an optional parameter where you can specify a specific account to send messages from. """ from smsgateway.backends import get_backend from smsgateway.sms import SMSRequest account_dict = get_account(using) backend = get_backend(account_dict['backend']) sms_request = SMSRequest(to, msg, signature, reliable=reliable) return backend.send(sms_request, account_dict) def send_queued(to, msg, signature, using=None, reliable=False, priority=None): """ Place SMS message in queue to be sent. """ from smsgateway.models import QueuedSMS queued_sms = QueuedSMS( to=to, content=msg, signature=signature, using=using if using is not None else '__none__', reliable=reliable ) if priority is not None: queued_sms.priority = priority queued_sms.save()
Add priority option to send_queued
Add priority option to send_queued
Python
bsd-3-clause
peterayeni/django-smsgateway,mvpoland/django-smsgateway,peterayeni/django-smsgateway,mvpoland/django-smsgateway,peterayeni/django-smsgateway,peterayeni/django-smsgateway,mvpoland/django-smsgateway
--- +++ @@ -26,15 +26,18 @@ sms_request = SMSRequest(to, msg, signature, reliable=reliable) return backend.send(sms_request, account_dict) -def send_queued(to, msg, signature, using=None, reliable=False): +def send_queued(to, msg, signature, using=None, reliable=False, priority=None): """ Place SMS message in queue to be sent. """ from smsgateway.models import QueuedSMS - QueuedSMS.objects.create( + queued_sms = QueuedSMS( to=to, content=msg, signature=signature, using=using if using is not None else '__none__', reliable=reliable ) + if priority is not None: + queued_sms.priority = priority + queued_sms.save()
cf0033ee371925218237efdb613bcd312c0faefa
forms.py
forms.py
from flask_wtf import FlaskForm from wtforms import StringField, TextAreaField, PasswordField, HiddenField from wtforms.validators import DataRequired, Length, URL, Optional class LoginForm(FlaskForm): username = StringField('Username', [Length(max=255)], render_kw={'inputmode': 'verbatim'}) password = PasswordField('Password', [Length(max=1024)]) class SignupForm(FlaskForm): username = StringField('Username', [Length(min=3, max=255)], render_kw={'inputmode': 'verbatim'}) password = PasswordField('Password', [Length(min=8, max=1024)]) class AddForm(FlaskForm): title = StringField('Title', [Length(max=255)]) url = StringField('URL', [Optional(), URL(), Length(max=255)]) username = StringField( 'Username', [Length(max=255)], render_kw={'inputmode': 'verbatim'}, ) other = TextAreaField('Other') class EditForm(AddForm): id = HiddenField()
from flask_wtf import FlaskForm from wtforms import StringField, TextAreaField, PasswordField, HiddenField from wtforms.validators import DataRequired, Length, URL, Optional class LoginForm(FlaskForm): username = StringField('Username', [Length(max=255)], render_kw={'inputmode': 'verbatim'}) password = PasswordField('Password', [Length(max=1024)]) class SignupForm(FlaskForm): username = StringField( 'Username', [Length(min=3, max=255)], render_kw={'inputmode': 'verbatim'}, id='newusername', ) password = PasswordField('Password', [Length(min=8, max=1024)]) class AddForm(FlaskForm): title = StringField('Title', [Length(max=255)]) url = StringField('URL', [Optional(), URL(), Length(max=255)]) username = StringField( 'Username', [Length(max=255)], render_kw={'inputmode': 'verbatim'}, ) other = TextAreaField('Other') class EditForm(AddForm): id = HiddenField()
Add 'newusername' id to username on signup page
Add 'newusername' id to username on signup page Needed for js frontend.
Python
mit
tortxof/flask-password,tortxof/flask-password,tortxof/flask-password
--- +++ @@ -7,7 +7,12 @@ password = PasswordField('Password', [Length(max=1024)]) class SignupForm(FlaskForm): - username = StringField('Username', [Length(min=3, max=255)], render_kw={'inputmode': 'verbatim'}) + username = StringField( + 'Username', + [Length(min=3, max=255)], + render_kw={'inputmode': 'verbatim'}, + id='newusername', + ) password = PasswordField('Password', [Length(min=8, max=1024)]) class AddForm(FlaskForm):
a6fc4d88d628fc86498ae7188350c915d514c3a7
froide/account/apps.py
froide/account/apps.py
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ from django.urls import reverse from .menu import menu_registry, MenuItem class AccountConfig(AppConfig): name = 'froide.account' verbose_name = _("Account") def ready(self): from froide.bounce.signals import user_email_bounced user_email_bounced.connect(deactivate_user_after_bounce) menu_registry.register(get_settings_menu_item) menu_registry.register(get_request_menu_item) def deactivate_user_after_bounce(sender, bounce, should_deactivate=False, **kwargs): if not should_deactivate: return if not bounce.user: return bounce.user.deactivate() def get_request_menu_item(request): return MenuItem( section='before_request', order=999, url=reverse('account-show'), label=_('My requests') ) def get_settings_menu_item(request): return MenuItem( section='after_settings', order=-1, url=reverse('account-settings'), label=_('Settings') )
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ from django.urls import reverse from .menu import menu_registry, MenuItem class AccountConfig(AppConfig): name = 'froide.account' verbose_name = _("Account") def ready(self): from froide.bounce.signals import user_email_bounced user_email_bounced.connect(deactivate_user_after_bounce) menu_registry.register(get_settings_menu_item) menu_registry.register(get_request_menu_item) menu_registry.register(get_profile_menu_item) def deactivate_user_after_bounce(sender, bounce, should_deactivate=False, **kwargs): if not should_deactivate: return if not bounce.user: return bounce.user.deactivate() def get_request_menu_item(request): return MenuItem( section='before_request', order=999, url=reverse('account-show'), label=_('My requests') ) def get_profile_menu_item(request): if request.user.private: return None # TODO: remove on launch if not request.user.is_staff: return None return MenuItem( section='before_settings', order=0, url=reverse('account-profile', kwargs={'slug': request.user.username}), label=_('My public profile') ) def get_settings_menu_item(request): return MenuItem( section='after_settings', order=-1, url=reverse('account-settings'), label=_('Settings') )
Add public profile account menu link
Add public profile account menu link
Python
mit
fin/froide,fin/froide,fin/froide,fin/froide
--- +++ @@ -16,6 +16,7 @@ menu_registry.register(get_settings_menu_item) menu_registry.register(get_request_menu_item) + menu_registry.register(get_profile_menu_item) def deactivate_user_after_bounce(sender, bounce, should_deactivate=False, **kwargs): @@ -34,6 +35,19 @@ ) +def get_profile_menu_item(request): + if request.user.private: + return None + # TODO: remove on launch + if not request.user.is_staff: + return None + return MenuItem( + section='before_settings', order=0, + url=reverse('account-profile', kwargs={'slug': request.user.username}), + label=_('My public profile') + ) + + def get_settings_menu_item(request): return MenuItem( section='after_settings', order=-1,
fe5c50c36170ed642f1ff3403d53e684e836483e
Sense/src/main/python/service.py
Sense/src/main/python/service.py
from flask import Flask, Response from sense_hat import SenseHat sense = SenseHat() sense.set_imu_config(True, True, True) app = Flask(__name__) @app.route('/') def all_sensors(): return "Hello, world!" @app.route('/humidity') def humidity(): return "Hello, world!" @app.route('/pressure') def pressure(): return "Hello, world!" @app.route('/temperature') def temperature(): return "Hello, world!" @app.route('/orientation') def orientation(): return str(sense.orientation) @app.route('/accelerometer') def accelerometer(): return "Hello, world!" @app.route('/magnetometer') def magnetometer(): return "Hello, world!" @app.route('/gyroscope') def gyroscope(): return "Hello, world!"
from flask import Flask, Response from sense_hat import SenseHat sense = SenseHat() sense.set_imu_config(False, False, True) app = Flask(__name__) @app.route('/') def all_sensors(): return "Hello, world!" @app.route('/humidity') def humidity(): return "Hello, world!" @app.route('/pressure') def pressure(): return "Hello, world!" @app.route('/temperature') def temperature(): return "Hello, world!" @app.route('/orientation') def orientation(): return str(sense.orientation) @app.route('/accelerometer') def accelerometer(): return "Hello, world!" @app.route('/magnetometer') def magnetometer(): return "Hello, world!" @app.route('/gyroscope') def gyroscope(): return "Hello, world!"
Use only accelerometer for orientation.
Use only accelerometer for orientation.
Python
mit
misalcedo/RapBot,misalcedo/RapBot,misalcedo/RapBot,misalcedo/RapBot
--- +++ @@ -3,7 +3,7 @@ sense = SenseHat() -sense.set_imu_config(True, True, True) +sense.set_imu_config(False, False, True) app = Flask(__name__)
9a08ca765744f63e5711a5d745d82280eb48b8b5
src/test/testcppcompiler.py
src/test/testcppcompiler.py
from nose.tools import * from libeeyore.cpp.cppcompiler import CppCompiler class FakeProcess( object ): def __init__( self, sys_op, retcode ): self.sys_op = sys_op self.returncode = retcode def communicate( self, inp = None ): if inp is None: istr = "" else: istr = inp self.sys_op.calls.append( "communicate(%s)" % istr ) return "", "" class FakeSystemOperations( object ): def __init__( self, retcode = 0 ): self.calls = [] self.retcode = retcode def Popen( self, args, stdin = None ): self.calls.append( "Popen(%s)" % ",".join( args ) ) return FakeProcess( self, self.retcode ) def test_CppCompiler_success(): fs = FakeSystemOperations() c = CppCompiler( fs ) c.run( "myprog", "testexe" ) assert_equal( fs.calls, [ "Popen(g++,-x,c++,-o,testexe,-)", "communicate(myprog)", ] ) # TODO: not just an exception @raises( Exception ) def test_CppCompiler_failure(): fs = FakeSystemOperations( 1 ) c = CppCompiler( fs ) c.run( "myprog", "testexe" )
from nose.tools import * from libeeyore.cpp.cppcompiler import CppCompiler from libeeyore.cpp.cmdrunner import CmdRunner class FakeProcess( object ): def __init__( self, sys_op, retcode ): self.sys_op = sys_op self.returncode = retcode def communicate( self, inp = None ): if inp is None: istr = "" else: istr = inp self.sys_op.calls.append( "communicate(%s)" % istr ) return "", "" class FakeSystemOperations( object ): def __init__( self, retcode = 0 ): self.calls = [] self.retcode = retcode def Popen( self, args, stdin = None ): self.calls.append( "Popen(%s)" % ",".join( args ) ) return FakeProcess( self, self.retcode ) def test_CppCompiler_success(): fs = FakeSystemOperations() c = CppCompiler( fs ) c.run( "myprog", "testexe" ) assert_equal( fs.calls, [ "Popen(g++,-x,c++,-o,testexe,-)", "communicate(myprog)", ] ) # TODO: not just an exception @raises( Exception ) def test_CppCompiler_failure(): fs = FakeSystemOperations( 1 ) c = CppCompiler( fs ) c.run( "myprog", "testexe" ) def test_CmdRunner(): fs = FakeSystemOperations( 3 ) r = CmdRunner( fs ) retcode = r.run( "exename" ) assert_equal( fs.calls, [ "Popen(exename)", "communicate()", ] ) assert_equal( retcode, 3 )
Add a test for CmdRunner.
Add a test for CmdRunner.
Python
mit
andybalaam/pepper,andybalaam/pepper,andybalaam/pepper,andybalaam/pepper,andybalaam/pepper
--- +++ @@ -2,6 +2,7 @@ from nose.tools import * from libeeyore.cpp.cppcompiler import CppCompiler +from libeeyore.cpp.cmdrunner import CmdRunner class FakeProcess( object ): @@ -48,4 +49,16 @@ c.run( "myprog", "testexe" ) +def test_CmdRunner(): + fs = FakeSystemOperations( 3 ) + r = CmdRunner( fs ) + retcode = r.run( "exename" ) + assert_equal( fs.calls, [ + "Popen(exename)", + "communicate()", + ] ) + + assert_equal( retcode, 3 ) + +
0613c115f0ffccda8c6de9021c44d11085d84a1b
simplesqlite/_logger.py
simplesqlite/_logger.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import from __future__ import unicode_literals import logbook logger = logbook.Logger("SimpleSQLie") logger.disable() def set_logger(is_enable): if is_enable: logger.enable() else: logger.disable() def set_log_level(log_level): """ Set logging level of this module. Using `logbook <http://logbook.readthedocs.io/en/stable/>`__ module for logging. :param int log_level: One of the log level of `logbook <http://logbook.readthedocs.io/en/stable/api/base.html>`__. Disabled logging if ``log_level`` is ``logbook.NOTSET``. """ if log_level == logbook.NOTSET: set_logger(is_enable=False) else: set_logger(is_enable=True) logger.level = log_level
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import from __future__ import unicode_literals import dataproperty import logbook import pytablereader logger = logbook.Logger("SimpleSQLie") logger.disable() def set_logger(is_enable): if is_enable != logger.disabled: return if is_enable: logger.enable() else: logger.disable() dataproperty.set_logger(is_enable) pytablereader.set_logger(is_enable) def set_log_level(log_level): """ Set logging level of this module. Using `logbook <http://logbook.readthedocs.io/en/stable/>`__ module for logging. :param int log_level: One of the log level of `logbook <http://logbook.readthedocs.io/en/stable/api/base.html>`__. Disabled logging if ``log_level`` is ``logbook.NOTSET``. """ if log_level == logger.level: return if log_level == logbook.NOTSET: set_logger(is_enable=False) else: set_logger(is_enable=True) logger.level = log_level dataproperty.set_log_level(log_level) pytablereader.set_log_level(log_level)
Modify to avoid excessive logger initialization
Modify to avoid excessive logger initialization
Python
mit
thombashi/SimpleSQLite,thombashi/SimpleSQLite
--- +++ @@ -7,7 +7,9 @@ from __future__ import absolute_import from __future__ import unicode_literals +import dataproperty import logbook +import pytablereader logger = logbook.Logger("SimpleSQLie") @@ -15,10 +17,16 @@ def set_logger(is_enable): + if is_enable != logger.disabled: + return + if is_enable: logger.enable() else: logger.disable() + + dataproperty.set_logger(is_enable) + pytablereader.set_logger(is_enable) def set_log_level(log_level): @@ -32,8 +40,14 @@ Disabled logging if ``log_level`` is ``logbook.NOTSET``. """ + if log_level == logger.level: + return + if log_level == logbook.NOTSET: set_logger(is_enable=False) else: set_logger(is_enable=True) logger.level = log_level + + dataproperty.set_log_level(log_level) + pytablereader.set_log_level(log_level)
7bc2d9f96a5e5bb677e8ea17bebe22516d78243c
index.py
index.py
from nltk.tokenize import word_tokenize, sent_tokenize import getopt import sys import os import io def load_data(dir_doc): docs = {} for dirpath, dirnames, filenames in os.walk(dir_doc): for name in filenames: file = os.path.join(dirpath, name) with io.open(file, 'r+') as f: docs[name] = f.read() return docs def usage(): print("usage: " + sys.argv[0] + " -i directory-of-documents -d dictionary-file -p postings-file") if __name__ == '__main__': dir_doc = dict_file = postings_file = None try: opts, args = getopt.getopt(sys.argv[1:], 'i:d:p:') except getopt.GetoptError as err: usage() sys.exit(2) for o, a in opts: if o == '-i': dir_doc = a elif o == '-d': dict_file = a elif o == '-p': postings_file = a else: assert False, "unhandled option" if dir_doc == None or dict_file == None or postings_file == None: usage() sys.exit(2) docs = load_data(dir_doc)
from nltk.tokenize import word_tokenize, sent_tokenize import getopt import sys import os import io def load_data(dir_doc): docs = {} for dirpath, dirnames, filenames in os.walk(dir_doc): for name in filenames: file = os.path.join(dirpath, name) with io.open(file, 'r+') as f: docs[name] = f.read() return docs def preprocess(docs): processed_docs = {} for doc_id, doc in docs.items(): processed_docs[doc_id] = word_tokenize(doc) return processed_docs def usage(): print("usage: " + sys.argv[0] + " -i directory-of-documents -d dictionary-file -p postings-file") if __name__ == '__main__': dir_doc = dict_file = postings_file = None try: opts, args = getopt.getopt(sys.argv[1:], 'i:d:p:') except getopt.GetoptError as err: usage() sys.exit(2) for o, a in opts: if o == '-i': dir_doc = a elif o == '-d': dict_file = a elif o == '-p': postings_file = a else: assert False, "unhandled option" if dir_doc == None or dict_file == None or postings_file == None: usage() sys.exit(2) docs = load_data(dir_doc) docs = preprocess(docs)
Implement tokenization in preprocess function
Implement tokenization in preprocess function
Python
mit
ikaruswill/vector-space-model,ikaruswill/boolean-retrieval
--- +++ @@ -13,6 +13,13 @@ docs[name] = f.read() return docs + +def preprocess(docs): + processed_docs = {} + for doc_id, doc in docs.items(): + processed_docs[doc_id] = word_tokenize(doc) + + return processed_docs def usage(): print("usage: " + sys.argv[0] + " -i directory-of-documents -d dictionary-file -p postings-file") @@ -38,3 +45,4 @@ sys.exit(2) docs = load_data(dir_doc) + docs = preprocess(docs)
6814bed9918640346e4a096c8f410a6fc2b5508e
corehq/tests/noseplugins/uniformresult.py
corehq/tests/noseplugins/uniformresult.py
"""A plugin to format test names uniformly for easy comparison Usage: # collect django tests COLLECT_ONLY=1 ./manage.py test -v2 --settings=settings 2> tests-django.txt # collect nose tests ./manage.py test -v2 --collect-only 2> tests-nose.txt # clean up django test output: s/skipped\ \'.*\'$/ok/ # sort each output file # diff tests-django.txt tests-nose.txt """ from types import ModuleType from nose.case import FunctionTestCase from nose.plugins import Plugin def uniform_description(test): if type(test).__name__ == "DocTestCase": return test._dt_test.name if isinstance(test, ModuleType): return test.__name__ if isinstance(test, type): return "%s:%s" % (test.__module__, test.__name__) if isinstance(test, FunctionTestCase): return str(test) name = "%s:%s.%s" % ( test.__module__, type(test).__name__, test._testMethodName ) return name #return sys.modules[test.__module__].__file__ class UniformTestResultPlugin(Plugin): """Format test descriptions for easy comparison """ name = "uniform-results" enabled = True def configure(self, options, conf): """Do not call super (always enabled)""" def describeTest(self, test): return uniform_description(test.test)
"""A plugin to format test names uniformly for easy comparison Usage: # collect django tests COLLECT_ONLY=1 ./manage.py test -v2 --settings=settings 2> tests-django.txt # collect nose tests ./manage.py test -v2 --collect-only 2> tests-nose.txt # clean up django test output: s/skipped\ \'.*\'$/ok/ # sort each output file # diff tests-django.txt tests-nose.txt """ from types import ModuleType from nose.case import FunctionTestCase from nose.plugins import Plugin def uniform_description(test): if type(test).__name__ == "DocTestCase": return test._dt_test.name if isinstance(test, ModuleType): return test.__name__ if isinstance(test, type): return "%s:%s" % (test.__module__, test.__name__) if isinstance(test, FunctionTestCase): descriptor = test.descriptor or test.test return "%s:%s args %s" % ( descriptor.__module__, descriptor.__name__, test.arg, ) name = "%s:%s.%s" % ( test.__module__, type(test).__name__, test._testMethodName ) return name #return sys.modules[test.__module__].__file__ class UniformTestResultPlugin(Plugin): """Format test descriptions for easy comparison """ name = "uniform-results" enabled = True def configure(self, options, conf): """Do not call super (always enabled)""" def describeTest(self, test): return uniform_description(test.test)
Use a copypastable format for function tests
Use a copypastable format for function tests
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
--- +++ @@ -26,7 +26,12 @@ if isinstance(test, type): return "%s:%s" % (test.__module__, test.__name__) if isinstance(test, FunctionTestCase): - return str(test) + descriptor = test.descriptor or test.test + return "%s:%s args %s" % ( + descriptor.__module__, + descriptor.__name__, + test.arg, + ) name = "%s:%s.%s" % ( test.__module__, type(test).__name__,
b89a6a10e2a1beafe893faa6eec6e2562ded7492
local-celery.py
local-celery.py
import sys from deployer.celery import app if __name__ == '__main__': argv = sys.argv if len(sys.argv) > 1 else [__file__, '--loglevel=info'] app.worker_main(argv=argv)
import sys from deployer.celery import app if __name__ == '__main__': argv = sys.argv if len(sys.argv) > 1 else [__file__, '--loglevel=info'] app.conf.CELERYD_CONCURRENCY = 2 app.worker_main(argv=argv)
Set concurrency to 2 for local
Set concurrency to 2 for local
Python
mit
totem/cluster-deployer,totem/cluster-deployer,totem/cluster-deployer
--- +++ @@ -3,4 +3,5 @@ if __name__ == '__main__': argv = sys.argv if len(sys.argv) > 1 else [__file__, '--loglevel=info'] + app.conf.CELERYD_CONCURRENCY = 2 app.worker_main(argv=argv)
6c02e42db82b0dfa808ac904c79ce00ed1a0f549
load_discussions.py
load_discussions.py
# -*- coding: utf-8 -*- from __future__ import print_function import argparse from models import DiscussionMarker import re from datetime import datetime from database import db_session def main(): parser = argparse.ArgumentParser() parser.add_argument('identifiers', type=str, nargs='+', help='Disqus identifiers to create markers for') args = parser.parse_args() for identifier in args.identifiers: m = re.match('\((\d+\.\d+),\s*(\d+\.\d+)\)', identifier) if not m: print("Failed processing: " + identifier) continue (latitude, longitude) = m.group(1, 2) marker = DiscussionMarker.parse({ 'latitude': latitude, 'longitude': longitude, 'title': identifier, 'identifier': identifier }) db_session.add(marker) db_session.commit() print("Added: " + identifier) if __name__ == "__main__": main()
# -*- coding: utf-8 -*- from __future__ import print_function import argparse from models import DiscussionMarker import re from database import db_session import sys def main(): parser = argparse.ArgumentParser() parser.add_argument('identifiers', type=str, nargs='*', help='Disqus identifiers to create markers for') args = parser.parse_args() identifiers = args.identifiers if args.identifiers else sys.stdin for identifier in identifiers: m = re.match('\((\d+\.\d+),\s*(\d+\.\d+)\)', identifier) if not m: print("Failed processing: " + identifier) continue (latitude, longitude) = m.group(1, 2) marker = DiscussionMarker.parse({ 'latitude': latitude, 'longitude': longitude, 'title': identifier, 'identifier': identifier }) try: db_session.add(marker) db_session.commit() print("Added: " + identifier, end="") except: db_session.rollback() print("Failed: " + identifier, end="") if __name__ == "__main__": main()
Allow loading discussions from file
Allow loading discussions from file
Python
bsd-3-clause
omerxx/anyway,njenia/anyway,njenia/anyway,esegal/anyway,esegal/anyway,hasadna/anyway,HamutalCohen3/anyway,njenia/anyway,OmerSchechter/anyway,esegal/anyway,hasadna/anyway,OmerSchechter/anyway,omerxx/anyway,boazin/anyway,HamutalCohen3/anyway,idogi/anyway,yosinv/anyway,idogi/anyway,boazin/anyway,idogi/anyway,yosinv/anyway,hasadna/anyway,HamutalCohen3/anyway,boazin/anyway,yosinv/anyway,omerxx/anyway,hasadna/anyway,OmerSchechter/anyway
--- +++ @@ -3,16 +3,18 @@ import argparse from models import DiscussionMarker import re -from datetime import datetime from database import db_session +import sys def main(): parser = argparse.ArgumentParser() - parser.add_argument('identifiers', type=str, nargs='+', + parser.add_argument('identifiers', type=str, nargs='*', help='Disqus identifiers to create markers for') args = parser.parse_args() - for identifier in args.identifiers: + identifiers = args.identifiers if args.identifiers else sys.stdin + + for identifier in identifiers: m = re.match('\((\d+\.\d+),\s*(\d+\.\d+)\)', identifier) if not m: print("Failed processing: " + identifier) @@ -24,9 +26,13 @@ 'title': identifier, 'identifier': identifier }) - db_session.add(marker) - db_session.commit() - print("Added: " + identifier) + try: + db_session.add(marker) + db_session.commit() + print("Added: " + identifier, end="") + except: + db_session.rollback() + print("Failed: " + identifier, end="") if __name__ == "__main__":
a870433fab72fe184f12353397ad916aabe5cb61
pegasus/gtfar/__init__.py
pegasus/gtfar/__init__.py
# Copyright 2007-2014 University Of Southern California # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'Rajiv Mayani'
# Copyright 2007-2014 University Of Southern California # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'Rajiv Mayani' __VERSION__ = 0.1 from flask import Flask from flask.ext.cache import Cache from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) # Load configuration defaults app.config.from_object('pegasus.gtfar.defaults') db = SQLAlchemy(app) cache = Cache(app)
Add boilerplate code to configure the Flask app.
Add boilerplate code to configure the Flask app.
Python
apache-2.0
pegasus-isi/pegasus-gtfar,pegasus-isi/pegasus-gtfar,pegasus-isi/pegasus-gtfar,pegasus-isi/pegasus-gtfar
--- +++ @@ -13,3 +13,17 @@ # limitations under the License. __author__ = 'Rajiv Mayani' + +__VERSION__ = 0.1 + +from flask import Flask +from flask.ext.cache import Cache +from flask.ext.sqlalchemy import SQLAlchemy + +app = Flask(__name__) + +# Load configuration defaults +app.config.from_object('pegasus.gtfar.defaults') + +db = SQLAlchemy(app) +cache = Cache(app)
9d02361c034591e44e1a6d745911ef72a3591950
pingparsing/_interface.py
pingparsing/_interface.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from __future__ import division import abc class PingParserInterface(object): @abc.abstractproperty def packet_transmit(self): # pragma: no cover pass @abc.abstractproperty def packet_receive(self): # pragma: no cover pass @abc.abstractproperty def packet_loss_rate(self): # pragma: no cover pass @abc.abstractproperty def packet_loss_count(self): # pragma: no cover pass @abc.abstractproperty def rtt_min(self): # pragma: no cover pass @abc.abstractproperty def rtt_avg(self): # pragma: no cover pass @abc.abstractproperty def rtt_max(self): # pragma: no cover pass @abc.abstractproperty def rtt_mdev(self): # pragma: no cover pass @abc.abstractproperty def packet_duplicate_rate(self): # pragma: no cover pass @abc.abstractproperty def packet_duplicate_count(self): # pragma: no cover pass
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from __future__ import division import abc import six @six.add_metaclass(abc.ABCMeta) class PingParserInterface(object): @abc.abstractproperty def packet_transmit(self): # pragma: no cover pass @abc.abstractproperty def packet_receive(self): # pragma: no cover pass @abc.abstractproperty def packet_loss_rate(self): # pragma: no cover pass @abc.abstractproperty def packet_loss_count(self): # pragma: no cover pass @abc.abstractproperty def rtt_min(self): # pragma: no cover pass @abc.abstractproperty def rtt_avg(self): # pragma: no cover pass @abc.abstractproperty def rtt_max(self): # pragma: no cover pass @abc.abstractproperty def rtt_mdev(self): # pragma: no cover pass @abc.abstractproperty def packet_duplicate_rate(self): # pragma: no cover pass @abc.abstractproperty def packet_duplicate_count(self): # pragma: no cover pass
Fix missing metaclass for an interface class
Fix missing metaclass for an interface class
Python
mit
thombashi/pingparsing,thombashi/pingparsing
--- +++ @@ -9,7 +9,10 @@ import abc +import six + +@six.add_metaclass(abc.ABCMeta) class PingParserInterface(object): @abc.abstractproperty
1ce26a0b0cbddb49047da0f8bac8214fb298c646
pymatgen/__init__.py
pymatgen/__init__.py
__author__ = "Shyue Ping Ong, Anubhav Jain, Michael Kocher, Geoffroy Hautier, Will Richards, Dan Gunter, Shreyas Cholia, Vincent L Chevrier, Rickard Armiento" __date__ = "Jun 28, 2012" __version__ = "2.0.0" """ Useful aliases for commonly used objects and modules. """ from pymatgen.core.periodic_table import Element, Specie from pymatgen.core.structure import Structure, Molecule, Composition from pymatgen.core.lattice import Lattice from pymatgen.serializers.json_coders import PMGJSONEncoder, PMGJSONDecoder from pymatgen.electronic_structure.core import Spin, Orbital
__author__ = "Shyue Ping Ong, Anubhav Jain, Michael Kocher, Geoffroy Hautier, Will Richards, Dan Gunter, Shreyas Cholia, Vincent L Chevrier, Rickard Armiento" __date__ = "Jun 28, 2012" __version__ = "2.0.0" """ Useful aliases for commonly used objects and modules. """ from pymatgen.core.periodic_table import Element, Specie from pymatgen.core.structure import Structure, Molecule, Composition from pymatgen.core.lattice import Lattice from pymatgen.serializers.json_coders import PMGJSONEncoder, PMGJSONDecoder from pymatgen.electronic_structure.core import Spin, Orbital from pymatgen.util.io_utils import file_open_zip_aware as openz
Add an alias to file_open_zip_aware as openz.
Add an alias to file_open_zip_aware as openz.
Python
mit
Dioptas/pymatgen,yanikou19/pymatgen,yanikou19/pymatgen,Bismarrck/pymatgen,migueldiascosta/pymatgen,rousseab/pymatgen,sonium0/pymatgen,migueldiascosta/pymatgen,Bismarrck/pymatgen,rousseab/pymatgen,Dioptas/pymatgen,rousseab/pymatgen,ctoher/pymatgen,ctoher/pymatgen,sonium0/pymatgen,Bismarrck/pymatgen,yanikou19/pymatgen,Bismarrck/pymatgen,Bismarrck/pymatgen,migueldiascosta/pymatgen,sonium0/pymatgen,ctoher/pymatgen
--- +++ @@ -10,3 +10,4 @@ from pymatgen.core.lattice import Lattice from pymatgen.serializers.json_coders import PMGJSONEncoder, PMGJSONDecoder from pymatgen.electronic_structure.core import Spin, Orbital +from pymatgen.util.io_utils import file_open_zip_aware as openz
b36d2b6760b9905638ad2202d2b7e0461eb9d7fc
scanner/ToolbarProxy.py
scanner/ToolbarProxy.py
from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot,pyqtSignal, pyqtProperty class ToolbarProxy(QObject): def __init__(self, parent = None): super().__init__(parent) self._state = 0 self._use_wizard = False stateChanged = pyqtSignal() wizardStateChanged = pyqtSignal() @pyqtProperty(bool,notify = wizardStateChanged) def wizardActive(self): return self._use_wizard @pyqtSlot(bool) def setWizardState(self, state): self._use_wizard = state self.wizardStateChanged.emit() @pyqtProperty(int,notify = stateChanged) def state(self): return self._state @pyqtSlot(int) def setState(self, state): self._state = state self.stateChanged.emit()
from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot,pyqtSignal, pyqtProperty class ToolbarProxy(QObject): def __init__(self, parent = None): super().__init__(parent) self._state = 1 self._use_wizard = False stateChanged = pyqtSignal() wizardStateChanged = pyqtSignal() @pyqtProperty(bool,notify = wizardStateChanged) def wizardActive(self): return self._use_wizard @pyqtSlot(bool) def setWizardState(self, state): self._use_wizard = state self.wizardStateChanged.emit() @pyqtProperty(int,notify = stateChanged) def state(self): return self._state @pyqtSlot(int) def setState(self, state): self._state = state self.stateChanged.emit()
Set standard state of wizard to one (so first step automatically starts)
Set standard state of wizard to one (so first step automatically starts)
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
--- +++ @@ -3,7 +3,7 @@ class ToolbarProxy(QObject): def __init__(self, parent = None): super().__init__(parent) - self._state = 0 + self._state = 1 self._use_wizard = False stateChanged = pyqtSignal()
b774bb5eb632743cc18961f31ea147799d8ba786
lib/rapidsms/backends/backend.py
lib/rapidsms/backends/backend.py
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 class Backend(object): def log(self, level, message): self.router.log(level, message) def start(self): raise NotImplementedError def stop(self): raise NotImplementedError def send(self): raise NotImplementedError def receive(self): raise NotImplementedError
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 class Backend(object): def __init__ (self, router): self.router = router def log(self, level, message): self.router.log(level, message) def start(self): raise NotImplementedError def stop(self): raise NotImplementedError def send(self): raise NotImplementedError def receive(self): raise NotImplementedError
Add a constructor method for Backend
Add a constructor method for Backend
Python
bsd-3-clause
rapidsms/rapidsms-legacy,rapidsms/rapidsms-legacy,rapidsms/rapidsms-legacy
--- +++ @@ -1,8 +1,9 @@ #!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 - class Backend(object): + def __init__ (self, router): + self.router = router def log(self, level, message): self.router.log(level, message)
6ea29a21a2bfd077891fbea1f60b97e92c33a32c
gpxpandas/gpxreader.py
gpxpandas/gpxreader.py
__author__ = 'max' import gpxpy import pandas as pd def parse_gpx(gpx_file_name): return gpxpy.parse(gpx_file_name) def data_frame_for_track_segment(segment): seg_dict = {} for point in segment.points: seg_dict[point.time] = [point.latitude, point.longitude, point.elevation, point.speed] seg_frame = pd.DataFrame(data=seg_dict) # Switch columns and rows s.t. timestamps are rows and gps data columns. seg_frame = seg_frame.T seg_frame.columns = ['latitude', 'longitude', 'altitude', 'speed'] return seg_frame def track_segment_mapping(track): segments = (data_frame_for_track_segment(segment) for segment in track.segments) return segments def pandas_data_frame_for_gpx(gpx): tracks_frames = (track_segment_mapping(track) for track in gpx.tracks) # Create a hierarchical DataFrame by unstacking. tracks_frame = pd.DataFrame(tracks_frames) unstacked_frame = tracks_frame.unstack() unstacked_frame.index.name = 'tracks' assert gpx.name d_frame = pd.DataFrame({gpx.name: unstacked_frame}).T d_frame.index.name = 'name' return d_frame
__author__ = 'max' import gpxpy import pandas as pd def parse_gpx(gpx_file_name): return gpxpy.parse(gpx_file_name) def data_frame_for_track_segment(segment): seg_dict = {} for point in segment.points: seg_dict[point.time] = [point.latitude, point.longitude, point.elevation, point.speed] seg_frame = pd.DataFrame(data=seg_dict) # Switch columns and rows s.t. timestamps are rows and gps data columns. seg_frame = seg_frame.T seg_frame.columns = ['latitude', 'longitude', 'altitude', 'speed'] return seg_frame def track_segment_mapping(track): segments = [data_frame_for_track_segment(segment) for segment in track.segments] return segments def pandas_data_frame_for_gpx(gpx): tracks_frames = [track_segment_mapping(track) for track in gpx.tracks] # Create a hierarchical DataFrame by unstacking. tracks_frame = pd.DataFrame(tracks_frames) unstacked_frame = tracks_frame.unstack() unstacked_frame.index.name = 'tracks' assert gpx.name d_frame = pd.DataFrame({gpx.name: unstacked_frame}).T d_frame.index.name = 'name' return d_frame
Return to list generator to enable pandas cmd output
Return to list generator to enable pandas cmd output
Python
mit
komax/gpx-pandas
--- +++ @@ -22,13 +22,13 @@ def track_segment_mapping(track): - segments = (data_frame_for_track_segment(segment) - for segment in track.segments) + segments = [data_frame_for_track_segment(segment) + for segment in track.segments] return segments def pandas_data_frame_for_gpx(gpx): - tracks_frames = (track_segment_mapping(track) for track in gpx.tracks) + tracks_frames = [track_segment_mapping(track) for track in gpx.tracks] # Create a hierarchical DataFrame by unstacking. tracks_frame = pd.DataFrame(tracks_frames) unstacked_frame = tracks_frame.unstack()
5482bea32870b14fabc8a0c3b366371de5327873
render_block/base.py
render_block/base.py
from django.template import loader from django.template.backends.django import Template as DjangoTemplate try: from django.template.backends.jinja2 import Template as Jinja2Template except ImportError: # Most likely Jinja2 isn't installed, in that case just create a class since # we always want it to be false anyway. class Jinja2Template(object): pass from render_block.django import django_render_block from render_block.exceptions import UnsupportedEngine def render_block_to_string(template_name, block_name, context=None, request=None): """ Loads the given template_name and renders the given block with the given dictionary as context. Returns a string. template_name The name of the template to load and render. If it's a list of template names, Django uses select_template() instead of get_template() to find the template. """ # Like render_to_string, template_name can be a string or a list/tuple. if isinstance(template_name, (tuple, list)): t = loader.select_template(template_name) else: t = loader.get_template(template_name) # Create the context instance. context = context or {} # The Django backend. if isinstance(t, DjangoTemplate): return django_render_block(t, block_name, context, request) elif isinstance(t, Jinja2Template): from render_block.jinja2 import jinja2_render_block return jinja2_render_block(t, block_name, context) else: raise UnsupportedEngine( 'Can only render blocks from the Django template backend.')
from django.template import loader from django.template.backends.django import Template as DjangoTemplate try: from django.template.backends.jinja2 import Template as Jinja2Template except ImportError: # Most likely Jinja2 isn't installed, in that case just create a class since # we always want it to be false anyway. class Jinja2Template: pass from render_block.django import django_render_block from render_block.exceptions import UnsupportedEngine def render_block_to_string(template_name, block_name, context=None, request=None): """ Loads the given template_name and renders the given block with the given dictionary as context. Returns a string. template_name The name of the template to load and render. If it's a list of template names, Django uses select_template() instead of get_template() to find the template. """ # Like render_to_string, template_name can be a string or a list/tuple. if isinstance(template_name, (tuple, list)): t = loader.select_template(template_name) else: t = loader.get_template(template_name) # Create the context instance. context = context or {} # The Django backend. if isinstance(t, DjangoTemplate): return django_render_block(t, block_name, context, request) elif isinstance(t, Jinja2Template): from render_block.jinja2 import jinja2_render_block return jinja2_render_block(t, block_name, context) else: raise UnsupportedEngine( 'Can only render blocks from the Django template backend.')
Remove some Python 2 syntax.
Remove some Python 2 syntax.
Python
isc
clokep/django-render-block,clokep/django-render-block
--- +++ @@ -5,7 +5,7 @@ except ImportError: # Most likely Jinja2 isn't installed, in that case just create a class since # we always want it to be false anyway. - class Jinja2Template(object): + class Jinja2Template: pass from render_block.django import django_render_block
8af8f3ab918a033fb250c06c4769ee3351ec9d5f
saau/utils/header.py
saau/utils/header.py
from operator import itemgetter import numpy as np from lxml.etree import fromstring, XMLSyntaxError def parse_lines(lines): for line in lines: try: xml_line = fromstring(line.encode('utf-8')) except XMLSyntaxError: attrs = [] else: attrs = [thing.tag for thing in xml_line.getiterator()] line = list(xml_line.getiterator())[-1].text yield line, attrs def render_header_to(font, ax, sy, lines, sx=0.5): calc = lambda q: q / 20 y_points = map(calc, np.arange(sy, 0, -0.5)) parsed = list(parse_lines(lines)) lines = map(itemgetter(0), parsed) line_attrs = map(itemgetter(1), parsed) lines = [ ax.figure.text(sx, y, text, ha='center') for y, text in zip(y_points, lines) ] for line, attrs in zip(lines, line_attrs): if 'b' in attrs: line.set_weight('extra bold') line.set_font_properties(font) line.set_fontsize(25) if 'i' in attrs: line.set_style('italic') return ax
import numpy as np from lxml.etree import fromstring, XMLSyntaxError def parse_lines(lines): for line in lines: try: xml_line = fromstring(line.encode('utf-8')) except XMLSyntaxError: attrs = [] else: attrs = [thing.tag for thing in xml_line.getiterator()] line = list(xml_line.getiterator())[-1].text yield line, attrs def render_header_to(font, ax, sy, lines, sx=0.5): calc = lambda q: q / 20 y_points = map(calc, np.arange(sy, 0, -0.5)) for y, (text, attrs) in zip(y_points, parse_lines(lines)): line = ax.figure.text(sx, y, text, ha='center') if 'b' in attrs: line.set_weight('extra bold') line.set_font_properties(font) line.set_fontsize(25) if 'i' in attrs: line.set_style('italic') return ax
Create and modify lines in same loop
Create and modify lines in same loop
Python
mit
Mause/statistical_atlas_of_au
--- +++ @@ -1,5 +1,3 @@ -from operator import itemgetter - import numpy as np from lxml.etree import fromstring, XMLSyntaxError @@ -21,16 +19,9 @@ calc = lambda q: q / 20 y_points = map(calc, np.arange(sy, 0, -0.5)) - parsed = list(parse_lines(lines)) - lines = map(itemgetter(0), parsed) - line_attrs = map(itemgetter(1), parsed) + for y, (text, attrs) in zip(y_points, parse_lines(lines)): + line = ax.figure.text(sx, y, text, ha='center') - lines = [ - ax.figure.text(sx, y, text, ha='center') - for y, text in zip(y_points, lines) - ] - - for line, attrs in zip(lines, line_attrs): if 'b' in attrs: line.set_weight('extra bold') line.set_font_properties(font)
e296cefacae7154fd4060ec76abb9ddefb6cd763
src/akllt/news/views.py
src/akllt/news/views.py
from django.shortcuts import render from akllt.models import NewsStory def news_items(request): return render(request, 'akllt/news/news_items.html', { 'news_items': NewsStory.objects.all()[:20] })
from django.shortcuts import render, get_object_or_404 from akllt.models import NewsStory def news_items(request): return render(request, 'akllt/news/news_items.html', { 'news_items': NewsStory.objects.all()[:20] }) def news_details(request, news_item_id): news_item = get_object_or_404(NewsStory, pk=news_item_id) return render(request, 'akllt/news/news_details.html', { 'news_item': news_item, })
Add view for news details
Add view for news details
Python
agpl-3.0
python-dirbtuves/akl.lt,python-dirbtuves/akl.lt,python-dirbtuves/akl.lt,python-dirbtuves/akl.lt,python-dirbtuves/akl.lt
--- +++ @@ -1,4 +1,4 @@ -from django.shortcuts import render +from django.shortcuts import render, get_object_or_404 from akllt.models import NewsStory @@ -7,3 +7,10 @@ return render(request, 'akllt/news/news_items.html', { 'news_items': NewsStory.objects.all()[:20] }) + + +def news_details(request, news_item_id): + news_item = get_object_or_404(NewsStory, pk=news_item_id) + return render(request, 'akllt/news/news_details.html', { + 'news_item': news_item, + })
35e1ba57785734789357f03a738e4d65152bb775
salt/cli/__init__.py
salt/cli/__init__.py
''' The management of salt command line utilities are stored in here ''' # Import python libs import optparse import os import sys # Import salt components import salt.client class SaltCMD(object): ''' The execution of a salt command happens here ''' def __init__(self): ''' Cretae a SaltCMD object ''' self.opts = self.__parse() def __parse(self): ''' Parse the command line ''' parser = optparse.OptionParser() parser.add_option('-t', '--timeout', default=5, type=int, dest='timeout', help='Set the return timeout for batch jobs') options, args = parser.parse_args() opts = {} opts['timeout'] = options.timeout opts['tgt'] = args[0] opts['fun'] = args[1] opts['arg'] = args[2:] return opts def run(self): ''' Execute the salt command line ''' local = salt.client.LocalClient() print local.cmd(self.opts['tgt'], self.opts['fun'], self.opts['arg'], self.opts['timeout'])
''' The management of salt command line utilities are stored in here ''' # Import python libs import optparse import os import sys # Import salt components import salt.client class SaltCMD(object): ''' The execution of a salt command happens here ''' def __init__(self): ''' Cretae a SaltCMD object ''' self.opts = self.__parse() def __parse(self): ''' Parse the command line ''' parser = optparse.OptionParser() parser.add_option('-t', '--timeout', default=5, type=int, dest='timeout', help='Set the return timeout for batch jobs') parser.add_option('-E', '--pcre', default=False, dest='pcre', action='store_true' help='Instead of using shell globs to evaluate the target'\ + ' servers, use pcre regular expressions') options, args = parser.parse_args() opts = {} opts['timeout'] = options.timeout opts['pcre'] = options.pcre opts['tgt'] = args[0] opts['fun'] = args[1] opts['arg'] = args[2:] return opts def run(self): ''' Execute the salt command line ''' local = salt.client.LocalClient() print local.cmd(self.opts['tgt'], self.opts['fun'], self.opts['arg'], self.opts['timeout'])
Add regex support call to the command line
Add regex support call to the command line
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -31,12 +31,20 @@ type=int, dest='timeout', help='Set the return timeout for batch jobs') + parser.add_option('-E', + '--pcre', + default=False, + dest='pcre', + action='store_true' + help='Instead of using shell globs to evaluate the target'\ + + ' servers, use pcre regular expressions') options, args = parser.parse_args() opts = {} opts['timeout'] = options.timeout + opts['pcre'] = options.pcre opts['tgt'] = args[0] opts['fun'] = args[1] opts['arg'] = args[2:]
f649913f8941837e5de5ca7b5134c04858f52e32
utils/publish_message.py
utils/publish_message.py
import amqp from contextlib import closing def __get_channel(connection): return connection.channel() def __get_message(message_body): return amqp.Message(message_body) def __declare_exchange(channel, exchange, type): channel.exchange_declare(exchange=exchange, type=type, durable=True, auto_delete=False) def __publish_message_to_exchange(channel, message, exchange, routing_key): channel.basic_publish_confirm(msg=message, exchange=exchange, routing_key=routing_key) def publish_message(message_body, exchange, type, routing_key): """ Publish a message to an exchange with exchange type and routing key specified. A message is sent to an exchange of specified type with the provided routing_key. The exchange is declared if one of the same name does not already exist. If one of the same name does already exist but has different parameters, an error is raised. The exchange has parameters durable=True and auto_delete=False set as default. :param message_body: The body of the message to be sent. :param exchange: The name of the exchange the message is sent to. :param type: The type of the exchange the message is sent to. :param routing_key: The routing key to be sent with the message. Usage:: >>> from utils import publish_message >>> publish_message('message_body', 'exchange', 'type', 'routing_key') """ with closing(amqp.Connection()) as connection: channel = __get_channel(connection) message = __get_message(message_body) __declare_exchange(channel, exchange, type) __publish_message_to_exchange(channel, message, exchange, routing_key)
import amqp from contextlib import closing def publish_message(message_body, exchange, type, routing_key): """ Publish a message to an exchange with exchange type and routing key specified. A message is sent to a specified exchange with the provided routing_key. :param message_body: The body of the message to be sent. :param exchange: The name of the exchange the message is sent to. :param routing_key: The routing key to be sent with the message. Usage:: >>> from utils import publish_message >>> publish_message('message', 'exchange', 'routing_key') """ with closing(amqp.Connection()) as connection: channel = connection.channel() msg = amqp.Message(message) channel.basic_publish_confirm(msg=msg, exchange=exchange, routing_key=routing_key)
Revert "Revert "EAFP and removing redundant functions""
Revert "Revert "EAFP and removing redundant functions"" This reverts commit b03c0898897bbd89f8701e1c4d6d84d263bbd039.
Python
mit
jdgillespie91/trackerSpend,jdgillespie91/trackerSpend
--- +++ @@ -2,36 +2,22 @@ from contextlib import closing -def __get_channel(connection): - return connection.channel() - -def __get_message(message_body): - return amqp.Message(message_body) - -def __declare_exchange(channel, exchange, type): - channel.exchange_declare(exchange=exchange, type=type, durable=True, auto_delete=False) - -def __publish_message_to_exchange(channel, message, exchange, routing_key): - channel.basic_publish_confirm(msg=message, exchange=exchange, routing_key=routing_key) - def publish_message(message_body, exchange, type, routing_key): """ Publish a message to an exchange with exchange type and routing key specified. - A message is sent to an exchange of specified type with the provided routing_key. The exchange is declared if one of the same name does not already exist. If one of the same name does already exist but has different parameters, an error is raised. The exchange has parameters durable=True and auto_delete=False set as default. + A message is sent to a specified exchange with the provided routing_key. :param message_body: The body of the message to be sent. :param exchange: The name of the exchange the message is sent to. - :param type: The type of the exchange the message is sent to. :param routing_key: The routing key to be sent with the message. Usage:: >>> from utils import publish_message - >>> publish_message('message_body', 'exchange', 'type', 'routing_key') + >>> publish_message('message', 'exchange', 'routing_key') """ with closing(amqp.Connection()) as connection: - channel = __get_channel(connection) - message = __get_message(message_body) - __declare_exchange(channel, exchange, type) - __publish_message_to_exchange(channel, message, exchange, routing_key) + channel = connection.channel() + msg = amqp.Message(message) + channel.basic_publish_confirm(msg=msg, exchange=exchange, routing_key=routing_key)
9b54d728a245855cba724a91d372a15a4f4abb6d
shop/checkout/models.py
shop/checkout/models.py
# -*- coding: utf-8 -*- """Checkout Models""" import functools from flask import redirect, url_for from fulfil_client.model import ModelType, StringType from shop.fulfilio import Model from shop.globals import current_cart, current_channel def not_empty_cart(function): @functools.wraps(function) def wrapper(*args, **kwargs): cart = current_cart if cart.is_empty: return redirect(url_for('cart.view_cart')) return function(*args, **kwargs) return wrapper def sale_has_non_guest_party(function): """ Ensure that the sale has a party who is not guest. The sign-in method authomatically changes the party to a party based on the session. """ @functools.wraps(function) def wrapper(*args, **kwargs): cart = current_cart if cart.sale and cart.sale.party and \ cart.sale.party.id == current_channel.anonymous_customer.id: return redirect(url_for('checkout.sign_in')) return function(*args, **kwargs) return wrapper class PaymentGateway(Model): __model_name__ = 'payment_gateway.gateway' provider = StringType() stripe_publishable_key = StringType() class PaymentProfile(Model): __model_name__ = 'party.payment_profile' party = ModelType('party.party') gateway = ModelType('payment_gateway.gateway') last_4_digits = StringType() rec_name = StringType()
# -*- coding: utf-8 -*- """Checkout Models""" import functools from flask import redirect, url_for from fulfil_client.model import ModelType, StringType from shop.fulfilio import Model from shop.globals import current_cart, current_channel def not_empty_cart(function): @functools.wraps(function) def wrapper(*args, **kwargs): cart = current_cart if cart.is_empty: return redirect(url_for('cart.view_cart')) return function(*args, **kwargs) return wrapper def sale_has_non_guest_party(function): """ Ensure that the sale has a party who is not guest. The sign-in method authomatically changes the party to a party based on the session. """ @functools.wraps(function) def wrapper(*args, **kwargs): cart = current_cart if cart.sale and cart.sale.party and \ cart.sale.party.id == current_channel.anonymous_customer.id: return redirect(url_for('checkout.sign_in')) return function(*args, **kwargs) return wrapper class PaymentGateway(Model): __model_name__ = 'payment_gateway.gateway' provider = StringType() stripe_publishable_key = StringType() class PaymentProfile(Model): __model_name__ = 'party.payment_profile' party = ModelType('party.party') gateway = ModelType('payment_gateway.gateway') last_4_digits = StringType() expiry_month = StringType() expiry_year = StringType() rec_name = StringType()
Add expiry fields on card model
Add expiry fields on card model
Python
bsd-3-clause
joeirimpan/shop,joeirimpan/shop,joeirimpan/shop
--- +++ @@ -47,4 +47,6 @@ party = ModelType('party.party') gateway = ModelType('payment_gateway.gateway') last_4_digits = StringType() + expiry_month = StringType() + expiry_year = StringType() rec_name = StringType()
f0bf059cfa7b6edc366a0b3246eac1f3ab68e865
solutions/comparison.py
solutions/comparison.py
''' comparison.py - Comparison of analytic and calculated solutions Created on 12 Aug 2010 @author: Ian Huston ''' from __future__ import division import numpy as np import analyticsolution import calcedsolution import fixtures def compare_one_step(m, srcclass, nix): """ Compare the analytic and calculated solutions for equations from `srclass` using the results from `m` at the timestep `nix`. """ fx = fixtures.fixture_from_model(m) asol = analyticsolution.NoPhaseBunchDaviesSolution(fx, srcclass) csol = calcedsolution.NoPhaseBunchDaviesCalced(fx, srcclass) #Need to make analytic solution use 128 bit floats to avoid overruns asol.srceqns.k = np.float128(asol.srceqns.k) analytic_result = asol.full_source_from_model(m, nix) calced_result = csol.full_source_from_model(m, nix) difference = analytic_result - calced_result error = np.abs(difference)/np.abs(analytic_result) return difference, error, analytic_result, calced_result
''' comparison.py - Comparison of analytic and calculated solutions Created on 12 Aug 2010 @author: Ian Huston ''' from __future__ import division import numpy as np import analyticsolution import calcedsolution import fixtures def compare_one_step(m, srcclass, nix): """ Compare the analytic and calculated solutions for equations from `srclass` using the results from `m` at the timestep `nix`. """ fx = fixtures.fixture_from_model(m) asol = analyticsolution.NoPhaseBunchDaviesSolution(fx, srcclass) csol = calcedsolution.NoPhaseBunchDaviesCalced(fx, srcclass) #Need to make analytic solution use 128 bit floats to avoid overruns asol.srceqns.k = np.float128(asol.srceqns.k) analytic_result = asol.full_source_from_model(m, nix) calced_result = csol.full_source_from_model(m, nix) difference = analytic_result - calced_result error = np.abs(difference)/np.abs(analytic_result) return difference, error, analytic_result, calced_result, asol.srceqns.k
Return k with other results.
Return k with other results.
Python
bsd-3-clause
ihuston/pyflation,ihuston/pyflation
--- +++ @@ -31,4 +31,4 @@ difference = analytic_result - calced_result error = np.abs(difference)/np.abs(analytic_result) - return difference, error, analytic_result, calced_result + return difference, error, analytic_result, calced_result, asol.srceqns.k
b30d02bd077f1b7785c41e567aa4c4b44bba6a29
backend/unimeet/mail/__init__.py
backend/unimeet/mail/__init__.py
__all__ = ['mail'] from .mail import send_mail, SUBJECTS
__all__ = ['mail'] from .mail import send_mail, SUBJECTS, send_contact_form, send_contact_response
Add send_contact_{form,response} functions to mail init
Add send_contact_{form,response} functions to mail init
Python
mit
dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet
--- +++ @@ -1,2 +1,2 @@ __all__ = ['mail'] -from .mail import send_mail, SUBJECTS +from .mail import send_mail, SUBJECTS, send_contact_form, send_contact_response
42cb2842f38ab57daadb8f201815a028744db08c
utils/wavconverter.py
utils/wavconverter.py
from os import makedirs import textwrap with open('../resources/sounds/blip.wav', 'rb') as i: data = i.read() header = """\ #ifndef BLIP_H #define BLIP_H #include <cstdint> #include <vector> static std::vector<std::uint8_t> blip = { %s }; #endif /* BLIP_H */ """ % '\n\t'.join( textwrap.wrap( ', '.join('0x%02x' % ord(y) for y in data), 80) ) makedirs('../src/res/') with open('../src/res/blip.h', 'w') as f: f.write(header)
from os import makedirs import textwrap with open('../resources/sounds/blip.wav', 'rb') as i: data = i.read() header = """\ #ifndef BLIP_H #define BLIP_H #include <cstdint> #include <vector> static std::vector<std::uint8_t> blip = { %s }; #endif /* BLIP_H */ """ % '\n\t'.join( textwrap.wrap( ', '.join('0x%02x' % ord(y) for y in data), 79) ) makedirs('../src/res/') with open('../src/res/blip.h', 'w') as f: f.write(header)
Fix off-by-one in header line wrapping.
Fix off-by-one in header line wrapping.
Python
mit
lejar/SC8E,lejar/SC8E,lejar/SC8E
--- +++ @@ -18,7 +18,7 @@ """ % '\n\t'.join( textwrap.wrap( ', '.join('0x%02x' % ord(y) for y in data), - 80) + 79) ) makedirs('../src/res/')
18cc17e3f2ac36c0087b1867fcd18d0e876c34b8
tracker/src/main/scripts/launch-workflow.py
tracker/src/main/scripts/launch-workflow.py
import sys import os import uuid from time import sleep if len(sys.argv) != 3: print "Wrong number of args" exit(1) workflow_name = sys.argv[1] num_runs = int(sys.argv[2]) for this_run in range(num_runs): run_uuid = str(uuid.uuid4()) launch_command = "airflow trigger_dag -r " + run_uuid + " " + workflow_name print("Launching workflow with command: " + launch_command) os.system(launch_command) print("Workflow %s launched.", run_uuid) sleep(0.5)
import sys import os import uuid from time import sleep if len(sys.argv) != 3: print "Wrong number of args" exit(1) workflow_name = sys.argv[1] num_runs = int(sys.argv[2]) for this_run in range(num_runs): run_uuid = str(uuid.uuid4()) launch_command = "airflow trigger_dag -r " + run_uuid + " " + workflow_name print("Launching workflow with command: " + launch_command) os.system(launch_command) print("Workflow %s launched.", run_uuid) sleep(1)
Use longer sleep time for workflow launcher.
Use longer sleep time for workflow launcher.
Python
mit
llevar/germline-regenotyper,llevar/germline-regenotyper
--- +++ @@ -18,5 +18,5 @@ print("Launching workflow with command: " + launch_command) os.system(launch_command) print("Workflow %s launched.", run_uuid) - sleep(0.5) + sleep(1)
a5f4636e5bea14770253e646b94970c226669e50
telemetry/telemetry/core/platform/platform_backend_unittest.py
telemetry/telemetry/core/platform/platform_backend_unittest.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import time import unittest from telemetry.core import platform as platform_module class PlatformBackendTest(unittest.TestCase): def testPowerMonitoringSync(self): # Tests that the act of monitoring power doesn't blow up. platform = platform_module.GetHostPlatform() can_monitor_power = platform.CanMonitorPower() self.assertIsInstance(can_monitor_power, bool) if not can_monitor_power: logging.warning('Test not supported on this platform.') return browser_mock = lambda: None # Android needs to access the package of the monitored app. if platform.GetOSName() == 'android': # pylint: disable=W0212 browser_mock._browser_backend = lambda: None # Monitor the launcher, which is always present. browser_mock._browser_backend.package = 'com.android.launcher' platform.StartMonitoringPower(browser_mock) time.sleep(0.001) output = platform.StopMonitoringPower() self.assertTrue(output.has_key('energy_consumption_mwh')) self.assertTrue(output.has_key('identifier'))
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import time import unittest from telemetry import decorators from telemetry.core import platform as platform_module class PlatformBackendTest(unittest.TestCase): @decorators.Disabled('mavericks') # crbug.com/423688 def testPowerMonitoringSync(self): # Tests that the act of monitoring power doesn't blow up. platform = platform_module.GetHostPlatform() can_monitor_power = platform.CanMonitorPower() self.assertIsInstance(can_monitor_power, bool) if not can_monitor_power: logging.warning('Test not supported on this platform.') return browser_mock = lambda: None # Android needs to access the package of the monitored app. if platform.GetOSName() == 'android': # pylint: disable=W0212 browser_mock._browser_backend = lambda: None # Monitor the launcher, which is always present. browser_mock._browser_backend.package = 'com.android.launcher' platform.StartMonitoringPower(browser_mock) time.sleep(0.001) output = platform.StopMonitoringPower() self.assertTrue(output.has_key('energy_consumption_mwh')) self.assertTrue(output.has_key('identifier'))
Disable power and smoke unit tests on Mac 10.9.
[telemetry] Disable power and smoke unit tests on Mac 10.9. powermetrics is failing on the bots. BUG=423688 TEST=trybots R=tonyg Review URL: https://codereview.chromium.org/746793002 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#305147}
Python
bsd-3-clause
SummerLW/Perf-Insight-Report,benschmaus/catapult,catapult-project/catapult,SummerLW/Perf-Insight-Report,catapult-project/catapult,catapult-project/catapult-csm,catapult-project/catapult,sahiljain/catapult,benschmaus/catapult,catapult-project/catapult-csm,SummerLW/Perf-Insight-Report,benschmaus/catapult,sahiljain/catapult,sahiljain/catapult,catapult-project/catapult,catapult-project/catapult-csm,catapult-project/catapult-csm,sahiljain/catapult,catapult-project/catapult-csm,sahiljain/catapult,catapult-project/catapult,catapult-project/catapult-csm,benschmaus/catapult,catapult-project/catapult,benschmaus/catapult,sahiljain/catapult,benschmaus/catapult,SummerLW/Perf-Insight-Report,SummerLW/Perf-Insight-Report,catapult-project/catapult,catapult-project/catapult-csm,SummerLW/Perf-Insight-Report,benschmaus/catapult
--- +++ @@ -6,10 +6,12 @@ import time import unittest +from telemetry import decorators from telemetry.core import platform as platform_module class PlatformBackendTest(unittest.TestCase): + @decorators.Disabled('mavericks') # crbug.com/423688 def testPowerMonitoringSync(self): # Tests that the act of monitoring power doesn't blow up. platform = platform_module.GetHostPlatform()
8a9e2666e173078ea98e52522442e6e943cc9e6e
banks.py
banks.py
""" Banks' header configurations. Stored in a dictionary where the keys are bank names in lowercase and only alpha-characters. A bank's header should include "date" and "amount", otherwise it cannot be parsed since YNAB requires these two fields. """ from collections import namedtuple Bank = namedtuple('Bank', ['name', 'header', 'delimiter']) banks = dict() def toKey(name : str) -> str: key = [c for c in name if c.isalpha()] key = ''.join(key) return key.lower() NordeaHeader = ['Date', 'Transaction', 'Memo', 'Amount', 'Balance'] Nordea = Bank('Nordea', NordeaHeader, delimiter=',') banks[toKey(Nordea.name)] = Nordea IcaHeader = ['Date', 'Payee', 'Transaction', 'Memo', 'Amount', 'Balance'] Ica = Bank('ICA Banken', IcaHeader, delimiter=';') banks[toKey(Ica.name)] = Ica
""" Banks' header configurations. Stored in a dictionary where the keys are bank names in lowercase and only alpha-characters. A bank's header should include "date" and "amount", otherwise it cannot be parsed since YNAB requires these two fields. """ from collections import namedtuple Bank = namedtuple('Bank', ['name', 'header', 'delimiter']) banks = dict() def toKey(name : str) -> str: key = [c for c in name if c.isalpha()] key = ''.join(key) return key.lower() NordeaOldHeader = ['Date', 'Transaction', 'Memo', 'Amount', 'Balance'] NordeaOld = Bank('Nordea (gamla)', NordeaOldHeader, delimiter=',') banks[toKey(NordeaOld.name)] = NordeaOld # All information regarding the payee is in a different field called "Rubrik" # while "Betalningsmottagare" (i.e, "payee" in English) is empty. # This makes no sense, but that's the format they currently use. NordeaHeader = ['Date', 'Amount', "Sender" ,"TruePayee", "Name", "Payee", "Balance", "Currency"] Nordea = Bank('Nordea', NordeaHeader, delimiter=';') banks[toKey(Nordea.name)] = Nordea IcaHeader = ['Date', 'Payee', 'Transaction', 'Memo', 'Amount', 'Balance'] Ica = Bank('ICA Banken', IcaHeader, delimiter=';') banks[toKey(Ica.name)] = Ica
Prepare for new Nordea header
Prepare for new Nordea header In June, Nordea will switch to a new web-interface. This new interface also has a new csv-export format. This commit adapts Nordea to the new format, while the previous header is called "Nordea (gamal)". I might remove the previous header come late June, after Nordea has made the switch.
Python
mit
adnilsson/Bank2YNAB
--- +++ @@ -14,8 +14,15 @@ key = ''.join(key) return key.lower() -NordeaHeader = ['Date', 'Transaction', 'Memo', 'Amount', 'Balance'] -Nordea = Bank('Nordea', NordeaHeader, delimiter=',') +NordeaOldHeader = ['Date', 'Transaction', 'Memo', 'Amount', 'Balance'] +NordeaOld = Bank('Nordea (gamla)', NordeaOldHeader, delimiter=',') +banks[toKey(NordeaOld.name)] = NordeaOld + +# All information regarding the payee is in a different field called "Rubrik" +# while "Betalningsmottagare" (i.e, "payee" in English) is empty. +# This makes no sense, but that's the format they currently use. +NordeaHeader = ['Date', 'Amount', "Sender" ,"TruePayee", "Name", "Payee", "Balance", "Currency"] +Nordea = Bank('Nordea', NordeaHeader, delimiter=';') banks[toKey(Nordea.name)] = Nordea IcaHeader = ['Date', 'Payee', 'Transaction', 'Memo', 'Amount', 'Balance']
b1aac6a0b29a6ed46b77aab37ff52c765a280ec6
ikalog/utils/matcher.py
ikalog/utils/matcher.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # IkaLog # ====== # Copyright (C) 2015 Takeshi HASEGAWA, Junki MIZUSHIMA # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from ikalog.utils.image_filters import * from ikalog.utils.ikamatcher1 import IkaMatcher1 as IkaMatcher
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # IkaLog # ====== # Copyright (C) 2015 Takeshi HASEGAWA, Junki MIZUSHIMA # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from ikalog.utils.image_filters import * from ikalog.utils.ikamatcher1 import IkaMatcher1 as IkaMatcher #from ikalog.utils.ikamatcher2.matcher import IkaMatcher2 as IkaMatcher
Switch to IkaMatcher2 (Numpy_8bit_fast); 10% faster in overall performance
utils: Switch to IkaMatcher2 (Numpy_8bit_fast); 10% faster in overall performance Signed-off-by: Takeshi HASEGAWA <80595b5c49522665976d35e515d02ac963124d00@gmail.com>
Python
apache-2.0
deathmetalland/IkaLog,hasegaw/IkaLog,deathmetalland/IkaLog,hasegaw/IkaLog,hasegaw/IkaLog,deathmetalland/IkaLog
--- +++ @@ -20,3 +20,4 @@ from ikalog.utils.image_filters import * from ikalog.utils.ikamatcher1 import IkaMatcher1 as IkaMatcher +#from ikalog.utils.ikamatcher2.matcher import IkaMatcher2 as IkaMatcher
a5fd2ece2f318030d7790014add66d1e5019ef0d
dodge.py
dodge.py
import platform class OSXDodger(object): allowed_version = "10.12.1" def __init__(self, applications_dir): self.app_dir = applications_dir def load_applications(self): """ Read all applications in the `/Applications/` dir """ self.pc_is_macintosh() def select_applications(self): """ Allow user to select an application they want not to appear on the Dock """ pass def load_dodger_filer(self): """ Load the file to modify for the application chosen by the user in `select_applications` The file to be loaded for is `info.plist` """ pass def dodge_application(self): """ Remive the application from the Dock """ pass @classmethod def pc_is_macintosh(cls): """ Check if it is an `Apple Computer` i.e a Mac @return bool """ system = platform.system().lower() sys_version = int((platform.mac_ver())[0].replace(".", "")) allowed_version = int(cls.allowed_version.replace(".", "")) if (system == "darwin") and (sys_version >= allowed_version): return True else: print("\nSorry :(") print("FAILED. OsX-dock-dodger is only applicable to computers " + "running OS X {} or higher".format(cls.allowed_version)) return False dodge = OSXDodger("/Applications/") dodge.load_applications()
import platform class OSXDodger(object): allowed_version = "10.6.1" allowed_system = "darwin" def __init__(self, applications_dir): self.app_dir = applications_dir def load_applications(self): """ Read all applications in the `/Applications/` dir """ self.pc_is_macintosh() def select_applications(self): """ Allow user to select an application they want not to appear on the Dock """ pass def load_dodger_filer(self): """ Load the file to modify for the application chosen by the user in `select_applications` The file to be loaded for is `info.plist` """ pass def dodge_application(self): """ Remive the application from the Dock """ pass @classmethod def pc_is_macintosh(cls): """ Check if it is an `Apple Computer` i.e a Mac @return bool """ system = platform.system().lower() sys_version = int((platform.mac_ver())[0].replace(".", "")) allowed_version = int(cls.allowed_version.replace(".", "")) if (system == cls.allowed_system) and (sys_version >= allowed_version): return True else: print("\nSorry :(") print("FAILED. OsX-dock-dodger is only applicable to computers " + "running OS X {} or higher".format(cls.allowed_version)) return False dodge = OSXDodger("/Applications/") dodge.load_applications()
Add allowed_system as a class variable
Add allowed_system as a class variable
Python
mit
yoda-yoda/osx-dock-dodger,denisKaranja/osx-dock-dodger
--- +++ @@ -2,7 +2,8 @@ class OSXDodger(object): - allowed_version = "10.12.1" + allowed_version = "10.6.1" + allowed_system = "darwin" def __init__(self, applications_dir): self.app_dir = applications_dir @@ -45,7 +46,7 @@ sys_version = int((platform.mac_ver())[0].replace(".", "")) allowed_version = int(cls.allowed_version.replace(".", "")) - if (system == "darwin") and (sys_version >= allowed_version): + if (system == cls.allowed_system) and (sys_version >= allowed_version): return True else: print("\nSorry :(")
6ebf55543e74771a80f4e871af5b3cfc8f845101
indico/MaKaC/plugins/Collaboration/RecordingManager/__init__.py
indico/MaKaC/plugins/Collaboration/RecordingManager/__init__.py
# -*- coding: utf-8 -*- ## ## $Id: __init__.py,v 1.10 2009/04/09 13:13:18 dmartinc Exp $ ## ## This file is part of CDS Indico. ## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 CERN. ## ## CDS Indico is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## CDS Indico is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with CDS Indico; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. from MaKaC.plugins import getModules, initModule from MaKaC.i18n import _ pluginType = "Collaboration" pluginName = "RecordingManager" pluginDescription = _("Recording Manager") modules = {} topModule = None
# -*- coding: utf-8 -*- ## ## $Id: __init__.py,v 1.10 2009/04/09 13:13:18 dmartinc Exp $ ## ## This file is part of CDS Indico. ## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 CERN. ## ## CDS Indico is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## CDS Indico is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with CDS Indico; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. from MaKaC.i18n import _ pluginType = "Collaboration" pluginName = "RecordingManager" pluginDescription = _("Recording Manager")
Make RecordingManager work with new plugin system
[FIX] Make RecordingManager work with new plugin system
Python
mit
OmeGak/indico,mvidalgarcia/indico,DirkHoffmann/indico,mic4ael/indico,mic4ael/indico,pferreir/indico,pferreir/indico,DirkHoffmann/indico,indico/indico,mic4ael/indico,DirkHoffmann/indico,pferreir/indico,OmeGak/indico,pferreir/indico,mic4ael/indico,indico/indico,mvidalgarcia/indico,ThiefMaster/indico,DirkHoffmann/indico,indico/indico,OmeGak/indico,mvidalgarcia/indico,OmeGak/indico,ThiefMaster/indico,ThiefMaster/indico,mvidalgarcia/indico,ThiefMaster/indico,indico/indico
--- +++ @@ -19,12 +19,8 @@ ## along with CDS Indico; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. -from MaKaC.plugins import getModules, initModule from MaKaC.i18n import _ pluginType = "Collaboration" pluginName = "RecordingManager" pluginDescription = _("Recording Manager") - -modules = {} -topModule = None
f532d81da92023e9db8994b129a37590e6df7fa2
docs/test-deps.py
docs/test-deps.py
#!/usr/bin/python3 # SPDX-License-Identifier: LGPL-2.1+ import sys import markdown from packaging.version import Version # https://github.com/fwupd/fwupd/pull/3337#issuecomment-858947695 if Version(markdown.version) < Version("3.3.3"): print("python3-markdown version 3.3.3 required for gi-docgen") sys.exit(1) # success sys.exit(0)
#!/usr/bin/python3 # SPDX-License-Identifier: LGPL-2.1+ import sys import markdown from packaging.version import Version # https://github.com/fwupd/fwupd/pull/3337#issuecomment-858947695 if Version(markdown.__version__) < Version("3.3.3"): print("python3-markdown version 3.3.3 required for gi-docgen") sys.exit(1) # success sys.exit(0)
Use __version__ to fix new versions of python-markdown
trivial: Use __version__ to fix new versions of python-markdown
Python
lgpl-2.1
fwupd/fwupd,fwupd/fwupd,fwupd/fwupd,fwupd/fwupd
--- +++ @@ -7,7 +7,7 @@ from packaging.version import Version # https://github.com/fwupd/fwupd/pull/3337#issuecomment-858947695 -if Version(markdown.version) < Version("3.3.3"): +if Version(markdown.__version__) < Version("3.3.3"): print("python3-markdown version 3.3.3 required for gi-docgen") sys.exit(1)
a8d0e4545b634c33dfff20b2a75372dfc0dcd3d6
setup.py
setup.py
from setuptools import setup, find_packages import os version = '0.5.1' here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.txt')).read() CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read() except IOError: README = CHANGES = '' setup(name='tgext.admin', version=version, description="Admin Controller add-on for basic TG identity model.", long_description=README + "\n" + CHANGES, # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=[ "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", ], keywords='turbogears2.extension, TG2, TG, sprox, Rest, internet, admin', author='Christopher Perkins', author_email='chris@percious.com', url='tgtools.googlecode.com', license='MIT', packages=find_packages(exclude=['ez_setup']), namespace_packages=['tgext'], include_package_data=True, zip_safe=True, install_requires=[ 'setuptools', 'tgext.crud>=0.4', # -*- Extra requirements: -*- ], entry_points=""" # -*- Entry points: -*- """, )
from setuptools import setup, find_packages import os version = '0.5.1' here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.txt')).read() CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read() except IOError: README = CHANGES = '' setup(name='tgext.admin', version=version, description="Admin Controller add-on for basic TG identity model.", long_description=README + "\n" + CHANGES, # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=[ "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", ], keywords='turbogears2.extension, TG2, TG, sprox, Rest, internet, admin', author='Christopher Perkins', author_email='chris@percious.com', url='tgtools.googlecode.com', license='MIT', packages=find_packages(exclude=['ez_setup']), namespace_packages=['tgext'], include_package_data=True, zip_safe=True, install_requires=[ 'setuptools', 'tgext.crud>=0.5.1', # -*- Extra requirements: -*- ], entry_points=""" # -*- Entry points: -*- """, )
Make it work with new tg Jinja quickstart
Make it work with new tg Jinja quickstart
Python
mit
pedersen/tgtools.tgext-admin,pedersen/tgtools.tgext-admin
--- +++ @@ -30,7 +30,7 @@ zip_safe=True, install_requires=[ 'setuptools', - 'tgext.crud>=0.4', + 'tgext.crud>=0.5.1', # -*- Extra requirements: -*- ], entry_points="""
329fc2bce695e8e750c82d9508fa4f31698e4303
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup, find_packages # This setup relies on setuptools since distutils is insufficient and badly hacked code version = '3.0.0' author = 'David-Leon Pohl, Jens Janssen' author_email = 'pohl@physik.uni-bonn.de, janssen@physik.uni-bonn.de' # requirements for core functionality from requirements.txt with open('requirements.txt') as f: install_requires = f.read().splitlines() setup( name='pixel_clusterizer', version=version, description='A fast, generic, and easy to use clusterizer to cluster hits of a pixel matrix in Python. The clustering happens with numba on numpy arrays to increase the speed.', url='https://github.com/SiLab-Bonn/pixel_clusterizer', license='GNU LESSER GENERAL PUBLIC LICENSE Version 2.1', long_description='', author=author, maintainer=author, author_email=author_email, maintainer_email=author_email, install_requires=install_requires, packages=find_packages(), include_package_data=True, # accept all data files and directories matched by MANIFEST.in or found in source control package_data={'': ['README.*', 'VERSION'], 'docs': ['*'], 'examples': ['*']}, keywords=['cluster', 'clusterizer', 'pixel'], platforms='any' )
#!/usr/bin/env python from setuptools import setup, find_packages # This setup relies on setuptools since distutils is insufficient and badly hacked code version = '3.1.1' author = 'David-Leon Pohl, Jens Janssen' author_email = 'pohl@physik.uni-bonn.de, janssen@physik.uni-bonn.de' # requirements for core functionality from requirements.txt with open('requirements.txt') as f: install_requires = f.read().splitlines() setup( name='pixel_clusterizer', version=version, description='A fast, generic, and easy to use clusterizer to cluster hits of a pixel matrix in Python. The clustering happens with numba on numpy arrays to increase the speed.', url='https://github.com/SiLab-Bonn/pixel_clusterizer', license='GNU LESSER GENERAL PUBLIC LICENSE Version 2.1', long_description='', author=author, maintainer=author, author_email=author_email, maintainer_email=author_email, install_requires=install_requires, packages=find_packages(), include_package_data=True, # accept all data files and directories matched by MANIFEST.in or found in source control package_data={'': ['README.*', 'VERSION'], 'docs': ['*'], 'examples': ['*']}, keywords=['cluster', 'clusterizer', 'pixel'], platforms='any' )
Increase version 3.0.0 -> 3.1.1
PRJ: Increase version 3.0.0 -> 3.1.1
Python
mit
SiLab-Bonn/pixel_clusterizer
--- +++ @@ -1,7 +1,7 @@ #!/usr/bin/env python from setuptools import setup, find_packages # This setup relies on setuptools since distutils is insufficient and badly hacked code -version = '3.0.0' +version = '3.1.1' author = 'David-Leon Pohl, Jens Janssen' author_email = 'pohl@physik.uni-bonn.de, janssen@physik.uni-bonn.de'
dfc12de614ba1cff12d2fb2654234af1a9a8e862
setup.py
setup.py
import os import codecs from setuptools import setup here = os.path.abspath(os.path.dirname(__file__)) def read(*parts): # intentionally *not* adding an encoding option to open return codecs.open(os.path.join(here, *parts), 'r').read() setup( name='backtrace', version="0.2.0", url='https://github.com/nir0s/backtrace', author='nir0s', author_email='nir36g@gmail.com', license='LICENSE', platforms='All', description='Makes tracebacks humanly readable', long_description=read('README.rst'), py_modules=['backtrace'], entry_points={'console_scripts': ['backtrace = backtrace:main']}, install_requires=[ "colorama==0.3.7", ], classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Natural Language :: English', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Operating System :: Microsoft', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
import os import codecs from setuptools import setup here = os.path.abspath(os.path.dirname(__file__)) def read(*parts): # intentionally *not* adding an encoding option to open return codecs.open(os.path.join(here, *parts), 'r').read() setup( name='backtrace', version="0.2.1", url='https://github.com/nir0s/backtrace', author='nir0s', author_email='nir36g@gmail.com', license='LICENSE', platforms='All', description='Makes tracebacks humanly readable', long_description=read('README.rst'), py_modules=['backtrace'], entry_points={'console_scripts': ['backtrace = backtrace:main']}, install_requires=[ "colorama==0.3.7", ], classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Natural Language :: English', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Operating System :: Microsoft', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
Update classifiers with python3.6 version support and update version
Update classifiers with python3.6 version support and update version
Python
apache-2.0
nir0s/backtrace
--- +++ @@ -12,7 +12,7 @@ setup( name='backtrace', - version="0.2.0", + version="0.2.1", url='https://github.com/nir0s/backtrace', author='nir0s', author_email='nir36g@gmail.com', @@ -30,6 +30,7 @@ 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', 'Natural Language :: English', 'Environment :: Console', 'Intended Audience :: Developers',
65691f0781253b68f67faa71b0e81d3ae1d0c363
setup.py
setup.py
#!/usr/bin/python from setuptools import setup setup( name='sseclient', version='0.0.7', author='Brent Tubbs', author_email='brent.tubbs@gmail.com', py_modules=['sseclient'], install_requires=['requests>=1.2.0', 'six'], description=( 'Python client library for reading Server Sent Event streams.'), long_description=open('README.rst').read(), url='http://bits.btubbs.com/sseclient', )
#!/usr/bin/python import sys from setuptools import setup pytest_runner = ['pytest-runner'] if 'ptr' in sys.argv else [] setup( name='sseclient', version='0.0.7', author='Brent Tubbs', author_email='brent.tubbs@gmail.com', py_modules=['sseclient'], install_requires=['requests>=1.2.0', 'six'], tests_require=['pytest', 'mock'], setup_requires=[] + pytest_runner, description=( 'Python client library for reading Server Sent Event streams.'), long_description=open('README.rst').read(), url='http://bits.btubbs.com/sseclient', )
Allow tests to be run with pytest-runner.
Allow tests to be run with pytest-runner.
Python
mit
btubbs/sseclient
--- +++ @@ -1,5 +1,8 @@ #!/usr/bin/python +import sys from setuptools import setup + +pytest_runner = ['pytest-runner'] if 'ptr' in sys.argv else [] setup( name='sseclient', @@ -8,6 +11,8 @@ author_email='brent.tubbs@gmail.com', py_modules=['sseclient'], install_requires=['requests>=1.2.0', 'six'], + tests_require=['pytest', 'mock'], + setup_requires=[] + pytest_runner, description=( 'Python client library for reading Server Sent Event streams.'), long_description=open('README.rst').read(),
9cc91babcfafb22d21d9fa077e0933f49291d5f6
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup setup(name='lcapy', version='0.21.5', description='Symbolic linear circuit analysis', author='Michael Hayes', requires=['sympy', 'numpy', 'scipy'], author_email='michael.hayes@canterbury.ac.nz', url='https://github.com/mph-/lcapy', download_url='https://github.com/mph-/lcapy', py_modules=['lcapy.core', 'lcapy.netlist', 'lcapy.oneport', 'lcapy.twoport', 'lcapy.threeport', 'lcapy.schematic', 'lcapy.mna', 'lcapy.plot', 'lcapy.latex', 'lcapy.grammar', 'lcapy.parser', 'lcapy.schemcpts', 'lcapy.schemmisc', 'lcapy.mnacpts', 'lcapy.sympify', 'lcapy.acdc', 'lcapy.network', 'lcapy.circuit', 'lcapy.netfile', 'lcapy.system', 'lcapy.laplace'], scripts=['scripts/schtex.py'], license='LGPL' )
#!/usr/bin/env python from distutils.core import setup setup(name='lcapy', version='0.21.6', description='Symbolic linear circuit analysis', author='Michael Hayes', requires=['sympy', 'numpy', 'scipy'], author_email='michael.hayes@canterbury.ac.nz', url='https://github.com/mph-/lcapy', download_url='https://github.com/mph-/lcapy', py_modules=['lcapy.core', 'lcapy.netlist', 'lcapy.oneport', 'lcapy.twoport', 'lcapy.threeport', 'lcapy.schematic', 'lcapy.mna', 'lcapy.plot', 'lcapy.latex', 'lcapy.grammar', 'lcapy.parser', 'lcapy.schemcpts', 'lcapy.schemmisc', 'lcapy.mnacpts', 'lcapy.sympify', 'lcapy.acdc', 'lcapy.network', 'lcapy.circuit', 'lcapy.netfile', 'lcapy.system', 'lcapy.laplace'], scripts=['scripts/schtex.py'], license='LGPL' )
Remove size keyword when generating netlist
Remove size keyword when generating netlist
Python
lgpl-2.1
mph-/lcapy
--- +++ @@ -3,7 +3,7 @@ from distutils.core import setup setup(name='lcapy', - version='0.21.5', + version='0.21.6', description='Symbolic linear circuit analysis', author='Michael Hayes', requires=['sympy', 'numpy', 'scipy'],
1f64bb362beb1e14f358e4018b553356eaf99ce7
setup.py
setup.py
# -*- coding: utf-8 -*- from distutils.core import setup setup( name='AMFM_decompy', version='1.0.4', author='Bernardo J.B. Schmitt', author_email='bernardo.jb.schmitt@gmail.com', packages=['amfm_decompy'], scripts=['bin/AMFM_test.py'], package_data = {'amfm_decompy': ['*.wav']}, url='https://github.com/bjbschmitt/AMFM_decompy/', license='LICENSE.txt', description='Package to decompose the voiced part of a speech signal into \ its modulated components, aka AM-FM decomposition.', long_description=open('README.txt').read(), )
# -*- coding: utf-8 -*- from distutils.core import setup setup( name='AMFM_decompy', version='1.0.4.1', author='Bernardo J.B. Schmitt', author_email='bernardo.jb.schmitt@gmail.com', packages=['amfm_decompy'], scripts=['bin/AMFM_test.py'], package_data = {'amfm_decompy': ['*.wav']}, url='https://github.com/bjbschmitt/AMFM_decompy/', license='LICENSE.txt', description='Package to decompose the voiced part of a speech signal into \ its modulated components, aka AM-FM decomposition.', long_description=open('README.txt').read(), )
Change version name to 1.0.4.1
Change version name to 1.0.4.1
Python
mit
bjbschmitt/AMFM_decompy
--- +++ @@ -4,7 +4,7 @@ setup( name='AMFM_decompy', - version='1.0.4', + version='1.0.4.1', author='Bernardo J.B. Schmitt', author_email='bernardo.jb.schmitt@gmail.com', packages=['amfm_decompy'],
b2f5b4d731cbed5094233b94cadc3a10fe9fe0c4
setup.py
setup.py
#!/usr/bin/env python import os from setuptools import setup import versioneer here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, "README.md"), encoding="utf-8") as f: long_description = f.read() setup( name="fsspec", version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", ], description="File-system specification", long_description=long_description, long_description_content_type="text/markdown", url="http://github.com/intake/filesystem_spec", maintainer="Martin Durant", maintainer_email="mdurant@anaconda.com", license="BSD", keywords="file", packages=["fsspec", "fsspec.implementations"], python_requires=">=3.5", install_requires=[open("requirements.txt").read().strip().split("\n")], zip_safe=False, )
#!/usr/bin/env python import os from setuptools import setup import versioneer here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, "README.md"), encoding="utf-8") as f: long_description = f.read() setup( name="fsspec", version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", ], description="File-system specification", long_description=long_description, long_description_content_type="text/markdown", url="http://github.com/intake/filesystem_spec", maintainer="Martin Durant", maintainer_email="mdurant@anaconda.com", license="BSD", keywords="file", packages=["fsspec", "fsspec.implementations"], python_requires=">=3.5", install_requires=open("requirements.txt").read().strip().split("\n"), zip_safe=False, )
Remove [] from around open()...split('\n')
Remove [] from around open()...split('\n') `split()` already returns a list so you don't need to wrap it in another list.
Python
bsd-3-clause
intake/filesystem_spec,fsspec/filesystem_spec,fsspec/filesystem_spec
--- +++ @@ -31,6 +31,6 @@ keywords="file", packages=["fsspec", "fsspec.implementations"], python_requires=">=3.5", - install_requires=[open("requirements.txt").read().strip().split("\n")], + install_requires=open("requirements.txt").read().strip().split("\n"), zip_safe=False, )
db6b3342b77b3a490007761398873fbb0234ccd5
setup.py
setup.py
from setuptools import setup, find_packages setup( name='django-robots', version=__import__('robots').__version__, description='Robots exclusion application for Django, complementing Sitemaps.', long_description=open('docs/overview.txt').read(), author='Jannis Leidel', author_email='jannis@leidel.info', url='http://github.com/jezdez/django-robots/', packages=find_packages(), zip_safe=False, package_data = { 'robots': [ 'locale/*/LC_MESSAGES/*', 'templates/robots/*.html', ], }, 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', ], setup_requires = ['s3sourceuploader',], )
from setuptools import setup, find_packages setup( name='django-robots-pbs', version=__import__('robots').__version__, description='Robots exclusion application for Django, complementing Sitemaps.', long_description=open('docs/overview.txt').read(), author='Jannis Leidel', author_email='jannis@leidel.info', url='http://github.com/jezdez/django-robots/', packages=find_packages(), zip_safe=False, package_data = { 'robots': [ 'locale/*/LC_MESSAGES/*', 'templates/robots/*.html', ], }, 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', ], setup_requires = ['s3sourceuploader',], )
Rename distributable name to avoid conflicts with releases from the parent project
Rename distributable name to avoid conflicts with releases from the parent project Since this is a fork we need to diferentiate between our project and parent project releases. If we rely only on the version we won't be able to avoid conflicts with oficial releases on pypi.
Python
bsd-3-clause
pbs/django-robots,pbs/django-robots,pbs/django-robots
--- +++ @@ -1,7 +1,7 @@ from setuptools import setup, find_packages setup( - name='django-robots', + name='django-robots-pbs', version=__import__('robots').__version__, description='Robots exclusion application for Django, complementing Sitemaps.', long_description=open('docs/overview.txt').read(),
18b249b7d7c195a96e3449e5c9bdfd70f1cd16d1
setup.py
setup.py
from setuptools import setup setup( name='tangled.mako', version='1.0a4.dev0', description='Tangled Mako integration', long_description=open('README.rst').read(), url='http://tangledframework.org/', download_url='https://github.com/TangledWeb/tangled.mako/tags', author='Wyatt Baldwin', author_email='self@wyattbaldwin.com', include_package_data=True, packages=[ 'tangled', 'tangled.mako', 'tangled.mako.tests', ], install_requires=[ 'tangled.web>=0.1a10', 'Mako>=1.0', ], extras_require={ 'dev': [ 'tangled[dev]>=0.1a9', 'tangled.web[dev]>=0.1a10', ], }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], )
from setuptools import setup setup( name='tangled.mako', version='1.0a4.dev0', description='Tangled Mako integration', long_description=open('README.rst').read(), url='http://tangledframework.org/', download_url='https://github.com/TangledWeb/tangled.mako/tags', author='Wyatt Baldwin', author_email='self@wyattbaldwin.com', include_package_data=True, packages=[ 'tangled', 'tangled.mako', 'tangled.mako.tests', ], install_requires=[ 'tangled.web>=0.1a10', 'Mako>=1.0', ], extras_require={ 'dev': [ 'tangled.web[dev]>=0.1a10', 'tangled[dev]>=1.0a11', ], }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], )
Upgrade tangled 0.1a9 => 1.0a11
Upgrade tangled 0.1a9 => 1.0a11
Python
mit
TangledWeb/tangled.mako
--- +++ @@ -22,8 +22,8 @@ ], extras_require={ 'dev': [ - 'tangled[dev]>=0.1a9', 'tangled.web[dev]>=0.1a10', + 'tangled[dev]>=1.0a11', ], }, classifiers=[
9e46b546dbaf5f56527f8f88b6fa3046c39a4f67
setup.py
setup.py
from setuptools import setup, find_packages import sys, os version = '0.20' setup(name='velruse', version=version, description="Simplifying third-party authentication for web applications.", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='Ben Bangert', author_email='ben@groovie.org', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ "WebOb>=1.0.4", "python-openid>=2.2.4", "nose>=0.11", "oauth2>=1.1.3", "pyyaml", "beaker", "routes", ], tests_require = [ 'lettuce>=0.1.21', 'lettuce_webdriver>=0.12', 'selenium' ], entry_points=""" [paste.app_factory] main = velruse.app:make_velruse_app """, )
from setuptools import setup, find_packages import sys, os version = '0.20a1' setup(name='velruse', version=version, description="Simplifying third-party authentication for web applications.", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='Ben Bangert', author_email='ben@groovie.org', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ "WebOb>=1.0.4", "python-openid>=2.2.4", "nose>=0.11", "oauth2>=1.1.3", "pyyaml", "beaker", "routes", ], tests_require = [ 'lettuce>=0.1.21', 'lettuce_webdriver>=0.1.2', 'selenium' ], entry_points=""" [paste.app_factory] main = velruse.app:make_velruse_app """, )
Add proper requirements on lettuce_webdriver, update for alpha release.
Add proper requirements on lettuce_webdriver, update for alpha release.
Python
mit
ImaginationForPeople/velruse,bbangert/velruse,ImaginationForPeople/velruse,miedzinski/velruse,bbangert/velruse,miedzinski/velruse
--- +++ @@ -1,7 +1,7 @@ from setuptools import setup, find_packages import sys, os -version = '0.20' +version = '0.20a1' setup(name='velruse', version=version, @@ -28,7 +28,7 @@ ], tests_require = [ 'lettuce>=0.1.21', - 'lettuce_webdriver>=0.12', + 'lettuce_webdriver>=0.1.2', 'selenium' ], entry_points="""
a5d7d05f83f0d7a5f3e6148f362b671434088e14
setup.py
setup.py
from setuptools import setup, find_packages try: import md5 # fix for "No module named _md5" error except ImportError: # python 3 moved md5 from hashlib import md5 tests_require = [ "dill", "coverage", "coveralls", "mock", "nose", ] setup(name="expiringdict", version="1.2.0", description="Dictionary with auto-expiring values for caching purposes", long_description=open("README.rst").read(), classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Topic :: Software Development :: Libraries", ], keywords="", author="Mailgun Technologies Inc.", author_email="admin@mailgun.com", url="https://www.mailgun.com/", license="Apache 2", packages=find_packages(exclude=["tests"]), include_package_data=True, zip_safe=True, tests_require=tests_require, install_requires=[ "typing", ], extras_require={ "tests": tests_require, })
from setuptools import setup, find_packages try: import md5 # fix for "No module named _md5" error except ImportError: # python 3 moved md5 from hashlib import md5 tests_require = [ "dill", "coverage", "coveralls", "mock", "nose", ] setup(name="expiringdict", version="1.2.0", description="Dictionary with auto-expiring values for caching purposes", long_description=open("README.rst").read(), classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Topic :: Software Development :: Libraries", ], keywords="", author="Mailgun Technologies Inc.", author_email="admin@mailgun.com", url="https://www.mailgun.com/", license="Apache 2", packages=find_packages(exclude=["tests"]), include_package_data=True, zip_safe=True, tests_require=tests_require, install_requires=[ 'typing;python_version<"3.5"', ], extras_require={ "tests": tests_require, })
Fix typing conflict on Python 3.7
Fix typing conflict on Python 3.7 When using bazel on Python3.7, I got error message below ``` Traceback (most recent call last): File "/private/var/tmp/_bazel_yujo/abf0a3d83a4b1d722a32424a453d5c05/sandbox/darwin-sandbox/39/execroot/__main__/bazel-out/darwin-fastbuild/bin/tests/unit/unit_tests.runfiles/__main__/tests/unit/runner.py", line 2, in <module> from typing import Any File "/private/var/tmp/_bazel_yujo/abf0a3d83a4b1d722a32424a453d5c05/sandbox/darwin-sandbox/39/execroot/__main__/bazel-out/darwin-fastbuild/bin/tests/unit/unit_tests.runfiles/pip_deps_pypi__typing_3_7_4_1/typing.py", line 1357, in <module> class Callable(extra=collections_abc.Callable, metaclass=CallableMeta): File "/private/var/tmp/_bazel_yujo/abf0a3d83a4b1d722a32424a453d5c05/sandbox/darwin-sandbox/39/execroot/__main__/bazel-out/darwin-fastbuild/bin/tests/unit/unit_tests.runfiles/pip_deps_pypi__typing_3_7_4_1/typing.py", line 1005, in __new__ self._abc_registry = extra._abc_registry AttributeError: type object 'Callable' has no attribute '_abc_registry' ``` After some research, I found this is because expiringdict requires 'typing' regardless of Python version. From [typing doc](https://docs.python.org/3/library/typing.html), it becomes part of standard library in python 3.5.
Python
apache-2.0
mailgun/expiringdict
--- +++ @@ -37,7 +37,7 @@ zip_safe=True, tests_require=tests_require, install_requires=[ - "typing", + 'typing;python_version<"3.5"', ], extras_require={ "tests": tests_require,
ec7d1b675d4c86ec852350c1ca3923aaa7c17670
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup, find_packages import os here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README')) as f: README = f.read() requires = [] setup(name='python-bitcoinlib', version='0.1.1', description='This python library provides an easy interface to the bitcoin data structures and protocol.', long_description=README, classifiers=[ "Programming Language :: Python", ], url='https://github.com/petertodd/python-bitcoinlib', keywords='bitcoin', packages=find_packages(), zip_safe=False, install_requires=requires, )
#!/usr/bin/env python from setuptools import setup, find_packages import os here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README')) as f: README = f.read() requires = [] setup(name='python-bitcoinlib', version='0.2-SNAPSHOT', description='This python library provides an easy interface to the bitcoin data structures and protocol.', long_description=README, classifiers=[ "Programming Language :: Python", ], url='https://github.com/petertodd/python-bitcoinlib', keywords='bitcoin', packages=find_packages(), zip_safe=False, install_requires=requires, )
Reset version for future development
Reset version for future development
Python
mit
petertodd/dust-b-gone
--- +++ @@ -10,7 +10,7 @@ requires = [] setup(name='python-bitcoinlib', - version='0.1.1', + version='0.2-SNAPSHOT', description='This python library provides an easy interface to the bitcoin data structures and protocol.', long_description=README, classifiers=[
6dc44607e11c250d78159f00264e3a19a3ea9c37
setup.py
setup.py
#!/usr/bin/python -tt # -*- coding: utf-8 -*- from setuptools import find_packages, setup import kitchen.release setup(name='kitchen', version=str(kitchen.release.__version__), description=kitchen.release.DESCRIPTION, author=kitchen.release.AUTHOR, author_email=kitchen.release.EMAIL, license=kitchen.release.LICENSE, url=kitchen.release.URL, download_url=kitchen.release.DOWNLOAD_URL, keywords='Useful Small Code Snippets', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Programming Language :: Python :: 2.3', 'Programming Language :: Python :: 2.4', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Text Processing :: General', ], packages=find_packages(), data_files = [], )
#!/usr/bin/python -tt # -*- coding: utf-8 -*- from setuptools import find_packages, setup import kitchen.release setup(name='kitchen', version=str(kitchen.release.__version__), description=kitchen.release.DESCRIPTION, author=kitchen.release.AUTHOR, author_email=kitchen.release.EMAIL, license=kitchen.release.LICENSE, url=kitchen.release.URL, download_url=kitchen.release.DOWNLOAD_URL, keywords='Useful Small Code Snippets', classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Programming Language :: Python :: 2.3', 'Programming Language :: Python :: 2.4', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Text Processing :: General', ], packages=find_packages(), data_files = [], )
Move development status from Alpha to Beta
Move development status from Alpha to Beta
Python
lgpl-2.1
fedora-infra/kitchen,fedora-infra/kitchen
--- +++ @@ -14,7 +14,7 @@ download_url=kitchen.release.DOWNLOAD_URL, keywords='Useful Small Code Snippets', classifiers=[ - 'Development Status :: 3 - Alpha', + 'Development Status :: 4 - Beta', 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Programming Language :: Python :: 2.3', 'Programming Language :: Python :: 2.4',
010627a11aae19bfd6b486b747c8390a0ecbbfde
setup.py
setup.py
from distutils.core import setup from setuptools import find_packages setup( name='d4rl', version='1.1', install_requires=['gym', 'numpy', 'mujoco_py', 'h5py', 'termcolor', # adept_envs dependency 'click', # adept_envs dependency 'dm_control @ git+git://github.com/deepmind/dm_control@master#egg=dm_control', 'mjrl @ git+git://github.com/aravindr93/mjrl@master#egg=mjrl'], packages=find_packages(), )
from distutils.core import setup from setuptools import find_packages setup( name='d4rl', version='1.1', install_requires=['gym', 'numpy', 'mujoco_py', 'h5py', 'termcolor', # adept_envs dependency 'click', # adept_envs dependency 'dm_control @ git+git://github.com/deepmind/dm_control@master#egg=dm_control', 'mjrl @ git+git://github.com/aravindr93/mjrl@master#egg=mjrl'], packages=find_packages(), package_data={'d4rl': ['locomotion/assets/*', 'hand_manipulation_suite/assets/*', 'hand_manipulation_suite/Adroit/*', 'hand_manipulation_suite/Adroit/gallery/*', 'hand_manipulation_suite/Adroit/resources/*', 'hand_manipulation_suite/Adroit/resources/meshes/*', 'hand_manipulation_suite/Adroit/resources/textures/*', ]}, include_package_data=True, )
Add assets for locomotion and DAPG to package data
Add assets for locomotion and DAPG to package data
Python
apache-2.0
rail-berkeley/d4rl,rail-berkeley/d4rl
--- +++ @@ -13,4 +13,13 @@ 'dm_control @ git+git://github.com/deepmind/dm_control@master#egg=dm_control', 'mjrl @ git+git://github.com/aravindr93/mjrl@master#egg=mjrl'], packages=find_packages(), + package_data={'d4rl': ['locomotion/assets/*', + 'hand_manipulation_suite/assets/*', + 'hand_manipulation_suite/Adroit/*', + 'hand_manipulation_suite/Adroit/gallery/*', + 'hand_manipulation_suite/Adroit/resources/*', + 'hand_manipulation_suite/Adroit/resources/meshes/*', + 'hand_manipulation_suite/Adroit/resources/textures/*', + ]}, + include_package_data=True, )
6652e642e2a7d6388b8a80f072b3161db6f66ee3
setup.py
setup.py
from setuptools import setup setup( name = "javasphinx", packages = ["javasphinx"], version = "0.9.8", author = "Chris Thunes", author_email = "cthunes@brewtab.com", url = "http://github.com/bronto/javasphinx", description = "Sphinx extension for documenting Java projects", classifiers = [ "Programming Language :: Python", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "License :: OSI Approved :: MIT License", "Intended Audience :: Developers", "Topic :: Software Development :: Libraries" ], install_requires=["javalang>=0.9.2"], entry_points={ 'console_scripts': [ 'javasphinx-apidoc = javasphinx.apidoc:main' ] }, long_description = """\ ========== javasphinx ========== javasphinx is an extension to the Sphinx documentation system which adds support for documenting Java projects. It includes a Java domain for writing documentation manually and a javasphinx-apidoc utility which will automatically generate API documentation from existing Javadoc markup. """ )
from setuptools import setup setup( name = "javasphinx", packages = ["javasphinx"], version = "0.9.8", author = "Chris Thunes", author_email = "cthunes@brewtab.com", url = "http://github.com/bronto/javasphinx", description = "Sphinx extension for documenting Java projects", classifiers = [ "Programming Language :: Python", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "License :: OSI Approved :: MIT License", "Intended Audience :: Developers", "Topic :: Software Development :: Libraries" ], install_requires=["javalang>=0.9.2", "lxml", "beautifulsoup4"], entry_points={ 'console_scripts': [ 'javasphinx-apidoc = javasphinx.apidoc:main' ] }, long_description = """\ ========== javasphinx ========== javasphinx is an extension to the Sphinx documentation system which adds support for documenting Java projects. It includes a Java domain for writing documentation manually and a javasphinx-apidoc utility which will automatically generate API documentation from existing Javadoc markup. """ )
Add lxml and beautifulsoup dependencies
Add lxml and beautifulsoup dependencies
Python
apache-2.0
socib/javasphinx,bronto/javasphinx,Zyzle/javasphinx
--- +++ @@ -17,7 +17,7 @@ "Intended Audience :: Developers", "Topic :: Software Development :: Libraries" ], - install_requires=["javalang>=0.9.2"], + install_requires=["javalang>=0.9.2", "lxml", "beautifulsoup4"], entry_points={ 'console_scripts': [ 'javasphinx-apidoc = javasphinx.apidoc:main'
03f2ec08fbf2133bcc78047bf5346939a5fe4315
setup.py
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages readme = open('README.md').read() history = open('HISTORY.md').read().replace('.. :changelog:', '') requirements = [ 'Django<=1.9', ] test_requirements = [ 'nose>=1.3,<2', 'factory_boy>=2.4,<3.0', 'fake-factory>=0.4.0,<1', 'nosexcover>=1.0.8, <2', 'ipdb', 'mock', ] setup( name='django-cache-manager', version='0.4', description='Cache manager for django models', long_description=readme + '\n\n' + history, author='Vijay Katam', url='https://github.com/vijaykatam/django-cache-manager', packages=find_packages(exclude=('tests',)), package_dir={'django_cache_manager': 'django_cache_manager'}, include_package_data=True, install_requires=requirements, zip_safe=False, keywords='django-cache-manager', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7' ], test_suite='nose.collector', tests_require=test_requirements, )
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages readme = open('README.md').read() history = open('HISTORY.md').read().replace('.. :changelog:', '') requirements = [ 'Django<1.10', ] test_requirements = [ 'nose>=1.3,<2', 'factory_boy>=2.4,<3.0', 'fake-factory>=0.4.0,<1', 'nosexcover>=1.0.8, <2', 'ipdb', 'mock', ] setup( name='django-cache-manager', version='0.4', description='Cache manager for django models', long_description=readme + '\n\n' + history, author='Vijay Katam', url='https://github.com/vijaykatam/django-cache-manager', packages=find_packages(exclude=('tests',)), package_dir={'django_cache_manager': 'django_cache_manager'}, include_package_data=True, install_requires=requirements, zip_safe=False, keywords='django-cache-manager', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7' ], test_suite='nose.collector', tests_require=test_requirements, )
Fix Django version in requirements
Fix Django version in requirements Current version of requirements in setup.py doesn't work well with (pip-compile)[https://github.com/nvie/pip-tools/] (concrete problem is discussed (here) [https://github.com/nvie/pip-tools/issues/323]). This commit changes `<=1.9` to `<1.10`.
Python
mit
vijaykatam/django-cache-manager
--- +++ @@ -7,7 +7,7 @@ history = open('HISTORY.md').read().replace('.. :changelog:', '') requirements = [ - 'Django<=1.9', + 'Django<1.10', ] test_requirements = [
c4db7397e5b91d0efd30b0b7549adb8a266cb8d4
setup.py
setup.py
import subprocess import sys from setuptools import Command, setup class RunTests(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): errno = subprocess.call([sys.executable, '-m', 'unittest', 'gis_metadata.tests.tests']) raise SystemExit(errno) setup( name='gis_metadata_parser', description='Parser for GIS metadata standards including FGDC and ISO-19115', keywords='arcgis,fgdc,iso,ISO-19115,ISO-19139,gis,metadata,parser,xml,gis_metadata,gis_metadata_parser', version='1.1', packages=[ 'gis_metadata', 'gis_metadata.tests' ], install_requires=[ 'parserutils>=1.1', 'six>=1.9.0' ], url='https://github.com/consbio/gis-metadata-parser', license='BSD', cmdclass={'test': RunTests} )
import subprocess import sys from setuptools import Command, setup class RunTests(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): errno = subprocess.call([sys.executable, '-m', 'unittest', 'gis_metadata.tests.tests']) raise SystemExit(errno) setup( name='gis_metadata_parser', description='Parser for GIS metadata standards including FGDC and ISO-19115', keywords='arcgis,fgdc,iso,ISO-19115,ISO-19139,gis,metadata,parser,xml,gis_metadata,gis_metadata_parser', version='1.1.1', packages=[ 'gis_metadata', 'gis_metadata.tests' ], install_requires=[ 'parserutils>=1.1', 'six>=1.9.0' ], url='https://github.com/consbio/gis-metadata-parser', license='BSD', cmdclass={'test': RunTests} )
Increment version (to fix dependencies)
Increment version (to fix dependencies)
Python
bsd-3-clause
consbio/gis-metadata-parser
--- +++ @@ -22,7 +22,7 @@ name='gis_metadata_parser', description='Parser for GIS metadata standards including FGDC and ISO-19115', keywords='arcgis,fgdc,iso,ISO-19115,ISO-19139,gis,metadata,parser,xml,gis_metadata,gis_metadata_parser', - version='1.1', + version='1.1.1', packages=[ 'gis_metadata', 'gis_metadata.tests' ],
40b9fd2252156a4bf21e23b197df3c1cb83d0a6e
setup.py
setup.py
from setuptools import setup setup(name='fortdepend', version='0.1.0', description='Automatically generate Fortran dependencies', author='Peter Hill', author_email='peter@fusionplasma.co.uk', url='https://github.com/ZedThree/fort_depend.py/', download_url='https://github.com/ZedThree/fort_depend.py/tarball/0.1.0', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Fortran', ], packages=['fortdepend'], install_requires=[ 'colorama >= 0.3.9', 'pcpp >= 1.1.0' ], extras_require={ 'tests': ['pytest >= 3.3.0'], 'docs': [ 'sphinx >= 1.4', 'sphinx-argparse >= 0.2.3' ], }, keywords=['build', 'dependencies', 'fortran'], entry_points={ 'console_scripts': [ 'fortdepend = fortdepend.__main__:main', ], }, )
from setuptools import setup with open("README.md", 'r') as f: long_description = f.read() setup(name='fortdepend', version='0.1.0', description='Automatically generate Fortran dependencies', long_description=long_description, long_description_content_type="test/markdown", author='Peter Hill', author_email='peter@fusionplasma.co.uk', url='https://github.com/ZedThree/fort_depend.py/', download_url='https://github.com/ZedThree/fort_depend.py/tarball/0.1.0', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Fortran', ], packages=['fortdepend'], install_requires=[ 'colorama >= 0.3.9', 'pcpp >= 1.1.0' ], extras_require={ 'tests': ['pytest >= 3.3.0'], 'docs': [ 'sphinx >= 1.4', 'sphinx-argparse >= 0.2.3' ], }, keywords=['build', 'dependencies', 'fortran'], entry_points={ 'console_scripts': [ 'fortdepend = fortdepend.__main__:main', ], }, )
Add README as long_description to package
Add README as long_description to package
Python
mit
ZedThree/fort_depend.py,ZedThree/fort_depend.py
--- +++ @@ -1,8 +1,13 @@ from setuptools import setup + +with open("README.md", 'r') as f: + long_description = f.read() setup(name='fortdepend', version='0.1.0', description='Automatically generate Fortran dependencies', + long_description=long_description, + long_description_content_type="test/markdown", author='Peter Hill', author_email='peter@fusionplasma.co.uk', url='https://github.com/ZedThree/fort_depend.py/',
78747b26f642af4d1404df5a3a6d08160f07d2f0
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup setup(name='hawkular-client', version='0.4.0', description='Python client to communicate with Hawkular over HTTP(S)', author='Michael Burman', author_email='miburman@redhat.com', url='http://github.com/hawkular/hawkular-client-python', packages=['hawkular'] )
#!/usr/bin/env python from distutils.core import setup from os import path from setuptools.command.install import install import pypandoc here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md')) as f: long_description = f.read() # Create rst here from Markdown z = pypandoc.convert('README.md','rst',format='markdown') with open('README.rst','w') as outfile: outfile.write(z) setup(name='hawkular-client', version='0.4.0', description='Python client to communicate with Hawkular server over HTTP(S)', author='Michael Burman', author_email='miburman@redhat.com', license='Apache License 2.0', url='http://github.com/hawkular/hawkular-client-python', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: System :: Monitoring', ], packages=['hawkular'] )
Change version to 0.4.0, add classifiers and readme conversion from markdown to rSt
Change version to 0.4.0, add classifiers and readme conversion from markdown to rSt
Python
apache-2.0
hawkular/hawkular-client-python,burmanm/hawkular-client-python,burmanm/hawkular-client-python,hawkular/hawkular-client-python
--- +++ @@ -1,12 +1,35 @@ #!/usr/bin/env python from distutils.core import setup +from os import path +from setuptools.command.install import install +import pypandoc +here = path.abspath(path.dirname(__file__)) + +with open(path.join(here, 'README.md')) as f: + long_description = f.read() + +# Create rst here from Markdown +z = pypandoc.convert('README.md','rst',format='markdown') + +with open('README.rst','w') as outfile: + outfile.write(z) + setup(name='hawkular-client', version='0.4.0', - description='Python client to communicate with Hawkular over HTTP(S)', + description='Python client to communicate with Hawkular server over HTTP(S)', author='Michael Burman', author_email='miburman@redhat.com', + license='Apache License 2.0', url='http://github.com/hawkular/hawkular-client-python', + classifiers=[ + 'Development Status :: 4 - Beta', + 'Intended Audience :: Developers', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 3', + 'Topic :: System :: Monitoring', + ], packages=['hawkular'] )
5f64cad0de80d6ecbbe4397161ae3b04620547ab
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup, find_packages import subprocess setup(name="singer-python", version='5.0.7', description="Singer.io utility library", author="Stitch", classifiers=['Programming Language :: Python :: 3 :: Only'], url="http://singer.io", install_requires=[ 'jsonschema==2.6.0', 'pendulum==1.2.0', 'simplejson==3.11.1', 'python-dateutil>=2.6.0', 'backoff==1.3.2', ], extras_require={ 'dev': [ 'pylint', 'nose' ] }, packages=find_packages(), package_data = { 'singer': [ 'logging.conf' ] }, )
#!/usr/bin/env python from setuptools import setup, find_packages import subprocess setup(name="singer-python", version='5.0.7', description="Singer.io utility library", author="Stitch", classifiers=['Programming Language :: Python :: 3 :: Only'], url="http://singer.io", install_requires=[ 'jsonschema==2.6.0', 'pendulum==1.2.0', 'simplejson==3.11.1', 'python-dateutil>=2.6.0', 'backoff==1.3.2', ], extras_require={ 'dev': [ 'pylint', 'nose', 'singer-tools' ] }, packages=find_packages(), package_data = { 'singer': [ 'logging.conf' ] }, )
Add singer-tools as a dev dependency
Add singer-tools as a dev dependency
Python
apache-2.0
singer-io/singer-python
--- +++ @@ -19,7 +19,8 @@ extras_require={ 'dev': [ 'pylint', - 'nose' + 'nose', + 'singer-tools' ] }, packages=find_packages(),
72b41b512f4413c456cd0bfde7da349b5094aadd
setup.py
setup.py
""" PyLatex ------- PyLatex is a Python library for creating LaTeX files. The point of this library is being an easy, but extensible interface between Python and Latex. """ from distutils.core import setup setup(name='PyLatex', version='0.2.0', author='Jelte Fennema', author_email='pylatex@jeltef.nl', description='A Python library for creating LaTeX files', long_description=__doc__, packages=['pylatex'], url='https://github.com/JelteF/PyLatex', license='MIT', )
""" PyLatex ------- PyLatex is a Python library for creating LaTeX files. The point of this library is being an easy, but extensible interface between Python and Latex. Features ~~~~~~~~ The library contains some basic features I have had the need for so far. Currently those are: - Document generation and compilation - Section, table and package classes - An escape function - Bold and italic functions Everything else you want you can still add to the document by adding LaTeX formatted strings. """ from distutils.core import setup setup(name='PyLatex', version='0.2.0', author='Jelte Fennema', author_email='pylatex@jeltef.nl', description='A Python library for creating LaTeX files', long_description=__doc__, packages=['pylatex'], url='https://github.com/JelteF/PyLatex', license='MIT', )
Update long description for PyPi
Update long description for PyPi
Python
mit
sebastianhaas/PyLaTeX,JelteF/PyLaTeX,ovaskevich/PyLaTeX,ovaskevich/PyLaTeX,sebastianhaas/PyLaTeX,JelteF/PyLaTeX,bjodah/PyLaTeX,votti/PyLaTeX,jendas1/PyLaTeX,votti/PyLaTeX,bjodah/PyLaTeX,jendas1/PyLaTeX
--- +++ @@ -6,6 +6,19 @@ is being an easy, but extensible interface between Python and Latex. +Features +~~~~~~~~ + +The library contains some basic features I have had the need for so far. +Currently those are: + +- Document generation and compilation +- Section, table and package classes +- An escape function +- Bold and italic functions + +Everything else you want you can still add to the document by adding LaTeX +formatted strings. """ from distutils.core import setup setup(name='PyLatex',
baf03e163753a3e1d1cecc20676722e22896170a
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-payfast', version='0.3.dev', author='Mikhail Korobov', author_email='kmike84@gmail.com', packages=find_packages(exclude=['payfast_tests']), url='http://bitbucket.org/kmike/django-payfast/', download_url = 'http://bitbucket.org/kmike/django-payfast/get/tip.gz', license = 'MIT license', description = 'A pluggable Django application for integrating payfast.co.za payment system.', long_description = open('README.rst').read().decode('utf8'), classifiers=( 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', ), )
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-payfast', version='0.3.dev', author='Mikhail Korobov', author_email='kmike84@gmail.com', maintainer='Piet Delport', maintainer_email='pjdelport@gmail.com', packages=find_packages(exclude=['payfast_tests']), url='http://bitbucket.org/kmike/django-payfast/', download_url = 'http://bitbucket.org/kmike/django-payfast/get/tip.gz', license = 'MIT license', description = 'A pluggable Django application for integrating payfast.co.za payment system.', long_description = open('README.rst').read().decode('utf8'), classifiers=( 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', ), )
Add maintainer: Piet Delport <pjdelport@gmail.com>
Add maintainer: Piet Delport <pjdelport@gmail.com>
Python
mit
reinbach/django-payfast
--- +++ @@ -6,6 +6,8 @@ version='0.3.dev', author='Mikhail Korobov', author_email='kmike84@gmail.com', + maintainer='Piet Delport', + maintainer_email='pjdelport@gmail.com', packages=find_packages(exclude=['payfast_tests']),
8c0b5f03c53f8d38d6fb0c2fed8787ccb97d6207
setup.py
setup.py
# /setup.py # # Installation and setup script for parse-shebang # # See /LICENCE.md for Copyright information """Installation and setup script for parse-shebang.""" from setuptools import find_packages, setup setup(name="parse-shebang", version="0.0.20", description="""Parse shebangs and return their components.""", long_description_markdown_filename="README.md", author="Sam Spilsbury", author_email="smspillaz@gmail.com", classifiers=["Development Status :: 3 - Alpha", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.1", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Intended Audience :: Developers", "Topic :: System :: Shells", "Topic :: Utilities", "License :: OSI Approved :: MIT License"], url="http://github.com/polysquare/python-parse-shebang", license="MIT", keywords="development", packages=find_packages(exclude=["test"]), install_requires=["six"], extras_require={ "upload": ["setuptools-markdown"] }, test_suite="nose.collector", zip_safe=True, include_package_data=True)
# /setup.py # # Installation and setup script for parse-shebang # # See /LICENCE.md for Copyright information """Installation and setup script for parse-shebang.""" from setuptools import find_packages, setup setup(name="parse-shebang", version="0.0.21", description="""Parse shebangs and return their components.""", long_description_markdown_filename="README.md", author="Sam Spilsbury", author_email="smspillaz@gmail.com", classifiers=["Development Status :: 3 - Alpha", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.1", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Intended Audience :: Developers", "Topic :: System :: Shells", "Topic :: Utilities", "License :: OSI Approved :: MIT License"], url="http://github.com/polysquare/python-parse-shebang", license="MIT", keywords="development", packages=find_packages(exclude=["test"]), install_requires=["six"], extras_require={ "upload": ["setuptools-markdown"] }, test_suite="nose.collector", zip_safe=True, include_package_data=True)
Bump version: 0.0.20 -> 0.0.21
Bump version: 0.0.20 -> 0.0.21 [ci skip]
Python
mit
polysquare/python-parse-shebang
--- +++ @@ -8,7 +8,7 @@ from setuptools import find_packages, setup setup(name="parse-shebang", - version="0.0.20", + version="0.0.21", description="""Parse shebangs and return their components.""", long_description_markdown_filename="README.md", author="Sam Spilsbury",
75252a9d0005cf5c42b037933c33b4270d754a66
setup.py
setup.py
import os from setuptools import setup, find_packages src_dir = os.path.dirname(__file__) install_requires = [ "troposphere==1.7.0", "awacs==0.6.0", "stacker==0.6.3", ] tests_require = [ "nose>=1.0", "mock==1.0.1", ] def read(filename): full_path = os.path.join(src_dir, filename) with open(full_path) as fd: return fd.read() if __name__ == "__main__": setup( name="stacker_blueprints", version="0.6.5", author="Michael Barrett", author_email="loki77@gmail.com", license="New BSD license", url="https://github.com/remind101/stacker_blueprints", description="Default blueprints for stacker", long_description=read("README.rst"), packages=find_packages(), install_requires=install_requires, tests_require=tests_require, test_suite="nose.collector", )
import os from setuptools import setup, find_packages src_dir = os.path.dirname(__file__) install_requires = [ "troposphere~=1.8.0", "awacs~=0.6.0", "stacker~=0.6.3", ] tests_require = [ "nose~=1.0", "mock~=2.0.0", ] def read(filename): full_path = os.path.join(src_dir, filename) with open(full_path) as fd: return fd.read() if __name__ == "__main__": setup( name="stacker_blueprints", version="0.6.5", author="Michael Barrett", author_email="loki77@gmail.com", license="New BSD license", url="https://github.com/remind101/stacker_blueprints", description="Default blueprints for stacker", long_description=read("README.rst"), packages=find_packages(), install_requires=install_requires, tests_require=tests_require, test_suite="nose.collector", )
Use compatible release versions for all dependencies
Use compatible release versions for all dependencies
Python
bsd-2-clause
remind101/stacker_blueprints,remind101/stacker_blueprints
--- +++ @@ -4,14 +4,14 @@ src_dir = os.path.dirname(__file__) install_requires = [ - "troposphere==1.7.0", - "awacs==0.6.0", - "stacker==0.6.3", + "troposphere~=1.8.0", + "awacs~=0.6.0", + "stacker~=0.6.3", ] tests_require = [ - "nose>=1.0", - "mock==1.0.1", + "nose~=1.0", + "mock~=2.0.0", ]
de613623c638b923a6bbfb6c33c373794d654000
setup.py
setup.py
from distutils.core import setup setup( name='django_dust', description='Distributed Upload STorage for Django. A file backend that mirrors all incoming media files to several servers', packages=[ 'django_dust', 'django_dust.management', 'django_dust.management.commands', 'django_dust.backends' ], )
from distutils.core import setup import os.path with open(os.path.join(os.path.dirname(__file__), 'README.md')) as f: long_description = f.read().partition('\n\n\n')[0].partition('\n\n')[2] setup( name='django_dust', version='0.1', description='Distributed Upload STorage for Django, a file backend ' 'that mirrors all incoming media files to several servers', long_description=long_description, packages=[ 'django_dust', 'django_dust.backends', 'django_dust.management', 'django_dust.management.commands', ], 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", "Topic :: Internet :: WWW/HTTP :: Site Management", ], )
Add version, long description and classifiers.
Add version, long description and classifiers.
Python
bsd-3-clause
aaugustin/django-resto
--- +++ @@ -1,12 +1,29 @@ from distutils.core import setup +import os.path + +with open(os.path.join(os.path.dirname(__file__), 'README.md')) as f: + long_description = f.read().partition('\n\n\n')[0].partition('\n\n')[2] setup( - name='django_dust', - description='Distributed Upload STorage for Django. A file backend that mirrors all incoming media files to several servers', + name='django_dust', + version='0.1', + description='Distributed Upload STorage for Django, a file backend ' + 'that mirrors all incoming media files to several servers', + long_description=long_description, packages=[ 'django_dust', + 'django_dust.backends', 'django_dust.management', 'django_dust.management.commands', - 'django_dust.backends' + ], + 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", + "Topic :: Internet :: WWW/HTTP :: Site Management", ], )
1d5735c111f4f5a0623b693d1531c3e7a0845a08
setup.py
setup.py
from setuptools import setup, find_packages import os version = '0.3.10' here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.txt')).read() CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read() except IOError: README = CHANGES = '' setup(name='tgext.admin', version=version, description="Admin Controller add-on for basic TG identity model.", long_description=README + "\n" + CHANGES, # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=[ "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", ], keywords='TG2, TG, sprox, Rest, internet, adminn', author='Christopher Perkins', author_email='chris@percious.com', url='tgtools.googlecode.com', license='MIT', packages=find_packages(exclude=['ez_setup']), namespace_packages=['tgext'], include_package_data=True, zip_safe=True, install_requires=[ 'setuptools', 'sprox>=0.6.4', 'tgext.crud>=0.3.7', # -*- Extra requirements: -*- ], entry_points=""" # -*- Entry points: -*- """, )
from setuptools import setup, find_packages import os version = '0.3.11' here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.txt')).read() CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read() except IOError: README = CHANGES = '' setup(name='tgext.admin', version=version, description="Admin Controller add-on for basic TG identity model.", long_description=README + "\n" + CHANGES, # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=[ "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", ], keywords='TG2, TG, sprox, Rest, internet, adminn', author='Christopher Perkins', author_email='chris@percious.com', url='tgtools.googlecode.com', license='MIT', packages=find_packages(exclude=['ez_setup']), namespace_packages=['tgext'], include_package_data=True, zip_safe=True, install_requires=[ 'setuptools', 'sprox>=0.6.4', 'tgext.crud>=0.3.7', # -*- Extra requirements: -*- ], entry_points=""" # -*- Entry points: -*- """, )
Increase to version 0.3.11 due to TG-dev requiring it for ming support
Increase to version 0.3.11 due to TG-dev requiring it for ming support
Python
mit
TurboGears/tgext.admin,TurboGears/tgext.admin
--- +++ @@ -1,7 +1,7 @@ from setuptools import setup, find_packages import os -version = '0.3.10' +version = '0.3.11' here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.txt')).read()
fa4c6ba6af2f7d936f6504473ab0a2ae50043db4
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='Police API', version='0.1', description='Python client library for the Police.uk API', author='Rock Kitchen Harris', packages=find_packages(), install_requires=[ 'requests==2.0.0', ], )
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='police_api', version='0.1', description='Python client library for the Police API', author='Rock Kitchen Harris', packages=find_packages(), install_requires=[ 'requests==2.0.0', ], )
Update package name and description
Update package name and description
Python
mit
rkhleics/police-api-client-python
--- +++ @@ -3,9 +3,9 @@ from setuptools import setup, find_packages setup( - name='Police API', + name='police_api', version='0.1', - description='Python client library for the Police.uk API', + description='Python client library for the Police API', author='Rock Kitchen Harris', packages=find_packages(), install_requires=[
00900c6559c73bea982cd843ff49c7e0f5f296d3
setup.py
setup.py
from setuptools import setup setup( name='qual', version='0.1', description='Calendar stuff', url='http://github.com/jwg4/qual', author='Jack Grahl', author_email='jack.grahl@yahoo.co.uk', license='Apache License 2.0', packages=['qual'], test_suite='nose.collector', tests_require=['nose', 'hypothesis', 'hypothesis[extras]'] )
from setuptools import setup setup( name='qual', version='0.1', description='Calendar stuff', url='http://github.com/jwg4/qual', author='Jack Grahl', author_email='jack.grahl@yahoo.co.uk', license='Apache License 2.0', packages=['qual'], test_suite='nose.collector', tests_require=['nose', 'hypothesis'] )
Remove this requirement as travis-ci doesnt understand it.
Remove this requirement as travis-ci doesnt understand it.
Python
apache-2.0
jwg4/qual,jwg4/calexicon
--- +++ @@ -10,6 +10,6 @@ license='Apache License 2.0', packages=['qual'], test_suite='nose.collector', - tests_require=['nose', 'hypothesis', 'hypothesis[extras]'] + tests_require=['nose', 'hypothesis'] )
b7cc6302904e7adbc21edf65a797ded421b35d9a
setup.py
setup.py
from setuptools import setup, find_packages setup( name='pyseeyou', version='0.3.0', description='A Python Parser for the ICU MessageFormat.', author='Siame Rafiq', author_email='mail@sia.me.uk', packages=find_packages(exclude=['tests']), install_requires=['parsimonious', 'toolz'], tests_require=['pytest'], url='https://github.com/rolepoint/pyseeyou', download_url='https://github.com/rolepoint/pyseeyou/archive/v0.3.0.tar.gz', keywords='python i18n messageformat python3 python2' )
from setuptools import setup, find_packages setup( name='pyseeyou', version='0.3.0', description='A Python Parser for the ICU MessageFormat.', author='Siame Rafiq', author_email='mail@sia.me.uk', packages=find_packages(exclude=['tests']), install_requires=['parsimonious', 'toolz', 'future'], tests_require=['pytest'], url='https://github.com/rolepoint/pyseeyou', download_url='https://github.com/rolepoint/pyseeyou/archive/v0.3.0.tar.gz', keywords='python i18n messageformat python3 python2' )
Add future as required lib for pypi install
Add future as required lib for pypi install
Python
mit
rolepoint/pyseeyou
--- +++ @@ -7,7 +7,7 @@ author='Siame Rafiq', author_email='mail@sia.me.uk', packages=find_packages(exclude=['tests']), - install_requires=['parsimonious', 'toolz'], + install_requires=['parsimonious', 'toolz', 'future'], tests_require=['pytest'], url='https://github.com/rolepoint/pyseeyou', download_url='https://github.com/rolepoint/pyseeyou/archive/v0.3.0.tar.gz',
0b6db0b19e9389b1c5e62ddab5cdab4886364252
setup.py
setup.py
from distutils.core import setup setup(name='slowboy', version='0.0.1', packages=['slowboy'], url='https://github.com/zmarvel/slowboy/', author='Zack Marvel', author_email='zpmarvel at gmail dot com', install_requires=[ "Pillow==4.1.1", "PySDL2==0.9.5", ])
from distutils.core import setup setup(name='slowboy', version='0.0.1', packages=['slowboy'], url='https://github.com/zmarvel/slowboy/', author='Zack Marvel', author_email='zpmarvel at gmail dot com', install_requires=[ "PySDL2", ], extras_require={ "dev": [ "Pillow", "pytest", ], } )
Move Pillow to development deps; add pytest to development deps
Move Pillow to development deps; add pytest to development deps
Python
mit
zmarvel/slowboy
--- +++ @@ -9,6 +9,12 @@ author='Zack Marvel', author_email='zpmarvel at gmail dot com', install_requires=[ - "Pillow==4.1.1", - "PySDL2==0.9.5", - ]) + "PySDL2", + ], + extras_require={ + "dev": [ + "Pillow", + "pytest", + ], + } + )
7df69e47b88988e9797d42e7329c8bfc61e2dbcc
reporter/test/logged_unittest.py
reporter/test/logged_unittest.py
# -*- coding: utf-8 -*- """ Provides a custom unit test base class which will log to sentry. :copyright: (c) 2010 by Tim Sutton :license: GPLv3, see LICENSE for more details. """ import unittest import logging from reporter import setup_logger setup_logger() LOGGER = logging.getLogger('osm-reporter') class LoggedTestCase(unittest.TestCase): """A test class that logs to sentry on failure.""" def failureException(self, msg): """Overloaded failure exception that will log to sentry. Args: msg: str - a string containing a message for the log entry. Returns: delegates to TestCase and returns the exception generated by it. Raises: see unittest.TestCase """ LOGGER.exception(msg) return self.super(LoggedTestCase, self).failureException(msg)
# -*- coding: utf-8 -*- """ Provides a custom unit test base class which will log to sentry. :copyright: (c) 2010 by Tim Sutton :license: GPLv3, see LICENSE for more details. """ import unittest import logging from reporter import setup_logger setup_logger() LOGGER = logging.getLogger('osm-reporter') class LoggedTestCase(unittest.TestCase): """A test class that logs to sentry on failure.""" def failureException(self, msg): """Overloaded failure exception that will log to sentry. :param msg: String containing a message for the log entry. :type msg: str :returns: delegates to TestCase and returns the exception generated by it. :rtype: Exception See unittest.TestCase to see what gets raised. """ LOGGER.exception(msg) return super(LoggedTestCase, self).failureException(msg)
Fix for calling super during exception logging
Fix for calling super during exception logging
Python
bsd-3-clause
meomancer/field-campaigner,meomancer/field-campaigner,meomancer/field-campaigner
--- +++ @@ -18,15 +18,14 @@ def failureException(self, msg): """Overloaded failure exception that will log to sentry. - Args: - msg: str - a string containing a message for the log entry. + :param msg: String containing a message for the log entry. + :type msg: str - Returns: - delegates to TestCase and returns the exception generated by it. + :returns: delegates to TestCase and returns the exception generated + by it. + :rtype: Exception - Raises: - see unittest.TestCase - + See unittest.TestCase to see what gets raised. """ LOGGER.exception(msg) - return self.super(LoggedTestCase, self).failureException(msg) + return super(LoggedTestCase, self).failureException(msg)
8e980445723f3f185eb88022adbd75f1a01aaef4
fabfile/ubuntu.py
fabfile/ubuntu.py
from StringIO import StringIO from fabric.api import local, task, run, env, sudo, get from fabric.tasks import execute from fabric.context_managers import lcd, hide @task def apt_update(): with hide('stdout'): sudo('apt-get update') sudo('apt-get -y upgrade')
from StringIO import StringIO from fabric.api import local, task, run, env, sudo, get from fabric.operations import reboot from fabric.tasks import execute from fabric.context_managers import lcd, hide @task def apt_update(): with hide('stdout'): sudo('apt-get update') sudo('DEBIAN_FRONTEND=noninteractive apt-get -y -o Dpkg::Options::="--force-confdef" -o \ Dpkg::Options::="--force-confold" upgrade') reboot()
Add apt-get upgrade without grub-install
Add apt-get upgrade without grub-install
Python
mit
maruina/kanedias,maruina/kanedias,maruina/kanedias,maruina/kanedias
--- +++ @@ -1,5 +1,6 @@ from StringIO import StringIO from fabric.api import local, task, run, env, sudo, get +from fabric.operations import reboot from fabric.tasks import execute from fabric.context_managers import lcd, hide @@ -8,4 +9,6 @@ def apt_update(): with hide('stdout'): sudo('apt-get update') - sudo('apt-get -y upgrade') + sudo('DEBIAN_FRONTEND=noninteractive apt-get -y -o Dpkg::Options::="--force-confdef" -o \ + Dpkg::Options::="--force-confold" upgrade') + reboot()
a7c9231829e676682d7719fb94f2792c812b9b99
rest_api/tasks.py
rest_api/tasks.py
from celery.task import task from celery.task.sets import subtask from rest_api.models import Url from rest_api.backend import Request #TODO: read long_url from memcache #TODO: ensure with retry that if we made a resquest we have to save the result #TODO: should we ensure that user are logged and have permission here two? class UrlAlreadyUpdatedError(Exception): pass @task(ignore_result=True) def url_short(url_id): logger = url_short.get_logger() logger.info("Url shortner to url_id: %s" % url_id) url_request.delay(url_id, callback=subtask(url_update)) @task(ignore_result=True) def url_request(url_id, callback): logger = url_request.get_logger() url = Url.objects.get(pk=url_id) logger.info("Requesting short url to: %s" % url) # request an url shortner for the given url short_url = Request().create(url.long_url) logger.info("Got response: %s" % short_url) # spawn a task to update url on db subtask(callback).delay(url_id, short_url) @task(ignore_result=True) def url_update(url_id, short_url): logger = url_update.get_logger() url = Url.objects.get(pk=url_id) # check we already update this url if url.key: msg = 'Url %s already updated, possible duplicate task!' % url raise UrlAlreadyUpdatedError(msg) url.key = short_url url.save() logger.info("Url %s updated with sucess!" % url)
from celery.task import task from celery.task.sets import subtask from rest_api.models import Url from rest_api.backend import Request #TODO: read long_url from memcache #TODO: ensure with retry that if we made a resquest we have to save the result #TODO: should we ensure that user are logged and have permission here two? class UrlAlreadyUpdatedError(Exception): pass @task(ignore_result=False) def url_short(url_id): url = Url.objects.get(pk=url_id) if url.key: raise UrlAlreadyUpdatedError( 'Url %s already updated, possible duplicate task!' % url) # request an url shortner for the given url short_url = Request().create(url.long_url) url.key = short_url url.save() return short_url
Use only on task to have control and it is finished
Use only on task to have control and it is finished
Python
bsd-2-clause
victorpoluceno/shortener_worker
--- +++ @@ -13,39 +13,17 @@ pass -@task(ignore_result=True) +@task(ignore_result=False) def url_short(url_id): - logger = url_short.get_logger() - logger.info("Url shortner to url_id: %s" % url_id) - url_request.delay(url_id, callback=subtask(url_update)) - - -@task(ignore_result=True) -def url_request(url_id, callback): - logger = url_request.get_logger() - url = Url.objects.get(pk=url_id) - logger.info("Requesting short url to: %s" % url) + if url.key: + raise UrlAlreadyUpdatedError( + 'Url %s already updated, possible duplicate task!' % url) # request an url shortner for the given url short_url = Request().create(url.long_url) - logger.info("Got response: %s" % short_url) - - # spawn a task to update url on db - subtask(callback).delay(url_id, short_url) - - -@task(ignore_result=True) -def url_update(url_id, short_url): - logger = url_update.get_logger() - url = Url.objects.get(pk=url_id) - - # check we already update this url - if url.key: - msg = 'Url %s already updated, possible duplicate task!' % url - raise UrlAlreadyUpdatedError(msg) url.key = short_url url.save() - logger.info("Url %s updated with sucess!" % url) + return short_url
fd98983e0880b6d2cf81a72da7d65082487359c1
lib/rapidsms/contrib/messagelog/app.py
lib/rapidsms/contrib/messagelog/app.py
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import datetime from rapidsms.apps.base import AppBase from .models import Message class App(AppBase): def _who(self, msg): to_return = {} if msg.contact: to_return["contact"] = msg.contact if msg.connection: to_return["connection"] = msg.connection if not to_return: raise ValueError return to_return def _log(self, direction, who, text): return Message.objects.create( date=datetime.datetime.now(), direction=direction, text=text, **who) def parse(self, msg): # annotate the message as we log them in case any other apps # want a handle to them msg.logger_msg = self._log("I", self._who(msg), msg.raw_text) def outgoing(self, msg): msg.logger_msg = self._log("O", self._who(msg), msg.text)
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import datetime from rapidsms.apps.base import AppBase from .models import Message try: from django.utils.timezone import now as datetime_now except ImportError: datetime_now = datetime.datetime.now class App(AppBase): def _who(self, msg): to_return = {} if msg.contact: to_return["contact"] = msg.contact if msg.connection: to_return["connection"] = msg.connection if not to_return: raise ValueError return to_return def _log(self, direction, who, text): return Message.objects.create( date=datetime_now(), direction=direction, text=text, **who) def parse(self, msg): # annotate the message as we log them in case any other apps # want a handle to them msg.logger_msg = self._log("I", self._who(msg), msg.raw_text) def outgoing(self, msg): msg.logger_msg = self._log("O", self._who(msg), msg.text)
Use new timezone-aware datetime.now with Django versions that support it
Use new timezone-aware datetime.now with Django versions that support it
Python
bsd-3-clause
lsgunth/rapidsms,peterayeni/rapidsms,caktus/rapidsms,caktus/rapidsms,lsgunth/rapidsms,lsgunth/rapidsms,catalpainternational/rapidsms,ehealthafrica-ci/rapidsms,caktus/rapidsms,peterayeni/rapidsms,catalpainternational/rapidsms,catalpainternational/rapidsms,eHealthAfrica/rapidsms,ehealthafrica-ci/rapidsms,ehealthafrica-ci/rapidsms,catalpainternational/rapidsms,peterayeni/rapidsms,lsgunth/rapidsms,eHealthAfrica/rapidsms,eHealthAfrica/rapidsms,peterayeni/rapidsms
--- +++ @@ -5,6 +5,12 @@ import datetime from rapidsms.apps.base import AppBase from .models import Message + + +try: + from django.utils.timezone import now as datetime_now +except ImportError: + datetime_now = datetime.datetime.now class App(AppBase): @@ -18,7 +24,7 @@ def _log(self, direction, who, text): return Message.objects.create( - date=datetime.datetime.now(), + date=datetime_now(), direction=direction, text=text, **who)
04c82d00517428bc60e7c4204f01e55452c2c8f2
oscar_mws/receivers.py
oscar_mws/receivers.py
import logging from django.utils.translation import ugettext_lazy as _ from oscar_mws.fulfillment import gateway logger = logging.getLogger('oscar_mws') def submit_order_to_mws(order, user, **kwargs): if kwargs.get('raw', False): return from oscar_mws.fulfillment.creator import FulfillmentOrderCreator order_creator = FulfillmentOrderCreator() submitted_orders = order_creator.create_fulfillment_order(order) gateway.submit_fulfillment_orders(submitted_orders) if not order_creator.errors: logger.info( _("Successfully submitted {0} orders to Amazon").format( len(submitted_orders) ) ) else: for order_id, error in order_creator.errors.iteritems(): logger.error( _("Error submitting order {0} to Amazon: {1}").format( order_id, error ) )
import logging from django.utils.translation import ugettext_lazy as _ logger = logging.getLogger('oscar_mws') def submit_order_to_mws(order, user, **kwargs): if kwargs.get('raw', False): return # these modules have to be imported here because they rely on loading # models from oscar_mws using get_model which are not fully loaded at this # point because the receivers module is imported into models.py from oscar_mws.fulfillment import gateway from oscar_mws.fulfillment.creator import FulfillmentOrderCreator order_creator = FulfillmentOrderCreator() submitted_orders = order_creator.create_fulfillment_order(order) gateway.submit_fulfillment_orders(submitted_orders) if not order_creator.errors: logger.info( _("Successfully submitted {0} orders to Amazon").format( len(submitted_orders) ) ) else: for order_id, error in order_creator.errors.iteritems(): logger.error( _("Error submitting order {0} to Amazon: {1}").format( order_id, error ) )
Fix issue with importing models in fulfillment gateway
Fix issue with importing models in fulfillment gateway
Python
bsd-3-clause
django-oscar/django-oscar-mws,django-oscar/django-oscar-mws
--- +++ @@ -1,8 +1,6 @@ import logging from django.utils.translation import ugettext_lazy as _ - -from oscar_mws.fulfillment import gateway logger = logging.getLogger('oscar_mws') @@ -11,6 +9,10 @@ if kwargs.get('raw', False): return + # these modules have to be imported here because they rely on loading + # models from oscar_mws using get_model which are not fully loaded at this + # point because the receivers module is imported into models.py + from oscar_mws.fulfillment import gateway from oscar_mws.fulfillment.creator import FulfillmentOrderCreator order_creator = FulfillmentOrderCreator()
44766469827fb3a0966b1370022834da87d8b3e8
setup.py
setup.py
#!/usr/bin/python from setuptools import setup, find_packages setup( name="sandsnake", license='Apache License 2.0', version="0.1.0", description="Manage activity indexes for objects.", long_description=open('README.rst', 'r').read(), author="Numan Sachwani", author_email="numan856@gmail.com", url="https://github.com/numan/sandsnake", packages=find_packages(exclude=['tests']), test_suite='nose.collector', install_requires=[ 'nydus>=0.10.5', 'redis>=2.7.2', 'python-dateutil==1.5', ], tests_require=[ 'nose>=1.0', ], classifiers=[ "Intended Audience :: Developers", 'Intended Audience :: System Administrators', "Programming Language :: Python", "Topic :: Software Development", "Topic :: Utilities", ], )
#!/usr/bin/python from setuptools import setup, find_packages setup( name="sandsnake", license='Apache License 2.0', version="0.1.0", description="Sorted indexes backed by redis.", long_description=open('README.rst', 'r').read(), author="Numan Sachwani", author_email="numan856@gmail.com", url="https://github.com/numan/sandsnake", packages=find_packages(exclude=['tests']), test_suite='nose.collector', install_requires=[ 'nydus>=0.10.5', 'redis>=2.7.2', 'python-dateutil==1.5', ], tests_require=[ 'nose>=1.0', ], classifiers=[ "Intended Audience :: Developers", 'Intended Audience :: System Administrators', "Programming Language :: Python", "Topic :: Software Development", "Topic :: Utilities", ], )
Update description to describe a more general case
Update description to describe a more general case
Python
apache-2.0
numan/sandsnake
--- +++ @@ -6,7 +6,7 @@ name="sandsnake", license='Apache License 2.0', version="0.1.0", - description="Manage activity indexes for objects.", + description="Sorted indexes backed by redis.", long_description=open('README.rst', 'r').read(), author="Numan Sachwani", author_email="numan856@gmail.com",
be447d2f3f9cfd059ccd30f2319fe6b54403eb78
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-pedantic-http-methods', description="Raises an exception when attempting to perform side effects " "in GET and HEAD HTTP methods.", version='1.0.2', url='https://chris-lamb.co.uk/projects/django-pedantic-http-methods', author='Chris Lamb', author_email='chris@chris-lamb.co.uk', license='BSD', packages=find_packages(), )
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-pedantic-http-methods', description="Raises an exception when attempting to perform side effects " "in GET and HEAD HTTP methods.", version='1.0.2', url='https://chris-lamb.co.uk/projects/django-pedantic-http-methods', author='Chris Lamb', author_email='chris@chris-lamb.co.uk', license='BSD', packages=find_packages(), install_requires=( 'Django>=1.8', ), )
Update Django requirement to latest LTS
Update Django requirement to latest LTS
Python
bsd-3-clause
lamby/django-pedantic-http-methods
--- +++ @@ -14,4 +14,8 @@ license='BSD', packages=find_packages(), + + install_requires=( + 'Django>=1.8', + ), )