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
886254938707035bbf404206cf62eabd29f54bb4
setup.py
setup.py
try: from setuptools import setup except ImportError: from distutils.core import setup import toml with open("README.rst") as readme_file: readme_string = readme_file.read() setup( name="toml", version=toml.__version__, description="Python Library for Tom's Obvious, Minimal Language", author="Uiri Noyb", author_email="uiri@xqz.ca", url="https://github.com/uiri/toml", packages=['toml'], license="License :: OSI Approved :: MIT License", long_description=readme_string, classifiers=[ 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6'] )
try: from setuptools import setup except ImportError: from distutils.core import setup import toml with open("README.rst") as readme_file: readme_string = readme_file.read() setup( name="toml", version=toml.__version__, description="Python Library for Tom's Obvious, Minimal Language", author="Uiri Noyb", author_email="uiri@xqz.ca", url="https://github.com/uiri/toml", packages=['toml'], license="License :: OSI Approved :: MIT License", long_description=readme_string, classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ] )
Add trove classifiers for additional Python support
Add trove classifiers for additional Python support - Include classifier for general Python 2/3 support. - Include classifier for general PyPy support. - Include classifier for Python 3.7 support. Testing added in 0c1bbf6be93b2f0a110a9000fb514301c4d5ab89.
Python
mit
uiri/toml,uiri/toml
--- +++ @@ -19,10 +19,17 @@ license="License :: OSI Approved :: MIT License", long_description=readme_string, classifiers=[ + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', - 'Programming Language :: Python :: 3.6'] + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: Implementation :: CPython', + 'Programming Language :: Python :: Implementation :: PyPy', + ] )
e5e2b270d7bdf1b8225405619908389319686146
tests/test_demos.py
tests/test_demos.py
import os from dallinger import db class TestBartlett1932(object): """Tests for the Bartlett1932 demo class""" def _make_one(self): from demos.bartlett1932.experiment import Bartlett1932 return Bartlett1932(self._db) def setup(self): self._db = db.init_db(drop_all=True) # This is only needed for config, which loads on import os.chdir('demos/bartlett1932') def teardown(self): self._db.rollback() self._db.close() os.chdir('../..') def test_instantiation(self): demo = self._make_one() assert demo is not None def test_networks_holds_single_experiment_node(self): demo = self._make_one() assert len(demo.networks()) == 1 assert u'experiment' == demo.networks()[0].role class TestEntryPointImport(object): def test_bartlett1932_entry_point(self): from demos.bartlett1932.experiment import Bartlett1932 as OrigExp from dallinger.experiments import Bartlett1932 assert Bartlett1932 is OrigExp
import os import subprocess from dallinger import db class TestDemos(object): """Verify all the built-in demos.""" def test_verify_all_demos(self): demo_paths = os.listdir("demos") for demo_path in demo_paths: if os.path.isdir(demo_path): os.chdir(demo_path) assert subprocess.check_call(["dallinger", "verify"]) os.chdir("..") class TestBartlett1932(object): """Tests for the Bartlett1932 demo class""" def _make_one(self): from demos.bartlett1932.experiment import Bartlett1932 return Bartlett1932(self._db) def setup(self): self._db = db.init_db(drop_all=True) # This is only needed for config, which loads on import os.chdir(os.path.join("demos", "bartlett1932")) def teardown(self): self._db.rollback() self._db.close() os.chdir(os.path.join("..", "..")) def test_instantiation(self): demo = self._make_one() assert demo is not None def test_networks_holds_single_experiment_node(self): demo = self._make_one() assert len(demo.networks()) == 1 assert u'experiment' == demo.networks()[0].role class TestEntryPointImport(object): def test_bartlett1932_entry_point(self): from demos.bartlett1932.experiment import Bartlett1932 as OrigExp from dallinger.experiments import Bartlett1932 assert Bartlett1932 is OrigExp
Test by verifying all demos
Test by verifying all demos
Python
mit
Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger
--- +++ @@ -1,5 +1,19 @@ import os +import subprocess + from dallinger import db + + +class TestDemos(object): + """Verify all the built-in demos.""" + + def test_verify_all_demos(self): + demo_paths = os.listdir("demos") + for demo_path in demo_paths: + if os.path.isdir(demo_path): + os.chdir(demo_path) + assert subprocess.check_call(["dallinger", "verify"]) + os.chdir("..") class TestBartlett1932(object): @@ -12,12 +26,12 @@ def setup(self): self._db = db.init_db(drop_all=True) # This is only needed for config, which loads on import - os.chdir('demos/bartlett1932') + os.chdir(os.path.join("demos", "bartlett1932")) def teardown(self): self._db.rollback() self._db.close() - os.chdir('../..') + os.chdir(os.path.join("..", "..")) def test_instantiation(self): demo = self._make_one()
64b26ba9cab7d432d3e4185a8edb12f9257ab473
setup.py
setup.py
# -*- coding: utf-8 -*- from distutils.core import setup setup( name = 'grades', packages = ['grades'], scripts = ['bin/grades'], version = '0.1', description = 'Minimalist grades management for teachers.', author = 'Loïc Séguin-C.', author_email = 'loicseguin@gmail.com', url = 'https://github.com/loicseguin/grades', download_url = 'https://github.com/loicseguin/grades/tarball/master', keywords = ['grades', 'student', 'teacher', 'class management'], classifiers = [ 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Education', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Topic :: Database', 'Topic :: Education', 'Topic :: Text Processing', 'Topic :: Utilities' ], long_description = """For managing student grades, most teachers use spreadsheet tools. With these tools, it is hard to maintain grades in plain text files that are easily readable by humans. The goal of grades is to let teachers manage their students' grade in plain text file while providing tools to parse the file and calculate students and group means.""" )
# -*- coding: utf-8 -*- from distutils.core import setup setup( name = 'grades', packages = ['grades'], scripts = ['bin/grades'], version = '0.1', description = 'Minimalist grades management for teachers.', author = 'Loïc Séguin-C.', author_email = 'loicseguin@gmail.com', url = 'https://github.com/loicseguin/grades', download_url = 'https://github.com/loicseguin/grades/tarball/master', keywords = ['grades', 'student', 'teacher', 'class management'], classifiers = [ 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Education', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Topic :: Database', 'Topic :: Education', 'Topic :: Text Processing', 'Topic :: Utilities' ], long_description = open('README.rst', 'r').read() )
Use README.rst as long description.
Use README.rst as long description.
Python
bsd-3-clause
loicseguin/grades
--- +++ @@ -26,9 +26,5 @@ 'Topic :: Text Processing', 'Topic :: Utilities' ], - long_description = """For managing student grades, most teachers use - spreadsheet tools. With these tools, it is hard to maintain grades in plain - text files that are easily readable by humans. The goal of grades is to let - teachers manage their students' grade in plain text file while providing - tools to parse the file and calculate students and group means.""" + long_description = open('README.rst', 'r').read() )
0922c8d06264f02f9b8de59e3546e499c8599326
tests/test_views.py
tests/test_views.py
import unittest from flask import current_app, url_for, get_flashed_messages from app import create_app, db from app.models import * class TestCreateAdmissionView(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() self.client = self.app.test_client(use_cookies=True) self.valid_admission_form = { 'id_lvrs_intern': 1, } def tearDown(self): db.session.remove() db.drop_all() self.app_context.pop() def test_duplicate_id_lvrs_intern(self): a = Admission(id_lvrs_intern=1) db.session.add(a) db.session.commit() data = { 'id_lvrs_intern': 1, 'samples-0-collection_date': '12/12/2012', 'samples-0-admission_date': '13/12/2012', } duplicate_id_lvrs_intern = 'Número Interno já cadastrado!' response = self.client.post( url_for('main.create_admission'), data=data, follow_redirects=True) self.assertTrue( duplicate_id_lvrs_intern in response.get_data(as_text=True))
import unittest from flask import current_app, url_for, get_flashed_messages from app import create_app, db from app.models import * class TestCreateAdmissionView(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() self.client = self.app.test_client(use_cookies=True) self.valid_admission_form = { 'id_lvrs_intern': 1, } def tearDown(self): db.session.remove() db.drop_all() self.app_context.pop() def test_duplicate_id_lvrs_intern(self): a = Admission(id_lvrs_intern=1) db.session.add(a) db.session.commit() data = { 'id_lvrs_intern': '1', 'samples-0-collection_date': '12/12/2012', 'samples-0-admission_date': '13/12/2012', } duplicate_id_lvrs_intern = 'Número Interno já cadastrado!' response = self.client.post( url_for('main.create_admission'), data=data, follow_redirects=True) self.assertTrue( duplicate_id_lvrs_intern in response.get_data(as_text=True)) self.assertTrue( len(Admission.query.filter_by(id_lvrs_intern='1').all()), 1)
Change id_lvrs_internt to string. Test if there's only one created
:bug: Change id_lvrs_internt to string. Test if there's only one created
Python
mit
gems-uff/labsys,gems-uff/labsys,gems-uff/labsys
--- +++ @@ -25,7 +25,7 @@ db.session.add(a) db.session.commit() data = { - 'id_lvrs_intern': 1, + 'id_lvrs_intern': '1', 'samples-0-collection_date': '12/12/2012', 'samples-0-admission_date': '13/12/2012', } @@ -34,3 +34,5 @@ url_for('main.create_admission'), data=data, follow_redirects=True) self.assertTrue( duplicate_id_lvrs_intern in response.get_data(as_text=True)) + self.assertTrue( + len(Admission.query.filter_by(id_lvrs_intern='1').all()), 1)
04534c096900ab09dda4caab5a4d5d6f00a340cb
setup.py
setup.py
from setuptools import setup, find_packages with open('README.rst') as f: long_description = f.read() setup( name='ocdsmerge', version='0.5.6', author='Open Contracting Partnership', author_email='data@open-contracting.org', url='https://github.com/open-contracting/ocds-merge', description='A library and reference implementation for merging OCDS releases', license='BSD', packages=find_packages(exclude=['tests']), long_description=long_description, install_requires=[ 'jsonref', 'requests', ], extras_require={ 'test': [ 'coveralls', 'jsonschema', 'pytest', 'pytest-cov', 'pytest-vcr', ], }, classifiers=[ 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 3.6', ], )
from setuptools import setup, find_packages with open('README.rst') as f: long_description = f.read() setup( name='ocdsmerge', version='0.5.6', author='Open Contracting Partnership', author_email='data@open-contracting.org', url='https://github.com/open-contracting/ocds-merge', description='A library and reference implementation for merging OCDS releases', license='BSD', packages=find_packages(exclude=['tests', 'tests.*']), long_description=long_description, install_requires=[ 'jsonref', 'requests', ], extras_require={ 'test': [ 'coveralls', 'jsonschema', 'pytest', 'pytest-cov', 'pytest-vcr', ], }, classifiers=[ 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 3.6', ], )
Exclude any future tests sub-packages from build.
Exclude any future tests sub-packages from build.
Python
bsd-3-clause
open-contracting/ocds-merge
--- +++ @@ -11,7 +11,7 @@ url='https://github.com/open-contracting/ocds-merge', description='A library and reference implementation for merging OCDS releases', license='BSD', - packages=find_packages(exclude=['tests']), + packages=find_packages(exclude=['tests', 'tests.*']), long_description=long_description, install_requires=[ 'jsonref',
6752007377e57850f21553e1aa2b85ca64c6e769
pesabot/client.py
pesabot/client.py
import requests from requests.auth import HTTPBasicAuth BASE_URL = 'https://pesabot.com/api/v1/' class Client(object): def __init__(self, email, password): self.auth = HTTPBasicAuth(email, password) def call(self, path, method='GET', payload={}): if method == 'POST': res = requests.post(BASE_URL+path, data=payload, auth=self.auth) else: res = requests.get(BASE_URL+path, auth=self.auth) return {'data': res.json(), 'status': res.status_code}
import requests from requests.auth import HTTPBasicAuth BASE_URL = 'https://pesabot.com/api/v1/' class Client(object): def __init__(self, email, password): self.auth = None if email and password: self.auth = HTTPBasicAuth(email, password) def call(self, path, method='GET', payload={}): if method == 'POST': res = requests.post(BASE_URL+path, data=payload, auth=self.auth) else: res = requests.get(BASE_URL+path, auth=self.auth) return {'data': res.json(), 'status': res.status_code}
Make auth optional for allow any routes to work
Make auth optional for allow any routes to work
Python
mit
pesabot/pesabot-py
--- +++ @@ -5,7 +5,9 @@ class Client(object): def __init__(self, email, password): - self.auth = HTTPBasicAuth(email, password) + self.auth = None + if email and password: + self.auth = HTTPBasicAuth(email, password) def call(self, path, method='GET', payload={}): if method == 'POST':
cd92e7186d8b0e1f8103b6f622c0622e7db88fb8
thecodingloverss.py
thecodingloverss.py
import feedparser, sys, urllib2 from bs4 import BeautifulSoup as BS from feedgen.feed import FeedGenerator from flask import Flask app = Flask(__name__) @app.route('/') def index(): d = feedparser.parse('http://thecodinglove.com/rss') fg = FeedGenerator() fg.title('The coding love with images.') fg.link(href='http://thecodinglove.com') fg.description('The coding love with images.') for entry in d.entries: title = entry.title href = entry.links[0].href bs = BS(urllib2.urlopen(href), "lxml") image = bs.p.img.get('src') imgsrc='<img src="%s">' % image fe = fg.add_entry() fe.id(href) fe.link(href=href) fe.title(title) fe.description(imgsrc) rssfeed = fg.rss_str(pretty=True) return rssfeed
import feedparser, sys, urllib2 from bs4 import BeautifulSoup as BS from feedgen.feed import FeedGenerator from flask import Flask app = Flask(__name__) @app.route('/') def index(): d = feedparser.parse('http://thecodinglove.com/rss') fg = FeedGenerator() fg.title('The coding love with images.') fg.link(href='http://thecodinglove.com') fg.description('The coding love with images.') for entry in d.entries: title = entry.title href = entry.links[0].href bs = BS(urllib2.urlopen(href), "lxml") published = entry.published image = bs.p.img.get('src') imgsrc='<img src="%s">' % image fe = fg.add_entry() fe.id(href) fe.link(href=href) fe.pubdate(published) fe.title(title) fe.description(imgsrc) rssfeed = fg.rss_str(pretty=True) return rssfeed
Set published date so the posts come in order.
Set published date so the posts come in order.
Python
mit
chrillux/thecodingloverss
--- +++ @@ -23,12 +23,15 @@ href = entry.links[0].href bs = BS(urllib2.urlopen(href), "lxml") + published = entry.published + image = bs.p.img.get('src') imgsrc='<img src="%s">' % image fe = fg.add_entry() fe.id(href) fe.link(href=href) + fe.pubdate(published) fe.title(title) fe.description(imgsrc)
f71a166598ab35bc15f298226bb510d43f78c810
bids/analysis/transformations/__init__.py
bids/analysis/transformations/__init__.py
from .compute import (sum, product, scale, orthogonalize, threshold, and_, or_, not_, demean, convolve_HRF) from .munge import (split, rename, assign, copy, factor, filter, select, remove, replace, to_dense) __all__ = [ 'and_', 'assign', 'convolve_HRF', 'copy', 'demean', 'factor', 'filter', 'not_', 'or_', 'orthogonalize', 'product', 'remove', 'rename', 'replace', 'scale', 'select', 'split', 'sum', 'threshold', 'to_dense' ]
from .compute import (sum, product, scale, orthogonalize, threshold, and_, or_, not_, demean, convolve) from .munge import (split, rename, assign, copy, factor, filter, select, delete, replace, to_dense) __all__ = [ 'and_', 'assign', 'convolve', 'copy', 'demean', 'delete', 'factor', 'filter', 'not_', 'or_', 'orthogonalize', 'product', 'rename', 'replace', 'scale', 'select', 'split', 'sum', 'threshold', 'to_dense' ]
Fix imports for renamed transformations
Fix imports for renamed transformations
Python
mit
INCF/pybids
--- +++ @@ -1,21 +1,21 @@ from .compute import (sum, product, scale, orthogonalize, threshold, and_, or_, - not_, demean, convolve_HRF) + not_, demean, convolve) from .munge import (split, rename, assign, copy, factor, filter, select, - remove, replace, to_dense) + delete, replace, to_dense) __all__ = [ 'and_', 'assign', - 'convolve_HRF', + 'convolve', 'copy', 'demean', + 'delete', 'factor', 'filter', 'not_', 'or_', 'orthogonalize', 'product', - 'remove', 'rename', 'replace', 'scale',
b5bef82ea6eb4269a164eda3ba95d7212f1c76d1
lib/cli/run_worker.py
lib/cli/run_worker.py
import sys from rq import Queue, Connection, Worker import cli import worker class RunWorkerCli(cli.BaseCli): ''' A wrapper for RQ workers. Wrapping RQ is the only way to generate notifications when a job fails. ''' def _get_args(self, arg_parser): ''' Customize arguments. ''' arg_parser.add_argument( 'queues', nargs='+', help='Names of queues for this worker to service.' ) def _run(self, args, config): ''' Main entry point. Adapted from http://python-rq.org/docs/workers/. ''' with Connection(): queues = map(Queue, args.queues) w = Worker(queues, exc_handler=worker.handle_exception) w.work()
import sys from redis import Redis from rq import Queue, Connection, Worker import cli import worker class RunWorkerCli(cli.BaseCli): ''' A wrapper for RQ workers. Wrapping RQ is the only way to generate notifications when a job fails. ''' def _get_args(self, arg_parser): ''' Customize arguments. ''' arg_parser.add_argument( 'queues', nargs='+', help='Names of queues for this worker to service.' ) def _run(self, args, config): ''' Main entry point. Adapted from http://python-rq.org/docs/workers/. ''' redis_config = dict(config.items('redis')) port = redis_config.get('port', 6379) host = redis_config.get('host', 'localhost') with Connection(Redis(host, port)): queues = map(Queue, args.queues) w = Worker(queues, exc_handler=worker.handle_exception) w.work()
Use connection settings from conf file.
Use connection settings from conf file.
Python
apache-2.0
TeamHG-Memex/hgprofiler,TeamHG-Memex/hgprofiler,TeamHG-Memex/hgprofiler,TeamHG-Memex/hgprofiler
--- +++ @@ -1,5 +1,5 @@ import sys - +from redis import Redis from rq import Queue, Connection, Worker import cli @@ -29,7 +29,11 @@ Adapted from http://python-rq.org/docs/workers/. ''' - with Connection(): + redis_config = dict(config.items('redis')) + port = redis_config.get('port', 6379) + host = redis_config.get('host', 'localhost') + + with Connection(Redis(host, port)): queues = map(Queue, args.queues) w = Worker(queues, exc_handler=worker.handle_exception) w.work()
621fc3e10ad296c21a27160a8a1263cf69e3079f
setup.py
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import uuid from pip.req import parse_requirements from setuptools import setup, find_packages requirements = parse_requirements('requirements.txt', session=uuid.uuid1()) reqs = [str(ir.req) for ir in requirements] readme = open('README.rst').read() setup(name='nuts', version='1.1', description='A Network Unit Test System', author='Andreas Stalder, David Meister, Matthias Gabriel, Urs Baumann', author_email='astalder@hsr.ch, dmeister@hsr.ch, mgabriel@hsr.ch, ubaumann@ins.hsr.ch', url='https://github.com/HSRNetwork/Nuts', packages=find_packages(), zip_safe=False, include_package_data=True, license='MIT', keywords='network testing unit system', long_description=readme, install_requires=reqs, entry_points={ 'console_scripts': [ 'nuts = nuts.main:main', ] }, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: System :: Networking', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.6', ], )
#!/usr/bin/env python # -*- coding: utf-8 -*- import uuid from pip.req import parse_requirements from setuptools import setup, find_packages requirements = parse_requirements('requirements.txt', session=uuid.uuid1()) reqs = [str(ir.req) for ir in requirements] readme = open('README.rst').read() setup(name='nuts', version='1.1.1', description='A Network Unit Test System', author='Andreas Stalder, David Meister, Matthias Gabriel, Urs Baumann', author_email='astalder@hsr.ch, dmeister@hsr.ch, mgabriel@hsr.ch, ubaumann@ins.hsr.ch', url='https://github.com/HSRNetwork/Nuts', packages=find_packages(), data_files=[('lib/python2.7/site-packages/nuts/service', ['nuts/service/testSchema.yaml'])], zip_safe=False, include_package_data=True, license='MIT', keywords='network testing unit system', long_description=readme, install_requires=reqs, entry_points={ 'console_scripts': [ 'nuts = nuts.main:main', ] }, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: System :: Networking', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.6', ], )
Fix missing testSchema in package
Fix missing testSchema in package
Python
mit
HSRNetwork/Nuts
--- +++ @@ -11,12 +11,13 @@ readme = open('README.rst').read() setup(name='nuts', - version='1.1', + version='1.1.1', description='A Network Unit Test System', author='Andreas Stalder, David Meister, Matthias Gabriel, Urs Baumann', author_email='astalder@hsr.ch, dmeister@hsr.ch, mgabriel@hsr.ch, ubaumann@ins.hsr.ch', url='https://github.com/HSRNetwork/Nuts', packages=find_packages(), + data_files=[('lib/python2.7/site-packages/nuts/service', ['nuts/service/testSchema.yaml'])], zip_safe=False, include_package_data=True, license='MIT',
774f7ac425f0a16934dae12d474982c5916435b4
setup.py
setup.py
from setuptools import setup setup( name='slacker', version='0.6.1', packages=['slacker'], description='Slack API client', author='Oktay Sancak', author_email='oktaysancak@gmail.com', url='http://github.com/os/slacker/', install_requires=['requests >= 2.2.1'], license='http://www.apache.org/licenses/LICENSE-2.0', test_suite='tests', classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4' ), keywords='slack api' )
from setuptools import setup setup( name='slacker', version='0.6.2', packages=['slacker'], description='Slack API client', author='Oktay Sancak', author_email='oktaysancak@gmail.com', url='http://github.com/os/slacker/', install_requires=['requests >= 2.2.1'], license='http://www.apache.org/licenses/LICENSE-2.0', test_suite='tests', classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4' ), keywords='slack api' )
Set version number to 0.6.2.
Set version number to 0.6.2.
Python
apache-2.0
techartorg/slacker,olasitarska/slacker,wkentaro/slacker,kashyap32/slacker,STANAPO/slacker,dastergon/slacker,wasabi0522/slacker,BetterWorks/slacker,hreeder/slacker,os/slacker
--- +++ @@ -3,7 +3,7 @@ setup( name='slacker', - version='0.6.1', + version='0.6.2', packages=['slacker'], description='Slack API client', author='Oktay Sancak',
cb08d632fac453403bc8b91391b14669dbe932cc
circonus/__init__.py
circonus/__init__.py
from __future__ import absolute_import __title__ = "circonus" __version__ = "0.0.0" from logging import NullHandler import logging from circonus.client import CirconusClient logging.getLogger(__name__).addHandler(NullHandler())
__title__ = "circonus" __version__ = "0.0.0" from logging import NullHandler import logging from circonus.client import CirconusClient logging.getLogger(__name__).addHandler(NullHandler())
Remove unnecessary absolute import statement.
Remove unnecessary absolute import statement.
Python
mit
monetate/circonus,monetate/circonus
--- +++ @@ -1,6 +1,3 @@ -from __future__ import absolute_import - - __title__ = "circonus" __version__ = "0.0.0"
3089eae072bd2e871c11251961ec35a09b83dd38
setup.py
setup.py
# # This file is part of Python-AD. Python-AD is free software that is made # available under the MIT license. Consult the file "LICENSE" that is # distributed together with this file for the exact licensing terms. # # Python-AD is copyright (c) 2007 by the Python-AD authors. See the file # "AUTHORS" for a complete overview. from setuptools import setup, Extension setup( name = 'python-ad', version = '0.9', description = 'An AD client library for Python', author = 'Geert Jansen', author_email = 'geert@boskant.nl', url = 'http://code.google.com/p/python-ad', license = 'MIT', classifiers = ['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python'], package_dir = {'': 'lib'}, packages = ['ad', 'ad.core', 'ad.protocol', 'ad.util'], install_requires = [ 'python-ldap', 'dnspython', 'ply' ], ext_modules = [Extension('ad.protocol.krb5', ['lib/ad/protocol/krb5.c'], libraries=['krb5'])], test_suite = 'nose.collector' )
# # This file is part of Python-AD. Python-AD is free software that is made # available under the MIT license. Consult the file "LICENSE" that is # distributed together with this file for the exact licensing terms. # # Python-AD is copyright (c) 2007 by the Python-AD authors. See the file # "AUTHORS" for a complete overview. from setuptools import setup, Extension setup( name = 'python-ad', version = '0.9', description = 'An AD client library for Python', author = 'Geert Jansen', author_email = 'geertj@gmail.com', url = 'https://github.com/geertj/python-ad', license = 'MIT', classifiers = ['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python'], package_dir = {'': 'lib'}, packages = ['ad', 'ad.core', 'ad.protocol', 'ad.util'], install_requires = [ 'python-ldap', 'dnspython', 'ply' ], ext_modules = [Extension('ad.protocol.krb5', ['lib/ad/protocol/krb5.c'], libraries=['krb5'])], test_suite = 'nose.collector' )
Change email address and home page.
Change email address and home page.
Python
mit
geertj/python-ad,theatlantic/python-active-directory,sfu-rcg/python-ad,geertj/python-ad,theatlantic/python-active-directory,sfu-rcg/python-ad
--- +++ @@ -13,8 +13,8 @@ version = '0.9', description = 'An AD client library for Python', author = 'Geert Jansen', - author_email = 'geert@boskant.nl', - url = 'http://code.google.com/p/python-ad', + author_email = 'geertj@gmail.com', + url = 'https://github.com/geertj/python-ad', license = 'MIT', classifiers = ['Development Status :: 4 - Beta', 'Intended Audience :: Developers',
a55957996f3e6ae1b7b98bea477e14da2070733e
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup setup( name='bandicoot', author='Yves-Alexandre de Montjoye', author_email='yvesalexandre@demontjoye.com', version="0.4", url="https://github.com/yvesalexandre/bandicoot", license="MIT", packages=[ 'bandicoot', 'bandicoot.helper', 'bandicoot.tests', 'bandicoot.special' ], description="A toolbox to analyze mobile phone metadata.", classifiers=[ 'Environment :: Plugins', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Scientific/Engineering :: Mathematics' ])
#!/usr/bin/env python from setuptools import setup setup( name='bandicoot', author='Yves-Alexandre de Montjoye', author_email='yvesalexandre@demontjoye.com', version="0.4", url="https://github.com/yvesalexandre/bandicoot", license="MIT", packages=[ 'bandicoot', 'bandicoot.helper', 'bandicoot.tests', 'bandicoot.special' ], description="A toolbox to analyze mobile phone metadata.", classifiers=[ 'Environment :: Plugins', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Scientific/Engineering :: Mathematics' ], extras_require={ 'tests': ['numpy', 'scipy', 'networkx'] })
Update PyPI classifiers and test requirements
Update PyPI classifiers and test requirements
Python
mit
yvesalexandre/bandicoot,yvesalexandre/bandicoot,yvesalexandre/bandicoot
--- +++ @@ -23,6 +23,10 @@ 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Scientific/Engineering :: Mathematics' - ]) + ], + extras_require={ + 'tests': ['numpy', 'scipy', 'networkx'] + })
d1182f48c086a1a875a6cf1b489a8aa172032141
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup import pypandoc setup( name='SVN-Ignore', py_modules=['sr', 'src.cli', 'src.svn_ignore'], version='1.1.1', description='An utility that provides .svnignore functionality similar to GIT', long_description=pypandoc.convert('README.md','rst',format='markdown'), author='Jord Nijhuis', author_email='jord@nijhuis.me', url='https://github.com/Sidesplitter/SVN-Ignore', license='MIT', classifiers=[ 'License :: OSI Approved :: MIT License', 'Topic :: Software Development :: Version Control', 'Development Status :: 5 - Production/Stable', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], include_package_data=True, entry_points={ 'console_scripts': [ 'svn-ignore = src.cli:main' ], }, keywords='svn cli util utils', setup_requires=['pytest-runner', 'pypandoc'], tests_require=['pytest', 'six'], )
#!/usr/bin/env python from setuptools import setup def get_long_description(): try: import pypandoc long_description = pypandoc.convert('README.md','rst',format='markdown') except Exception: print('WARNING: Failed to convert README.md to rst, pypandoc was not present') f = open('README.md') long_description = f.read() f.close() return long_description setup( name='SVN-Ignore', py_modules=['sr', 'src.cli', 'src.svn_ignore'], version='1.1.1', description='An utility that provides .svnignore functionality similar to GIT', long_description=get_long_description(), author='Jord Nijhuis', author_email='jord@nijhuis.me', url='https://github.com/Sidesplitter/SVN-Ignore', license='MIT', classifiers=[ 'License :: OSI Approved :: MIT License', 'Topic :: Software Development :: Version Control', 'Development Status :: 5 - Production/Stable', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], include_package_data=True, entry_points={ 'console_scripts': [ 'svn-ignore = src.cli:main' ], }, keywords='svn cli util utils', setup_requires=['pytest-runner', 'pypandoc'], tests_require=['pytest', 'six'], )
Add a fallback for when pypandoc is not present
Add a fallback for when pypandoc is not present Signed-off-by: Jord Nijhuis
Python
mit
Sidesplitter/SVN-Ignore
--- +++ @@ -1,15 +1,25 @@ #!/usr/bin/env python from setuptools import setup -import pypandoc +def get_long_description(): + try: + import pypandoc + long_description = pypandoc.convert('README.md','rst',format='markdown') + except Exception: + print('WARNING: Failed to convert README.md to rst, pypandoc was not present') + f = open('README.md') + long_description = f.read() + f.close() + + return long_description setup( name='SVN-Ignore', py_modules=['sr', 'src.cli', 'src.svn_ignore'], version='1.1.1', description='An utility that provides .svnignore functionality similar to GIT', - long_description=pypandoc.convert('README.md','rst',format='markdown'), + long_description=get_long_description(), author='Jord Nijhuis', author_email='jord@nijhuis.me', url='https://github.com/Sidesplitter/SVN-Ignore',
05196edc526d8843119ae0e8776ff1e02660251d
setup.py
setup.py
from setuptools import setup setup(name='solcast', version='0.2.1a', description='Client library for the Solcast API', license='MIT', url='https://github.com/cjtapper/solcast-py', author='Chris Tapper', author_email='cj.tapper@gmail.com', packages=['solcast'], install_requires=[ 'requests', 'isodate' ] )
from setuptools import setup setup(name='solcast', version='0.2.1', description='Client library for the Solcast API', license='MIT', url='https://github.com/cjtapper/solcast-py', author='Chris Tapper', author_email='cj.tapper@gmail.com', packages=['solcast'], install_requires=[ 'requests', 'isodate' ] )
Prepare version 0.2.1 for merge
Prepare version 0.2.1 for merge
Python
mit
cjtapper/solcast-py
--- +++ @@ -1,6 +1,6 @@ from setuptools import setup setup(name='solcast', - version='0.2.1a', + version='0.2.1', description='Client library for the Solcast API', license='MIT', url='https://github.com/cjtapper/solcast-py',
085ad8285e795019909b7fe58fe1c67b2f7bd92a
setup.py
setup.py
# encoding: utf-8 import os from setuptools import setup, find_packages # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django_hstore_flattenfields', version='0.7.3', description='Django with dynamic fields in hstore', author=u'Iuri Diniz', author_email='iuridiniz@gmail.com', maintainer=u'Luís Araújo', maintainer_email='caitifbrito@gmail.com', url='https://github.com/multmeio/django-hstore-flattenfields', packages=find_packages( exclude=['example', 'example.*']), # long_description=read('README.rst'), classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], zip_safe=False, install_requires=[ 'Django==1.4.3', 'django-orm-extensions==3.0b3', ] )
# encoding: utf-8 import os from setuptools import setup, find_packages # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django_hstore_flattenfields', version='0.7.2', description='Django with dynamic fields in hstore', author=u'Iuri Diniz', author_email='iuridiniz@gmail.com', maintainer=u'Luís Araújo', maintainer_email='caitifbrito@gmail.com', url='https://github.com/multmeio/django-hstore-flattenfields', packages=find_packages( exclude=['example', 'example.*']), # long_description=read('README.rst'), classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], zip_safe=False, install_requires=[ 'Django==1.4.3', 'django-orm-extensions==3.0b3', ] )
Revert "version 0.7.3 - fix DateFields"
Revert "version 0.7.3 - fix DateFields" This reverts commit ea9568f0c30cb0bffeaeb0bd4dd809a724f535ce.
Python
bsd-3-clause
multmeio/django-hstore-flattenfields,multmeio/django-hstore-flattenfields
--- +++ @@ -11,7 +11,7 @@ setup( name='django_hstore_flattenfields', - version='0.7.3', + version='0.7.2', description='Django with dynamic fields in hstore', author=u'Iuri Diniz', author_email='iuridiniz@gmail.com',
4975df993b4c05cf8108a278d941852fa959cd2c
setup.py
setup.py
from setuptools import setup, find_packages try: from pyqt_distutils.build_ui import build_ui cmdclass={'build_ui': build_ui} except ImportError: cmdclass={} setup( name='gauges', version='0.1', description='PyQt5 + Autobahn/Twisted version of Gauges Crossbar demo', url='http://github.com/estan/gauges', author='Elvis Stansvik', license='License :: OSI Approved :: MIT License', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Communications', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], packages=find_packages(), install_requires=[ 'autobahn', 'twisted', 'pyOpenSSL', 'service_identity', 'qt5reactor-fork', ], entry_points={ 'gui_scripts': [ 'gauges-qt=gauges.gauges_qt:main' ], }, cmdclass=cmdclass )
from setuptools import setup, find_packages try: from pyqt_distutils.build_ui import build_ui cmdclass={'build_ui': build_ui} except ImportError: cmdclass={} setup( name='gauges', version='0.1', description='PyQt5 + Autobahn/Twisted version of Gauges Crossbar demo', url='http://github.com/estan/gauges', author='Elvis Stansvik', license='License :: OSI Approved :: MIT License', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Communications', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], packages=find_packages(), install_requires=[ 'autobahn', 'twisted', 'pyOpenSSL', 'service_identity', 'qt5reactor', ], entry_points={ 'gui_scripts': [ 'gauges-qt=gauges.gauges_qt:main' ], }, cmdclass=cmdclass )
Change qt5reactor-fork dependency to qt5reactor.
Change qt5reactor-fork dependency to qt5reactor. The author of qt5reactor has now changed the name.
Python
mit
estan/gauges
--- +++ @@ -27,7 +27,7 @@ 'twisted', 'pyOpenSSL', 'service_identity', - 'qt5reactor-fork', + 'qt5reactor', ], entry_points={ 'gui_scripts': [
75228cef16a6f2e135757475632f25ce3ef447fb
setup.py
setup.py
""" Flask-Ask ------------- Easy Alexa Skills Kit integration for Flask """ from setuptools import setup from pip.req import parse_requirements setup( name='Flask-Ask', version='0.9.7', url='https://github.com/johnwheeler/flask-ask', license='Apache 2.0', author='John Wheeler', author_email='john@johnwheeler.org', description='Rapid Alexa Skills Kit Development for Amazon Echo Devices in Python', long_description=__doc__, packages=['flask_ask'], zip_safe=False, include_package_data=True, platforms='any', install_requires=[ str(item.req) for item in parse_requirements('requirements.txt', session=False) ], test_requires=[ 'mock', 'requests' ], test_suite='tests', classifiers=[ 'License :: OSI Approved :: Apache Software License', 'Framework :: Flask', 'Programming Language :: Python', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
""" Flask-Ask ------------- Easy Alexa Skills Kit integration for Flask """ from setuptools import setup def parse_requirements(filename): """ load requirements from a pip requirements file """ lineiter = (line.strip() for line in open(filename)) return [line for line in lineiter if line and not line.startswith("#")] setup( name='Flask-Ask', version='0.9.7', url='https://github.com/johnwheeler/flask-ask', license='Apache 2.0', author='John Wheeler', author_email='john@johnwheeler.org', description='Rapid Alexa Skills Kit Development for Amazon Echo Devices in Python', long_description=__doc__, packages=['flask_ask'], zip_safe=False, include_package_data=True, platforms='any', install_requires=parse_requirements('requirements.txt'), test_requires=[ 'mock', 'requests' ], test_suite='tests', classifiers=[ 'License :: OSI Approved :: Apache Software License', 'Framework :: Flask', 'Programming Language :: Python', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
Fix issue with PIP 10
Fix issue with PIP 10
Python
apache-2.0
johnwheeler/flask-ask
--- +++ @@ -5,7 +5,11 @@ Easy Alexa Skills Kit integration for Flask """ from setuptools import setup -from pip.req import parse_requirements + +def parse_requirements(filename): + """ load requirements from a pip requirements file """ + lineiter = (line.strip() for line in open(filename)) + return [line for line in lineiter if line and not line.startswith("#")] setup( name='Flask-Ask', @@ -20,10 +24,7 @@ zip_safe=False, include_package_data=True, platforms='any', - install_requires=[ - str(item.req) for item in - parse_requirements('requirements.txt', session=False) - ], + install_requires=parse_requirements('requirements.txt'), test_requires=[ 'mock', 'requests'
a39019b62a0281e7bd046fc614e42332fd3b92bd
setup.py
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from setuptools import setup, find_packages setup( name = 'cloudsizzle', fullname = 'CloudSizzle', version = '0.1', author = '', author_email = '', license = 'MIT', url = 'http://cloudsizzle.cs.hut.fi', description = 'Social study plan9er for Aalto University students', install_requires = [ 'Django >= 1.1', 'Scrapy == 0.8', 'kpwrapper >= 1.0.0', 'asi >= 0.9', ], packages = find_packages(), include_package_data = True, test_suite = 'cloudsizzle.tests.suite', dependency_links = [ 'http://public.futurice.com/~ekan/eggs', 'http://ftp.edgewall.com/pub/bitten/', ], extras_require = { 'Bitten': ['bitten'], }, entry_points = { 'distutils.commands': [ 'unittest = bitten.util.testrunner:unittest [Bitten]' ], }, )
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from setuptools import setup, find_packages setup( name = 'cloudsizzle', fullname = 'CloudSizzle', version = '0.1', author = '', author_email = '', license = 'MIT', url = 'http://cloudsizzle.cs.hut.fi', description = 'Social study plan9er for Aalto University students', install_requires = [ 'Django >= 1.1', 'Scrapy == 0.8', 'kpwrapper >= 1.0.0', 'asi >= 0.9', ], packages = find_packages(), include_package_data = True, test_suite = 'cloudsizzle.tests.suite', tests_require = [ 'MiniMock >= 1.2', ], dependency_links = [ 'http://public.futurice.com/~ekan/eggs', 'http://ftp.edgewall.com/pub/bitten/', ], extras_require = { 'Bitten': ['bitten'], }, entry_points = { 'distutils.commands': [ 'unittest = bitten.util.testrunner:unittest [Bitten]' ], }, )
Add MiniMock to the list of unittest dependencies.
Add MiniMock to the list of unittest dependencies.
Python
mit
jpvanhal/cloudsizzle,jpvanhal/cloudsizzle
--- +++ @@ -22,6 +22,9 @@ packages = find_packages(), include_package_data = True, test_suite = 'cloudsizzle.tests.suite', + tests_require = [ + 'MiniMock >= 1.2', + ], dependency_links = [ 'http://public.futurice.com/~ekan/eggs', 'http://ftp.edgewall.com/pub/bitten/',
2706d3086eaff99538eacaafa58776393ab1f5d6
setup.py
setup.py
from setuptools import setup from storm import version # magic setup( name='tornado-storm', version=version, description='A simple ORM for Tornado', author='Craig Campbell', author_email='iamcraigcampbell@gmail.com', url='https://github.com/ccampbell/storm', download_url='https://github.com/ccampbell/storm/archive/0.1.0.zip#egg=tornado-storm-0.1.0', license='MIT', install_requires=['tornado >= 3.1', 'motor == 0.1.1'], py_modules=['storm'], platforms=["any"] )
from setuptools import setup, find_packages from storm import version # magic setup( name='tornado-storm', version=version, description='A simple ORM for Tornado', author='Craig Campbell', author_email='iamcraigcampbell@gmail.com', url='https://github.com/ccampbell/storm', download_url='https://github.com/ccampbell/storm/archive/0.1.0.zip#egg=tornado-storm-0.1.0', license='MIT', install_requires=['tornado >= 3.1', 'motor >= 0.1.1'], packages=find_packages(), py_modules=['storm'], platforms=["any"] )
Make sure installation works locally
Make sure installation works locally
Python
mit
ccampbell/storm,liujiantong/storm
--- +++ @@ -1,4 +1,4 @@ -from setuptools import setup +from setuptools import setup, find_packages from storm import version # magic @@ -11,7 +11,8 @@ url='https://github.com/ccampbell/storm', download_url='https://github.com/ccampbell/storm/archive/0.1.0.zip#egg=tornado-storm-0.1.0', license='MIT', - install_requires=['tornado >= 3.1', 'motor == 0.1.1'], + install_requires=['tornado >= 3.1', 'motor >= 0.1.1'], + packages=find_packages(), py_modules=['storm'], platforms=["any"] )
1cc218ca24574813408eb460b801fd0ecefe514b
setup.py
setup.py
from setuptools import setup, find_packages setup( name='django-mininews', version='0.1', packages=find_packages(exclude=['example_project']), license='MIT', description='Boilerplate for creating publishable lists of objects', long_description=open('README.rst').read(), install_requires=[ 'django-model-utils', 'factory-boy', ], url='https://github.com/richardbarran/django-mininews', author='Richard Barran', author_email='richard@arbee-design.co.uk', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
from setuptools import setup, find_packages setup( name='django-mininews', version='0.1', packages=find_packages(exclude=['example_project']), license='MIT', description='Boilerplate for creating publishable lists of objects', long_description=open('README.rst').read(), install_requires=[ 'django-model-utils==2.0.3', 'factory-boy==2.3.1', ], url='https://github.com/richardbarran/django-mininews', author='Richard Barran', author_email='richard@arbee-design.co.uk', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
Add version numbers to dependencies
Add version numbers to dependencies
Python
mit
richardbarran/django-mininews,richardbarran/django-mininews,richardbarran/django-minipub,richardbarran/django-minipub,richardbarran/django-mininews
--- +++ @@ -8,8 +8,8 @@ description='Boilerplate for creating publishable lists of objects', long_description=open('README.rst').read(), install_requires=[ - 'django-model-utils', - 'factory-boy', + 'django-model-utils==2.0.3', + 'factory-boy==2.3.1', ], url='https://github.com/richardbarran/django-mininews', author='Richard Barran',
226ee320cf35c530a6aa7f94bd64fc71908234e3
setup.py
setup.py
from setuptools import setup, find_packages setup( name="ducted", version='1.2', url='http://github.com/ducted/duct', license='MIT', description="A monitoring agent and event processor", author='Colin Alston', author_email='colin.alston@gmail.com', packages=find_packages() + [ "twisted.plugins", ], package_data={ 'twisted.plugins': ['twisted/plugins/duct_plugin.py'] }, include_package_data=True, install_requires=[ 'zope.interface', 'Twisted', 'PyYaml', 'pyOpenSSL', 'protobuf', 'construct<2.6', 'pysnmp==4.2.5', 'cryptography', ], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: System :: Monitoring', ], )
from setuptools import setup, find_packages setup( name="ducted", version='1.2', url='http://github.com/ducted/duct', license='MIT', description="A monitoring agent and event processor", author='Colin Alston', author_email='colin.alston@gmail.com', packages=find_packages() + [ "twisted.plugins", ], package_data={ 'twisted.plugins': ['twisted/plugins/duct_plugin.py'] }, include_package_data=True, install_requires=[ 'zope.interface', 'Twisted', 'PyYaml', 'pyOpenSSL', 'protobuf', 'construct<2.6', 'pysnmp==4.2.5', 'cryptography', 'service_identity' ], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: System :: Monitoring', ], )
Add service identity package to quiet warnings
Add service identity package to quiet warnings
Python
mit
ducted/duct,ducted/duct,ducted/duct,ducted/duct
--- +++ @@ -25,6 +25,7 @@ 'construct<2.6', 'pysnmp==4.2.5', 'cryptography', + 'service_identity' ], classifiers=[ 'Development Status :: 5 - Production/Stable',
b1754f63327e641693a733afccd79dbf92666dec
setup.py
setup.py
from setuptools import find_packages, setup import os # Get version and release info, which is all stored in pulse2percept/version.py ver_file = os.path.join('pulse2percept', 'version.py') with open(ver_file) as f: exec(f.read()) opts = dict(name=NAME, maintainer=MAINTAINER, maintainer_email=MAINTAINER_EMAIL, description=DESCRIPTION, long_description=LONG_DESCRIPTION, url=URL, download_url=DOWNLOAD_URL, license=LICENSE, classifiers=CLASSIFIERS, author=AUTHOR, author_email=AUTHOR_EMAIL, platforms=PLATFORMS, version=VERSION, packages=find_packages(), requires=REQUIRES) if __name__ == '__main__': setup(**opts)
from setuptools import find_packages, setup import os # Get version and release info, which is all stored in pulse2percept/version.py ver_file = os.path.join('pulse2percept', 'version.py') with open(ver_file) as f: exec(f.read()) opts = dict(name=NAME, maintainer=MAINTAINER, maintainer_email=MAINTAINER_EMAIL, description=DESCRIPTION, long_description=LONG_DESCRIPTION, url=URL, download_url=DOWNLOAD_URL, license=LICENSE, classifiers=CLASSIFIERS, author=AUTHOR, author_email=AUTHOR_EMAIL, platforms=PLATFORMS, version=VERSION, packages=find_packages(), install_requires=REQUIRES, requires=REQUIRES) if __name__ == '__main__': setup(**opts)
Add install_requires for smoother pip installation
Add install_requires for smoother pip installation See also: https://github.com/uwescience/shablona/pull/54
Python
bsd-3-clause
mbeyeler/pulse2percept,uwescience/pulse2percept,uwescience/pulse2percept,uwescience/pulse2percept
--- +++ @@ -20,6 +20,7 @@ platforms=PLATFORMS, version=VERSION, packages=find_packages(), + install_requires=REQUIRES, requires=REQUIRES)
0f9fa91b3aeba056f1c1153c7920f085f5a0788c
setup.py
setup.py
""" Flask-JWT-Extended ------------------- Flask-Login provides jwt endpoint protection for Flask. """ from setuptools import setup setup(name='Flask-JWT-Extended', version='1.5.0', url='https://github.com/vimalloc/flask-jwt-extended', license='MIT', author='Landon Gilbert-Bland', author_email='landogbland@gmail.com', description='Extended JWT integration with Flask', long_description='Extended JWT integration with Flask', keywords = ['flask', 'jwt', 'json web token'], packages=['flask_jwt_extended'], zip_safe=False, platforms='any', install_requires=['Flask', 'PyJWT', 'simplekv', 'cryptography'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ])
""" Flask-JWT-Extended ------------------- Flask-Login provides jwt endpoint protection for Flask. """ from setuptools import setup setup(name='Flask-JWT-Extended', version='1.5.0', url='https://github.com/vimalloc/flask-jwt-extended', license='MIT', author='Landon Gilbert-Bland', author_email='landogbland@gmail.com', description='Extended JWT integration with Flask', long_description='Extended JWT integration with Flask', keywords = ['flask', 'jwt', 'json web token'], packages=['flask_jwt_extended'], zip_safe=False, platforms='any', install_requires=['Flask', 'PyJWT', 'simplekv'], extras_require={ 'asymmetric_crypto': ["cryptography"] } classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ])
Make cryptography an optional install dependency
Make cryptography an optional install dependency
Python
mit
vimalloc/flask-jwt-extended
--- +++ @@ -17,7 +17,10 @@ packages=['flask_jwt_extended'], zip_safe=False, platforms='any', - install_requires=['Flask', 'PyJWT', 'simplekv', 'cryptography'], + install_requires=['Flask', 'PyJWT', 'simplekv'], + extras_require={ + 'asymmetric_crypto': ["cryptography"] + } classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment',
2a42a82d72d8bfbf11b605002bc4781fee320ea3
setup.py
setup.py
import sys try: from setuptools import setup except ImportError: from distutils import setup if sys.version_info[0] == 2: base_dir = 'python2' elif sys.version_info[0] == 3: base_dir = 'python3' readme = open('README.rst', 'r') README_TEXT = readme.read() readme.close() setup( name='aniso8601', version='0.90dev', description='A library for parsing ISO 8601 strings.', long_description=README_TEXT, author='Brandon Nielsen', author_email='nielsenb@jetfuse.net', url='https://bitbucket.org/nielsenb/aniso8601', packages=['aniso8601'], package_dir={ 'aniso8601' : base_dir + '/aniso8601', }, classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
import sys try: from setuptools import setup except ImportError: from distutils import setup if sys.version_info[0] == 2: base_dir = 'python2' elif sys.version_info[0] == 3: base_dir = 'python3' readme = open('README.rst', 'r') README_TEXT = readme.read() readme.close() setup( name='aniso8601', version='0.90dev', description='A library for parsing ISO 8601 strings.', long_description=README_TEXT, author='Brandon Nielsen', author_email='nielsenb@jetfuse.net', url='https://bitbucket.org/nielsenb/aniso8601', packages=['aniso8601'], package_dir={ 'aniso8601' : base_dir + '/aniso8601', }, classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
Add python2 specifically to classifier list.
Add python2 specifically to classifier list.
Python
bsd-3-clause
3stack-software/python-aniso8601-relativedelta
--- +++ @@ -31,6 +31,7 @@ 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', + 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules' ]
d3e20471497cad17d5f8a2c70d7be53f80efe000
setup.py
setup.py
from setuptools import setup setup(name='pagerduty_events_api', version='0.2.0', description='Python wrapper for Pagerduty Events API', url='https://github.com/BlasiusVonSzerencsi/pagerduty-events-api', download_url='https://github.com/BlasiusVonSzerencsi/pagerduty-events-api/tarball/0.1.1', author='Balazs Szerencsi', author_email='balazs.szerencsi@icloud.com', license='MIT', packages=['pagerduty_events_api'], zip_safe=False, test_suite='nose.collector', tests_require=['nose', 'ddt'], install_requires=['requests'], keywords=['pagerduty', 'event', 'api', 'incident', 'trigger', 'acknowledge', 'resolve'])
from setuptools import setup setup(name='pagerduty_events_api', version='0.2.0', description='Python wrapper for Pagerduty Events API', url='https://github.com/BlasiusVonSzerencsi/pagerduty-events-api', download_url='https://github.com/BlasiusVonSzerencsi/pagerduty-events-api/tarball/0.2.0', author='Balazs Szerencsi', author_email='balazs.szerencsi@icloud.com', license='MIT', packages=['pagerduty_events_api'], zip_safe=False, test_suite='nose.collector', tests_require=['nose', 'ddt'], install_requires=['requests'], keywords=['pagerduty', 'event', 'api', 'incident', 'trigger', 'acknowledge', 'resolve'])
Update download URL to match current version / tag.
Update download URL to match current version / tag.
Python
mit
BlasiusVonSzerencsi/pagerduty-events-api
--- +++ @@ -4,7 +4,7 @@ version='0.2.0', description='Python wrapper for Pagerduty Events API', url='https://github.com/BlasiusVonSzerencsi/pagerduty-events-api', - download_url='https://github.com/BlasiusVonSzerencsi/pagerduty-events-api/tarball/0.1.1', + download_url='https://github.com/BlasiusVonSzerencsi/pagerduty-events-api/tarball/0.2.0', author='Balazs Szerencsi', author_email='balazs.szerencsi@icloud.com', license='MIT',
0a1b387de5bcb1c7a8d223cce6f654a8bac5fed7
setup.py
setup.py
# encoding: utf-8 from setuptools import setup setup( name="django-minio-storage", license="MIT", use_scm_version=True, description="Django file storage using the minio python client", author="Tom Houlé", author_email="tom@kafunsho.be", url="https://github.com/py-pa/django-minio-storage", packages=[ "minio_storage", "minio_storage/management/", "minio_storage/management/commands/", ], setup_requires=["setuptools_scm"], install_requires=["django>=1.11", "minio>=4.0.21"], extras_require={"test": ["coverage", "requests"]}, classifiers=[ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Framework :: Django", ], )
# encoding: utf-8 from setuptools import setup with open('README.md') as f: long_description = f.read() setup( name="django-minio-storage", license="MIT", use_scm_version=True, description="Django file storage using the minio python client", long_description=long_description, long_description_content_type='text/markdown', author="Tom Houlé", author_email="tom@kafunsho.be", url="https://github.com/py-pa/django-minio-storage", packages=[ "minio_storage", "minio_storage/management/", "minio_storage/management/commands/", ], setup_requires=["setuptools_scm"], install_requires=["django>=1.11", "minio>=4.0.21"], extras_require={"test": ["coverage", "requests"]}, classifiers=[ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Framework :: Django", ], )
Add long_description to package metadata for display by PyPI
Add long_description to package metadata for display by PyPI
Python
apache-2.0
tomhoule/django-minio-storage
--- +++ @@ -1,11 +1,16 @@ # encoding: utf-8 from setuptools import setup + +with open('README.md') as f: + long_description = f.read() setup( name="django-minio-storage", license="MIT", use_scm_version=True, description="Django file storage using the minio python client", + long_description=long_description, + long_description_content_type='text/markdown', author="Tom Houlé", author_email="tom@kafunsho.be", url="https://github.com/py-pa/django-minio-storage",
b5ee678115391885a00cfd1ee114c6b5b22f7a55
setup.py
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from distutils.core import setup setup( name='facebook-python-sdk', version='0.2.0', description='This client library is designed to support the Facebook Graph API and the official Facebook JavaScript SDK, which is the canonical way to implement Facebook authentication.', author='Facebook', url='http://github.com/pythonforfacebook/facebook-sdk', py_modules=[ 'facebook', ], )
#!/usr/bin/env python from distutils.core import setup setup( name='facebook-sdk', version='0.2.0', description='This client library is designed to support the Facebook Graph API and the official Facebook JavaScript SDK, which is the canonical way to implement Facebook authentication.', author='Facebook', url='http://github.com/pythonforfacebook/facebook-sdk', py_modules=[ 'facebook', ], )
Rename the package so we can push to PyPi
Rename the package so we can push to PyPi
Python
apache-2.0
Aloomaio/facebook-sdk,mobolic/facebook-sdk
--- +++ @@ -1,9 +1,8 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- from distutils.core import setup setup( - name='facebook-python-sdk', + name='facebook-sdk', version='0.2.0', description='This client library is designed to support the Facebook Graph API and the official Facebook JavaScript SDK, which is the canonical way to implement Facebook authentication.', author='Facebook', @@ -12,3 +11,4 @@ 'facebook', ], ) +
6122a8488613bdd7d5aaf80e7238cd2d80687a91
stock.py
stock.py
class Stock: def __init__(self, symbol): self.symbol = symbol self.price = None def update(self, timestamp, price): if price < 0: raise ValueError("price should not be negative") self.price = price
class Stock: def __init__(self, symbol): self.symbol = symbol self.price_history = [] @property def price(self): if self.price_history: return self.price_history[-1] else: return None def update(self, timestamp, price): if price < 0: raise ValueError("price should not be negative") self.price_history.append(price)
Update price attribute to price_history list as well as update function accordingly.
Update price attribute to price_history list as well as update function accordingly.
Python
mit
bsmukasa/stock_alerter
--- +++ @@ -1,9 +1,16 @@ class Stock: def __init__(self, symbol): self.symbol = symbol - self.price = None + self.price_history = [] + + @property + def price(self): + if self.price_history: + return self.price_history[-1] + else: + return None def update(self, timestamp, price): if price < 0: raise ValueError("price should not be negative") - self.price = price + self.price_history.append(price)
1583aaf429e252f32439759e1363f3908efa0b03
tasks.py
tasks.py
from celery import Celery from allsky import single_image_raspistill celery = Celery('tasks', broker='redis://localhost:6379/0', backend='redis://localhost:6379/0') @celery.task def background_task(): # some long running task here (this simple example has no output) pid = single_image_raspistill(filename='static/snap.jpg')
from celery import Celery from allsky import single_image_raspistill celery = Celery('tasks', broker='redis://localhost:6379/0', backend='redis://localhost:6379/0') @celery.task def background_task(): # some long running task here (this simple example has no output) pid = single_image_raspistill(filename='static/snap.jpg', exp=120000000)
Set a higher default for darks
Set a higher default for darks
Python
mit
zemogle/raspberrysky
--- +++ @@ -7,4 +7,4 @@ @celery.task def background_task(): # some long running task here (this simple example has no output) - pid = single_image_raspistill(filename='static/snap.jpg') + pid = single_image_raspistill(filename='static/snap.jpg', exp=120000000)
43c1f230382a3b7ad7776d28840c5305bb919ab9
jujugui/__init__.py
jujugui/__init__.py
# Copyright 2015 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). from pyramid.config import Configurator def main(global_config, **settings): """Return a Pyramid WSGI application.""" config = Configurator(settings=settings) return make_application(config) def make_application(config): """Set up the routes and return the WSGI application.""" # We use two separate included app/routes so that we can # have the gui parts behind a separate route from the # assets when we embed it in e.g. the storefront. config.include('jujugui.gui') config.include('jujugui.assets') return config.make_wsgi_app()
# Copyright 2015 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). from pyramid.config import Configurator def main(global_config, **settings): """Return a Pyramid WSGI application.""" config = Configurator(settings=settings) return make_application(config) def make_application(config): """Set up the routes and return the WSGI application.""" # We use two separate included app/routes so that we can # have the gui parts behind a separate route from the # assets when we embed it in e.g. the storefront. # NOTE: kadams54, 2015-08-04: It's very important that assets be listed # first; if it isn't, then the jujugui.gui routes override those specified # in assets and any asset requests will go to the main app. config.include('jujugui.assets') config.include('jujugui.gui') return config.make_wsgi_app()
Fix load order to fix routes.
Fix load order to fix routes.
Python
agpl-3.0
bac/juju-gui,bac/juju-gui,mitechie/juju-gui,mitechie/juju-gui,mitechie/juju-gui,mitechie/juju-gui,bac/juju-gui,bac/juju-gui
--- +++ @@ -15,6 +15,9 @@ # We use two separate included app/routes so that we can # have the gui parts behind a separate route from the # assets when we embed it in e.g. the storefront. + # NOTE: kadams54, 2015-08-04: It's very important that assets be listed + # first; if it isn't, then the jujugui.gui routes override those specified + # in assets and any asset requests will go to the main app. + config.include('jujugui.assets') config.include('jujugui.gui') - config.include('jujugui.assets') return config.make_wsgi_app()
75a4733d059f6aad758f93a9c6e4878093afd184
test-messages.py
test-messages.py
#!/usr/bin/python2 # # test-messages.py - This script publish a random MQTT messages every 2 s. # # Copyright (c) 2013-2015, Fabian Affolter <fabian@affolter-engineering.ch> # Released under the MIT license. See LICENSE file for details. # import random import time import mosquitto timestamp = int(time.time()) broker = '127.0.0.1' port = 1883 element = 'home' areas = ['front', 'back', 'kitchen', 'basement', 'living'] entrances = ['door', 'window'] states = ['true', 'false'] print 'Messages are published on topic %s/#... -> CTRL + C to shutdown' \ % element while True: area = random.choice(areas) if (area in ['basement', 'living']): topic = element + '/' + area + '/temp' message = random.randrange(0, 30, 1) else: topic = element + '/' + area + '/' + random.choice(entrances) message = random.choice(states) client = mosquitto.Mosquitto("mqtt-panel-test") client.connect(broker) client.publish(topic, message) time.sleep(2)
#!/usr/bin/python3 # # test-messages.py - This script publish a random MQTT messages every 2 s. # # Copyright (c) 2013-2016, Fabian Affolter <fabian@affolter-engineering.ch> # Released under the MIT license. See LICENSE file for details. # import random import time import paho.mqtt.client as mqtt timestamp = int(time.time()) broker = '127.0.0.1' port = 1883 element = 'home' areas = ['front', 'back', 'kitchen', 'basement', 'living'] entrances = ['door', 'window'] states = ['true', 'false'] print('Messages are published on topic %s/#... -> CTRL + C to shutdown' \ % element) while True: area = random.choice(areas) if (area in ['basement', 'living']): topic = element + '/' + area + '/temp' message = random.randrange(0, 30, 1) else: topic = element + '/' + area + '/' + random.choice(entrances) message = random.choice(states) mqttclient = mqtt.Client("mqtt-panel-test") mqttclient.connect(broker, port=int(port)) mqttclient.publish(topic, message) time.sleep(2)
Switch to paho-mqtt and make ready for py3
Switch to paho-mqtt and make ready for py3
Python
mit
fabaff/mqtt-panel,fabaff/mqtt-panel,fabaff/mqtt-panel
--- +++ @@ -1,13 +1,13 @@ -#!/usr/bin/python2 +#!/usr/bin/python3 # # test-messages.py - This script publish a random MQTT messages every 2 s. # -# Copyright (c) 2013-2015, Fabian Affolter <fabian@affolter-engineering.ch> +# Copyright (c) 2013-2016, Fabian Affolter <fabian@affolter-engineering.ch> # Released under the MIT license. See LICENSE file for details. # import random import time -import mosquitto +import paho.mqtt.client as mqtt timestamp = int(time.time()) @@ -18,8 +18,8 @@ entrances = ['door', 'window'] states = ['true', 'false'] -print 'Messages are published on topic %s/#... -> CTRL + C to shutdown' \ - % element +print('Messages are published on topic %s/#... -> CTRL + C to shutdown' \ + % element) while True: area = random.choice(areas) @@ -30,7 +30,8 @@ topic = element + '/' + area + '/' + random.choice(entrances) message = random.choice(states) - client = mosquitto.Mosquitto("mqtt-panel-test") - client.connect(broker) - client.publish(topic, message) + mqttclient = mqtt.Client("mqtt-panel-test") + mqttclient.connect(broker, port=int(port)) + mqttclient.publish(topic, message) time.sleep(2) +
de1afc2feb1e7572ee7a59909247a2cde67492c9
tests/sample3.py
tests/sample3.py
class Bad(Exception): def __repr__(self): raise RuntimeError("I'm a bad class!") def a(): x = Bad() return x def b(): x = Bad() raise x a() try: b() except Exception as exc: print(exc)
class Bad(Exception): __slots__ = [] def __repr__(self): raise RuntimeError("I'm a bad class!") def a(): x = Bad() return x def b(): x = Bad() raise x a() try: b() except Exception as exc: print(exc)
Add __slots__ to satisfy tests (rudimentary_repr is still ordinary __repr__ if __slots__ are there).
Add __slots__ to satisfy tests (rudimentary_repr is still ordinary __repr__ if __slots__ are there).
Python
bsd-2-clause
ionelmc/python-hunter
--- +++ @@ -1,4 +1,6 @@ class Bad(Exception): + __slots__ = [] + def __repr__(self): raise RuntimeError("I'm a bad class!")
9274cd94442b2507b2d83e2a3e305a0a3b5dc802
zhihudaily/utils.py
zhihudaily/utils.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import re import requests from zhihudaily.cache import cache @cache.memoize(timeout=1200) def make_request(url): session = requests.Session() session.headers.update({'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux \ x86_64; rv:28.0) Gecko/20100101 Firefox/28.0'}) r = session.get(url) return r def get_news_info(response): display_date = response.json()['display_date'] date = response.json()['date'] news_list = [item for item in response.json()['news']] return display_date, date, news_list def handle_image(news_list): """Point all the images to my server, because use zhihudaily's images directly may get 403 error. """ for news in news_list: items = re.search(r'(?<=http://)(.*?)\.zhimg.com/(.*)$', news['image']).groups() news['image'] = ( 'http://zhihudaily.lord63.com/img/{0}/{1}'.format( items[0], items[1])) return news_list
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import re import requests from zhihudaily.cache import cache @cache.memoize(timeout=1200) def make_request(url): session = requests.Session() session.headers.update({'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux \ x86_64; rv:28.0) Gecko/20100101 Firefox/28.0'}) r = session.get(url) return r def get_news_info(response): display_date = response.json()['display_date'] date = response.json()['date'] news_list = response.json()['news'] return display_date, date, news_list def handle_image(news_list): """Point all the images to my server, because use zhihudaily's images directly may get 403 error. """ for news in news_list: items = re.search(r'(?<=http://)(.*?)\.zhimg.com/(.*)$', news['image']).groups() news['image'] = ( 'http://zhihudaily.lord63.com/img/{0}/{1}'.format( items[0], items[1])) return news_list
Fix the unnecessary list comprehension
Fix the unnecessary list comprehension
Python
mit
lord63/zhihudaily,lord63/zhihudaily,lord63/zhihudaily
--- +++ @@ -22,7 +22,7 @@ def get_news_info(response): display_date = response.json()['display_date'] date = response.json()['date'] - news_list = [item for item in response.json()['news']] + news_list = response.json()['news'] return display_date, date, news_list
9aa673593baa67d6e7fc861015041cfb6b69c6c3
bin/list_winconf.py
bin/list_winconf.py
#!/usr/bin/env python def main(): import argparse from ranwinconf.common import generate_host_config parser = argparse.ArgumentParser() parser.add_argument('host', type=str, help="Name or IP of the host to get configuration from") parser.add_argument('--output', type=str, nargs='?', default='<stdout>', help="Output file to write the configuration, default is <stdout>") parser.add_argument('--user', type=str, nargs='?', default='', help="Name the account to use to connect to host") parser.add_argument('--pwd', type=str, nargs='?', default='', help="Password of the account to use to connect to host") args = parser.parse_args() host = args.host target = args.output user = args.user password = args.pwd generate_host_config(host, target, user, password) if __name__ == '__main__': main()
#!/usr/bin/env python def main(): import argparse from ranwinconf.common import generate_host_config parser = argparse.ArgumentParser() parser.add_argument('host', type=str, help="Name or IP of the host to get configuration from") parser.add_argument('--output', type=str, nargs='?', default='<stdout>', help="Output file to write the configuration, default is <stdout>") parser.add_argument('--user', type=str, nargs='?', default='', help="Name the account to use to connect to host") parser.add_argument('--pwd', type=str, nargs='?', default='', help="Password of the account to use to connect to host") args = parser.parse_args() host = args.host target = args.output user = args.user password = args.pwd generate_host_config(host, target, user, password) if __name__ == '__main__': # HACK HACK HACK # Put Python script dir at the end, as script and module clash :-( import sys sys.path = sys.path[1:] + [sys.path[0]] main()
Fix import of common module
Fix import of common module
Python
mit
sebbrochet/ranwinconf
--- +++ @@ -21,4 +21,8 @@ if __name__ == '__main__': + # HACK HACK HACK + # Put Python script dir at the end, as script and module clash :-( + import sys + sys.path = sys.path[1:] + [sys.path[0]] main()
c5127ec22cc5328baf829159a21c7bdf78044f55
webapp.py
webapp.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import json import traceback from bottle import route, run, get, request, response, abort from db import search, info @route('/v1/pois.json') def pois_v1(): global _db filter = request.query.get('filter', None) if filter is None: abort(501, "Unfiltered searches not allowed.") result = search(database=_db, verbose=False, query=filter) response.content_type = 'application/json' return json.dumps(result, ensure_ascii=False) if __name__ == '__main__': from optparse import OptionParser parser = OptionParser() parser.add_option("--host", dest="host", help="bind to HOST", metavar="HOST", default="localhost") parser.add_option("--port", dest="port", help="bind to PORT", metavar="PORT", type="int", default=8022) parser.add_option("-d", "--database", dest="db", help="use database FILE", metavar="FILE", default="paikkis.db") opts, args = parser.parse_args() _db = opts.db run(host=opts.host, port=opts.port)
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import json import re import traceback from bottle import route, run, get, request, response, abort from db import search, info @route('/v1/pois.json') def pois_v1(): global _db filter = request.query.get('filter', None) if filter is None: abort(501, "Unfiltered searches not allowed.") filter = re.sub('[\W_]+', ',', filter) result = search(database=_db, verbose=False, query=filter) response.content_type = 'application/json' return json.dumps(result, ensure_ascii=False) if __name__ == '__main__': from optparse import OptionParser parser = OptionParser() parser.add_option("--host", dest="host", help="bind to HOST", metavar="HOST", default="localhost") parser.add_option("--port", dest="port", help="bind to PORT", metavar="PORT", type="int", default=8022) parser.add_option("-d", "--database", dest="db", help="use database FILE", metavar="FILE", default="paikkis.db") opts, args = parser.parse_args() _db = opts.db run(host=opts.host, port=opts.port)
Replace all extra characters with commas in queries; improves matching
Replace all extra characters with commas in queries; improves matching
Python
mit
guaq/paikkis
--- +++ @@ -2,6 +2,7 @@ # -*- coding: utf-8 -*- from __future__ import print_function import json +import re import traceback from bottle import route, run, get, request, response, abort from db import search, info @@ -13,6 +14,8 @@ filter = request.query.get('filter', None) if filter is None: abort(501, "Unfiltered searches not allowed.") + + filter = re.sub('[\W_]+', ',', filter) result = search(database=_db, verbose=False, query=filter) response.content_type = 'application/json'
0004bde0d40dfea167d76a83c20acfffc0abfa28
poyo/__init__.py
poyo/__init__.py
# -*- coding: utf-8 -*- from .exceptions import PoyoException from .parser import parse_string __author__ = 'Raphael Pierzina' __email__ = 'raphael@hackebrot.de' __version__ = '0.3.0' __all__ = ['parse_string', 'PoyoException']
# -*- coding: utf-8 -*- import logging from .exceptions import PoyoException from .parser import parse_string __author__ = 'Raphael Pierzina' __email__ = 'raphael@hackebrot.de' __version__ = '0.3.0' logging.getLogger(__name__).addHandler(logging.NullHandler()) __all__ = ['parse_string', 'PoyoException']
Add NullHandler to poyo root logger
Add NullHandler to poyo root logger
Python
mit
hackebrot/poyo
--- +++ @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*- + +import logging from .exceptions import PoyoException from .parser import parse_string @@ -7,4 +9,6 @@ __email__ = 'raphael@hackebrot.de' __version__ = '0.3.0' +logging.getLogger(__name__).addHandler(logging.NullHandler()) + __all__ = ['parse_string', 'PoyoException']
9ef86f0b5ff1b4e1521a3dc075ff16bc6aef2d0c
museum_site/scroll.py
museum_site/scroll.py
from django.db import models class Scroll(models.Model): # Constants SCROLL_TOP = """``` ╞╤═════════════════════════════════════════════╤╡ │ Scroll ### │ ╞═════════════════════════════════════════════╡ │ • • • • • • • • •│""" SCROLL_BOTTOM = """\n │ • • • • • • • • •│ ╞╧═════════════════════════════════════════════╧╡```""" # Fields identifier = models.IntegerField() content = models.TextField(default="") source = models.CharField(max_length=160) published = models.BooleanField(default=False) suggestion = models.CharField(max_length=500, blank=True, default="") class Meta: ordering = ["-id"] def __str__(self): return "Scroll #{} ID:{} Pub:{}".format(self.identifier, self.id, self.published) def lines(self): return self.content.split("\n") def render_for_discord(self): lines = self.lines() output = self.SCROLL_TOP.replace("###", ("000"+str(self.identifier))[-3:]) for line in lines: line = line.replace("\r", "") line = line.replace("\n", "") output += "\n │ " + (line + " " * 42)[:42] + " │ " output += self.SCROLL_BOTTOM return output
from django.db import models class Scroll(models.Model): # Constants SCROLL_TOP = """``` ╞╤═════════════════════════════════════════════╤╡ │ Scroll ### │ ╞═════════════════════════════════════════════╡ │ • • • • • • • • •│""" SCROLL_BOTTOM = """\n │ • • • • • • • • •│ ╞╧═════════════════════════════════════════════╧╡```""" # Fields identifier = models.IntegerField() content = models.TextField( default="" help_text="Lines starting with @ will be skipped. Initial whitespace is trimmed by DB, so an extra @ line is a fix." ) source = models.CharField(max_length=160) published = models.BooleanField(default=False) suggestion = models.CharField(max_length=500, blank=True, default="") class Meta: ordering = ["-id"] def __str__(self): return "Scroll #{} ID:{} Pub:{}".format(self.identifier, self.id, self.published) def lines(self): return self.content.split("\n") def render_for_discord(self): lines = self.lines() output = self.SCROLL_TOP.replace("###", ("000"+str(self.identifier))[-3:]) for line in lines: line = line.replace("\r", "") line = line.replace("\n", "") if line[0] == "@": continue output += "\n │ " + (line + " " * 42)[:42] + " │ " output += self.SCROLL_BOTTOM return output
Fix for truncated whitespace on DB level
Fix for truncated whitespace on DB level
Python
mit
DrDos0016/z2,DrDos0016/z2,DrDos0016/z2
--- +++ @@ -14,7 +14,10 @@ # Fields identifier = models.IntegerField() - content = models.TextField(default="") + content = models.TextField( + default="" + help_text="Lines starting with @ will be skipped. Initial whitespace is trimmed by DB, so an extra @ line is a fix." + ) source = models.CharField(max_length=160) published = models.BooleanField(default=False) suggestion = models.CharField(max_length=500, blank=True, default="") @@ -35,6 +38,8 @@ for line in lines: line = line.replace("\r", "") line = line.replace("\n", "") + if line[0] == "@": + continue output += "\n │ " + (line + " " * 42)[:42] + " │ " output += self.SCROLL_BOTTOM
530f540b11959956c0cd08b95b2c7c373d829c8e
python/sherlock-and-valid-string.py
python/sherlock-and-valid-string.py
#!/bin/python3 import math import os import random import re import sys from collections import Counter def isValid(s): return "YES" if containsOnlyOneDifferentCharacterCount(s) else "NO" def containsOnlyOneDifferentCharacterCount(string): characterCounts = Counter(string) if allOccurencesAreEqual(characterCounts): return True else: # Try to remove one occurence of every character for character in characterCounts: characterCountWithOneRemovedCharacter = dict.copy(characterCounts) characterCountWithOneRemovedCharacter[character] -= 1 if allOccurencesAreEqual(characterCountWithOneRemovedCharacter): return True return False def allOccurencesAreEqual(dict): return len(set(dict.values())) == 1 if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() result = isValid(s) fptr.write(result + '\n') fptr.close()
#!/bin/python3 import math import os import random import re import sys from collections import Counter import copy def isValid(s): return "YES" if containsOnlyOneDifferentCharacterCount(s) else "NO" def containsOnlyOneDifferentCharacterCount(string): characterCounts = Counter(string) if allOccurencesAreEqual(characterCounts): return True else: # Try to remove one occurence of every character for character in characterCounts: characterCountWithOneRemovedCharacter = characterCounts.copy() characterCountWithOneRemovedCharacter[character] -= 1 characterCountWithOneRemovedCharacter += Counter() # remove zero and negative counts if allOccurencesAreEqual(characterCountWithOneRemovedCharacter): return True return False def allOccurencesAreEqual(dict): return len(set(dict.values())) == 1 if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() result = isValid(s) fptr.write(result + '\n') fptr.close()
Handle edge case with zero count
Handle edge case with zero count
Python
mit
rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank
--- +++ @@ -6,6 +6,7 @@ import re import sys from collections import Counter +import copy def isValid(s): @@ -19,8 +20,9 @@ else: # Try to remove one occurence of every character for character in characterCounts: - characterCountWithOneRemovedCharacter = dict.copy(characterCounts) + characterCountWithOneRemovedCharacter = characterCounts.copy() characterCountWithOneRemovedCharacter[character] -= 1 + characterCountWithOneRemovedCharacter += Counter() # remove zero and negative counts if allOccurencesAreEqual(characterCountWithOneRemovedCharacter): return True return False
a67b71ebadbffa864f60869878198ce4e2eb3fa3
class4/exercise7.py
class4/exercise7.py
from getpass import getpass from netmiko import ConnectHandler def main(): password = getpass() pynet_rtr2 = {'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': 'pyclass', 'password': password, 'port': 8022} ssh_connection = ConnectHandler(**pynet_rtr2) ssh_connection.config_mode() logging_command = ['logging buffered 20031'] ssh_connection.send_config_set(logging_command) output = ssh_connection.send_command('show run | inc logging buffered') outp = output.split(' ') print "The new size of logging buffered is %s" % outp[2] if __name__ == "__main__": main()
# Use Netmiko to change the logging buffer size (logging buffered <size>) on pynet-rtr2. from getpass import getpass from netmiko import ConnectHandler def main(): password = getpass() pynet_rtr2 = {'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': 'pyclass', 'password': password, 'port': 8022} ssh_connection = ConnectHandler(**pynet_rtr2) ssh_connection.config_mode() logging_command = ['logging buffered 20031'] ssh_connection.send_config_set(logging_command) output = ssh_connection.send_command('show run | inc logging buffered') outp = output.split(' ') print "The new size of logging buffered is %s" % outp[2] if __name__ == "__main__": main()
Use Netmiko to change the logging buffer size (logging buffered <size>) on pynet-rtr2.
Use Netmiko to change the logging buffer size (logging buffered <size>) on pynet-rtr2.
Python
apache-2.0
linkdebian/pynet_course
--- +++ @@ -1,3 +1,5 @@ +# Use Netmiko to change the logging buffer size (logging buffered <size>) on pynet-rtr2. + from getpass import getpass from netmiko import ConnectHandler
3fb1c14f750afa742f476e3b2fcc4d39662554e3
osf/models/subject.py
osf/models/subject.py
# -*- coding: utf-8 -*- from django.db import models from website.util import api_v2_url from osf.models.base import BaseModel, ObjectIDMixin class Subject(ObjectIDMixin, BaseModel): """A subject discipline that may be attached to a preprint.""" modm_model_path = 'website.project.taxonomies.Subject' modm_query = None text = models.CharField(null=False, max_length=256, unique=True) # max length on prod: 73 parents = models.ManyToManyField('self', symmetrical=False, related_name='children') def __unicode__(self): return '{} with id {}'.format(self.name, self.id) @property def absolute_api_v2_url(self): return api_v2_url('taxonomies/{}/'.format(self._id)) @property def child_count(self): """For v1 compat.""" return self.children.count() def get_absolute_url(self): return self.absolute_api_v2_url @property def hierarchy(self): if self.parents.exists(): return self.parents.first().hierarchy + [self._id] return [self._id]
# -*- coding: utf-8 -*- from django.db import models from website.util import api_v2_url from osf.models.base import BaseModel, ObjectIDMixin class Subject(ObjectIDMixin, BaseModel): """A subject discipline that may be attached to a preprint.""" modm_model_path = 'website.project.taxonomies.Subject' modm_query = None text = models.CharField(null=False, max_length=256, unique=True) # max length on prod: 73 parents = models.ManyToManyField('self', symmetrical=False, related_name='children') def __unicode__(self): return '{} with id {}'.format(self.text, self.id) @property def absolute_api_v2_url(self): return api_v2_url('taxonomies/{}/'.format(self._id)) @property def child_count(self): """For v1 compat.""" return self.children.count() def get_absolute_url(self): return self.absolute_api_v2_url @property def hierarchy(self): if self.parents.exists(): return self.parents.first().hierarchy + [self._id] return [self._id]
Change unicode rep to use Subject text
Change unicode rep to use Subject text
Python
apache-2.0
crcresearch/osf.io,Nesiehr/osf.io,CenterForOpenScience/osf.io,laurenrevere/osf.io,chrisseto/osf.io,icereval/osf.io,brianjgeiger/osf.io,CenterForOpenScience/osf.io,felliott/osf.io,aaxelb/osf.io,aaxelb/osf.io,chrisseto/osf.io,felliott/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,mfraezz/osf.io,leb2dg/osf.io,caseyrollins/osf.io,sloria/osf.io,chennan47/osf.io,mattclark/osf.io,HalcyonChimera/osf.io,Johnetordoff/osf.io,cwisecarver/osf.io,icereval/osf.io,crcresearch/osf.io,adlius/osf.io,caseyrollins/osf.io,Nesiehr/osf.io,HalcyonChimera/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,saradbowman/osf.io,TomBaxter/osf.io,icereval/osf.io,mattclark/osf.io,baylee-d/osf.io,HalcyonChimera/osf.io,sloria/osf.io,TomBaxter/osf.io,laurenrevere/osf.io,cwisecarver/osf.io,pattisdr/osf.io,mfraezz/osf.io,binoculars/osf.io,leb2dg/osf.io,caseyrollins/osf.io,caneruguz/osf.io,aaxelb/osf.io,Johnetordoff/osf.io,pattisdr/osf.io,hmoco/osf.io,CenterForOpenScience/osf.io,cwisecarver/osf.io,chrisseto/osf.io,saradbowman/osf.io,pattisdr/osf.io,chennan47/osf.io,adlius/osf.io,brianjgeiger/osf.io,baylee-d/osf.io,caneruguz/osf.io,binoculars/osf.io,TomBaxter/osf.io,hmoco/osf.io,baylee-d/osf.io,brianjgeiger/osf.io,erinspace/osf.io,felliott/osf.io,Nesiehr/osf.io,cslzchen/osf.io,crcresearch/osf.io,CenterForOpenScience/osf.io,sloria/osf.io,felliott/osf.io,caneruguz/osf.io,erinspace/osf.io,chennan47/osf.io,chrisseto/osf.io,erinspace/osf.io,caneruguz/osf.io,cslzchen/osf.io,cwisecarver/osf.io,leb2dg/osf.io,binoculars/osf.io,hmoco/osf.io,mattclark/osf.io,mfraezz/osf.io,adlius/osf.io,hmoco/osf.io,cslzchen/osf.io,mfraezz/osf.io,Nesiehr/osf.io,leb2dg/osf.io,adlius/osf.io,brianjgeiger/osf.io,Johnetordoff/osf.io,laurenrevere/osf.io
--- +++ @@ -15,7 +15,7 @@ parents = models.ManyToManyField('self', symmetrical=False, related_name='children') def __unicode__(self): - return '{} with id {}'.format(self.name, self.id) + return '{} with id {}'.format(self.text, self.id) @property def absolute_api_v2_url(self):
49067acc356503f27b132183edc0884d8fd43af3
numba/exttypes/tests/test_type_recognition.py
numba/exttypes/tests/test_type_recognition.py
""" >>> test_typeof() """ import sys import numba from numba import * from nose.tools import raises @jit class Base(object): value1 = double value2 = int_ @void(int_, double) def __init__(self, value1, value2): self.value1 = value1 self.value2 = value2 @jit class Derived(Base): value3 = float_ @void(int_) def setvalue(self, value): self.value3 = value @autojit def base_typeof(): obj1 = Base(10, 11.0) return numba.typeof(obj1.value1), numba.typeof(obj1.value2) @autojit def derived_typeof(): obj = Derived(10, 11.0) return (numba.typeof(obj.value1), numba.typeof(obj.value2), numba.typeof(obj.value3)) def test_typeof(): pass # TODO: type recognition of extension object instantiation # assert base_typeof() == (double, int_), base_typeof() # assert derived_typeof() == (double, int_, float_), derived_typeof() if __name__ == '__main__': numba.testmod()
""" >>> test_typeof() """ import numba from numba import * def make_base(compiler): @compiler class Base(object): value1 = double value2 = int_ @void(int_, double) def __init__(self, value1, value2): self.value1 = value1 self.value2 = value2 return Base Base = make_base(jit) @jit class Derived(Base): value3 = float_ @void(int_) def setvalue(self, value): self.value3 = value @autojit def base_typeof(): obj1 = Base(10, 11.0) return numba.typeof(obj1.value1), numba.typeof(obj1.value2) @autojit def derived_typeof(): obj = Derived(10, 11.0) return (numba.typeof(obj.value1), numba.typeof(obj.value2), numba.typeof(obj.value3)) def test_typeof(): pass # TODO: type recognition of extension object instantiation # assert base_typeof() == (double, int_), base_typeof() # assert derived_typeof() == (double, int_, float_), derived_typeof() #------------------------------------------------------------------------ # Test Specialized autojit typeof #------------------------------------------------------------------------ AutoBase = make_base(autojit) @autojit def attrtypes(obj): return numba.typeof(obj.value1), numba.typeof(obj.value2) def test_autobase(): obj = AutoBase(10, 11.0) assert attrtypes(obj) == (double, int_) if __name__ == '__main__': test_typeof() test_autobase()
Test autojit specialized extension attribute type recognition
Test autojit specialized extension attribute type recognition
Python
bsd-2-clause
gdementen/numba,jriehl/numba,seibert/numba,stefanseefeld/numba,gmarkall/numba,numba/numba,sklam/numba,pitrou/numba,seibert/numba,pitrou/numba,gmarkall/numba,stefanseefeld/numba,cpcloud/numba,IntelLabs/numba,sklam/numba,IntelLabs/numba,gmarkall/numba,stuartarchibald/numba,IntelLabs/numba,jriehl/numba,pombredanne/numba,gmarkall/numba,stonebig/numba,gmarkall/numba,stefanseefeld/numba,stonebig/numba,gdementen/numba,stefanseefeld/numba,stuartarchibald/numba,numba/numba,gdementen/numba,pombredanne/numba,sklam/numba,jriehl/numba,sklam/numba,shiquanwang/numba,numba/numba,stuartarchibald/numba,IntelLabs/numba,GaZ3ll3/numba,IntelLabs/numba,ssarangi/numba,pitrou/numba,pitrou/numba,jriehl/numba,cpcloud/numba,GaZ3ll3/numba,cpcloud/numba,pombredanne/numba,sklam/numba,seibert/numba,stuartarchibald/numba,gdementen/numba,ssarangi/numba,pombredanne/numba,GaZ3ll3/numba,GaZ3ll3/numba,numba/numba,stefanseefeld/numba,numba/numba,ssarangi/numba,cpcloud/numba,pitrou/numba,jriehl/numba,shiquanwang/numba,stonebig/numba,seibert/numba,seibert/numba,pombredanne/numba,stonebig/numba,stuartarchibald/numba,ssarangi/numba,GaZ3ll3/numba,gdementen/numba,ssarangi/numba,cpcloud/numba,stonebig/numba,shiquanwang/numba
--- +++ @@ -2,21 +2,24 @@ >>> test_typeof() """ -import sys import numba from numba import * -from nose.tools import raises -@jit -class Base(object): +def make_base(compiler): + @compiler + class Base(object): - value1 = double - value2 = int_ + value1 = double + value2 = int_ - @void(int_, double) - def __init__(self, value1, value2): - self.value1 = value1 - self.value2 = value2 + @void(int_, double) + def __init__(self, value1, value2): + self.value1 = value1 + self.value2 = value2 + + return Base + +Base = make_base(jit) @jit class Derived(Base): @@ -45,5 +48,21 @@ # assert base_typeof() == (double, int_), base_typeof() # assert derived_typeof() == (double, int_, float_), derived_typeof() + +#------------------------------------------------------------------------ +# Test Specialized autojit typeof +#------------------------------------------------------------------------ + +AutoBase = make_base(autojit) + +@autojit +def attrtypes(obj): + return numba.typeof(obj.value1), numba.typeof(obj.value2) + +def test_autobase(): + obj = AutoBase(10, 11.0) + assert attrtypes(obj) == (double, int_) + if __name__ == '__main__': - numba.testmod() + test_typeof() + test_autobase()
6e67e2882c71e291dc1f161ffc7638f42c86ddbc
dmdlib/randpatterns/ephys_comms.py
dmdlib/randpatterns/ephys_comms.py
import zmq def send_message(msg, hostname='localhost', port=5556): """ sends a message to openephys ZMQ socket. :param msg: string :param hostname: ip address to send to :param port: zmq port number :return: none """ with zmq.Context() as ctx: with ctx.socket(zmq.REQ) as sock: sock.connect('tcp://{}:{}'.format(hostname, port)) sock.send_string(msg) _ = sock.recv_string() return
""" Module handling the communication with OpenEphys. """ import zmq TIMEOUT_MS = 250 # time to wait for ZMQ socket to respond before error. HOSTNAME = 'localhost' PORT = 5556 _ctx = zmq.Context() # should be only one made per process. def send_message(msg, hostname=HOSTNAME, port=PORT): """ sends a message to openephys ZMQ socket. Raises OpenEphysError if port is unresponsive. :param msg: string :param hostname: ip address to send to :param port: zmq port number :return: none """ failed = False with _ctx.socket(zmq.REQ) as sock: sock.connect('tcp://{}:{}'.format(hostname, port)) sock.send_string(msg, zmq.NOBLOCK) evs = sock.poll(TIMEOUT_MS) # wait for host process to respond. # Poll returns 0 after timeout if no events detected. This means that openephys is broken, so error: if evs < 1: failed = True else: sock.recv_string() if failed: # raise out of context (after socket is closed...) raise OpenEphysError('Cannot connect to OpenEphys.') def record_start(uuid, filepath, hostname=HOSTNAME, port=PORT): """ Convenience function for sending data about the start of a recording to OpenEphys :param uuid: :param filepath: :param hostname: :param port: :return: """ msg = 'Pattern file saved at: {}.'.format(filepath) send_message(msg, hostname, port) msg2 = 'Pattern file uuid: {}.'.format(uuid) send_message(msg2, hostname, port) def record_presentation(name, hostname=HOSTNAME, port=PORT): """ Convenience function for sending data about start of a presentation epoch. :param name: name of the epoch (ie AAA, AAB, etc). :param hostname: default 'localhost' :param port: default 5556 """ msg = 'Starting presentation {}'.format(name) send_message(msg, hostname, port) class OpenEphysError(Exception): pass
Fix zmq communications module Does not hang when connection is unavailable
Fix zmq communications module Does not hang when connection is unavailable
Python
mit
olfa-lab/DmdLib
--- +++ @@ -1,18 +1,67 @@ +""" +Module handling the communication with OpenEphys. +""" import zmq +TIMEOUT_MS = 250 # time to wait for ZMQ socket to respond before error. +HOSTNAME = 'localhost' +PORT = 5556 -def send_message(msg, hostname='localhost', port=5556): +_ctx = zmq.Context() # should be only one made per process. + + +def send_message(msg, hostname=HOSTNAME, port=PORT): """ sends a message to openephys ZMQ socket. + + Raises OpenEphysError if port is unresponsive. + :param msg: string :param hostname: ip address to send to :param port: zmq port number :return: none """ - with zmq.Context() as ctx: - with ctx.socket(zmq.REQ) as sock: - sock.connect('tcp://{}:{}'.format(hostname, port)) - sock.send_string(msg) - _ = sock.recv_string() - return + failed = False + with _ctx.socket(zmq.REQ) as sock: + sock.connect('tcp://{}:{}'.format(hostname, port)) + sock.send_string(msg, zmq.NOBLOCK) + evs = sock.poll(TIMEOUT_MS) # wait for host process to respond. + + # Poll returns 0 after timeout if no events detected. This means that openephys is broken, so error: + if evs < 1: + failed = True + else: + sock.recv_string() + if failed: # raise out of context (after socket is closed...) + raise OpenEphysError('Cannot connect to OpenEphys.') + +def record_start(uuid, filepath, hostname=HOSTNAME, port=PORT): + """ + Convenience function for sending data about the start of a recording to OpenEphys + :param uuid: + :param filepath: + :param hostname: + :param port: + :return: + """ + msg = 'Pattern file saved at: {}.'.format(filepath) + send_message(msg, hostname, port) + msg2 = 'Pattern file uuid: {}.'.format(uuid) + send_message(msg2, hostname, port) + + +def record_presentation(name, hostname=HOSTNAME, port=PORT): + """ + Convenience function for sending data about start of a presentation epoch. + + :param name: name of the epoch (ie AAA, AAB, etc). + :param hostname: default 'localhost' + :param port: default 5556 + """ + msg = 'Starting presentation {}'.format(name) + send_message(msg, hostname, port) + + +class OpenEphysError(Exception): + pass
3d3d6ef8393339f7246e6c6a9693d883ca3246f2
marconi/__init__.py
marconi/__init__.py
# Copyright (c) 2013 Rackspace Hosting, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # Import guard. No module level import during the setup procedure. try: if __MARCONI_SETUP__: # NOQA import sys as _sys _sys.stderr.write('Running from marconi source directory.\n') del _sys except NameError: import marconi.queues.bootstrap Bootstrap = marconi.queues.bootstrap.Bootstrap import marconi.version __version__ = marconi.version.version_info.cached_version_string()
# Copyright (c) 2013 Rackspace Hosting, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import marconi.queues.bootstrap import marconi.version Bootstrap = marconi.queues.bootstrap.Bootstrap __version__ = marconi.version.version_info.cached_version_string()
Remove the __MARCONI_SETUP_ global from init
Remove the __MARCONI_SETUP_ global from init This was used to know when Marconi was being loaded and avoid registering configuration options and doing other things. This is not necessary anymore. Change-Id: Icf43302581eefb563b10ddec5831eeec0d068872 Partially-Implements: py3k-support
Python
apache-2.0
openstack/zaqar,openstack/zaqar,rackerlabs/marconi,openstack/zaqar,openstack/zaqar
--- +++ @@ -13,16 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. -# Import guard. No module level import during the setup procedure. -try: - if __MARCONI_SETUP__: # NOQA - import sys as _sys - _sys.stderr.write('Running from marconi source directory.\n') - del _sys -except NameError: - import marconi.queues.bootstrap - Bootstrap = marconi.queues.bootstrap.Bootstrap - +import marconi.queues.bootstrap import marconi.version +Bootstrap = marconi.queues.bootstrap.Bootstrap + + __version__ = marconi.version.version_info.cached_version_string()
7a571230e9678f30e6178da01769424213471355
libapol/__init__.py
libapol/__init__.py
"""The SETools SELinux policy analysis library.""" # Copyright 2014, Tresys Technology, LLC # # This file is part of SETools. # # SETools is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 2.1 of # the License, or (at your option) any later version. # # SETools is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with SETools. If not, see # <http://www.gnu.org/licenses/>. # __version__ = "4.0.0-alpha" # Python classes for policy representation import policyrep from policyrep import SELinuxPolicy # Component Queries import typequery import userquery import boolquery import polcapquery # Rule Queries import terulequery import rbacrulequery import mlsrulequery # Information Flow Analysis import infoflow import permmap # Domain Transition Analysis import dta
"""The SETools SELinux policy analysis library.""" # Copyright 2014, Tresys Technology, LLC # # This file is part of SETools. # # SETools is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 2.1 of # the License, or (at your option) any later version. # # SETools is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with SETools. If not, see # <http://www.gnu.org/licenses/>. # __version__ = "4.0.0-alpha" # Python classes for policy representation import policyrep from policyrep import SELinuxPolicy # Component Queries import typequery import rolequery import userquery import boolquery import polcapquery # Rule Queries import terulequery import rbacrulequery import mlsrulequery # Information Flow Analysis import infoflow import permmap # Domain Transition Analysis import dta
Add missing libapol rolequery import.
Add missing libapol rolequery import.
Python
lgpl-2.1
TresysTechnology/setools,TresysTechnology/setools,TresysTechnology/setools,TresysTechnology/setools
--- +++ @@ -26,6 +26,7 @@ # Component Queries import typequery +import rolequery import userquery import boolquery import polcapquery
e6c41d8bd83b6710114a9d37915a0b3bbeb78d2a
sms_sponsorship/tests/load_tests.py
sms_sponsorship/tests/load_tests.py
# coding: utf-8 # pylint: disable=W7936 from locust import HttpLocust, TaskSet, task from random import randint class SmsSponsorWorkflow(TaskSet): @task(1) def send_sms(self): url = "/sms/mnc?sender=%2B41789364{}&service=compassion".format( randint(100, 999)) self.client.get(url) class SmsSponsor(HttpLocust): task_set = SmsSponsorWorkflow
# coding: utf-8 # pylint: disable=W7936 from locust import HttpLocust, TaskSet, task from random import randint class SmsSponsorWorkflow(TaskSet): @task(1) def send_sms(self): url = "/sms/mnc?sender=%2B4199{}&service=compassion&text=test".format( randint(1000000, 9999999)) self.client.get(url) class SmsSponsor(HttpLocust): task_set = SmsSponsorWorkflow
Replace phone number and avoid sending SMS for load testing
Replace phone number and avoid sending SMS for load testing
Python
agpl-3.0
eicher31/compassion-modules,eicher31/compassion-modules,ecino/compassion-modules,ecino/compassion-modules,CompassionCH/compassion-modules,ecino/compassion-modules,CompassionCH/compassion-modules,CompassionCH/compassion-modules,eicher31/compassion-modules,eicher31/compassion-modules,ecino/compassion-modules,ecino/compassion-modules,CompassionCH/compassion-modules,eicher31/compassion-modules
--- +++ @@ -8,8 +8,8 @@ @task(1) def send_sms(self): - url = "/sms/mnc?sender=%2B41789364{}&service=compassion".format( - randint(100, 999)) + url = "/sms/mnc?sender=%2B4199{}&service=compassion&text=test".format( + randint(1000000, 9999999)) self.client.get(url)
de69b88f47714848e4a73b6375d9665fb48faeda
climlab/__init__.py
climlab/__init__.py
__version__ = '0.5.0.dev0' # this should ensure that we can still import constants.py as climlab.constants from climlab.utils import constants from climlab.utils import thermo, legendre # some more useful shorcuts from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal from climlab.domain import domain from climlab.domain.field import Field, global_mean from climlab.domain.axis import Axis from climlab.domain.initial import column_state, surface_state from climlab.process import Process, TimeDependentProcess, ImplicitProcess, DiagnosticProcess, EnergyBudget from climlab.process import process_like, get_axes
__version__ = '0.5.0' # this should ensure that we can still import constants.py as climlab.constants from climlab.utils import constants from climlab.utils import thermo, legendre # some more useful shorcuts from climlab.model.column import GreyRadiationModel, RadiativeConvectiveModel, BandRCModel from climlab.model.ebm import EBM, EBM_annual, EBM_seasonal from climlab.domain import domain from climlab.domain.field import Field, global_mean from climlab.domain.axis import Axis from climlab.domain.initial import column_state, surface_state from climlab.process import Process, TimeDependentProcess, ImplicitProcess, DiagnosticProcess, EnergyBudget from climlab.process import process_like, get_axes
Increment version number to 0.5.0
Increment version number to 0.5.0
Python
mit
cjcardinale/climlab,brian-rose/climlab,cjcardinale/climlab,cjcardinale/climlab,brian-rose/climlab
--- +++ @@ -1,4 +1,4 @@ -__version__ = '0.5.0.dev0' +__version__ = '0.5.0' # this should ensure that we can still import constants.py as climlab.constants from climlab.utils import constants
feb46fccee8f07d1ad563440cf52b344594f411c
cached_counts/models.py
cached_counts/models.py
from django.db import models from django.core.urlresolvers import reverse from django.template.defaultfilters import slugify class CachedCount(models.Model): """ Fairly generic model for storing counts of various sorts. The object_id is used for linking through to the relevant URL. """ count_type = models.CharField(blank=False, max_length=100, db_index=True) name = models.CharField(blank=False, max_length=100) count = models.IntegerField(blank=False, null=False) object_id = models.CharField(blank=True, max_length=100) class Meta: ordering = ['-count'] @classmethod def total_2015(cls): print cls.objects.get(name="total_2015") return cls.objects.get(name="total_2015").count @property def object_url(self): if self.count_type == "constituency": return reverse('constituency', kwargs={ 'mapit_area_id': self.object_id, 'ignored_slug': slugify(self.name) })
from django.db import models from django.core.urlresolvers import reverse from django.template.defaultfilters import slugify class CachedCount(models.Model): """ Fairly generic model for storing counts of various sorts. The object_id is used for linking through to the relevant URL. """ count_type = models.CharField(blank=False, max_length=100, db_index=True) name = models.CharField(blank=False, max_length=100) count = models.IntegerField(blank=False, null=False) object_id = models.CharField(blank=True, max_length=100) class Meta: ordering = ['-count', 'name'] @classmethod def total_2015(cls): print cls.objects.get(name="total_2015") return cls.objects.get(name="total_2015").count @property def object_url(self): if self.count_type == "constituency": return reverse('constituency', kwargs={ 'mapit_area_id': self.object_id, 'ignored_slug': slugify(self.name) })
Order by -count, name as there are duplicate names
Order by -count, name as there are duplicate names
Python
agpl-3.0
YoQuieroSaber/yournextrepresentative,mysociety/yournextrepresentative,openstate/yournextrepresentative,DemocracyClub/yournextrepresentative,openstate/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextrepresentative,datamade/yournextmp-popit,datamade/yournextmp-popit,datamade/yournextmp-popit,mysociety/yournextrepresentative,datamade/yournextmp-popit,mysociety/yournextrepresentative,mysociety/yournextmp-popit,openstate/yournextrepresentative,openstate/yournextrepresentative,openstate/yournextrepresentative,mysociety/yournextmp-popit,DemocracyClub/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,neavouli/yournextrepresentative,YoQuieroSaber/yournextrepresentative,YoQuieroSaber/yournextrepresentative,DemocracyClub/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextrepresentative,neavouli/yournextrepresentative,YoQuieroSaber/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,YoQuieroSaber/yournextrepresentative
--- +++ @@ -15,7 +15,7 @@ object_id = models.CharField(blank=True, max_length=100) class Meta: - ordering = ['-count'] + ordering = ['-count', 'name'] @classmethod def total_2015(cls):
fdd57913aa11c29ecf160f32a9091e59de598899
plugins/YTranslate.py
plugins/YTranslate.py
""" Yandex Translation API """ import logging from urllib.parse import quote from telegram import Bot, Update from telegram.ext import Updater from requests import post import constants # pylint: disable=E0401 import settings LOGGER = logging.getLogger("YTranslate") YAURL = "https://translate.yandex.net/api/v1.5/tr.json/translate?" YAURL += "key=%s" % settings.YANDEX_TRANSLATION_TOKEN def preload(updater: Updater, level): """ This loads whenever plugin starts Even if you dont need it, you SHOULD put at least return None, otherwise your plugin wont load """ return def translate(bot: Bot, update: Update, user, args): # pylint: disable=W0613 """/tl""" if update.message.reply_to_message: if len(args) > 0: lang = args[0].lower() else: lang = "en" yandex = post(YAURL, params={"text":update.message.reply_to_message.text, "lang":lang}).json() try: return yandex["lang"].upper() + "\n" + yandex["text"][0], constants.TEXT except KeyError: return "Unknown language:%s" % args[0].upper(), constants.TEXT COMMANDS = [ { "command":"/tl", "function":translate, "description":"Translates message to english. Example: [In Reply To Message] /tl", "inline_support":True } ]
""" Yandex Translation API """ import logging from urllib.parse import quote from telegram import Bot, Update from telegram.ext import Updater from requests import post import constants # pylint: disable=E0401 import settings import octeon LOGGER = logging.getLogger("YTranslate") YAURL = "https://translate.yandex.net/api/v1.5/tr.json/translate?" YAURL += "key=%s" % settings.YANDEX_TRANSLATION_TOKEN def preload(updater: Updater, level): """ This loads whenever plugin starts Even if you dont need it, you SHOULD put at least return None, otherwise your plugin wont load """ return def translate(bot: Bot, update: Update, user, args): # pylint: disable=W0613 """/tl""" if update.message.reply_to_message: if len(args) > 0: lang = args[0].lower() else: lang = "en" yandex = post(YAURL, params={"text":update.message.reply_to_message.text, "lang":lang}).json() try: return octeon.message(yandex["lang"].upper() + "\n" + yandex["text"][0]) except KeyError: return octeon.message(yandex["error"], failed=True) COMMANDS = [ { "command":"/tl", "function":translate, "description":"Translates message to english. Example: [In Reply To Message] /tl", "inline_support":True } ]
Update translate plugin to new message format
Update translate plugin to new message format
Python
mit
ProtoxiDe22/Octeon
--- +++ @@ -10,6 +10,7 @@ import constants # pylint: disable=E0401 import settings +import octeon LOGGER = logging.getLogger("YTranslate") YAURL = "https://translate.yandex.net/api/v1.5/tr.json/translate?" @@ -32,9 +33,9 @@ lang = "en" yandex = post(YAURL, params={"text":update.message.reply_to_message.text, "lang":lang}).json() try: - return yandex["lang"].upper() + "\n" + yandex["text"][0], constants.TEXT + return octeon.message(yandex["lang"].upper() + "\n" + yandex["text"][0]) except KeyError: - return "Unknown language:%s" % args[0].upper(), constants.TEXT + return octeon.message(yandex["error"], failed=True) COMMANDS = [ {
7c08497e3e3e08f3ebf82eb594c25c1ab65b4d9d
SocialNPHS/language/tweet.py
SocialNPHS/language/tweet.py
""" Given a tweet, tokenize it and shit. """ import nltk from nltk.tokenize import TweetTokenizer from SocialNPHS.sources.twitter.auth import api from SocialNPHS.sources.twitter import user def get_tweet_tags(tweet): """ Break up a tweet into individual word parts """ tknzr = TweetTokenizer() tokens = tknzr.tokenize(tweet) # replace handles with real names for n, tok in enumerate(tokens): if tok.startswith('@'): handle = tok.strip("@") if handle in user.students: usr = user.NPUser(handle) tokens[n] = usr.fullname else: # TODO: replace with twitter alias pass return nltk.pos_tag(tokens)
""" Given a tweet, tokenize it and shit. """ import nltk from nltk.tokenize import TweetTokenizer from SocialNPHS.sources.twitter.auth import api from SocialNPHS.sources.twitter import user def get_tweet_tags(tweet): """ Break up a tweet into individual word parts """ tknzr = TweetTokenizer() tokens = tknzr.tokenize(tweet) # replace handles with real names for n, tok in enumerate(tokens): if tok.startswith('@'): handle = tok.strip("@") if handle in user.students: # If we have a database entry for the mentioned user, we can # easily substitute a full name. usr = user.NPUser(handle) tokens[n] = usr.fullname else: # If there is no database entry, we use the user's alias. While # this is the full name in many cases, it is often not reliable usr = api.get_user(handle) tokens[n] = usr.name return nltk.pos_tag(tokens)
Implement fallback for tokenizing non-nphs tagged users
Implement fallback for tokenizing non-nphs tagged users
Python
mit
SocialNPHS/SocialNPHS
--- +++ @@ -18,9 +18,13 @@ if tok.startswith('@'): handle = tok.strip("@") if handle in user.students: + # If we have a database entry for the mentioned user, we can + # easily substitute a full name. usr = user.NPUser(handle) tokens[n] = usr.fullname else: - # TODO: replace with twitter alias - pass + # If there is no database entry, we use the user's alias. While + # this is the full name in many cases, it is often not reliable + usr = api.get_user(handle) + tokens[n] = usr.name return nltk.pos_tag(tokens)
a212c5c859cef769bbe3d46c1da816bf6218b773
corehq/messaging/smsbackends/test/models.py
corehq/messaging/smsbackends/test/models.py
from django.conf import settings from corehq.apps.sms.mixin import SMSBackend from corehq.apps.sms.models import SQLSMSBackend from corehq.apps.sms.forms import BackendForm class TestSMSBackend(SMSBackend): @classmethod def get_api_id(cls): return "TEST" @classmethod def get_generic_name(cls): return "Test" @classmethod def get_form_class(cls): return BackendForm def send(self, msg, *args, **kwargs): debug = getattr(settings, "DEBUG", False) if debug: print "***************************************************" print "Message To: %s" % msg.phone_number print "Message Content: %s" % msg.text print "***************************************************" @classmethod def _migration_get_sql_model_class(cls): return SQLTestSMSBackend class SQLTestSMSBackend(SQLSMSBackend): class Meta: app_label = 'sms' proxy = True @classmethod def _migration_get_couch_model_class(cls): return TestSMSBackend @classmethod def get_available_extra_fields(cls): return []
from django.conf import settings from corehq.apps.sms.mixin import SMSBackend from corehq.apps.sms.models import SQLSMSBackend from corehq.apps.sms.forms import BackendForm class TestSMSBackend(SMSBackend): @classmethod def get_api_id(cls): return "TEST" @classmethod def get_generic_name(cls): return "Test" @classmethod def get_form_class(cls): return BackendForm def send(self, msg, *args, **kwargs): debug = getattr(settings, "DEBUG", False) if debug: print "***************************************************" print "Message To: %s" % msg.phone_number print "Message Content: %s" % msg.text print "***************************************************" @classmethod def _migration_get_sql_model_class(cls): return SQLTestSMSBackend class SQLTestSMSBackend(SQLSMSBackend): class Meta: app_label = 'sms' proxy = True @classmethod def _migration_get_couch_model_class(cls): return TestSMSBackend @classmethod def get_available_extra_fields(cls): return [] @classmethod def get_api_id(cls): return 'TEST' @classmethod def get_generic_name(cls): return "Test" @classmethod def get_form_class(cls): return BackendForm def send(self, msg, *args, **kwargs): debug = getattr(settings, 'DEBUG', False) if debug: print "***************************************************" print "Message To: %s" % msg.phone_number print "Message Content: %s" % msg.text print "***************************************************"
Copy test backend code from couch model to sql model
Copy test backend code from couch model to sql model
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq
--- +++ @@ -42,3 +42,23 @@ @classmethod def get_available_extra_fields(cls): return [] + + @classmethod + def get_api_id(cls): + return 'TEST' + + @classmethod + def get_generic_name(cls): + return "Test" + + @classmethod + def get_form_class(cls): + return BackendForm + + def send(self, msg, *args, **kwargs): + debug = getattr(settings, 'DEBUG', False) + if debug: + print "***************************************************" + print "Message To: %s" % msg.phone_number + print "Message Content: %s" % msg.text + print "***************************************************"
68680b8b116e10ae4e35c39b8a62c0307ee65fe4
node/deduplicate.py
node/deduplicate.py
#!/usr/bin/env python from nodes import Node class Deduplicate(Node): char = "}" args = 1 results = 2 @Node.test_func([2], [4]) @Node.test_func([1.5], [3]) def double(self, inp: Node.number): """inp*2""" self.results = 1 return inp*2 def func(self, seq:Node.indexable): """remove duplicates from seq""" if isinstance(seq, str): return "".join(set(seq)) return [type(seq)(set(seq))]
#!/usr/bin/env python from nodes import Node class Deduplicate(Node): char = "}" args = 1 results = 1 @Node.test_func([2], [4]) @Node.test_func([1.5], [3]) def double(self, inp: Node.number): """inp*2""" return inp*2 @Node.test_func([[1,2,3,1,1]], [[1,2,3]]) @Node.test_func(["hi!!!"], ["hi!"]) def func(self, seq:Node.indexable): """remove duplicates from seq""" seen = set() seen_add = seen.add if isinstance(seq, str): return "".join(x for x in seq if not (x in seen or seen_add(x))) return[type(seq)([x for x in seq if not (x in seen or seen_add(x))])]
Fix dedupe not preserving order
Fix dedupe not preserving order
Python
mit
muddyfish/PYKE,muddyfish/PYKE
--- +++ @@ -5,17 +5,20 @@ class Deduplicate(Node): char = "}" args = 1 - results = 2 + results = 1 @Node.test_func([2], [4]) @Node.test_func([1.5], [3]) def double(self, inp: Node.number): """inp*2""" - self.results = 1 return inp*2 + @Node.test_func([[1,2,3,1,1]], [[1,2,3]]) + @Node.test_func(["hi!!!"], ["hi!"]) def func(self, seq:Node.indexable): """remove duplicates from seq""" + seen = set() + seen_add = seen.add if isinstance(seq, str): - return "".join(set(seq)) - return [type(seq)(set(seq))] + return "".join(x for x in seq if not (x in seen or seen_add(x))) + return[type(seq)([x for x in seq if not (x in seen or seen_add(x))])]
3de1cdba6c438a5bc52c10fa469b675117b9ce45
src/trajectory/lissajous_trajectory.py
src/trajectory/lissajous_trajectory.py
#!/usr/bin/env python from math import pi, sin, cos from .trajectory import Trajectory class LissajousTrajectory(object, Trajectory): def __init__(self, A, B, a, b, period, delta=pi/2): Trajectory.__init__(self) self.A = A self.B = B self.a = a self.b = b self.period = period self.delta = delta def get_position_at(self, t): super(LissajousTrajectory, self).get_position_at(t) self.position.x = self.A * sin(2 * pi * t * self.a / self.period + self.delta) self.position.y = -self.B * sin(2 * pi * t * self.b / self.period) return self.position def get_name(self): return str(LissajousTrajectory.__name__).replace('Trajectory', '').lower()
#!/usr/bin/env python from math import pi, sin from .trajectory import Trajectory class LissajousTrajectory(object, Trajectory): def __init__(self, A, B, a, b, period, delta=pi/2): Trajectory.__init__(self) self.A = A self.B = B self.a = a self.b = b self.period = period self.delta = delta def get_position_at(self, t): super(LissajousTrajectory, self).get_position_at(t) self.position.x = self.A * sin(2 * pi * t * self.a / self.period + self.delta) self.position.y = self.B * sin(2 * pi * t * self.b / self.period) return self.position def get_name(self): return str(LissajousTrajectory.__name__).replace('Trajectory', '').lower()
Fix wrong formula for y position
fix: Fix wrong formula for y position
Python
mit
bit0001/trajectory_tracking,bit0001/trajectory_tracking
--- +++ @@ -1,5 +1,5 @@ #!/usr/bin/env python -from math import pi, sin, cos +from math import pi, sin from .trajectory import Trajectory @@ -17,7 +17,7 @@ def get_position_at(self, t): super(LissajousTrajectory, self).get_position_at(t) self.position.x = self.A * sin(2 * pi * t * self.a / self.period + self.delta) - self.position.y = -self.B * sin(2 * pi * t * self.b / self.period) + self.position.y = self.B * sin(2 * pi * t * self.b / self.period) return self.position
8f98b52ec670ecfe89f243348f7815b0ae71eed7
gog_utils/gol_connection.py
gog_utils/gol_connection.py
"""Module hosting class representing connection to GoL.""" import json import requests import os import stat WEBSITE_URL = "http://www.gogonlinux.com" AVAILABLE_GAMES = "/available" BETA_GAMES = "/available-beta" def obtain_available_games(): """Returns JSON list of all available games.""" resp = requests.get(url=(WEBSITE_URL + AVAILABLE_GAMES)) return json.loads(resp.text) def obtain_beta_available_games(): """Obtains JSON list of all available beta games.""" resp = requests.get(url=(WEBSITE_URL + BETA_GAMES)) return json.loads(resp.text) def download_script(target, url): """Function to download data from url to target.""" reqs = requests.get(url) with open(target, "w+") as file_handle: file_handle.write(reqs.content) os.chmod(target, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
"""Module hosting class representing connection to GoL.""" import json import requests import os import stat WEBSITE_URL = "http://www.gogonlinux.com" AVAILABLE_GAMES = "/available" BETA_GAMES = "/available-beta" def obtain_available_games(): """Returns JSON list of all available games.""" resp = requests.get(url=(WEBSITE_URL + AVAILABLE_GAMES)) return json.loads(resp.text) #pylint: disable=E1103 def obtain_beta_available_games(): """Obtains JSON list of all available beta games.""" resp = requests.get(url=(WEBSITE_URL + BETA_GAMES)) return json.loads(resp.text) #pylint: disable=E1103 def download_script(target, url): """Function to download data from url to target.""" reqs = requests.get(url) with open(target, "w+") as file_handle: file_handle.write(reqs.content) #pylint: disable=E1103 os.chmod(target, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
Disable falsely reported pylint errors due to unresolved library type
Disable falsely reported pylint errors due to unresolved library type Signed-off-by: Morgawr <528620cabbf4155b02d05fdb6013cd6bb6ad54b5@gmail.com>
Python
bsd-3-clause
Morgawr/gogonlinux,Morgawr/gogonlinux
--- +++ @@ -12,16 +12,16 @@ def obtain_available_games(): """Returns JSON list of all available games.""" resp = requests.get(url=(WEBSITE_URL + AVAILABLE_GAMES)) - return json.loads(resp.text) + return json.loads(resp.text) #pylint: disable=E1103 def obtain_beta_available_games(): """Obtains JSON list of all available beta games.""" resp = requests.get(url=(WEBSITE_URL + BETA_GAMES)) - return json.loads(resp.text) + return json.loads(resp.text) #pylint: disable=E1103 def download_script(target, url): """Function to download data from url to target.""" reqs = requests.get(url) with open(target, "w+") as file_handle: - file_handle.write(reqs.content) + file_handle.write(reqs.content) #pylint: disable=E1103 os.chmod(target, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
31cf067f3e4da104551baf0e02332e22a75bb80a
tests/commit/field/test__field_math.py
tests/commit/field/test__field_math.py
from unittest import TestCase from phi import math from phi.geom import Box from phi import field from phi.physics import Domain class TestFieldMath(TestCase): def test_gradient(self): domain = Domain(x=4, y=3) phi = domain.grid() * (1, 2) grad = field.gradient(phi, stack_dim='gradient') self.assertEqual(('spatial', 'spatial', 'channel', 'channel'), grad.shape.types) def test_divergence_centered(self): v = field.CenteredGrid(math.ones(x=3, y=3), Box[0:1, 0:1], math.extrapolation.ZERO) * (1, 0) # flow to the right div = field.divergence(v).values math.assert_close(div.y[0], (1.5, 0, -1.5))
from unittest import TestCase from phi import math from phi.field import StaggeredGrid, CenteredGrid from phi.geom import Box from phi import field from phi.physics import Domain class TestFieldMath(TestCase): def test_gradient(self): domain = Domain(x=4, y=3) phi = domain.grid() * (1, 2) grad = field.gradient(phi, stack_dim='gradient') self.assertEqual(('spatial', 'spatial', 'channel', 'channel'), grad.shape.types) def test_divergence_centered(self): v = field.CenteredGrid(math.ones(x=3, y=3), Box[0:1, 0:1], math.extrapolation.ZERO) * (1, 0) # flow to the right div = field.divergence(v).values math.assert_close(div.y[0], (1.5, 0, -1.5)) def test_trace_function(self): def f(x: StaggeredGrid, y: CenteredGrid): return x + (y >> x) ft = field.trace_function(f) domain = Domain(x=4, y=3) x = domain.staggered_grid(1) y = domain.vector_grid(1) res_f = f(x, y) res_ft = ft(x, y) self.assertEqual(res_f.shape, res_ft.shape) field.assert_close(res_f, res_ft)
Add unit test, update documentation
Add unit test, update documentation
Python
mit
tum-pbs/PhiFlow,tum-pbs/PhiFlow
--- +++ @@ -1,6 +1,7 @@ from unittest import TestCase from phi import math +from phi.field import StaggeredGrid, CenteredGrid from phi.geom import Box from phi import field from phi.physics import Domain @@ -18,3 +19,17 @@ v = field.CenteredGrid(math.ones(x=3, y=3), Box[0:1, 0:1], math.extrapolation.ZERO) * (1, 0) # flow to the right div = field.divergence(v).values math.assert_close(div.y[0], (1.5, 0, -1.5)) + + def test_trace_function(self): + def f(x: StaggeredGrid, y: CenteredGrid): + return x + (y >> x) + + ft = field.trace_function(f) + domain = Domain(x=4, y=3) + x = domain.staggered_grid(1) + y = domain.vector_grid(1) + + res_f = f(x, y) + res_ft = ft(x, y) + self.assertEqual(res_f.shape, res_ft.shape) + field.assert_close(res_f, res_ft)
04cd17bb03f2b15cf37313cb3261dd37902d82b0
run_coveralls.py
run_coveralls.py
#!/bin/env/python # -*- coding: utf-8 import os from subprocess import call if __name__ == '__main__': if 'TRAVIS' in os.environ: rc = call('coveralls') raise SystemExit(rc)
#!/bin/env/python # -*- coding: utf-8 import os from subprocess import call if __name__ == '__main__': if 'TRAVIS' in os.environ: print("Calling coveralls") rc = call('coveralls') raise SystemExit(rc)
Add a check that coveralls is actually called
Add a check that coveralls is actually called
Python
mit
browniebroke/deezer-python,browniebroke/deezer-python,pfouque/deezer-python,browniebroke/deezer-python
--- +++ @@ -7,5 +7,6 @@ if __name__ == '__main__': if 'TRAVIS' in os.environ: + print("Calling coveralls") rc = call('coveralls') raise SystemExit(rc)
39161521ce75eddf3187a7412e4c22cbca88752d
logtacts/settings/heroku.py
logtacts/settings/heroku.py
from .base import * import dj_database_url DEBUG = False TEMPLATE_DEBUG = DEBUG DATABASES['default'] = dj_database_url.parse(get_env_variable('LOGTACTS_DB_URL')) SECRET_KEY = get_env_variable("LOGTACTS_SECRET_KEY") ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', '.herokuapp.com', '.pebble.ink', ] STATIC_URL = '//logtacts.s3.amazonaws.com/assets/' INSTALLED_APPS += ( 'gunicorn', )
from .base import * import dj_database_url DEBUG = False TEMPLATE_DEBUG = DEBUG DATABASES['default'] = dj_database_url.parse(get_env_variable('LOGTACTS_DB_URL')) SECRET_KEY = get_env_variable("LOGTACTS_SECRET_KEY") ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', '.herokuapp.com', '.pebble.ink', '.logtacts.com', ] STATIC_URL = '//logtacts.s3.amazonaws.com/assets/' INSTALLED_APPS += ( 'gunicorn', )
Add logtacts domain to allowed hosts
Add logtacts domain to allowed hosts
Python
mit
phildini/logtacts,phildini/logtacts,phildini/logtacts,phildini/logtacts,phildini/logtacts
--- +++ @@ -13,6 +13,7 @@ '127.0.0.1', '.herokuapp.com', '.pebble.ink', + '.logtacts.com', ] STATIC_URL = '//logtacts.s3.amazonaws.com/assets/'
f13f14b134d76acac9cad8a93b47315fb0df1ba9
utils/stepvals.py
utils/stepvals.py
import math def get_range(val, step): stepvals = [i*step for i in xrange(int(math.ceil(val/step)))][1:] if not stepvals[-1] == val: # if last element isn't the actual value stepvals += [val] # add it in return stepvals
import math def get_range(val, step): if args.step >= val: raise Exception("Step value is too large! Must be smaller than value.") stepvals = [i*step for i in xrange(int(math.ceil(val/step)))][1:] if not stepvals[-1] == val: # if last element isn't the actual value stepvals += [val] # add it in return stepvals
Raise exception if step value is invalid.
Raise exception if step value is invalid.
Python
mit
wei2912/bce-simulation,wei2912/bce-simulation,wei2912/bce-simulation,wei2912/bce-simulation
--- +++ @@ -1,6 +1,9 @@ import math def get_range(val, step): + if args.step >= val: + raise Exception("Step value is too large! Must be smaller than value.") + stepvals = [i*step for i in xrange(int(math.ceil(val/step)))][1:] if not stepvals[-1] == val: # if last element isn't the actual value stepvals += [val] # add it in
beac0323253454f343b32d42d8c065cfc4fcc04f
src/epiweb/apps/reminder/models.py
src/epiweb/apps/reminder/models.py
import datetime from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class Reminder(models.Model): user = models.ForeignKey(User, unique=True) last_reminder = models.DateTimeField() next_reminder = models.DateField() wday = models.IntegerField() active = models.BooleanField() def add_reminder(sender, **kwargs): instance = kwargs.get('instance', None) try: reminder = Reminder.objects.get(user=instance) except Reminder.DoesNotExist: now = datetime.datetime.now() next = now + datetime.timedelta(days=7) reminder = Reminder() reminder.user = instance reminder.last_reminder = now reminder.next_reminder = next reminder.wday = now.timetuple().tm_wday reminder.active = True reminder.save() post_save.connect(add_reminder, sender=User)
import datetime from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save _ = lambda x: x # Reference: http://docs.python.org/library/time.html # - tm_wday => range [0,6], Monday is 0 MONDAY = 0 TUESDAY = 1 WEDNESDAY = 2 THURSDAY = 3 FRIDAY = 4 SATURDAY = 5 SUNDAY = 6 DAYS = ( (MONDAY, _('Monday')), (TUESDAY, _('Tuesday')), (WEDNESDAY, _('Wednesday')), (THURSDAY, _('Thursday')), (FRIDAY, _('Friday')), (SATURDAY, _('Saturday')), (SUNDAY, _('Sunday')) ) class Reminder(models.Model): user = models.ForeignKey(User, unique=True) last_reminder = models.DateTimeField() next_reminder = models.DateField() wday = models.IntegerField(choices=DAYS, verbose_name="Day", default=MONDAY) active = models.BooleanField() def add_reminder(sender, **kwargs): instance = kwargs.get('instance', None) try: reminder = Reminder.objects.get(user=instance) except Reminder.DoesNotExist: now = datetime.datetime.now() next = now + datetime.timedelta(days=7) reminder = Reminder() reminder.user = instance reminder.last_reminder = now reminder.next_reminder = next reminder.wday = now.timetuple().tm_wday reminder.active = True reminder.save() post_save.connect(add_reminder, sender=User)
Set available options for weekday field of reminder's model
Set available options for weekday field of reminder's model
Python
agpl-3.0
ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website
--- +++ @@ -4,11 +4,34 @@ from django.contrib.auth.models import User from django.db.models.signals import post_save +_ = lambda x: x + +# Reference: http://docs.python.org/library/time.html +# - tm_wday => range [0,6], Monday is 0 +MONDAY = 0 +TUESDAY = 1 +WEDNESDAY = 2 +THURSDAY = 3 +FRIDAY = 4 +SATURDAY = 5 +SUNDAY = 6 + +DAYS = ( + (MONDAY, _('Monday')), + (TUESDAY, _('Tuesday')), + (WEDNESDAY, _('Wednesday')), + (THURSDAY, _('Thursday')), + (FRIDAY, _('Friday')), + (SATURDAY, _('Saturday')), + (SUNDAY, _('Sunday')) +) + class Reminder(models.Model): user = models.ForeignKey(User, unique=True) last_reminder = models.DateTimeField() next_reminder = models.DateField() - wday = models.IntegerField() + wday = models.IntegerField(choices=DAYS, verbose_name="Day", + default=MONDAY) active = models.BooleanField() def add_reminder(sender, **kwargs):
4f4d083ea8be7da6a4aecfd4bf15dc4e91a2d72d
palm/blink_model.py
palm/blink_model.py
import numpy from palm.aggregated_kinetic_model import AggregatedKineticModel from palm.probability_vector import make_prob_vec_from_state_ids from palm.state_collection import StateIDCollection class BlinkModel(AggregatedKineticModel): ''' BlinkModel is an AggregatedKineticModel. Two observation classes are expected: 1. dark (no fluorescence detected) 2. bright (fluorescence detected) ''' def __init__(self, state_enumerator, route_mapper, parameter_set, fermi_activation=False): super(BlinkModel, self).__init__(state_enumerator, route_mapper, parameter_set, fermi_activation) self.all_inactive_state_id = self.initial_state_id self.all_bleached_state_id = self.final_state_id def get_initial_probability_vector(self): dark_state_id_collection = self.state_ids_by_class_dict['dark'] initial_prob_vec = make_prob_vec_from_state_ids(dark_state_id_collection) initial_prob_vec.set_state_probability(self.all_inactive_state_id, 1.0) return initial_prob_vec
import numpy from palm.aggregated_kinetic_model import AggregatedKineticModel from palm.probability_vector import make_prob_vec_from_state_ids from palm.state_collection import StateIDCollection class BlinkModel(AggregatedKineticModel): ''' BlinkModel is an AggregatedKineticModel. Two observation classes are expected: 1. dark (no fluorescence detected) 2. bright (fluorescence detected) ''' def __init__(self, state_enumerator, route_mapper, parameter_set, fermi_activation=False): super(BlinkModel, self).__init__(state_enumerator, route_mapper, parameter_set, fermi_activation) self.all_inactive_state_id = self.initial_state_id self.all_bleached_state_id = self.final_state_id def get_initial_probability_vector(self): dark_state_id_collection = self.state_ids_by_class_dict['dark'] initial_prob_vec = make_prob_vec_from_state_ids(dark_state_id_collection) initial_prob_vec.set_state_probability(self.all_inactive_state_id, 1.0) return initial_prob_vec def get_final_probability_vector(self): dark_state_id_collection = self.state_ids_by_class_dict['dark'] final_prob_vec = make_prob_vec_from_state_ids(dark_state_id_collection) final_prob_vec.set_state_probability(self.all_bleached_state_id, 1.0) return final_prob_vec
Add method for final probability vector, which corresponds to all-photobleached collection.
Add method for final probability vector, which corresponds to all-photobleached collection.
Python
bsd-2-clause
grollins/palm
--- +++ @@ -22,3 +22,9 @@ initial_prob_vec = make_prob_vec_from_state_ids(dark_state_id_collection) initial_prob_vec.set_state_probability(self.all_inactive_state_id, 1.0) return initial_prob_vec + + def get_final_probability_vector(self): + dark_state_id_collection = self.state_ids_by_class_dict['dark'] + final_prob_vec = make_prob_vec_from_state_ids(dark_state_id_collection) + final_prob_vec.set_state_probability(self.all_bleached_state_id, 1.0) + return final_prob_vec
939a96a93d959bf2c26da37adb672f5538c1f222
mmmpaste/db.py
mmmpaste/db.py
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_session, sessionmaker from hashlib import md5 engine = create_engine("sqlite:///db/pastebin.db") session = scoped_session(sessionmaker(bind = engine, autoflush = False)) Base = declarative_base(bind = engine) def init_db(): """ Creates the database schema. Import the models below to add them to the schema generation. Nothing happens when the database already exists. """ from mmmpaste.models import Paste Base.metadata.create_all() def nuke_db(): """ Drop the bass. """ from mmmpaste.models import Paste Base.metadata.drop_all() def new_paste(content, filename = None): from mmmpaste.models import Paste, Content hash = md5(content).hexdigest() dupe = session.query(Content).filter_by(hash = hash).first() paste = Paste(Content(content), filename) if dupe is not None: paste.content = dupe session.add(paste) session.commit() def get_paste(id): from mmmpaste.models import Paste return session.query(Paste).filter_by(id = id).first()
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_session, sessionmaker from hashlib import md5 engine = create_engine("sqlite:///db/pastebin.db") session = scoped_session(sessionmaker(bind = engine, autoflush = False)) Base = declarative_base(bind = engine) def init_db(): """ Creates the database schema. Import the models below to add them to the schema generation. Nothing happens when the database already exists. """ from mmmpaste.models import Paste Base.metadata.create_all() def nuke_db(): """ Drop the bass. """ from mmmpaste.models import Paste Base.metadata.drop_all() def new_paste(content, filename = None): from mmmpaste.models import Paste, Content from mmmpaste.base62 import b62_encode hash = md5(content).hexdigest() dupe = session.query(Content).filter_by(hash = hash).first() paste = Paste(content, filename) if dupe is not None: paste.content = dupe session.add(paste) session.commit() paste.id_b62 = b62_encode(paste.id) session.commit() return paste.id_b62 def get_paste(id_b62): from mmmpaste.models import Paste return session.query(Paste).filter_by(id_b62 = id_b62).first()
Update base 62 id after paste creation.
Update base 62 id after paste creation.
Python
bsd-2-clause
ryanc/mmmpaste,ryanc/mmmpaste
--- +++ @@ -30,10 +30,11 @@ def new_paste(content, filename = None): from mmmpaste.models import Paste, Content + from mmmpaste.base62 import b62_encode hash = md5(content).hexdigest() dupe = session.query(Content).filter_by(hash = hash).first() - paste = Paste(Content(content), filename) + paste = Paste(content, filename) if dupe is not None: paste.content = dupe @@ -41,7 +42,12 @@ session.add(paste) session.commit() + paste.id_b62 = b62_encode(paste.id) + session.commit() -def get_paste(id): + return paste.id_b62 + + +def get_paste(id_b62): from mmmpaste.models import Paste - return session.query(Paste).filter_by(id = id).first() + return session.query(Paste).filter_by(id_b62 = id_b62).first()
25e4e89cf062375cf1a27e8697a7d79b5c662296
what_json/urls.py
what_json/urls.py
from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^checks$', 'what_json.views.checks'), url(r'^add_torrent$', 'what_json.views.add_torrent'), url(r'^sync$', 'what_json.views.sync'), url(r'^sync_replicas$', 'what_json.views.sync_replicas'), url(r'^update_freeleech$', 'what_json.views.update_freeleech'), url(r'^load_balance$', 'what_json.views.run_load_balance'), url(r'^move_torrent$', 'what_json.views.move_torrent_to_location'), url(r'^torrents_info$', 'what_json.views.torrents_info'), url(r'^refresh_whattorrent$', 'what_json.views.refresh_whattorrent'), url(r'^what_proxy$', 'what_json.views.what_proxy'), )
from django.conf.urls import patterns, url urlpatterns = patterns( '', url(r'^checks$', 'what_json.views.checks'), url(r'^add_torrent$', 'what_json.views.add_torrent'), url(r'^sync$', 'what_json.views.sync'), url(r'^sync_replicas$', 'what_json.views.sync_replicas'), url(r'^update_freeleech$', 'what_json.views.update_freeleech'), url(r'^load_balance$', 'what_json.views.run_load_balance'), url(r'^move_torrent$', 'what_json.views.move_torrent_to_location'), url(r'^torrents_info$', 'what_json.views.torrents_info'), url(r'^refresh_whattorrent$', 'what_json.views.refresh_whattorrent'), url(r'^what_proxy$', 'what_json.views.what_proxy'), )
Fix one more flake8 error.
Fix one more flake8 error.
Python
mit
karamanolev/WhatManager2,grandmasterchef/WhatManager2,grandmasterchef/WhatManager2,MADindustries/WhatManager2,karamanolev/WhatManager2,davols/WhatManager2,karamanolev/WhatManager2,karamanolev/WhatManager2,MADindustries/WhatManager2,davols/WhatManager2,grandmasterchef/WhatManager2,davols/WhatManager2,grandmasterchef/WhatManager2,MADindustries/WhatManager2,MADindustries/WhatManager2
--- +++ @@ -1,4 +1,4 @@ -from django.conf.urls import patterns, include, url +from django.conf.urls import patterns, url urlpatterns = patterns( '',
1ecc62d453a122443924b21cf04edf661f9d1878
mwikiircbot.py
mwikiircbot.py
import ircbotframe import sys class Handler: def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]): self.channels = channels self.bot = ircbotframe.ircBot(host, port, name, description) self.bot.bind("376", self.endMOTD) self.bot.start() def endMOTD(self, sender, headers, message): for chan in self.channels: self.bot.joinchan(chan) def main(cmd, args): if len(args) < 2: print("Usage: " + cmd + " <host> <channel> [<channel> ...]") return elif len(args) > 1: Handler(host=args[0], channels=args[1:]) if __name__ == "__main__": if __name__ == '__main__': main(sys.argv[0], sys.argv[1:] if len(sys.argv) > 1 else [])
import ircbotframe import sys class Handler: def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]): self.channels = channels self.bot = ircbotframe.ircBot(host, port, name, description) self.bot.bind("376", self.endMOTD) self.bot.start() def endMOTD(self, sender, headers, message): for chan in self.channels: self.bot.joinchan(chan) def main(cmd, args): args = args[:] parsemode = ["host"] host = None name = "MediaWiki" channels = [] while len(args) > 0: if len(parsemode) < 1: if args[0] == "-n": parsemode.insert(0, "name") else: channels.append(args[0]) else: if parsemode[0] == "name": name = args[0] elif parsemode[0] == "host": host = args[0] parsemode = parsemode[1:] args = args[1:] if host == None: print("Usage: " + cmd + " [-n <name>] <host> <channel> [<channel> ...]") return elif len(args) > 1: Handler(host=host, name=name channels=channels) if __name__ == "__main__": if __name__ == '__main__': main(sys.argv[0], sys.argv[1:] if len(sys.argv) > 1 else [])
Add command line argument to set bot name
Add command line argument to set bot name
Python
mit
fenhl/mwikiircbot
--- +++ @@ -13,11 +13,29 @@ self.bot.joinchan(chan) def main(cmd, args): - if len(args) < 2: - print("Usage: " + cmd + " <host> <channel> [<channel> ...]") + args = args[:] + parsemode = ["host"] + host = None + name = "MediaWiki" + channels = [] + while len(args) > 0: + if len(parsemode) < 1: + if args[0] == "-n": + parsemode.insert(0, "name") + else: + channels.append(args[0]) + else: + if parsemode[0] == "name": + name = args[0] + elif parsemode[0] == "host": + host = args[0] + parsemode = parsemode[1:] + args = args[1:] + if host == None: + print("Usage: " + cmd + " [-n <name>] <host> <channel> [<channel> ...]") return elif len(args) > 1: - Handler(host=args[0], channels=args[1:]) + Handler(host=host, name=name channels=channels) if __name__ == "__main__": if __name__ == '__main__':
996cab9efe8c1bbc9a6922b76b1982ce37dcdccd
pigeonpost/tasks.py
pigeonpost/tasks.py
import datetime import logging from celery.task import task from django.core.mail.backends.smtp import EmailBackend from django.contrib.auth.models import User from pigeonpost.models import ContentQueue, Outbox logger = logging.getLogger('pigeonpost.tasks') def queue_to_send(sender, **kwargs): # Check to see if the object is mailable try: now = datetime.today() countdown = 0 if hasattr(sender, 'email_defer'): countdown = sender.email_defer() scheduled = now + datetime.timedelta(seconds=countdown) # Save it in the model try: post = ContentQueue.get(content_object=sender) except ContentQueue.DoesNotExist: post = ContentQueue(content_object=sender, scheduled=scheduled) post.save() # Create a task to send sendmessages.delay(sender, countdown=countdown) except AttributeError: if not hasattr(sender, 'email_render') or not hasattr(sender, 'email_user'): logger.error('%r requires both email_render and email_user methods.' % sender) else: raise @task def send_messages(content, backend=EmailBackend): users = User.objects.all() for user in users: if content.email_user(user): content.email_render(user) # send the message
import datetime import logging from celery.task import task from django.core.mail.backends.smtp import EmailBackend from django.contrib.auth.models import User from pigeonpost.models import ContentQueue, Outbox logger = logging.getLogger('pigeonpost.tasks') @task def queue_to_send(sender, **kwargs): # Check to see if the object is mailable try: now = datetime.today() countdown = 0 if hasattr(sender, 'email_defer'): countdown = sender.email_defer() scheduled = now + datetime.timedelta(seconds=countdown) # Save it in the model try: post = ContentQueue.get(content_object=sender) except ContentQueue.DoesNotExist: post = ContentQueue(content_object=sender, scheduled=scheduled) post.save() # Create a task to send sendmessages.delay(sender, countdown=countdown) except AttributeError: if not hasattr(sender, 'email_render') or not hasattr(sender, 'email_user'): logger.error('%r requires both email_render and email_user methods.' % sender) else: raise @task def send_messages(content, backend=EmailBackend): users = User.objects.all() for user in users: if content.email_user(user): content.email_render(user) # send the message
Make queue_to_send a celery task
Make queue_to_send a celery task
Python
mit
dragonfly-science/django-pigeonpost,dragonfly-science/django-pigeonpost
--- +++ @@ -10,6 +10,7 @@ logger = logging.getLogger('pigeonpost.tasks') +@task def queue_to_send(sender, **kwargs): # Check to see if the object is mailable try:
97f58ddc46946640870acf7d0f3d950c46d380d3
tests/conftest.py
tests/conftest.py
# -*- coding: utf-8 -*- ''' General-purpose fixtures for vdirsyncer's testsuite. ''' import logging import os import click_log from hypothesis import HealthCheck, Verbosity, settings import pytest @pytest.fixture(autouse=True) def setup_logging(): click_log.basic_config('vdirsyncer').setLevel(logging.DEBUG) try: import pytest_benchmark except ImportError: @pytest.fixture def benchmark(): return lambda x: x() else: del pytest_benchmark settings.suppress_health_check = [HealthCheck.too_slow] settings.register_profile("ci", settings( max_examples=1000, verbosity=Verbosity.verbose, )) settings.register_profile("deterministic", settings( derandomize=True, )) if os.environ.get('DETERMINISTIC_TESTS', 'false').lower() == 'true': settings.load_profile("deterministic") elif os.environ.get('CI', 'false').lower() == 'true': settings.load_profile("ci")
# -*- coding: utf-8 -*- ''' General-purpose fixtures for vdirsyncer's testsuite. ''' import logging import os import click_log from hypothesis import HealthCheck, Verbosity, settings import pytest @pytest.fixture(autouse=True) def setup_logging(): click_log.basic_config('vdirsyncer').setLevel(logging.DEBUG) try: import pytest_benchmark except ImportError: @pytest.fixture def benchmark(): return lambda x: x() else: del pytest_benchmark settings.suppress_health_check = [HealthCheck.too_slow] settings.register_profile("ci", settings( max_examples=1000, verbosity=Verbosity.verbose, )) settings.register_profile("deterministic", settings( derandomize=True, perform_health_check=False )) if os.environ.get('DETERMINISTIC_TESTS', 'false').lower() == 'true': settings.load_profile("deterministic") elif os.environ.get('CI', 'false').lower() == 'true': settings.load_profile("ci")
Disable health checks for distro builds
Disable health checks for distro builds
Python
mit
untitaker/vdirsyncer,untitaker/vdirsyncer,untitaker/vdirsyncer
--- +++ @@ -35,6 +35,7 @@ )) settings.register_profile("deterministic", settings( derandomize=True, + perform_health_check=False )) if os.environ.get('DETERMINISTIC_TESTS', 'false').lower() == 'true':
e7ad2be6cdb87b84bfa77ff9824f2e9913c17599
tests/test_cmd.py
tests/test_cmd.py
import base64 import os from distutils.core import Command class TestCommand(Command): description = "Launch all tests under fusion_tables app" user_options = [] def initialize_options(self): pass def finalize_options(self): pass def create_client_secret_file(self): client_secret = open("/tmp/client_secret.json", "w") data = os.environ.get("CLIENT_SECRET").decode("utf-8") client_secret.write(base64.b64decode(data)) client_secret.close() def configure_settings(self): from django.conf import settings settings.configure( DATABASES={ "default": { "NAME": ":memory:", "ENGINE": "django.db.backends.sqlite3", "TEST": { "NAME": ":memory:" } } }, INSTALLED_APPS=( "django.contrib.contenttypes", "fusion_tables", ), ROOT_URLCONF="tests.urls", MODELS_TO_SYNC=("fusion_tables.SampleModel", ), CLIENT_SECRET_JSON_FILEPATH="/tmp/client_secret.json", LOCATION_FIELDS=("TextField", ) ) def run(self): import django from django.core.management import call_command self.create_client_secret_file() self.configure_settings() django.setup() call_command("test", "fusion_tables")
import base64 import os from distutils.core import Command class TestCommand(Command): description = "Launch all tests under fusion_tables app" user_options = [] def initialize_options(self): pass def finalize_options(self): pass def create_client_secret_file(self): client_secret = open("/tmp/client_secret.json", "w") data = os.environ.get("CLIENT_SECRET") client_secret.write(base64.b64decode(data)) client_secret.close() def configure_settings(self): from django.conf import settings settings.configure( DATABASES={ "default": { "NAME": ":memory:", "ENGINE": "django.db.backends.sqlite3", "TEST": { "NAME": ":memory:" } } }, INSTALLED_APPS=( "django.contrib.contenttypes", "fusion_tables", ), ROOT_URLCONF="tests.urls", MODELS_TO_SYNC=("fusion_tables.SampleModel", ), CLIENT_SECRET_JSON_FILEPATH="/tmp/client_secret.json", LOCATION_FIELDS=("TextField", ) ) def run(self): import django from django.core.management import call_command self.create_client_secret_file() self.configure_settings() django.setup() call_command("test", "fusion_tables")
Revert "Fix unit test python3 compatibility."
Revert "Fix unit test python3 compatibility." This reverts commit 6807e5a5966f1f37f69a54e255a9981918cc8fb6.
Python
mit
bsvetchine/django-fusion-tables
--- +++ @@ -15,7 +15,7 @@ def create_client_secret_file(self): client_secret = open("/tmp/client_secret.json", "w") - data = os.environ.get("CLIENT_SECRET").decode("utf-8") + data = os.environ.get("CLIENT_SECRET") client_secret.write(base64.b64decode(data)) client_secret.close()
40a08503edef360bc2d07f1bfe5ecd37ffc4b1d1
oz/__init__.py
oz/__init__.py
""" Class for automated operating system installation. Oz is a set of classes to do automated operating system installation. It has built-in knowledge of the proper things to do for each of the supported operating systems, so the data that the user must provide is very minimal. This data is supplied in the form of an XML document that describes what type of operating system is to be installed and where to get the installation media. Oz handles the rest. The simplest Oz program (without error handling or any advanced features) would look something like: import oz.TDL import oz.GuestFactory tdl_xml = \"\"\" <template> <name>f13jeos</name> <os> <name>Fedora</name> <version>13</version> <arch>x86_64</arch> <install type='url'> <url>http://download.fedoraproject.org/pub/fedora/linux/releases/13/Fedor </install> </os> <description>Fedora 13</description> </template> \"\"\" tdl = oz.TDL.TDL(tdl_xml) guest = oz.GuestFactory.guest_factory(tdl, None, None) guest.generate_install_media() guest.generate_diskimage() guest.install() """
Add some basic pydoc documentation.
Add some basic pydoc documentation. Signed-off-by: Chris Lalancette <60b62644009db6b194cc0445b64e9b27bb26433a@redhat.com>
Python
lgpl-2.1
nullr0ute/oz,cernops/oz,imcleod/oz,moofrank/oz,NeilBryant/oz,nullr0ute/oz,clalancette/oz,mgagne/oz,clalancette/oz,NeilBryant/oz,ndonegan/oz,ndonegan/oz,mgagne/oz,cernops/oz,moofrank/oz,imcleod/oz
--- +++ @@ -0,0 +1,37 @@ +""" +Class for automated operating system installation. + +Oz is a set of classes to do automated operating system installation. It +has built-in knowledge of the proper things to do for each of the supported +operating systems, so the data that the user must provide is very minimal. +This data is supplied in the form of an XML document that describes what +type of operating system is to be installed and where to get the +installation media. Oz handles the rest. + +The simplest Oz program (without error handling or any advanced features) +would look something like: + +import oz.TDL +import oz.GuestFactory + +tdl_xml = \"\"\" +<template> + <name>f13jeos</name> + <os> + <name>Fedora</name> + <version>13</version> + <arch>x86_64</arch> + <install type='url'> + <url>http://download.fedoraproject.org/pub/fedora/linux/releases/13/Fedor + </install> + </os> + <description>Fedora 13</description> +</template> +\"\"\" + +tdl = oz.TDL.TDL(tdl_xml) +guest = oz.GuestFactory.guest_factory(tdl, None, None) +guest.generate_install_media() +guest.generate_diskimage() +guest.install() +"""
dfa1424896b015fe376c523e13d0a59ceacca298
test/797-add-missing-boundaries.py
test/797-add-missing-boundaries.py
# NE data - no OSM elements # boundary between NV and CA is _also_ a "statistical" boundary assert_has_feature( 7, 21, 49, 'boundaries', { 'kind': 'state' }) # boundary between MT and ND is _also_ a "statistical meta" boundary assert_has_feature( 7, 21, 49, 'boundaries', { 'kind': 'state' })
# NE data - no OSM elements # boundary between NV and CA is _also_ a "statistical" boundary assert_has_feature( 7, 21, 49, 'boundaries', { 'kind': 'state' }) # boundary between MT and ND is _also_ a "statistical meta" boundary assert_has_feature( 7, 27, 44, 'boundaries', { 'kind': 'state' })
Test more than one thing
Test more than one thing The test _should_ have tested two boundaries with different `featurecla`, but ended up being a copy/paste error. This fixes that.
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
--- +++ @@ -6,5 +6,5 @@ # boundary between MT and ND is _also_ a "statistical meta" boundary assert_has_feature( - 7, 21, 49, 'boundaries', + 7, 27, 44, 'boundaries', { 'kind': 'state' })
e42019c5648dddc2f705836401e422dd4077b55e
bottle_websocket/__init__.py
bottle_websocket/__init__.py
from plugin import websocket from server import GeventWebSocketServer __all__ = ['websocket', 'GeventWebSocketServer'] __version__ = '0.2.8'
from .plugin import websocket from .server import GeventWebSocketServer __all__ = ['websocket', 'GeventWebSocketServer'] __version__ = '0.2.8'
Update import syntax to fit python3
Update import syntax to fit python3
Python
mit
zeekay/bottle-websocket
--- +++ @@ -1,5 +1,5 @@ -from plugin import websocket -from server import GeventWebSocketServer +from .plugin import websocket +from .server import GeventWebSocketServer __all__ = ['websocket', 'GeventWebSocketServer'] __version__ = '0.2.8'
40d1645f4ad2aca18203ee5ebef1cbbecffa3c51
project/apps/api/signals.py
project/apps/api/signals.py
from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings from .models import ( Contest, ) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def user_post_save(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) @receiver(post_save, sender=Contest) def contest_post_save(sender, instance=None, created=False, **kwargs): if created: instance.build() instance.save()
from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings from .models import ( Contest, ) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def user_post_save(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) @receiver(post_save, sender=Contest) def contest_post_save(sender, instance=None, created=False, raw=False, **kwargs): if not raw: if created: instance.build() instance.save()
Add check for fixture loading
Add check for fixture loading
Python
bsd-2-clause
dbinetti/barberscore-django,barberscore/barberscore-api,dbinetti/barberscore-django,barberscore/barberscore-api,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore,barberscore/barberscore-api
--- +++ @@ -20,7 +20,8 @@ @receiver(post_save, sender=Contest) -def contest_post_save(sender, instance=None, created=False, **kwargs): - if created: - instance.build() - instance.save() +def contest_post_save(sender, instance=None, created=False, raw=False, **kwargs): + if not raw: + if created: + instance.build() + instance.save()
d48ae791364a0d29d60636adfde1f143858794cd
api/identifiers/serializers.py
api/identifiers/serializers.py
from rest_framework import serializers as ser from api.base.utils import absolute_reverse from api.base.serializers import JSONAPISerializer, RelationshipField, IDField, LinksField class IdentifierSerializer(JSONAPISerializer): category = ser.CharField(read_only=True) filterable_fields = frozenset(['category']) value = ser.CharField(read_only=True) referent = RelationshipField( related_view='registrations:registration-detail', related_view_kwargs={'node_id': '<referent._id>'}, ) id = IDField(source='_id', read_only=True) links = LinksField({'self': 'self_url'}) class Meta: type_ = 'identifiers' def get_absolute_url(self, obj): return obj.absolute_api_v2_url def get_id(self, obj): return obj._id def get_detail_url(self, obj): import ipdb; ipdb.set_trace() return '{}/identifiers/{}'.format(obj.absolute_api_v2_url, obj._id) def self_url(self, obj): return absolute_reverse('identifiers:identifier-detail', kwargs={ 'identifier_id': obj._id, })
from rest_framework import serializers as ser from api.base.utils import absolute_reverse from api.base.serializers import JSONAPISerializer, RelationshipField, IDField, LinksField class IdentifierSerializer(JSONAPISerializer): category = ser.CharField(read_only=True) filterable_fields = frozenset(['category']) value = ser.CharField(read_only=True) referent = RelationshipField( related_view='registrations:registration-detail', related_view_kwargs={'node_id': '<referent._id>'}, ) id = IDField(source='_id', read_only=True) links = LinksField({'self': 'self_url'}) class Meta: type_ = 'identifiers' def get_absolute_url(self, obj): return obj.absolute_api_v2_url def get_id(self, obj): return obj._id def get_detail_url(self, obj): return '{}/identifiers/{}'.format(obj.absolute_api_v2_url, obj._id) def self_url(self, obj): return absolute_reverse('identifiers:identifier-detail', kwargs={ 'identifier_id': obj._id, })
Remove rogue debugger how embarassing
Remove rogue debugger how embarassing
Python
apache-2.0
rdhyee/osf.io,alexschiller/osf.io,Johnetordoff/osf.io,caneruguz/osf.io,acshi/osf.io,abought/osf.io,amyshi188/osf.io,erinspace/osf.io,DanielSBrown/osf.io,chrisseto/osf.io,leb2dg/osf.io,mattclark/osf.io,samchrisinger/osf.io,alexschiller/osf.io,mluke93/osf.io,monikagrabowska/osf.io,mfraezz/osf.io,DanielSBrown/osf.io,crcresearch/osf.io,rdhyee/osf.io,caneruguz/osf.io,laurenrevere/osf.io,amyshi188/osf.io,acshi/osf.io,saradbowman/osf.io,samchrisinger/osf.io,HalcyonChimera/osf.io,hmoco/osf.io,aaxelb/osf.io,mluo613/osf.io,HalcyonChimera/osf.io,zamattiac/osf.io,mfraezz/osf.io,baylee-d/osf.io,DanielSBrown/osf.io,caneruguz/osf.io,samchrisinger/osf.io,laurenrevere/osf.io,mattclark/osf.io,SSJohns/osf.io,acshi/osf.io,mluke93/osf.io,cslzchen/osf.io,wearpants/osf.io,hmoco/osf.io,crcresearch/osf.io,CenterForOpenScience/osf.io,SSJohns/osf.io,wearpants/osf.io,abought/osf.io,felliott/osf.io,wearpants/osf.io,brianjgeiger/osf.io,SSJohns/osf.io,jnayak1/osf.io,TomBaxter/osf.io,abought/osf.io,pattisdr/osf.io,aaxelb/osf.io,Nesiehr/osf.io,jnayak1/osf.io,crcresearch/osf.io,alexschiller/osf.io,baylee-d/osf.io,baylee-d/osf.io,chennan47/osf.io,Johnetordoff/osf.io,CenterForOpenScience/osf.io,leb2dg/osf.io,emetsger/osf.io,samchrisinger/osf.io,adlius/osf.io,monikagrabowska/osf.io,zamattiac/osf.io,chrisseto/osf.io,jnayak1/osf.io,binoculars/osf.io,erinspace/osf.io,adlius/osf.io,cwisecarver/osf.io,emetsger/osf.io,aaxelb/osf.io,brianjgeiger/osf.io,kwierman/osf.io,wearpants/osf.io,mluo613/osf.io,leb2dg/osf.io,zamattiac/osf.io,adlius/osf.io,cslzchen/osf.io,caseyrollins/osf.io,brianjgeiger/osf.io,erinspace/osf.io,monikagrabowska/osf.io,SSJohns/osf.io,chennan47/osf.io,rdhyee/osf.io,CenterForOpenScience/osf.io,chennan47/osf.io,TomBaxter/osf.io,cwisecarver/osf.io,pattisdr/osf.io,TomBaxter/osf.io,sloria/osf.io,sloria/osf.io,CenterForOpenScience/osf.io,amyshi188/osf.io,emetsger/osf.io,binoculars/osf.io,Nesiehr/osf.io,zamattiac/osf.io,kwierman/osf.io,mluo613/osf.io,icereval/osf.io,hmoco/osf.io,saradbowman/osf.io,caseyrollins/osf.io,mfraezz/osf.io,caneruguz/osf.io,felliott/osf.io,mluo613/osf.io,rdhyee/osf.io,emetsger/osf.io,Nesiehr/osf.io,alexschiller/osf.io,cslzchen/osf.io,hmoco/osf.io,Nesiehr/osf.io,kwierman/osf.io,chrisseto/osf.io,jnayak1/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,felliott/osf.io,acshi/osf.io,sloria/osf.io,amyshi188/osf.io,mfraezz/osf.io,adlius/osf.io,HalcyonChimera/osf.io,felliott/osf.io,laurenrevere/osf.io,mluo613/osf.io,caseyrollins/osf.io,aaxelb/osf.io,kwierman/osf.io,monikagrabowska/osf.io,mluke93/osf.io,alexschiller/osf.io,Johnetordoff/osf.io,icereval/osf.io,mattclark/osf.io,cslzchen/osf.io,binoculars/osf.io,HalcyonChimera/osf.io,abought/osf.io,icereval/osf.io,pattisdr/osf.io,DanielSBrown/osf.io,chrisseto/osf.io,brianjgeiger/osf.io,acshi/osf.io,cwisecarver/osf.io,cwisecarver/osf.io,mluke93/osf.io,Johnetordoff/osf.io
--- +++ @@ -30,7 +30,6 @@ return obj._id def get_detail_url(self, obj): - import ipdb; ipdb.set_trace() return '{}/identifiers/{}'.format(obj.absolute_api_v2_url, obj._id) def self_url(self, obj):
b375210cf7c6d6d327af61206b6ab36aaaeec6e0
posts/admin.py
posts/admin.py
from django.contrib import admin from reversion import VersionAdmin from base.admin import PrettyFilterMixin, RestrictedCompetitionAdminMixin from base.util import admin_commentable, editonly_fieldsets from .models import Post # Reversion-enabled Admin for problems @admin_commentable @editonly_fieldsets class PostAdmin(RestrictedCompetitionAdminMixin, VersionAdmin): list_display = ( 'title', 'published', 'get_sites', 'added_by', 'added_at', ) list_filter = ( 'published', 'added_at', 'added_by' ) search_fields = ( 'text', 'title' ) readonly_fields = ( 'added_by', 'modified_by', 'added_at', 'modified_at' ) prepopulated_fields = {"slug": ("title",)} fieldsets = ( (None, { 'fields': ('title', 'slug', 'text', 'sites', 'published', 'gallery') }), ) editonly_fieldsets = ( ('Details', { 'classes': ('grp-collapse', 'grp-closed'), 'fields': ('added_by', 'modified_by', 'added_at', 'modified_at') }), ) class Media: js = [ 'grappelli/tinymce/jscripts/tiny_mce/tiny_mce.js', 'grappelli/tinymce_setup/tinymce_setup.js', ] # Register to the admin site admin.site.register(Post, PostAdmin)
from django.contrib import admin from reversion import VersionAdmin from base.admin import PrettyFilterMixin, RestrictedCompetitionAdminMixin from base.util import admin_commentable, editonly_fieldsets from .models import Post # Reversion-enabled Admin for problems @admin_commentable @editonly_fieldsets class PostAdmin(RestrictedCompetitionAdminMixin, VersionAdmin): list_display = ( 'title', 'published', 'get_sites', 'added_by', 'added_at', ) list_filter = ( 'published', 'sites', 'added_at', 'added_by' ) search_fields = ( 'text', 'title' ) readonly_fields = ( 'added_by', 'modified_by', 'added_at', 'modified_at' ) prepopulated_fields = {"slug": ("title",)} fieldsets = ( (None, { 'fields': ('title', 'slug', 'text', 'sites', 'published', 'gallery') }), ) editonly_fieldsets = ( ('Details', { 'classes': ('grp-collapse', 'grp-closed'), 'fields': ('added_by', 'modified_by', 'added_at', 'modified_at') }), ) class Media: js = [ 'grappelli/tinymce/jscripts/tiny_mce/tiny_mce.js', 'grappelli/tinymce_setup/tinymce_setup.js', ] # Register to the admin site admin.site.register(Post, PostAdmin)
Add ability to filter posts by site
posts: Add ability to filter posts by site
Python
mit
rtrembecky/roots,tbabej/roots,rtrembecky/roots,tbabej/roots,rtrembecky/roots,matus-stehlik/roots,matus-stehlik/roots,tbabej/roots,matus-stehlik/roots
--- +++ @@ -23,6 +23,7 @@ list_filter = ( 'published', + 'sites', 'added_at', 'added_by' )
cd201b193ae71c82f006d9532f926bbc49b6fce9
datacommons/__init__.py
datacommons/__init__.py
# Copyright 2017 Google Inc. # # 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 datacommons import Client
# Copyright 2017 Google Inc. # # 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 .datacommons import Client
Fix relative import that does not work with py 3.
Fix relative import that does not work with py 3.
Python
apache-2.0
datacommonsorg/api-python,datacommonsorg/api-python
--- +++ @@ -11,4 +11,4 @@ # 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 datacommons import Client +from .datacommons import Client
4fde2d2c5ccd82373dab802f731d83cc2d3345df
tests/tests_core/test_core_util.py
tests/tests_core/test_core_util.py
import numpy as np from poliastro.core import util def test_rotation_matrix_x(): result = util.rotation_matrix(0.218, 0) expected = np.array( [[1.0, 0.0, 0.0], [0.0, 0.97633196, -0.21627739], [0.0, 0.21627739, 0.97633196]] ) assert np.allclose(expected, result) def test_rotation_matrix_y(): result = util.rotation_matrix(0.218, 1) expected = np.array( [[0.97633196, 0.0, 0.21627739], [0.0, 1.0, 0.0], [0.21627739, 0.0, 0.97633196]] ) assert np.allclose(expected, result) def test_rotation_matrix_z(): result = util.rotation_matrix(0.218, 2) expected = np.array( [[0.97633196, -0.21627739, 0.0], [0.21627739, 0.97633196, 0.0], [0.0, 0.0, 1.0]] ) assert np.allclose(expected, result)
import numpy as np from poliastro.core import util def test_rotation_matrix_x(): result = util.rotation_matrix(0.218, 0) expected = np.array( [[1.0, 0.0, 0.0], [0.0, 0.97633196, -0.21627739], [0.0, 0.21627739, 0.97633196]] ) assert np.allclose(expected, result) def test_rotation_matrix_y(): result = util.rotation_matrix(0.218, 1) expected = np.array( [[0.97633196, 0.0, 0.21627739], [0.0, 1.0, 0.0], [0.21627739, 0.0, 0.97633196]] ) assert np.allclose(expected, result) def test_rotation_matrix_z(): result = util.rotation_matrix(0.218, 2) expected = np.array( [[0.97633196, -0.21627739, 0.0], [0.21627739, 0.97633196, 0.0], [0.0, 0.0, 1.0]] ) assert np.allclose(expected, result)
Fix line endings in file
Fix line endings in file
Python
mit
Juanlu001/poliastro,Juanlu001/poliastro,Juanlu001/poliastro,poliastro/poliastro
ccdfafcf58fdf3dc1d95acc090445e56267bd4ab
numpy/distutils/__init__.py
numpy/distutils/__init__.py
from __version__ import version as __version__ # Must import local ccompiler ASAP in order to get # customized CCompiler.spawn effective. import ccompiler import unixccompiler from info import __doc__ from npy_pkg_config import * try: import __config__ _INSTALLED = True except ImportError: _INSTALLED = False if _INSTALLED: from numpy.testing import Tester test = Tester().test bench = Tester().bench
import sys if sys.version_info[0] < 3: from __version__ import version as __version__ # Must import local ccompiler ASAP in order to get # customized CCompiler.spawn effective. import ccompiler import unixccompiler from info import __doc__ from npy_pkg_config import * try: import __config__ _INSTALLED = True except ImportError: _INSTALLED = False else: from numpy.distutils.__version__ import version as __version__ # Must import local ccompiler ASAP in order to get # customized CCompiler.spawn effective. import numpy.distutils.ccompiler import numpy.distutils.unixccompiler from numpy.distutils.info import __doc__ from numpy.distutils.npy_pkg_config import * try: import numpy.distutils.__config__ _INSTALLED = True except ImportError: _INSTALLED = False if _INSTALLED: from numpy.testing import Tester test = Tester().test bench = Tester().bench
Fix relative import in top numpy.distutils.
Fix relative import in top numpy.distutils.
Python
bsd-3-clause
stefanv/numpy,madphysicist/numpy,matthew-brett/numpy,githubmlai/numpy,Dapid/numpy,ahaldane/numpy,bringingheavendown/numpy,GrimDerp/numpy,matthew-brett/numpy,KaelChen/numpy,dwf/numpy,ewmoore/numpy,shoyer/numpy,GaZ3ll3/numpy,stefanv/numpy,gfyoung/numpy,mhvk/numpy,numpy/numpy,SunghanKim/numpy,Anwesh43/numpy,rgommers/numpy,MaPePeR/numpy,matthew-brett/numpy,empeeu/numpy,stefanv/numpy,chiffa/numpy,dwillmer/numpy,ajdawson/numpy,jakirkham/numpy,gfyoung/numpy,GaZ3ll3/numpy,chatcannon/numpy,anntzer/numpy,seberg/numpy,rhythmsosad/numpy,bringingheavendown/numpy,stuarteberg/numpy,jakirkham/numpy,dwf/numpy,solarjoe/numpy,WarrenWeckesser/numpy,solarjoe/numpy,behzadnouri/numpy,SiccarPoint/numpy,hainm/numpy,ddasilva/numpy,MaPePeR/numpy,empeeu/numpy,trankmichael/numpy,bmorris3/numpy,trankmichael/numpy,mathdd/numpy,MichaelAquilina/numpy,hainm/numpy,drasmuss/numpy,bertrand-l/numpy,ChristopherHogan/numpy,ekalosak/numpy,musically-ut/numpy,has2k1/numpy,dwillmer/numpy,dwillmer/numpy,andsor/numpy,rajathkumarmp/numpy,AustereCuriosity/numpy,cowlicks/numpy,pbrod/numpy,jankoslavic/numpy,ogrisel/numpy,pdebuyl/numpy,tacaswell/numpy,nguyentu1602/numpy,simongibbons/numpy,ViralLeadership/numpy,joferkington/numpy,jankoslavic/numpy,bmorris3/numpy,kiwifb/numpy,mattip/numpy,shoyer/numpy,shoyer/numpy,chiffa/numpy,jorisvandenbossche/numpy,andsor/numpy,mingwpy/numpy,githubmlai/numpy,pdebuyl/numpy,sonnyhu/numpy,sigma-random/numpy,bmorris3/numpy,mhvk/numpy,larsmans/numpy,abalkin/numpy,mindw/numpy,sinhrks/numpy,drasmuss/numpy,rmcgibbo/numpy,pizzathief/numpy,CMartelLML/numpy,Eric89GXL/numpy,numpy/numpy-refactor,KaelChen/numpy,felipebetancur/numpy,empeeu/numpy,Yusa95/numpy,rhythmsosad/numpy,rudimeier/numpy,bmorris3/numpy,numpy/numpy,NextThought/pypy-numpy,ewmoore/numpy,jschueller/numpy,KaelChen/numpy,kirillzhuravlev/numpy,tynn/numpy,jschueller/numpy,brandon-rhodes/numpy,jonathanunderwood/numpy,naritta/numpy,skymanaditya1/numpy,endolith/numpy,njase/numpy,jonathanunderwood/numpy,pbrod/numpy,mhvk/numpy,dato-code/numpy,charris/numpy,ekalosak/numpy,immerrr/numpy,matthew-brett/numpy,ChanderG/numpy,rajathkumarmp/numpy,joferkington/numpy,stefanv/numpy,Eric89GXL/numpy,ssanderson/numpy,dimasad/numpy,utke1/numpy,madphysicist/numpy,larsmans/numpy,ESSS/numpy,tacaswell/numpy,Linkid/numpy,sinhrks/numpy,rmcgibbo/numpy,chatcannon/numpy,pyparallel/numpy,GrimDerp/numpy,empeeu/numpy,endolith/numpy,ContinuumIO/numpy,BMJHayward/numpy,jschueller/numpy,mhvk/numpy,naritta/numpy,mhvk/numpy,kirillzhuravlev/numpy,AustereCuriosity/numpy,tacaswell/numpy,gfyoung/numpy,ViralLeadership/numpy,madphysicist/numpy,hainm/numpy,sigma-random/numpy,simongibbons/numpy,abalkin/numpy,groutr/numpy,Linkid/numpy,nguyentu1602/numpy,brandon-rhodes/numpy,MSeifert04/numpy,bertrand-l/numpy,grlee77/numpy,dch312/numpy,pelson/numpy,Srisai85/numpy,grlee77/numpy,abalkin/numpy,WarrenWeckesser/numpy,dwf/numpy,jankoslavic/numpy,cjermain/numpy,KaelChen/numpy,Dapid/numpy,mingwpy/numpy,felipebetancur/numpy,mortada/numpy,mingwpy/numpy,numpy/numpy-refactor,CMartelLML/numpy,maniteja123/numpy,nbeaver/numpy,githubmlai/numpy,rhythmsosad/numpy,pizzathief/numpy,rajathkumarmp/numpy,njase/numpy,ekalosak/numpy,dch312/numpy,cowlicks/numpy,MichaelAquilina/numpy,rherault-insa/numpy,stuarteberg/numpy,SunghanKim/numpy,SiccarPoint/numpy,stuarteberg/numpy,dato-code/numpy,naritta/numpy,WarrenWeckesser/numpy,trankmichael/numpy,tdsmith/numpy,naritta/numpy,mwiebe/numpy,seberg/numpy,rgommers/numpy,CMartelLML/numpy,pyparallel/numpy,embray/numpy,ogrisel/numpy,MSeifert04/numpy,Anwesh43/numpy,ContinuumIO/numpy,pelson/numpy,skymanaditya1/numpy,WillieMaddox/numpy,rgommers/numpy,dwillmer/numpy,SiccarPoint/numpy,kirillzhuravlev/numpy,endolith/numpy,MaPePeR/numpy,argriffing/numpy,MichaelAquilina/numpy,pbrod/numpy,ogrisel/numpy,seberg/numpy,jakirkham/numpy,nguyentu1602/numpy,rherault-insa/numpy,ahaldane/numpy,astrofrog/numpy,trankmichael/numpy,mathdd/numpy,rudimeier/numpy,rhythmsosad/numpy,ChanderG/numpy,skwbc/numpy,nbeaver/numpy,maniteja123/numpy,mathdd/numpy,embray/numpy,AustereCuriosity/numpy,ahaldane/numpy,seberg/numpy,SiccarPoint/numpy,solarjoe/numpy,mattip/numpy,mwiebe/numpy,b-carter/numpy,ewmoore/numpy,simongibbons/numpy,BMJHayward/numpy,ContinuumIO/numpy,b-carter/numpy,rmcgibbo/numpy,leifdenby/numpy,MSeifert04/numpy,cjermain/numpy,dato-code/numpy,utke1/numpy,mortada/numpy,leifdenby/numpy,hainm/numpy,leifdenby/numpy,Srisai85/numpy,astrofrog/numpy,utke1/numpy,dimasad/numpy,andsor/numpy,sonnyhu/numpy,pbrod/numpy,charris/numpy,nguyentu1602/numpy,larsmans/numpy,Yusa95/numpy,madphysicist/numpy,simongibbons/numpy,drasmuss/numpy,matthew-brett/numpy,kiwifb/numpy,chiffa/numpy,has2k1/numpy,felipebetancur/numpy,MaPePeR/numpy,pelson/numpy,felipebetancur/numpy,mortada/numpy,nbeaver/numpy,ekalosak/numpy,astrofrog/numpy,shoyer/numpy,pizzathief/numpy,Anwesh43/numpy,BabeNovelty/numpy,rmcgibbo/numpy,Anwesh43/numpy,rajathkumarmp/numpy,Yusa95/numpy,maniteja123/numpy,charris/numpy,ChristopherHogan/numpy,ddasilva/numpy,gmcastil/numpy,njase/numpy,musically-ut/numpy,pizzathief/numpy,moreati/numpy,ChristopherHogan/numpy,numpy/numpy,mindw/numpy,NextThought/pypy-numpy,pyparallel/numpy,jonathanunderwood/numpy,mwiebe/numpy,WillieMaddox/numpy,kiwifb/numpy,BabeNovelty/numpy,SunghanKim/numpy,dwf/numpy,grlee77/numpy,astrofrog/numpy,ogrisel/numpy,astrofrog/numpy,numpy/numpy-refactor,sigma-random/numpy,kirillzhuravlev/numpy,CMartelLML/numpy,behzadnouri/numpy,GaZ3ll3/numpy,moreati/numpy,Srisai85/numpy,jorisvandenbossche/numpy,jschueller/numpy,WarrenWeckesser/numpy,cowlicks/numpy,groutr/numpy,joferkington/numpy,GrimDerp/numpy,ewmoore/numpy,rherault-insa/numpy,argriffing/numpy,musically-ut/numpy,BMJHayward/numpy,jakirkham/numpy,ogrisel/numpy,pbrod/numpy,embray/numpy,ewmoore/numpy,WillieMaddox/numpy,bertrand-l/numpy,dimasad/numpy,ssanderson/numpy,ESSS/numpy,SunghanKim/numpy,has2k1/numpy,jankoslavic/numpy,andsor/numpy,skwbc/numpy,ESSS/numpy,ajdawson/numpy,jorisvandenbossche/numpy,stuarteberg/numpy,GaZ3ll3/numpy,Srisai85/numpy,ssanderson/numpy,ddasilva/numpy,mingwpy/numpy,grlee77/numpy,argriffing/numpy,tynn/numpy,mortada/numpy,tdsmith/numpy,gmcastil/numpy,dwf/numpy,Eric89GXL/numpy,tdsmith/numpy,tynn/numpy,GrimDerp/numpy,dato-code/numpy,ViralLeadership/numpy,immerrr/numpy,dimasad/numpy,NextThought/pypy-numpy,pdebuyl/numpy,BMJHayward/numpy,yiakwy/numpy,sigma-random/numpy,Eric89GXL/numpy,jorisvandenbossche/numpy,yiakwy/numpy,Yusa95/numpy,mindw/numpy,embray/numpy,simongibbons/numpy,gmcastil/numpy,jorisvandenbossche/numpy,anntzer/numpy,moreati/numpy,MSeifert04/numpy,MSeifert04/numpy,ahaldane/numpy,Dapid/numpy,anntzer/numpy,skymanaditya1/numpy,pdebuyl/numpy,tdsmith/numpy,githubmlai/numpy,WarrenWeckesser/numpy,ChanderG/numpy,mathdd/numpy,mattip/numpy,Linkid/numpy,BabeNovelty/numpy,cjermain/numpy,pelson/numpy,mindw/numpy,brandon-rhodes/numpy,behzadnouri/numpy,dch312/numpy,ajdawson/numpy,sonnyhu/numpy,mattip/numpy,sinhrks/numpy,chatcannon/numpy,yiakwy/numpy,groutr/numpy,rudimeier/numpy,anntzer/numpy,MichaelAquilina/numpy,immerrr/numpy,grlee77/numpy,larsmans/numpy,madphysicist/numpy,stefanv/numpy,ChanderG/numpy,shoyer/numpy,immerrr/numpy,numpy/numpy-refactor,numpy/numpy,musically-ut/numpy,ajdawson/numpy,ahaldane/numpy,embray/numpy,brandon-rhodes/numpy,joferkington/numpy,charris/numpy,endolith/numpy,rudimeier/numpy,pizzathief/numpy,pelson/numpy,cowlicks/numpy,numpy/numpy-refactor,skymanaditya1/numpy,yiakwy/numpy,has2k1/numpy,BabeNovelty/numpy,NextThought/pypy-numpy,jakirkham/numpy,bringingheavendown/numpy,sonnyhu/numpy,b-carter/numpy,Linkid/numpy,ChristopherHogan/numpy,rgommers/numpy,sinhrks/numpy,dch312/numpy,cjermain/numpy,skwbc/numpy
--- +++ @@ -1,19 +1,35 @@ +import sys -from __version__ import version as __version__ +if sys.version_info[0] < 3: + from __version__ import version as __version__ + # Must import local ccompiler ASAP in order to get + # customized CCompiler.spawn effective. + import ccompiler + import unixccompiler -# Must import local ccompiler ASAP in order to get -# customized CCompiler.spawn effective. -import ccompiler -import unixccompiler + from info import __doc__ + from npy_pkg_config import * -from info import __doc__ -from npy_pkg_config import * + try: + import __config__ + _INSTALLED = True + except ImportError: + _INSTALLED = False +else: + from numpy.distutils.__version__ import version as __version__ + # Must import local ccompiler ASAP in order to get + # customized CCompiler.spawn effective. + import numpy.distutils.ccompiler + import numpy.distutils.unixccompiler -try: - import __config__ - _INSTALLED = True -except ImportError: - _INSTALLED = False + from numpy.distutils.info import __doc__ + from numpy.distutils.npy_pkg_config import * + + try: + import numpy.distutils.__config__ + _INSTALLED = True + except ImportError: + _INSTALLED = False if _INSTALLED: from numpy.testing import Tester
fa0821f49e26f508971c2f3c97b8696c98901e49
opensimplex_test.py
opensimplex_test.py
from PIL import Image # Depends on the Pillow lib from opensimplex import OpenSimplexNoise WIDTH = 512 HEIGHT = 512 FEATURE_SIZE = 24 def main(): simplex = OpenSimplexNoise() im = Image.new('L', (WIDTH, HEIGHT)) for y in range(0, HEIGHT): for x in range(0, WIDTH): #value = simplex.noise2d(x / FEATURE_SIZE, y / FEATURE_SIZE) value = simplex.noise2d(x * 0.05, y * 0.05) color = int((value + 1) * 128) im.putpixel((x, y), color) im.show() if __name__ == '__main__': main()
from PIL import Image # Depends on the Pillow lib from opensimplex import OpenSimplexNoise WIDTH = 512 HEIGHT = 512 FEATURE_SIZE = 24 def main(): simplex = OpenSimplexNoise() im = Image.new('L', (WIDTH, HEIGHT)) for y in range(0, HEIGHT): for x in range(0, WIDTH): #value = simplex.noise2d(x / FEATURE_SIZE, y / FEATURE_SIZE) value = simplex.noise2d(x * 0.05, y * 0.05) color = int((value + 1) * 128) im.putpixel((x, y), color) im.show() im.save('noise.png') if __name__ == '__main__': main()
Save the generated noise image.
Save the generated noise image.
Python
mit
lmas/opensimplex,antiface/opensimplex
--- +++ @@ -19,6 +19,7 @@ im.putpixel((x, y), color) im.show() + im.save('noise.png') if __name__ == '__main__': main()
6da81cd09aa39d92e39b06bb2a65e1d1b1306b35
config.py
config.py
import os class Config: SECRET_KEY = os.environ.get('SECRET_KEY') SQLALCHEMY_COMMIT_ON_TEARDOWN = True @staticmethod def init_app(app): pass class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') class TestingConfig(Config): TESTING = True if os.environ.get('TEST_DATABASE_URL'): SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') else: basedir = os.path.abspath(os.path.dirname(__file__)) SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'data-test.sqlite') class ProductionConfig(Config): SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') @classmethod def init_app(cls, app): pass class HerokuConfig(ProductionConfig): @classmethod def init_app(cls, app): ProductionConfig.init_app(app) # # log to stderr # import logging # from logging import StreamHandler # file_handler = StreamHandler() # file_handler.setLevel(logging.WARNING) # app.logger.addHandler(file_handler) config = { 'development': DevelopmentConfig, 'testing': TestingConfig, 'production': ProductionConfig, 'heroku': HerokuConfig, 'default': DevelopmentConfig }
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.environ.get('SECRET_KEY') SQLALCHEMY_COMMIT_ON_TEARDOWN = True @staticmethod def init_app(app): pass class DevelopmentConfig(Config): DEBUG = True if os.environ.get('DEV_DATABASE_URL'): SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') else: SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite') class TestingConfig(Config): TESTING = True if os.environ.get('TEST_DATABASE_URL'): SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') else: SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'data-test.sqlite') class ProductionConfig(Config): SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') @classmethod def init_app(cls, app): pass class HerokuConfig(ProductionConfig): @classmethod def init_app(cls, app): ProductionConfig.init_app(app) # # log to stderr # import logging # from logging import StreamHandler # file_handler = StreamHandler() # file_handler.setLevel(logging.WARNING) # app.logger.addHandler(file_handler) config = { 'development': DevelopmentConfig, 'testing': TestingConfig, 'production': ProductionConfig, 'heroku': HerokuConfig, 'default': DevelopmentConfig }
Use sqlite if no DEV_DATABASE specified in development env
Use sqlite if no DEV_DATABASE specified in development env
Python
mit
boltzj/movies-in-sf
--- +++ @@ -1,5 +1,6 @@ import os +basedir = os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.environ.get('SECRET_KEY') @@ -12,7 +13,11 @@ class DevelopmentConfig(Config): DEBUG = True - SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') + + if os.environ.get('DEV_DATABASE_URL'): + SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') + else: + SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite') class TestingConfig(Config): @@ -21,7 +26,6 @@ if os.environ.get('TEST_DATABASE_URL'): SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') else: - basedir = os.path.abspath(os.path.dirname(__file__)) SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'data-test.sqlite')
e8ab72d069633aca71ae60d62ece3c0146289b18
xc7/utils/vivado_output_timing.py
xc7/utils/vivado_output_timing.py
""" Utility for generating TCL script to output timing information from a design checkpoint. """ import argparse def create_runme(f_out, args): print( """ report_timing_summary source {util_tcl} write_timing_info timing_{name}.json5 """.format(name=args.name, util_tcl=args.util_tcl), file=f_out ) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--name', required=True) parser.add_argument('--util_tcl', required=True) parser.add_argument('--output_tcl', required=True) args = parser.parse_args() with open(args.output_tcl, 'w') as f: create_runme(f, args) if __name__ == "__main__": main()
""" Utility for generating TCL script to output timing information from a design checkpoint. """ import argparse def create_output_timing(f_out, args): print( """ source {util_tcl} write_timing_info timing_{name}.json5 report_timing_summary """.format(name=args.name, util_tcl=args.util_tcl), file=f_out ) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--name', required=True) parser.add_argument('--util_tcl', required=True) parser.add_argument('--output_tcl', required=True) args = parser.parse_args() with open(args.output_tcl, 'w') as f: create_output_timing(f, args) if __name__ == "__main__": main()
Correct function name and put report_timing_summary at end of script.
Correct function name and put report_timing_summary at end of script. Signed-off-by: Keith Rothman <1bc19627a439baf17510dc2d0b2d250c96d445a5@users.noreply.github.com>
Python
isc
SymbiFlow/symbiflow-arch-defs,SymbiFlow/symbiflow-arch-defs
--- +++ @@ -4,13 +4,13 @@ import argparse -def create_runme(f_out, args): +def create_output_timing(f_out, args): print( """ -report_timing_summary - source {util_tcl} write_timing_info timing_{name}.json5 + +report_timing_summary """.format(name=args.name, util_tcl=args.util_tcl), file=f_out ) @@ -25,7 +25,7 @@ args = parser.parse_args() with open(args.output_tcl, 'w') as f: - create_runme(f, args) + create_output_timing(f, args) if __name__ == "__main__":
3bd8354db0931e8721e397a32bf696b023e692b7
test/664-raceway.py
test/664-raceway.py
# https://www.openstreetmap.org/way/28825404 assert_has_feature( 16, 10476, 25242, 'roads', { 'id': 28825404, 'kind': 'minor_road', 'highway': 'raceway' }) # Thunderoad Speedway Go-carts https://www.openstreetmap.org/way/59440900 assert_has_feature( 16, 10516, 25247, 'roads', { 'id': 59440900, 'kind': 'minor_road', 'highway': 'raceway' })
# https://www.openstreetmap.org/way/28825404 assert_has_feature( 16, 10476, 25242, 'roads', { 'id': 28825404, 'kind': 'minor_road', 'highway': 'raceway' }) # https://www.openstreetmap.org/way/59440900 # Thunderoad Speedway Go-carts assert_has_feature( 16, 10516, 25247, 'roads', { 'id': 59440900, 'kind': 'minor_road', 'highway': 'raceway' })
Put weblink on separate line
Put weblink on separate line
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
--- +++ @@ -3,7 +3,8 @@ 16, 10476, 25242, 'roads', { 'id': 28825404, 'kind': 'minor_road', 'highway': 'raceway' }) -# Thunderoad Speedway Go-carts https://www.openstreetmap.org/way/59440900 +# https://www.openstreetmap.org/way/59440900 +# Thunderoad Speedway Go-carts assert_has_feature( 16, 10516, 25247, 'roads', { 'id': 59440900, 'kind': 'minor_road', 'highway': 'raceway' })
0321d00276d803d5abee63f2a899681bd569235a
noisytweets/keywordsmanager.py
noisytweets/keywordsmanager.py
import time from noisytweets.tweetstreamer import TweetStreamer class KeywordsManager: max_keywords = 100 ping_timeout = 30 def __init__(self): self._keywords_tracking = [] self._keywords_info = {} self._tweetstreamer = TweetStreamer() def _get_dead_keywords(): dead_keywords = [] for keyword in self._keywords_tracking: if time.time() - self._keywords_info['last_ping'] > ping_timeout: dead_keywords.append(keyword) return dead_keywords def _untrack_keyword(keyword): if keyword in self._keywords_tracking: self._keywords_tracking.remove(keyword) del self._keywords_info[keyword] def ping_keyword(self, keyword): if keyword in self._keywords_tracking: self._keywords_info[keyword]['last_ping'] = time.time() # TODO: respect max_keywords self._keywords_tracking.append(keyword) self._keywords_info[keyword] = {} self._keywords_info[keyword]['last_ping'] = time.time() self._tweetstreamer.update_keywords_tracking(self._keywords_tracking)
import time from noisytweets.tweetstreamer import TweetStreamer class KeywordsManager: max_keywords = 100 ping_timeout = 30 def __init__(self): self._keywords_tracking = [] self._keywords_info = {} self._tweetstreamer = TweetStreamer() def _get_dead_keywords(): dead_keywords = [] for keyword in self._keywords_tracking: if time.time() - self._keywords_info['last_ping'] > ping_timeout: dead_keywords.append(keyword) return dead_keywords def _untrack_keyword(keyword): if keyword in self._keywords_tracking: self._keywords_tracking.remove(keyword) del self._keywords_info[keyword] def ping_keyword(self, keyword): if keyword in self._keywords_tracking: self._keywords_info[keyword]['last_ping'] = time.time() return # TODO: respect max_keywords self._keywords_tracking.append(keyword) self._keywords_info[keyword] = {} self._keywords_info[keyword]['last_ping'] = time.time() self._tweetstreamer.update_keywords_tracking(self._keywords_tracking)
Return if keyword is already being tracked.
Return if keyword is already being tracked.
Python
agpl-3.0
musalbas/listentotwitter,musalbas/listentotwitter,musalbas/listentotwitter
--- +++ @@ -30,6 +30,7 @@ def ping_keyword(self, keyword): if keyword in self._keywords_tracking: self._keywords_info[keyword]['last_ping'] = time.time() + return # TODO: respect max_keywords
998ab6f457a04ab24bbe062d9704242a207356fb
numpy/setupscons.py
numpy/setupscons.py
#!/usr/bin/env python def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('numpy',parent_package,top_path, setup_name = 'setupscons.py') config.add_subpackage('distutils') config.add_subpackage('testing') config.add_subpackage('f2py') config.add_subpackage('core') config.add_subpackage('lib') config.add_subpackage('oldnumeric') config.add_subpackage('numarray') config.add_subpackage('fft') config.add_subpackage('linalg') config.add_subpackage('random') config.add_subpackage('ma') config.add_data_dir('doc') config.add_data_dir('tests') config.scons_make_config_py() # installs __config__.py return config if __name__ == '__main__': print 'This is the wrong setup.py file to run'
#!/usr/bin/env python from os.path import join as pjoin def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration from numpy.distutils.misc_util import scons_generate_config_py pkgname = 'numpy' config = Configuration(pkgname,parent_package,top_path, setup_name = 'setupscons.py') config.add_subpackage('distutils') config.add_subpackage('testing') config.add_subpackage('f2py') config.add_subpackage('core') config.add_subpackage('lib') config.add_subpackage('oldnumeric') config.add_subpackage('numarray') config.add_subpackage('fft') config.add_subpackage('linalg') config.add_subpackage('random') config.add_subpackage('ma') config.add_data_dir('doc') config.add_data_dir('tests') def add_config(*args, **kw): # Generate __config__, handle inplace issues. if kw['scons_cmd'].inplace: target = pjoin(kw['pkg_name'], '__config__.py') else: target = pjoin(kw['scons_cmd'].build_lib, kw['pkg_name'], '__config__.py') scons_generate_config_py(target) config.add_sconscript(None, post_hook = add_config) return config if __name__ == '__main__': print 'This is the wrong setup.py file to run'
Handle inplace generation of __config__.
Handle inplace generation of __config__. git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@5583 94b884b6-d6fd-0310-90d3-974f1d3f35e1
Python
bsd-3-clause
efiring/numpy-work,Ademan/NumPy-GSoC,jasonmccampbell/numpy-refactor-sprint,efiring/numpy-work,illume/numpy3k,Ademan/NumPy-GSoC,illume/numpy3k,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,chadnetzer/numpy-gaurdro,chadnetzer/numpy-gaurdro,efiring/numpy-work,jasonmccampbell/numpy-refactor-sprint,teoliphant/numpy-refactor,Ademan/NumPy-GSoC,teoliphant/numpy-refactor,efiring/numpy-work,chadnetzer/numpy-gaurdro,illume/numpy3k,illume/numpy3k,chadnetzer/numpy-gaurdro,jasonmccampbell/numpy-refactor-sprint,teoliphant/numpy-refactor,teoliphant/numpy-refactor,Ademan/NumPy-GSoC
--- +++ @@ -1,8 +1,12 @@ #!/usr/bin/env python +from os.path import join as pjoin def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration - config = Configuration('numpy',parent_package,top_path, setup_name = 'setupscons.py') + from numpy.distutils.misc_util import scons_generate_config_py + + pkgname = 'numpy' + config = Configuration(pkgname,parent_package,top_path, setup_name = 'setupscons.py') config.add_subpackage('distutils') config.add_subpackage('testing') config.add_subpackage('f2py') @@ -16,7 +20,16 @@ config.add_subpackage('ma') config.add_data_dir('doc') config.add_data_dir('tests') - config.scons_make_config_py() # installs __config__.py + + def add_config(*args, **kw): + # Generate __config__, handle inplace issues. + if kw['scons_cmd'].inplace: + target = pjoin(kw['pkg_name'], '__config__.py') + else: + target = pjoin(kw['scons_cmd'].build_lib, kw['pkg_name'], '__config__.py') + scons_generate_config_py(target) + config.add_sconscript(None, post_hook = add_config) + return config if __name__ == '__main__':
7644ed0e5f0fb3f57798ae65ecd87488d6a7cee1
sync_watchdog.py
sync_watchdog.py
from tapiriik.database import db, close_connections from tapiriik.sync import SyncStep import os import signal import socket from datetime import timedelta, datetime print("Sync watchdog run at %s" % datetime.now()) host = socket.gethostname() for worker in db.sync_workers.find({"Host": host}): # Does the process still exist? alive = True try: os.kill(worker["Process"], 0) except os.error: print("%s is no longer alive" % worker) alive = False # Has it been stalled for too long? if worker["State"] == SyncStep.List: timeout = timedelta(minutes=45) # This can take a loooooooong time else: timeout = timedelta(minutes=10) # But everything else shouldn't if alive and worker["Heartbeat"] < datetime.utcnow() - timeout: print("%s timed out" % worker) os.kill(worker["Process"], signal.SIGKILL) alive = False # Clear it from the database if it's not alive. if not alive: db.sync_workers.remove({"_id": worker["_id"]}) # Unlock users attached to it. for user in db.users.find({"SynchronizationWorker": worker["Process"], "SynchronizationHost": host}): print("\t Unlocking %s" % user["_id"]) db.users.update({"SynchronizationWorker": worker["Process"], "SynchronizationHost": host}, {"$unset":{"SynchronizationWorker": True}}, multi=True) close_connections()
from tapiriik.database import db, close_connections from tapiriik.sync import SyncStep import os import signal import socket from datetime import timedelta, datetime print("Sync watchdog run at %s" % datetime.now()) host = socket.gethostname() for worker in db.sync_workers.find({"Host": host}): # Does the process still exist? alive = True try: os.kill(worker["Process"], 0) except os.error: print("%s is no longer alive" % worker) alive = False # Has it been stalled for too long? if worker["State"] == SyncStep.List: timeout = timedelta(minutes=45) # This can take a loooooooong time else: timeout = timedelta(minutes=10) # But everything else shouldn't if alive and worker["Heartbeat"] < datetime.utcnow() - timeout: print("%s timed out" % worker) os.kill(worker["Process"], signal.SIGKILL) alive = False # Clear it from the database if it's not alive. if not alive: db.sync_workers.remove({"_id": worker["_id"]}) close_connections()
Remove locking logic from sync watchdog
Remove locking logic from sync watchdog
Python
apache-2.0
abs0/tapiriik,marxin/tapiriik,cgourlay/tapiriik,cheatos101/tapiriik,brunoflores/tapiriik,olamy/tapiriik,abs0/tapiriik,abs0/tapiriik,cmgrote/tapiriik,marxin/tapiriik,cheatos101/tapiriik,mjnbike/tapiriik,cheatos101/tapiriik,campbellr/tapiriik,gavioto/tapiriik,abhijit86k/tapiriik,cpfair/tapiriik,dmschreiber/tapiriik,niosus/tapiriik,cgourlay/tapiriik,cpfair/tapiriik,cmgrote/tapiriik,cpfair/tapiriik,gavioto/tapiriik,mjnbike/tapiriik,cmgrote/tapiriik,dlenski/tapiriik,gavioto/tapiriik,campbellr/tapiriik,marxin/tapiriik,brunoflores/tapiriik,mduggan/tapiriik,cgourlay/tapiriik,brunoflores/tapiriik,dmschreiber/tapiriik,dlenski/tapiriik,niosus/tapiriik,cheatos101/tapiriik,niosus/tapiriik,abhijit86k/tapiriik,abhijit86k/tapiriik,campbellr/tapiriik,olamy/tapiriik,olamy/tapiriik,cmgrote/tapiriik,mduggan/tapiriik,gavioto/tapiriik,mjnbike/tapiriik,mduggan/tapiriik,dlenski/tapiriik,niosus/tapiriik,dlenski/tapiriik,mduggan/tapiriik,dmschreiber/tapiriik,abs0/tapiriik,marxin/tapiriik,cgourlay/tapiriik,campbellr/tapiriik,olamy/tapiriik,brunoflores/tapiriik,dmschreiber/tapiriik,cpfair/tapiriik,mjnbike/tapiriik,abhijit86k/tapiriik
--- +++ @@ -32,9 +32,5 @@ # Clear it from the database if it's not alive. if not alive: db.sync_workers.remove({"_id": worker["_id"]}) - # Unlock users attached to it. - for user in db.users.find({"SynchronizationWorker": worker["Process"], "SynchronizationHost": host}): - print("\t Unlocking %s" % user["_id"]) - db.users.update({"SynchronizationWorker": worker["Process"], "SynchronizationHost": host}, {"$unset":{"SynchronizationWorker": True}}, multi=True) close_connections()
67b83335956adc0892f32a21099e199dd2753a5d
todoman/__init__.py
todoman/__init__.py
from todoman import version __version__ = version.version __documentation__ = "https://todoman.rtfd.org/en/latest/"
from todoman import version # type: ignore __version__ = version.version __documentation__ = "https://todoman.rtfd.org/en/latest/"
Make mypy ignore auto-generated file
Make mypy ignore auto-generated file It won't be present in CI, and may not be present when developing.
Python
isc
pimutils/todoman
--- +++ @@ -1,4 +1,4 @@ -from todoman import version +from todoman import version # type: ignore __version__ = version.version __documentation__ = "https://todoman.rtfd.org/en/latest/"
4ad6f599cdcebc34e9f32a5ab8eaf44a3845ed21
pinry/pins/forms.py
pinry/pins/forms.py
from django import forms from .models import Pin class PinForm(forms.ModelForm): url = forms.CharField(required=False) image = forms.ImageField(label='or Upload', required=False) class Meta: model = Pin fields = ['url', 'image', 'description', 'tags'] def clean(self): cleaned_data = super(PinForm, self).clean() url = cleaned_data.get('url') image = cleaned_data.get('image') if url: image_file_types = ['png', 'gif', 'jpeg', 'jpg'] if not url.split('.')[-1].lower() in image_file_types: raise forms.ValidationError("Requested URL is not an image file. " "Only images are currently supported.") try: Pin.objects.get(url=url) raise forms.ValidationError("URL has already been pinned!") except Pin.DoesNotExist: pass protocol = url.split(':')[0] if protocol not in ['http', 'https']: raise forms.ValidationError("Currently only support HTTP and " "HTTPS protocols, please be sure " "you include this in the URL.") try: Pin.objects.get(url=url) raise forms.ValidationError("URL has already been pinned!") except Pin.DoesNotExist: pass elif image: pass else: raise forms.ValidationError("Need either a URL or Upload.") return cleaned_data
from django import forms from .models import Pin class PinForm(forms.ModelForm): url = forms.CharField(required=False) image = forms.ImageField(label='or Upload', required=False) _errors = { 'not_image': 'Requested URL is not an image file. Only images are currently supported.', 'pinned': 'URL has already been pinned!', 'protocol': 'Currently only support HTTP and HTTPS protocols, please be sure you include this in the URL.', 'nothing': 'Need either a URL or Upload', } class Meta: model = Pin fields = ['url', 'image', 'description', 'tags'] def clean(self): cleaned_data = super(PinForm, self).clean() url = cleaned_data.get('url') image = cleaned_data.get('image') if url: image_file_types = ['png', 'gif', 'jpeg', 'jpg'] if not url.split('.')[-1].lower() in image_file_types: raise forms.ValidationError(self._errors['not_image']) protocol = url.split(':')[0] if protocol not in ['http', 'https']: raise forms.ValidationError(self._errors['protocol']) try: Pin.objects.get(url=url) raise forms.ValidationError(self._errors['pinned']) except Pin.DoesNotExist: pass elif image: pass else: raise forms.ValidationError(self._errors['nothing']) return cleaned_data
Move ValidationError messages to a dictionary that can be accessed from PinForm.clean
Move ValidationError messages to a dictionary that can be accessed from PinForm.clean
Python
bsd-2-clause
supervacuo/pinry,Stackato-Apps/pinry,wangjun/pinry,dotcom900825/xishi,QLGu/pinry,pinry/pinry,lapo-luchini/pinry,dotcom900825/xishi,supervacuo/pinry,MSylvia/pinry,Stackato-Apps/pinry,lapo-luchini/pinry,wangjun/pinry,QLGu/pinry,pinry/pinry,MSylvia/pinry,MSylvia/pinry,pinry/pinry,Stackato-Apps/pinry,pinry/pinry,supervacuo/pinry,QLGu/pinry,rafirosenberg/pinry,rafirosenberg/pinry,wangjun/pinry,lapo-luchini/pinry,lapo-luchini/pinry
--- +++ @@ -6,6 +6,13 @@ class PinForm(forms.ModelForm): url = forms.CharField(required=False) image = forms.ImageField(label='or Upload', required=False) + + _errors = { + 'not_image': 'Requested URL is not an image file. Only images are currently supported.', + 'pinned': 'URL has already been pinned!', + 'protocol': 'Currently only support HTTP and HTTPS protocols, please be sure you include this in the URL.', + 'nothing': 'Need either a URL or Upload', + } class Meta: model = Pin @@ -20,26 +27,18 @@ if url: image_file_types = ['png', 'gif', 'jpeg', 'jpg'] if not url.split('.')[-1].lower() in image_file_types: - raise forms.ValidationError("Requested URL is not an image file. " - "Only images are currently supported.") + raise forms.ValidationError(self._errors['not_image']) + protocol = url.split(':')[0] + if protocol not in ['http', 'https']: + raise forms.ValidationError(self._errors['protocol']) try: Pin.objects.get(url=url) - raise forms.ValidationError("URL has already been pinned!") - except Pin.DoesNotExist: - pass - protocol = url.split(':')[0] - if protocol not in ['http', 'https']: - raise forms.ValidationError("Currently only support HTTP and " - "HTTPS protocols, please be sure " - "you include this in the URL.") - try: - Pin.objects.get(url=url) - raise forms.ValidationError("URL has already been pinned!") + raise forms.ValidationError(self._errors['pinned']) except Pin.DoesNotExist: pass elif image: pass else: - raise forms.ValidationError("Need either a URL or Upload.") + raise forms.ValidationError(self._errors['nothing']) return cleaned_data
b8bad6cda4bdc78d15303002db6687fbae447e51
openacademy/model/openacademy_course.py
openacademy/model/openacademy_course.py
from openerp import models, fields, api class Course(models.Model): _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) # Field reserved to identified name record description = fields.Text(string='Description') responsible_id = fields.Many2one('res.users', ondelete='set null', string="Responsible", index=True) session_ids = fields.One2many('openacademy.session','course_id', string="Sessions") _sql_constraints = [ ('name_description_check', 'CHECK(name != description)', "The title of the course should not be the description"), ('name_unique', 'UNIQUE(name)', "The course title must be unique"), ]
from openerp import models, fields, api class Course(models.Model): _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) # Field reserved to identified name record description = fields.Text(string='Description') responsible_id = fields.Many2one('res.users', ondelete='set null', string="Responsible", index=True) session_ids = fields.One2many('openacademy.session','course_id', string="Sessions") _sql_constraints = [ ('name_description_check', 'CHECK(name != description)', "The title of the course should not be the description"), ('name_unique', 'UNIQUE(name)', "The course title must be unique"), ] @api.one #api.one send default params: cr, uid, id, context def copy(self, default=None): copied_count = self.search_count( [('name', '=like', u"Copy of {}%".format(self.name))]) if not copied_count: new_name = u"Copy of {}".format(self.name) else: new_name = u"Copy of {} ({})".format(self.name, copied_count) default['name'] = new_name return super(Course, self).copy(default)
Modify copy method into inherit
[REF] openacademy: Modify copy method into inherit
Python
apache-2.0
felipejta/openacademy-project_072015
--- +++ @@ -21,3 +21,16 @@ 'UNIQUE(name)', "The course title must be unique"), ] + + @api.one #api.one send default params: cr, uid, id, context + def copy(self, default=None): + + copied_count = self.search_count( + [('name', '=like', u"Copy of {}%".format(self.name))]) + if not copied_count: + new_name = u"Copy of {}".format(self.name) + else: + new_name = u"Copy of {} ({})".format(self.name, copied_count) + + default['name'] = new_name + return super(Course, self).copy(default)
f80bd7dbb1b66f3fec52200ecfbc50d779caca05
src/tmlib/workflow/jterator/args.py
src/tmlib/workflow/jterator/args.py
from tmlib.workflow.args import Argument from tmlib.workflow.args import BatchArguments from tmlib.workflow.args import SubmissionArguments from tmlib.workflow.args import ExtraArguments from tmlib.workflow.registry import batch_args from tmlib.workflow.registry import submission_args from tmlib.workflow.registry import extra_args @batch_args('jterator') class JteratorBatchArguments(BatchArguments): plot = Argument( type=bool, default=False, flag='p', disabled=True, help='whether plotting should be activated' ) @submission_args('jterator') class JteratorSubmissionArguments(SubmissionArguments): pass def get_names_of_existing_pipelines(experiment): '''Gets names of all existing jterator pipelines for a given experiment. Parameters ---------- experiment: tmlib.models.Experiment processed experiment Returns ------- List[str] names of jterator pipelines ''' import os from tmlib.workflow.jterator.project import list_projects return [ os.path.basename(project) for project in list_projects(os.path.join(experiment.workflow_location, 'jterator')) ] @extra_args('jterator') class JteratorExtraArguments(ExtraArguments): pipeline = Argument( type=str, help='name of the pipeline that should be processed', required=True, flag='p', get_choices=get_names_of_existing_pipelines )
from tmlib.workflow.args import Argument from tmlib.workflow.args import BatchArguments from tmlib.workflow.args import SubmissionArguments from tmlib.workflow.args import ExtraArguments from tmlib.workflow.registry import batch_args from tmlib.workflow.registry import submission_args from tmlib.workflow.registry import extra_args @batch_args('jterator') class JteratorBatchArguments(BatchArguments): plot = Argument( type=bool, default=False, flag='p', disabled=True, help='whether plotting should be activated' ) @submission_args('jterator') class JteratorSubmissionArguments(SubmissionArguments): pass def get_names_of_existing_pipelines(experiment): '''Gets names of all existing jterator pipelines for a given experiment. Parameters ---------- experiment: tmlib.models.Experiment processed experiment Returns ------- List[str] names of jterator pipelines ''' import os from tmlib.workflow.jterator.project import list_projects directory = os.path.join(experiment.workflow_location, 'jterator') if not os.path.exists(directory): return [] else: return [ os.path.basename(project) for project in list_projects(directory) ] @extra_args('jterator') class JteratorExtraArguments(ExtraArguments): pipeline = Argument( type=str, help='name of the pipeline that should be processed', required=True, flag='p', get_choices=get_names_of_existing_pipelines )
Fix bug in function that lists existing jterator projects
Fix bug in function that lists existing jterator projects
Python
agpl-3.0
TissueMAPS/TmLibrary,TissueMAPS/TmLibrary,TissueMAPS/TmLibrary,TissueMAPS/TmLibrary,TissueMAPS/TmLibrary
--- +++ @@ -37,11 +37,14 @@ ''' import os from tmlib.workflow.jterator.project import list_projects - return [ - os.path.basename(project) - for project - in list_projects(os.path.join(experiment.workflow_location, 'jterator')) - ] + directory = os.path.join(experiment.workflow_location, 'jterator') + if not os.path.exists(directory): + return [] + else: + return [ + os.path.basename(project) + for project in list_projects(directory) + ] @extra_args('jterator')
86df5fe205e3a913f5048bef3aa29804dd731d4b
docdown/__init__.py
docdown/__init__.py
# -*- coding: utf-8 -*- __author__ = """Jason Emerick""" __email__ = 'jason@mobelux.com' __version__ = '__version__ = '__version__ = '__version__ = '0.2.7''''
# -*- coding: utf-8 -*- __author__ = """Jason Emerick""" __email__ = 'jason@mobelux.com' __version__ = '0.2.7'
Fix (another) syntax error. Thanks, bumpversion
Fix (another) syntax error. Thanks, bumpversion
Python
bsd-3-clause
livio/DocDown-Python,livio/DocDown-Python,livio/DocDown-Python,livio/DocDown-Python,livio/DocDown-Python,livio/DocDown-Python
--- +++ @@ -2,4 +2,4 @@ __author__ = """Jason Emerick""" __email__ = 'jason@mobelux.com' -__version__ = '__version__ = '__version__ = '__version__ = '0.2.7'''' +__version__ = '0.2.7'
7e1d42e6730336296ef3b702eb4cde64ce8410c5
dockerpuller/app.py
dockerpuller/app.py
from flask import Flask from flask import request from flask import jsonify import json import subprocess app = Flask(__name__) config = None @app.route('/', methods=['POST']) def hook_listen(): if request.method == 'POST': token = request.args.get('token') if token == config['token']: hook = request.args.get('hook') if hook: hook_value = config['hooks'].get(hook) if hook_value: #payload = request.get_json() try: subprocess.call(hook_value) return jsonify(success=True), 200 except OSError as e: return jsonify(success=False, error=str(e)), 400 else: return jsonify(success=False, error="Hook not found"), 404 else: return jsonify(success=False, error="Invalid request: missing hook"), 400 else: return jsonify(success=False, error="Invalid token"), 400 def load_config(): with open('config.json') as config_file: return json.load(config_file) if __name__ == '__main__': config = load_config() app.run(host=config['host'], port=config['port'])
from flask import Flask from flask import request from flask import jsonify import json import subprocess app = Flask(__name__) config = None @app.route('/', methods=['POST']) def hook_listen(): if request.method == 'POST': token = request.args.get('token') if token == config['token']: hook = request.args.get('hook') if hook: hook_value = config['hooks'].get(hook) if hook_value: #payload = request.get_json() try: subprocess.call(hook_value) return jsonify(success=True), 200 except OSError as e: return jsonify(success=False, error=str(e)), 400 else: return jsonify(success=False, error="Hook not found"), 404 else: return jsonify(success=False, error="Invalid request: missing hook"), 400 else: return jsonify(success=False, error="Invalid token"), 400 def load_config(): with open('config.json') as config_file: return json.load(config_file) if __name__ == '__main__': config = load_config() app.run(host=config.get('host', 'localhost'), port=config.get('port', 8000))
Define default values for host and port
Define default values for host and port
Python
mit
glowdigitalmedia/docker-puller,nicocoffo/docker-puller,nicocoffo/docker-puller,glowdigitalmedia/docker-puller
--- +++ @@ -37,4 +37,4 @@ if __name__ == '__main__': config = load_config() - app.run(host=config['host'], port=config['port']) + app.run(host=config.get('host', 'localhost'), port=config.get('port', 8000))
9808e97747785c27387ad1ce9ffc3e9a05c80f08
enigma.py
enigma.py
import string class Steckerbrett: def __init__(self): pass class Walzen: def __init__(self): pass class Enigma: def __init__(self): pass def cipher(self, message): pass
import string class Steckerbrett: def __init__(self): pass class Umkehrwalze: def __init__(self, wiring): self.wiring = wiring def encode(self, letter): return self.wiring[string.ascii_uppercase.index(letter)] class Walzen: def __init__(self): pass class Enigma: def __init__(self): pass def cipher(self, message): pass
Create class for the reflectors
Create class for the reflectors
Python
mit
ranisalt/enigma
--- +++ @@ -4,6 +4,14 @@ class Steckerbrett: def __init__(self): pass + + +class Umkehrwalze: + def __init__(self, wiring): + self.wiring = wiring + + def encode(self, letter): + return self.wiring[string.ascii_uppercase.index(letter)] class Walzen:
e7cb98a1006d292a96670a11c807d0bbf9075ebd
scenario/_consts.py
scenario/_consts.py
from collections import OrderedDict ACTORS = list('NRAIOVF') FILE_COMMANDS = ['copy', 'compare'] VERBOSITY = OrderedDict( [ ('RETURN_CODE', 0), ('RESULT' , 1), ('ERROR' , 2), ('EXECUTION' , 3), ('DEBUG' , 4), ]) VERBOSITY_DEFAULT = VERBOSITY['RESULT'] TIMEOUT_DEFAULT = 1
from collections import OrderedDict ACTORS = list('NRAIOVF') FILE_COMMANDS = ['copy', 'compare'] VERBOSITY = OrderedDict( [ ('RETURN_CODE', 0), ('RESULT' , 1), ('ERROR' , 2), ('EXECUTION' , 3), ('DEBUG' , 4), ]) VERBOSITY_DEFAULT = VERBOSITY['RESULT'] TIMEOUT_DEFAULT = 10
Update timeout to 10 seconds
Update timeout to 10 seconds
Python
mit
shlomihod/scenario,shlomihod/scenario,shlomihod/scenario
--- +++ @@ -14,4 +14,4 @@ VERBOSITY_DEFAULT = VERBOSITY['RESULT'] -TIMEOUT_DEFAULT = 1 +TIMEOUT_DEFAULT = 10
f710479e01d50dad03133d76b349398ab11e8675
backend/constants.py
backend/constants.py
# Fill out with value from # https://firebase.corp.google.com/project/trogdors-29fa4/settings/database FIREBASE_SECRET = "ZiD9uLhDnrLq2n416MjWjn0JOrci6H0oGm7bKyVN" FIREBASE_EMAIL = "" ALLEGIANCES = ('horde', 'resistance', 'none') TEST_ENDPOINT = 'http://localhost:8080' PLAYER_VOLUNTEER_ARGS = ( 'helpAdvertising', 'helpLogistics', 'helpCommunications', 'helpModerator', 'helpCleric', 'helpSorcerer', 'helpAdmin', 'helpPhotographer', 'helpChronicler', 'helpServer', 'helpClient', 'helpMobile')
# Fill out with value from # https://console.firebase.google.com/project/trogdors-29fa4/settings/serviceaccounts/databasesecrets FIREBASE_SECRET = "" FIREBASE_EMAIL = "" ALLEGIANCES = ('horde', 'resistance', 'none') TEST_ENDPOINT = 'http://localhost:8080' PLAYER_VOLUNTEER_ARGS = ( 'helpAdvertising', 'helpLogistics', 'helpCommunications', 'helpModerator', 'helpCleric', 'helpSorcerer', 'helpAdmin', 'helpPhotographer', 'helpChronicler', 'helpServer', 'helpClient', 'helpMobile')
Drop FIREBASE_SECRET (since been revoked)
Drop FIREBASE_SECRET (since been revoked)
Python
apache-2.0
google/playhvz,google/playhvz,google/playhvz,google/playhvz,google/playhvz,google/playhvz,google/playhvz,google/playhvz
--- +++ @@ -1,6 +1,6 @@ # Fill out with value from -# https://firebase.corp.google.com/project/trogdors-29fa4/settings/database -FIREBASE_SECRET = "ZiD9uLhDnrLq2n416MjWjn0JOrci6H0oGm7bKyVN" +# https://console.firebase.google.com/project/trogdors-29fa4/settings/serviceaccounts/databasesecrets +FIREBASE_SECRET = "" FIREBASE_EMAIL = "" ALLEGIANCES = ('horde', 'resistance', 'none') TEST_ENDPOINT = 'http://localhost:8080'
b85751e356c091d2dffe8366a94fbb42bfcad34e
src/SMESH_SWIG/SMESH_GroupLyingOnGeom.py
src/SMESH_SWIG/SMESH_GroupLyingOnGeom.py
import SMESH def BuildGroupLyingOn(theMesh, theElemType, theName, theShape): aMeshGen = salome.lcc.FindOrLoadComponent("FactoryServer", "SMESH") aFilterMgr = aMeshGen.CreateFilterManager() aFilter = aFilterMgr.CreateFilter() aLyingOnGeom = aFilterMgr.CreateLyingOnGeom() aLyingOnGeom.SetGeom(theShape) aLyingOnGeom.SetElementType(theElemType) aFilter.SetPredicate(aLyingOnGeom) anIds = aFilter.GetElementsId(theMesh) aGroup = theMesh.CreateGroup(theElemType, theName) aGroup.Add(anIds) #Example ## from SMESH_test1 import * ## smesh.Compute(mesh, box) ## BuildGroupLyingOn(mesh, SMESH.FACE, "Group of faces lying on edge", edge ) ## salome.sg.updateObjBrowser(1);
from meshpy import * def BuildGroupLyingOn(theMesh, theElemType, theName, theShape): aFilterMgr = smesh.CreateFilterManager() aFilter = aFilterMgr.CreateFilter() aLyingOnGeom = aFilterMgr.CreateLyingOnGeom() aLyingOnGeom.SetGeom(theShape) aLyingOnGeom.SetElementType(theElemType) aFilter.SetPredicate(aLyingOnGeom) anIds = aFilter.GetElementsId(theMesh) aGroup = theMesh.CreateGroup(theElemType, theName) aGroup.Add(anIds) #Example ## from SMESH_test1 import * ## smesh.Compute(mesh, box) ## BuildGroupLyingOn(mesh, SMESH.FACE, "Group of faces lying on edge", edge ) ## salome.sg.updateObjBrowser(1);
Fix a bug - salome.py is not imported here and this causes run-time Python exception
Fix a bug - salome.py is not imported here and this causes run-time Python exception
Python
lgpl-2.1
FedoraScientific/salome-smesh,FedoraScientific/salome-smesh,FedoraScientific/salome-smesh,FedoraScientific/salome-smesh
--- +++ @@ -1,9 +1,7 @@ -import SMESH +from meshpy import * def BuildGroupLyingOn(theMesh, theElemType, theName, theShape): - aMeshGen = salome.lcc.FindOrLoadComponent("FactoryServer", "SMESH") - - aFilterMgr = aMeshGen.CreateFilterManager() + aFilterMgr = smesh.CreateFilterManager() aFilter = aFilterMgr.CreateFilter() aLyingOnGeom = aFilterMgr.CreateLyingOnGeom()
c3957dbb25a8b5eeeccd37f218976721249b93e2
src/competition/tests/validator_tests.py
src/competition/tests/validator_tests.py
from django.test import TestCase from django.template.defaultfilters import slugify from django.core.exceptions import ValidationError from competition.validators import greater_than_zero, non_negative, validate_name class ValidationFunctionTest(TestCase): def test_greater_than_zero(self): """Check greater_than_zero validator""" self.assertRaises(ValidationError, greater_than_zero, 0) self.assertRaises(ValidationError, greater_than_zero, -1) self.assertIsNone(greater_than_zero(1)) def test_non_negative(self): """Check non_negative validator""" self.assertRaises(ValidationError, non_negative, -1) self.assertIsNone(non_negative(0)) self.assertIsNone(non_negative(1)) def test_validate_name(self): """Check name validator""" # Try some valid names valid_names = ['MegaMiner-AI 10: Galapagos', 'Chess 2012', '2012 Chess', 'B.L.O.O.M. 2: Revenge of the Flowers', '__main__'] for name in valid_names: self.assertIsNone(validate_name(name)) self.assertRaises(ValidationError, validate_name, "..") self.assertRaises(ValidationError, validate_name, "_..") self.assertRaises(ValidationError, validate_name, "_") self.assertRaises(ValidationError, validate_name, "____") self.assertRaises(ValidationError, validate_name, ".Nope") self.assertRaises(ValidationError, validate_name, ".Nope")
from django.test import TestCase from django.template.defaultfilters import slugify from django.core.exceptions import ValidationError from competition.validators import greater_than_zero, non_negative, validate_name class ValidationFunctionTest(TestCase): def test_greater_than_zero(self): """Check greater_than_zero validator""" self.assertRaises(ValidationError, greater_than_zero, 0) self.assertRaises(ValidationError, greater_than_zero, -1) self.assertIsNone(greater_than_zero(1)) def test_non_negative(self): """Check non_negative validator""" self.assertRaises(ValidationError, non_negative, -1) self.assertIsNone(non_negative(0)) self.assertIsNone(non_negative(1)) def test_validate_name(self): """Check name validator""" # Try some valid names valid_names = ['MegaMiner-AI 10: Galapagos', 'Chess 2012', '2012 Chess', 'B.L.O.O.M. 2: Revenge of the Flowers'] for name in valid_names: self.assertIsNone(validate_name(name)) self.assertRaises(ValidationError, validate_name, "..") self.assertRaises(ValidationError, validate_name, "_..") self.assertRaises(ValidationError, validate_name, "_") self.assertRaises(ValidationError, validate_name, "____") self.assertRaises(ValidationError, validate_name, ".Nope") self.assertRaises(ValidationError, validate_name, ".Nope")
Correct unit tests to comply with new team name RE
Correct unit tests to comply with new team name RE
Python
bsd-3-clause
michaelwisely/django-competition,michaelwisely/django-competition,michaelwisely/django-competition
--- +++ @@ -23,7 +23,7 @@ """Check name validator""" # Try some valid names valid_names = ['MegaMiner-AI 10: Galapagos', 'Chess 2012', '2012 Chess', - 'B.L.O.O.M. 2: Revenge of the Flowers', '__main__'] + 'B.L.O.O.M. 2: Revenge of the Flowers'] for name in valid_names: self.assertIsNone(validate_name(name))
5ab6c21bbcaaf9b919c9a796ec00d1a805ec1b0d
apps/bplan/emails.py
apps/bplan/emails.py
from adhocracy4.emails import Email class OfficeWorkerNotification(Email): template_name = 'meinberlin_bplan/emails/office_worker_notification' @property def office_worker_email(self): project = self.object.project return project.externalproject.bplan.office_worker_email def get_receivers(self): return [self.office_worker_email] def get_context(self): context = super().get_context() context['project'] = self.object.project return context class SubmitterConfirmation(Email): template_name = 'meinberlin_bplan/emails/submitter_confirmation' fallback_language = 'de' def get_receivers(self): return [self.object.email] def get_context(self): context = super().get_context() context['project'] = self.object.project return context
from adhocracy4.emails import Email class OfficeWorkerNotification(Email): template_name = 'meinberlin_bplan/emails/office_worker_notification' @property def office_worker_email(self): project = self.object.project return project.externalproject.bplan.office_worker_email def get_receivers(self): return [self.office_worker_email] def get_context(self): context = super().get_context() context['project'] = self.object.project return context class SubmitterConfirmation(Email): template_name = 'meinberlin_bplan/emails/submitter_confirmation' def get_receivers(self): return [self.object.email] def get_context(self): context = super().get_context() context['project'] = self.object.project return context
Set bplan default email to english as default
Set bplan default email to english as default
Python
agpl-3.0
liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin
--- +++ @@ -20,7 +20,6 @@ class SubmitterConfirmation(Email): template_name = 'meinberlin_bplan/emails/submitter_confirmation' - fallback_language = 'de' def get_receivers(self): return [self.object.email]
fa86706ae6cf77ef71402bb86d12cdd3cb79dafc
shub/logout.py
shub/logout.py
import re, click from shub.utils import get_key_netrc, NETRC_FILE @click.command(help='remove Scrapinghug API key from the netrc file') @click.pass_context def cli(context): if not get_key_netrc(): context.fail('Key not found in netrc file') with open(NETRC_FILE, 'r+') as out: key_re = r'machine\s+scrapinghub\.com\s+login\s+\w+\s+password\s+""\s*' content = out.read() content_new = re.sub(key_re, '', content) if content_new != content: out.seek(0) out.truncate() out.write(content_new) if get_key_netrc(): context.fail( 'Error removing key from the netrc file.' 'Please, open the file ~/.netrc and remove it manually')
import re, click from shub.utils import get_key_netrc, NETRC_FILE @click.command(help='remove Scrapinghug API key from the netrc file') @click.pass_context def cli(context): if not get_key_netrc(): context.fail('Key not found in netrc file') error, msg = remove_sh_key() if error: context.fail(msg) if get_key_netrc(): context.fail( 'Error removing key from the netrc file.' 'Please, open the file ~/.netrc and remove it manually') def remove_sh_key(): key_re = r'machine\s+scrapinghub\.com\s+login\s+\w+\s+password\s+""\s*' error_msg = '' try: with open(NETRC_FILE, 'r+') as out: content = out.read() content_new = re.sub(key_re, '', content) if content_new == content: error_msg = 'Regex didn\'t match. \ Key wasn\'t removed from netrc file' else: out.seek(0) out.truncate() out.write(content_new) except Exception as err: error_msg = str(err) if error_msg: return True, error_msg else: return False, ''
Add verification for removing key from netrc file
Add verification for removing key from netrc file
Python
bsd-3-clause
scrapinghub/shub
--- +++ @@ -6,15 +6,31 @@ def cli(context): if not get_key_netrc(): context.fail('Key not found in netrc file') - with open(NETRC_FILE, 'r+') as out: - key_re = r'machine\s+scrapinghub\.com\s+login\s+\w+\s+password\s+""\s*' - content = out.read() - content_new = re.sub(key_re, '', content) - if content_new != content: - out.seek(0) - out.truncate() - out.write(content_new) + error, msg = remove_sh_key() + if error: + context.fail(msg) if get_key_netrc(): context.fail( 'Error removing key from the netrc file.' 'Please, open the file ~/.netrc and remove it manually') + +def remove_sh_key(): + key_re = r'machine\s+scrapinghub\.com\s+login\s+\w+\s+password\s+""\s*' + error_msg = '' + try: + with open(NETRC_FILE, 'r+') as out: + content = out.read() + content_new = re.sub(key_re, '', content) + if content_new == content: + error_msg = 'Regex didn\'t match. \ + Key wasn\'t removed from netrc file' + else: + out.seek(0) + out.truncate() + out.write(content_new) + except Exception as err: + error_msg = str(err) + if error_msg: + return True, error_msg + else: + return False, ''
5ff35d282b61cfdfc53deaa0f1bc0f83850ff7a5
downstream_node/lib/utils.py
downstream_node/lib/utils.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json def model_to_json(model): """ Returns a JSON representation of an SQLAlchemy-backed object. From Zato: https://github.com/zatosource/zato """ _json = {} _json['fields'] = {} _json['pk'] = getattr(model, 'id') for col in model._sa_class_manager.mapper.mapped_table.columns: _json['fields'][col.name] = getattr(model, col.name) return json.dumps([_json])
#!/usr/bin/env python # -*- coding: utf-8 -*- import json def model_to_json(model): """ Returns a JSON representation of an SQLAlchemy-backed object. From Zato: https://github.com/zatosource/zato """ _json = {} _json['fields'] = {} _json['pk'] = getattr(model, 'id') for col in model._sa_class_manager.mapper.mapped_table.columns: _json['fields'][col.name] = getattr(model, col.name) return json.dumps([_json]) def query_to_list(query): lst = [] for row in query.all(): row_dict = {} for col in row.__mapper__.mapped_table.columns: row_dict[col.name] = getattr(row, col.name) lst.append(row_dict) return lst
Add helper method to turn queries into json-serializable lists
Add helper method to turn queries into json-serializable lists
Python
mit
Storj/downstream-node,Storj/downstream-node
--- +++ @@ -18,3 +18,12 @@ return json.dumps([_json]) + +def query_to_list(query): + lst = [] + for row in query.all(): + row_dict = {} + for col in row.__mapper__.mapped_table.columns: + row_dict[col.name] = getattr(row, col.name) + lst.append(row_dict) + return lst
bafef6a175116aff519579822f2382e8fbbd8808
spotipy/__init__.py
spotipy/__init__.py
VERSION='2.4.5' from client import * from oauth2 import * from util import *
VERSION='2.4.5' from .client import * from .oauth2 import * from .util import *
Make import statements explicit relative imports
Make import statements explicit relative imports
Python
mit
plamere/spotipy
--- +++ @@ -1,5 +1,5 @@ VERSION='2.4.5' -from client import * -from oauth2 import * -from util import * +from .client import * +from .oauth2 import * +from .util import *
a589aa63f250a347ab24b7309e65ef25c7281437
src/sentry/utils/imports.py
src/sentry/utils/imports.py
""" sentry.utils.imports ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import pkgutil import six class ModuleProxyCache(dict): def __missing__(self, key): if '.' not in key: return __import__(key) module_name, class_name = key.rsplit('.', 1) module = __import__(module_name, {}, {}, [class_name]) handler = getattr(module, class_name) # We cache a NoneType for missing imports to avoid repeated lookups self[key] = handler return handler _cache = ModuleProxyCache() def import_string(path): """ Path must be module.path.ClassName >>> cls = import_string('sentry.models.Group') """ result = _cache[path] return result def import_submodules(context, root_module, path): """ Import all submodules and register them in the ``context`` namespace. >>> import_submodules(locals(), __name__, __path__) """ for loader, module_name, is_pkg in pkgutil.walk_packages(path, root_module + '.'): module = loader.find_module(module_name).load_module(module_name) for k, v in six.iteritems(vars(module)): if not k.startswith('_'): context[k] = v context[module_name] = module
""" sentry.utils.imports ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import pkgutil import six class ModuleProxyCache(dict): def __missing__(self, key): if '.' not in key: return __import__(key) module_name, class_name = key.rsplit('.', 1) module = __import__(module_name, {}, {}, [class_name]) handler = getattr(module, class_name) # We cache a NoneType for missing imports to avoid repeated lookups self[key] = handler return handler _cache = ModuleProxyCache() def import_string(path): """ Path must be module.path.ClassName >>> cls = import_string('sentry.models.Group') """ result = _cache[path] return result def import_submodules(context, root_module, path): """ Import all submodules and register them in the ``context`` namespace. >>> import_submodules(locals(), __name__, __path__) """ for loader, module_name, is_pkg in pkgutil.walk_packages(path, root_module + '.'): # this causes a Runtime error with model conflicts # module = loader.find_module(module_name).load_module(module_name) module = __import__(module_name, globals(), locals(), ['__name__']) for k, v in six.iteritems(vars(module)): if not k.startswith('_'): context[k] = v context[module_name] = module
Correct import behavior to prevent Runtime error
Correct import behavior to prevent Runtime error
Python
bsd-3-clause
gencer/sentry,jean/sentry,fotinakis/sentry,gencer/sentry,looker/sentry,BuildingLink/sentry,gencer/sentry,jean/sentry,JackDanger/sentry,fotinakis/sentry,BuildingLink/sentry,beeftornado/sentry,zenefits/sentry,beeftornado/sentry,looker/sentry,ifduyue/sentry,ifduyue/sentry,JamesMura/sentry,ifduyue/sentry,JamesMura/sentry,BuildingLink/sentry,zenefits/sentry,fotinakis/sentry,ifduyue/sentry,zenefits/sentry,zenefits/sentry,beeftornado/sentry,BuildingLink/sentry,JamesMura/sentry,jean/sentry,gencer/sentry,ifduyue/sentry,jean/sentry,alexm92/sentry,mvaled/sentry,gencer/sentry,alexm92/sentry,looker/sentry,JackDanger/sentry,mvaled/sentry,mvaled/sentry,BuildingLink/sentry,JamesMura/sentry,JackDanger/sentry,fotinakis/sentry,looker/sentry,zenefits/sentry,mvaled/sentry,mvaled/sentry,jean/sentry,JamesMura/sentry,alexm92/sentry,looker/sentry,mvaled/sentry
--- +++ @@ -46,7 +46,9 @@ >>> import_submodules(locals(), __name__, __path__) """ for loader, module_name, is_pkg in pkgutil.walk_packages(path, root_module + '.'): - module = loader.find_module(module_name).load_module(module_name) + # this causes a Runtime error with model conflicts + # module = loader.find_module(module_name).load_module(module_name) + module = __import__(module_name, globals(), locals(), ['__name__']) for k, v in six.iteritems(vars(module)): if not k.startswith('_'): context[k] = v
d35aa7344ed96c8e1e17ea74ba14a760a3c8a418
spacy/about.py
spacy/about.py
# inspired from: # https://python-packaging-user-guide.readthedocs.org/en/latest/single_source_version/ # https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py __title__ = 'spacy' __version__ = '1.0.0+a' __summary__ = 'Industrial-strength NLP' __uri__ = 'https://spacy.io' __author__ = 'Matthew Honnibal' __email__ = 'matt@spacy.io' __license__ = 'MIT' __models__ = { 'en': 'en>=1.1.0,<1.2.0', 'de': 'de>=1.0.0,<1.1.0', }
# inspired from: # https://python-packaging-user-guide.readthedocs.org/en/latest/single_source_version/ # https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py __title__ = 'spacy' __version__ = '1.0.0-a' __summary__ = 'Industrial-strength NLP' __uri__ = 'https://spacy.io' __author__ = 'Matthew Honnibal' __email__ = 'matt@spacy.io' __license__ = 'MIT' __models__ = { 'en': 'en>=1.1.0,<1.2.0', 'de': 'de>=1.0.0,<1.1.0', }
Change version ID to make PyPi happy
Change version ID to make PyPi happy
Python
mit
banglakit/spaCy,recognai/spaCy,spacy-io/spaCy,honnibal/spaCy,honnibal/spaCy,oroszgy/spaCy.hu,oroszgy/spaCy.hu,aikramer2/spaCy,explosion/spaCy,honnibal/spaCy,explosion/spaCy,banglakit/spaCy,recognai/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,banglakit/spaCy,spacy-io/spaCy,raphael0202/spaCy,oroszgy/spaCy.hu,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,explosion/spaCy,explosion/spaCy,banglakit/spaCy,aikramer2/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,aikramer2/spaCy,recognai/spaCy,Gregory-Howard/spaCy,spacy-io/spaCy,recognai/spaCy,banglakit/spaCy,Gregory-Howard/spaCy,oroszgy/spaCy.hu,raphael0202/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,spacy-io/spaCy,banglakit/spaCy,aikramer2/spaCy,explosion/spaCy,recognai/spaCy,oroszgy/spaCy.hu,Gregory-Howard/spaCy,spacy-io/spaCy,oroszgy/spaCy.hu,raphael0202/spaCy
--- +++ @@ -4,7 +4,7 @@ # https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py __title__ = 'spacy' -__version__ = '1.0.0+a' +__version__ = '1.0.0-a' __summary__ = 'Industrial-strength NLP' __uri__ = 'https://spacy.io' __author__ = 'Matthew Honnibal'