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
40f1c31098bd09e98d50727d08becf0d55ca8409
__init__.py
__init__.py
from __future__ import print_function import os from flask import Flask, render_template, request, redirect, url_for, send_from_directory from werkzeug import secure_filename UPLOAD_FOLDER = '/app/input' ALLOWED_EXTENSIONS = set(['txt','xls','xlsx','csv','tsv','md']) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and \ filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS @app.route('/', methods=['GET','POST']) def upload_file(): if request.method == 'POST': file = request.files['files'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return redirect(url_for('upload_file', filename=filename)) return render_template('index.html') @app.route('/uploads/<filename>') def uploaded_file(filename): return send_form_directory(app.config['UPLOAD_FOLDER']) if __name__ == '__main__': port = int(os.environ.get('PORT', 5050)) app.run(host='0.0.0.0', port=port, debug=True, use_reloader=True)
from __future__ import print_function import os from flask import Flask, render_template, request, redirect, url_for, send_from_directory from werkzeug import secure_filename UPLOAD_FOLDER = '/app/input' ALLOWED_EXTENSIONS = set(['txt','xls','xlsx','csv','tsv','md']) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['MAX_CONTENT_LENGTH'] = 100*1024*1024 #set max upload file size to 100mb def allowed_file(filename): return '.' in filename and \ filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS @app.route('/', methods=['GET','POST']) def upload_file(): if request.method == 'POST': file = request.files['files'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return redirect(url_for('upload_file', filename=filename)) return render_template('index.html') @app.route('/uploads/<filename>') def uploaded_file(filename): return send_form_directory(app.config['UPLOAD_FOLDER']) if __name__ == '__main__': port = int(os.environ.get('PORT', 5050)) app.run(host='0.0.0.0', port=port, debug=True, use_reloader=True)
Add upload file size limit
Add upload file size limit
Python
mit
ehhop/ehhapp-formulary,ehhop/ehhapp-formulary,ehhop/ehhapp-formulary
--- +++ @@ -8,6 +8,7 @@ app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER +app.config['MAX_CONTENT_LENGTH'] = 100*1024*1024 #set max upload file size to 100mb def allowed_file(filename): return '.' in filename and \
30bd8b9b4d18579cdf9b723f82f35987c1ad9176
__main__.py
__main__.py
from scanresults import ScanResults import sys sr = ScanResults() sr.add_files(*sys.argv[1:]) sr.train() out = sr.sentences() if out is not None: print(out)
from scanresults import ScanResults import sys from argparse import ArgumentParser parser = ArgumentParser(description='Generate markov text from a corpus') parser.add_argument('-t','--train', default=2, type=int, metavar='train_n', help="The size of the Markov state prefix to train the corpus on") parser.add_argument('-s','--sentences', default=25, type=int, metavar='sentences', help="The number of sentences to print") parser.add_argument('corpus_path', nargs="+", help="Paths to corpus files to train on. Globs are permitted") args = parser.parse_args() sr = ScanResults() sr.add_files(*args.corpus_path) sr.train(args.train) out = sr.sentences(args.sentences) if out is not None: print(out)
Enable command-line args for configuration
Enable command-line args for configuration
Python
bsd-3-clause
darrenpmeyer/scanresults,darrenpmeyer/scanresults
--- +++ @@ -1,10 +1,20 @@ from scanresults import ScanResults import sys +from argparse import ArgumentParser + +parser = ArgumentParser(description='Generate markov text from a corpus') +parser.add_argument('-t','--train', default=2, type=int, metavar='train_n', + help="The size of the Markov state prefix to train the corpus on") +parser.add_argument('-s','--sentences', default=25, type=int, metavar='sentences', + help="The number of sentences to print") +parser.add_argument('corpus_path', nargs="+", + help="Paths to corpus files to train on. Globs are permitted") +args = parser.parse_args() sr = ScanResults() -sr.add_files(*sys.argv[1:]) +sr.add_files(*args.corpus_path) -sr.train() -out = sr.sentences() +sr.train(args.train) +out = sr.sentences(args.sentences) if out is not None: print(out)
5459dfc62e3a0d5b36b6d9405232382c1f8b663a
__init__.py
__init__.py
import sys import os sys.path.insert(0, os.path.dirname(__file__)) from . import multiscanner, storage common = multiscanner.common multiscan = multiscanner.multiscan parse_reports = multiscanner.parse_reports config_init = multiscanner.config_init
import os import sys sys.path.insert(0, os.path.dirname(__file__)) from . import multiscanner common = multiscanner.common multiscan = multiscanner.multiscan parse_reports = multiscanner.parse_reports config_init = multiscanner.config_init
Remove unused imports and sort
Remove unused imports and sort
Python
mpl-2.0
jmlong1027/multiscanner,jmlong1027/multiscanner,mitre/multiscanner,MITRECND/multiscanner,mitre/multiscanner,MITRECND/multiscanner,mitre/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner
--- +++ @@ -1,7 +1,10 @@ +import os import sys -import os + sys.path.insert(0, os.path.dirname(__file__)) -from . import multiscanner, storage + +from . import multiscanner + common = multiscanner.common multiscan = multiscanner.multiscan parse_reports = multiscanner.parse_reports
e8d99b27864d32ad149ffc276dfa78bfdff22c56
__main__.py
__main__.py
#!/usr/bin/env python3 import token import lexer as l import parser as p import evaluator as e import context as c def main(ctx): string = input(">> ") string = string.replace("\\n", "\n") + ";" tokens = l.lex(string) parser = p.Parser(tokens) program = parser.parse_program() if len(parser.errors) > 0: parser.print_errors() else: # print(program) print(e.eval(program, ctx)) if __name__ == "__main__": ctx = c.Context() while True: try: main(ctx) except (KeyboardInterrupt, EOFError): print('Goodbye!') break
#!/usr/bin/env python3 import token import lexer as l import parser as p import evaluator as e import context as c def main(ctx): string = input("⧫ ") string = string.replace("\\n", "\n") + ";" tokens = l.lex(string) parser = p.Parser(tokens) program = parser.parse_program() if len(parser.errors) > 0: parser.print_errors() else: # print(program) print(e.eval(program, ctx)) if __name__ == "__main__": ctx = c.Context() while True: try: main(ctx) except (KeyboardInterrupt, EOFError): print('Goodbye!') break
Change prompt to a diamond
Change prompt to a diamond
Python
mit
Zac-Garby/pluto-lang
--- +++ @@ -7,7 +7,7 @@ import context as c def main(ctx): - string = input(">> ") + string = input("⧫ ") string = string.replace("\\n", "\n") + ";" tokens = l.lex(string)
15307ebe2c19c1a3983b0894152ba81fdde34619
exp/descriptivestats.py
exp/descriptivestats.py
import pandas import numpy import matplotlib.pyplot as plt def univariate_stats(): num_examples = 1000 z = pandas.Series(numpy.random.randn(num_examples)) # Minimum print(z.min()) # Maximum print(z.max()) # Mean print(z.mean()) # Median print(z.median()) # Variance print(z.var()) # Standard deviation print(z.std()) # Mean absolute deviation print(z.mad()) # Interquartile range print(z.quantile(0.75) - z.quantile(0.25)) z.plot(kind="hist") def multivariate_stats(): num_examples = 1000 x = pandas.Series(numpy.random.randn(num_examples)) y = x + pandas.Series(numpy.random.randn(num_examples)) z = x + pandas.Series(numpy.random.randn(num_examples)) # Covariance print(y.cov(z)) # Covariance of y with itself is equal to variance print(y.cov(y), y.var()) # Correlation print(y.corr(z)) univariate_stats() multivariate_stats() plt.show()
import pandas import numpy import matplotlib.pyplot as plt def univariate_stats(): # Generate 1000 random numbers from a normal distribution num_examples = 1000 z = pandas.Series(numpy.random.randn(num_examples)) # Minimum print(z.min()) # Maximum print(z.max()) # Mean print(z.mean()) # Median print(z.median()) # Variance print(z.var()) # Standard deviation print(z.std()) # Mean absolute deviation print(z.mad()) # Interquartile range print(z.quantile(0.75) - z.quantile(0.25)) z.plot(kind="hist") def multivariate_stats(): num_examples = 1000 x = pandas.Series(numpy.random.randn(num_examples)) y = x + pandas.Series(numpy.random.randn(num_examples)) z = x + pandas.Series(numpy.random.randn(num_examples)) # Covariance print(y.cov(z)) # Covariance of y with itself is equal to variance print(y.cov(y), y.var()) # Correlation print(y.corr(z)) univariate_stats() multivariate_stats() plt.show()
Add comment on dist of first function
Add comment on dist of first function
Python
mit
charanpald/tyre-hug
--- +++ @@ -4,6 +4,7 @@ def univariate_stats(): + # Generate 1000 random numbers from a normal distribution num_examples = 1000 z = pandas.Series(numpy.random.randn(num_examples))
3999e9812a766066dcccf6a4d07174144cb9f72d
wurstmineberg.45s.py
wurstmineberg.45s.py
#!/usr/local/bin/python3 import requests people = requests.get('https://api.wurstmineberg.de/v2/people.json').json() status = requests.get('https://api.wurstmineberg.de/v2/world/wurstmineberg/status.json').json() print(len(status['list'])) print('---') print('Version: {}|color=gray'.format(status['version'])) for wmb_id in status['list']: display_name = people['people'].get(wmb_id, {}).get('name', wmb_id) if people['people'].get(wmb_id, False) and people['people'][wmb_id].get('slack', False): slack_name = people['people'][wmb_id]['slack']['username'] slack_url = 'https://wurstmineberg.slack.com/messages/@' + slack_name else: slack_url = None print('{}|href=https://wurstmineberg.de/people/{} color=#2889be'.format(display_name, wmb_id)) if slack_url is not None: print('@{}|alternate=true href={} color=red'.format(slack_name, slack_url)) print('---') print('Start Minecraft | bash=/usr/bin/open param1=-a param2=Minecraft terminal=false')
#!/usr/local/bin/python3 import requests people = requests.get('https://api.wurstmineberg.de/v2/people.json').json() status = requests.get('https://api.wurstmineberg.de/v2/world/wurstmineberg/status.json').json() print(len(status['list'])) print('---') print('Version: {ver}|href=http://minecraft.gamepedia.com/{ver} color=gray'.format(ver=status['version'])) for wmb_id in status['list']: display_name = people['people'].get(wmb_id, {}).get('name', wmb_id) if people['people'].get(wmb_id, False) and people['people'][wmb_id].get('slack', False): slack_name = people['people'][wmb_id]['slack']['username'] slack_url = 'https://wurstmineberg.slack.com/messages/@' + slack_name else: slack_url = None print('{}|href=https://wurstmineberg.de/people/{} color=#2889be'.format(display_name, wmb_id)) if slack_url is not None: print('@{}|alternate=true href={} color=red'.format(slack_name, slack_url)) print('---') print('Start Minecraft | bash=/usr/bin/open param1=-a param2=Minecraft terminal=false')
Add Minecraft Wiki link to version item
Add Minecraft Wiki link to version item
Python
mit
wurstmineberg/bitbar-server-status
--- +++ @@ -8,7 +8,7 @@ print(len(status['list'])) print('---') -print('Version: {}|color=gray'.format(status['version'])) +print('Version: {ver}|href=http://minecraft.gamepedia.com/{ver} color=gray'.format(ver=status['version'])) for wmb_id in status['list']: display_name = people['people'].get(wmb_id, {}).get('name', wmb_id) if people['people'].get(wmb_id, False) and people['people'][wmb_id].get('slack', False):
d792201bc311a15e5df48259008331b771c59aca
flexx/ui/layouts/_layout.py
flexx/ui/layouts/_layout.py
""" Layout widgets """ from . import Widget class Layout(Widget): """ Abstract class for widgets that organize their child widgets. Panel widgets are layouts that do not take the natural size of their content into account, making them more efficient and suited for high-level layout. Other layouts, like HBox, are more suited for laying out content where the natural size is important. """ CSS = """ body { margin: 0; padding: 0; overflow: hidden; } .flx-Layout { /* sizing of widgets/layouts inside layout is defined per layout */ width: 100%; height: 100%; margin: 0px; padding: 0px; border-spacing: 0px; border: 0px; } """
""" Layout widgets """ from . import Widget class Layout(Widget): """ Abstract class for widgets that organize their child widgets. Panel widgets are layouts that do not take the natural size of their content into account, making them more efficient and suited for high-level layout. Other layouts, like HBox, are more suited for laying out content where the natural size is important. """ CSS = """ body { margin: 0; padding: 0; /*overflow: hidden;*/ } .flx-Layout { /* sizing of widgets/layouts inside layout is defined per layout */ width: 100%; height: 100%; margin: 0px; padding: 0px; border-spacing: 0px; border: 0px; } """
Fix CSS problem when Flexx is enbedded in page-app
Fix CSS problem when Flexx is enbedded in page-app
Python
bsd-2-clause
jrversteegh/flexx,JohnLunzer/flexx,zoofIO/flexx,JohnLunzer/flexx,jrversteegh/flexx,JohnLunzer/flexx,zoofIO/flexx
--- +++ @@ -18,7 +18,7 @@ body { margin: 0; padding: 0; - overflow: hidden; + /*overflow: hidden;*/ } .flx-Layout {
9e2f9b040d0dde3237daca1c483c8b2bf0170663
archlinux/archpack_settings.py
archlinux/archpack_settings.py
# # Biicode Arch Linux package settings. # # Check PKGBUILD_template docs for those settings and # what they mean. # def settings(): return { "version": "2.6.1", "release_number": "1", "arch_deps": ["cmake>=3.0.2", "zlib", "glibc", "sqlite", "wget", "python2-pmw" ], "debian_deps": ["zlib1g", "libc-bin", "libsqlite3-0", "wget", "lib32z1", "python-tk" ] } if __name__ == '__main__': print(settings())
# # Biicode Arch Linux package settings. # # Check PKGBUILD_template docs for those settings and # what they mean. # def settings(): return { "version": "2.7", "release_number": "1", "arch_deps": ["cmake>=3.0.2", "zlib", "glibc", "sqlite", "wget", "python2-pmw" ], "debian_deps": ["zlib1g", "libc-bin", "libsqlite3-0", "wget", "lib32z1", "python-tk" ] } if __name__ == '__main__': print(settings())
Update Arch package to 2.7
Update Arch package to 2.7
Python
bsd-2-clause
bowlofstew/packages,biicode/packages,biicode/packages,bowlofstew/packages
--- +++ @@ -6,7 +6,7 @@ # def settings(): - return { "version": "2.6.1", + return { "version": "2.7", "release_number": "1", "arch_deps": ["cmake>=3.0.2", "zlib",
ecd33e00eb5eb8ff58358e01a6d618262e8381a6
astropy/io/vo/setup_package.py
astropy/io/vo/setup_package.py
from distutils.core import Extension from os.path import join from astropy import setup_helpers def get_extensions(build_type='release'): VO_DIR = 'astropy/io/vo/src' return [Extension( "astropy.io.vo.tablewriter", [join(VO_DIR, "tablewriter.c")], include_dirs=[VO_DIR])] def get_package_data(): return { 'astropy.io.vo': [ 'data/ucd1p-words.txt', 'data/*.xsd', 'data/*.dtd'], 'astropy.io.vo.tests': [ 'data/*.xml', 'data/*.gz', 'data/*.json', 'data/*.fits', 'data/*.txt'], 'astropy.io.vo.validator': [ 'urls/*.dat.gz']} def get_legacy_alias(): return setup_helpers.add_legacy_alias( 'vo', 'astropy.io.vo', '0.7.2')
from distutils.core import Extension from os.path import join from astropy import setup_helpers def get_extensions(build_type='release'): VO_DIR = 'astropy/io/vo/src' return [Extension( "astropy.io.vo.tablewriter", [join(VO_DIR, "tablewriter.c")], include_dirs=[VO_DIR])] def get_package_data(): return { 'astropy.io.vo': [ 'data/ucd1p-words.txt', 'data/*.xsd', 'data/*.dtd'], 'astropy.io.vo.tests': [ 'data/*.xml', 'data/*.gz', 'data/*.json', 'data/*.fits', 'data/*.txt'], 'astropy.io.vo.validator': [ 'urls/*.dat.gz']} def get_legacy_alias(): return setup_helpers.add_legacy_alias( 'vo', 'astropy.io.vo', '0.8')
Update upstream version of vo
Update upstream version of vo
Python
bsd-3-clause
larrybradley/astropy,MSeifert04/astropy,tbabej/astropy,dhomeier/astropy,tbabej/astropy,StuartLittlefair/astropy,mhvk/astropy,astropy/astropy,lpsinger/astropy,DougBurke/astropy,aleksandr-bakanov/astropy,StuartLittlefair/astropy,dhomeier/astropy,joergdietrich/astropy,MSeifert04/astropy,stargaser/astropy,pllim/astropy,StuartLittlefair/astropy,larrybradley/astropy,saimn/astropy,AustereCuriosity/astropy,DougBurke/astropy,StuartLittlefair/astropy,AustereCuriosity/astropy,aleksandr-bakanov/astropy,funbaker/astropy,stargaser/astropy,kelle/astropy,joergdietrich/astropy,joergdietrich/astropy,joergdietrich/astropy,AustereCuriosity/astropy,dhomeier/astropy,AustereCuriosity/astropy,mhvk/astropy,astropy/astropy,saimn/astropy,saimn/astropy,funbaker/astropy,bsipocz/astropy,dhomeier/astropy,saimn/astropy,aleksandr-bakanov/astropy,kelle/astropy,pllim/astropy,bsipocz/astropy,tbabej/astropy,lpsinger/astropy,bsipocz/astropy,DougBurke/astropy,MSeifert04/astropy,larrybradley/astropy,pllim/astropy,kelle/astropy,stargaser/astropy,pllim/astropy,astropy/astropy,larrybradley/astropy,bsipocz/astropy,kelle/astropy,aleksandr-bakanov/astropy,mhvk/astropy,funbaker/astropy,kelle/astropy,DougBurke/astropy,tbabej/astropy,joergdietrich/astropy,astropy/astropy,dhomeier/astropy,saimn/astropy,MSeifert04/astropy,tbabej/astropy,funbaker/astropy,astropy/astropy,stargaser/astropy,lpsinger/astropy,lpsinger/astropy,larrybradley/astropy,mhvk/astropy,pllim/astropy,StuartLittlefair/astropy,AustereCuriosity/astropy,lpsinger/astropy,mhvk/astropy
--- +++ @@ -26,4 +26,4 @@ def get_legacy_alias(): return setup_helpers.add_legacy_alias( - 'vo', 'astropy.io.vo', '0.7.2') + 'vo', 'astropy.io.vo', '0.8')
5abac5e7cdc1d67ec6ed0996a5b132fae20af530
compare_text_of_urls.py
compare_text_of_urls.py
#!/usr/bin/env python from __future__ import print_function import json import os from os.path import join, dirname, abspath import subprocess import sys from get_text_from_url import process_page def main(argv=None): if argv is None: argv = sys.argv arg = argv[1:] # Enter two URLs with a space between them if len(arg) > 0: # Developers can supply URL as an argument... urls = arg[0] else: # ... but normally the URL comes from the allSettings.json file with open(os.path.expanduser("~/allSettings.json")) as settings: urls = json.load(settings)['source-url'] parsed_urls = urls.strip().split(' ') assert len(parsed_urls) == 2, 'Two URLs not entered.' diff_urls(parsed_urls[0], parsed_urls[1]) def diff_urls(url1, url2): text1 = process_page('text_from_url1', url1) text2 = process_page('text_from_url2', url2) subprocess.check_output("./diff_text.sh", cwd=dirname(abspath(__file__))) if __name__ == '__main__': main()
#!/usr/bin/env python from __future__ import print_function import json import os from os.path import join, dirname, abspath import subprocess import sys from get_text_from_url import process_page def main(argv=None): if argv is None: argv = sys.argv arg = argv[1:] # Enter two URLs with a space between them if len(arg) > 0: # Developers can supply URL as an argument... urls = arg[0] else: # ... but normally the URL comes from the allSettings.json file with open(os.path.expanduser("~/allSettings.json")) as settings_json: settings = json.load(settings_json) url1 = settings['source-url'] url2 = settings['source-url2'] assert url1 and url2, 'Two URLs not entered.' diff_urls(url1, url2) def diff_urls(url1, url2): text1 = process_page('text_from_url1', url1) text2 = process_page('text_from_url2', url2) subprocess.check_output("./diff_text.sh", cwd=dirname(abspath(__file__))) if __name__ == '__main__': main()
Use the URLs input in the UI boxes
Use the URLs input in the UI boxes Parse JSON from two separate URL input boxes, instead of using one input box and parsing one long string containing both URLs.
Python
agpl-3.0
scraperwiki/difference-tool,scraperwiki/difference-tool,scraperwiki/difference-tool,scraperwiki/difference-tool
--- +++ @@ -21,12 +21,12 @@ urls = arg[0] else: # ... but normally the URL comes from the allSettings.json file - with open(os.path.expanduser("~/allSettings.json")) as settings: - urls = json.load(settings)['source-url'] - - parsed_urls = urls.strip().split(' ') - assert len(parsed_urls) == 2, 'Two URLs not entered.' - diff_urls(parsed_urls[0], parsed_urls[1]) + with open(os.path.expanduser("~/allSettings.json")) as settings_json: + settings = json.load(settings_json) + url1 = settings['source-url'] + url2 = settings['source-url2'] + assert url1 and url2, 'Two URLs not entered.' + diff_urls(url1, url2) def diff_urls(url1, url2):
f81c36d4fe31815ed6692b573ad660067151d215
zaqarclient/_i18n.py
zaqarclient/_i18n.py
# Copyright 2014 Red Hat, Inc # All Rights .Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo.i18n import * # noqa _translators = TranslatorFactory(domain='zaqarclient') # The primary translation function using the well-known name "_" _ = _translators.primary # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical
# Copyright 2014 Red Hat, Inc # All Rights .Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_i18n import * # noqa _translators = TranslatorFactory(domain='zaqarclient') # The primary translation function using the well-known name "_" _ = _translators.primary # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical
Drop use of 'oslo' namespace package
Drop use of 'oslo' namespace package The Oslo libraries have moved all of their code out of the 'oslo' namespace package into per-library packages. The namespace package was retained during kilo for backwards compatibility, but will be removed by the liberty-2 milestone. This change removes the use of the namespace package, replacing it with the new package names. The patches in the libraries will be put on hold until application patches have landed, or L2, whichever comes first. At that point, new versions of the libraries without namespace packages will be released as a major version update. Please merge this patch, or an equivalent, before L2 to avoid problems with those library releases. Blueprint: remove-namespace-packages https://blueprints.launchpad.net/oslo-incubator/+spec/remove-namespace-packages Change-Id: Id54b2381f00d9905c4bb07821f54c5aaaa48d970
Python
apache-2.0
openstack/python-zaqarclient
--- +++ @@ -13,7 +13,7 @@ # License for the specific language governing permissions and limitations # under the License. -from oslo.i18n import * # noqa +from oslo_i18n import * # noqa _translators = TranslatorFactory(domain='zaqarclient')
c691c256682bec5f9a242ab71ab42d296bbf88a9
nightreads/posts/admin.py
nightreads/posts/admin.py
from django.contrib import admin # Register your models here.
from django.contrib import admin from .models import Post, Tag admin.site.register(Post) admin.site.register(Tag)
Add `Post`, `Tag` models to Admin
Add `Post`, `Tag` models to Admin
Python
mit
avinassh/nightreads,avinassh/nightreads
--- +++ @@ -1,3 +1,6 @@ from django.contrib import admin -# Register your models here. +from .models import Post, Tag + +admin.site.register(Post) +admin.site.register(Tag)
4fe8a1c1b294f0d75a901d4e8e80f47f5583e44e
pages/lms/info.py
pages/lms/info.py
from e2e_framework.page_object import PageObject from ..lms import BASE_URL class InfoPage(PageObject): """ Info pages for the main site. These are basically static pages, so we use one page object to represent them all. """ # Dictionary mapping section names to URL paths SECTION_PATH = { 'about': '/about', 'faq': '/faq', 'press': '/press', 'contact': '/contact', 'terms': '/tos', 'privacy': '/privacy', 'honor': '/honor', } # Dictionary mapping URLs to expected css selector EXPECTED_CSS = { '/about': 'section.vision', '/faq': 'section.faq', '/press': 'section.press', '/contact': 'section.contact', '/tos': 'section.tos', '/privacy': 'section.privacy-policy', '/honor': 'section.honor-code', } @property def name(self): return "lms.info" @property def requirejs(self): return [] @property def js_globals(self): return [] def url(self, section=None): return BASE_URL + self.SECTION_PATH[section] def is_browser_on_page(self): stripped_url = self.browser.url.replace(BASE_URL, "") css_sel = self.EXPECTED_CSS[stripped_url] return self.is_css_present(css_sel) @classmethod def sections(cls): return cls.SECTION_PATH.keys()
from e2e_framework.page_object import PageObject from ..lms import BASE_URL class InfoPage(PageObject): """ Info pages for the main site. These are basically static pages, so we use one page object to represent them all. """ # Dictionary mapping section names to URL paths SECTION_PATH = { 'about': '/about', 'faq': '/faq', 'press': '/press', 'contact': '/contact', 'terms': '/tos', 'privacy': '/privacy', 'honor': '/honor', } # Dictionary mapping URLs to expected css selector EXPECTED_CSS = { '/about': 'section.vision', '/faq': 'section.faq', '/press': 'section.press', '/contact': 'section.contact', '/tos': 'section.tos', '/privacy': 'section.privacy-policy', '/honor': 'section.honor-code', } @property def name(self): return "lms.info" @property def requirejs(self): return [] @property def js_globals(self): return [] def url(self, section=None): return BASE_URL + self.SECTION_PATH[section] def is_browser_on_page(self): # Find the appropriate css based on the URL for url_path, css_sel in self.EXPECTED_CSS.iteritems(): if self.browser.url.endswith(url_path): return self.is_css_present(css_sel) # Could not find the CSS based on the URL return False @classmethod def sections(cls): return cls.SECTION_PATH.keys()
Fix for test failure introduced by basic auth changes
Fix for test failure introduced by basic auth changes
Python
agpl-3.0
edx/edx-e2e-tests,raeeschachar/edx-e2e-mirror,raeeschachar/edx-e2e-mirror,edx/edx-e2e-tests
--- +++ @@ -47,9 +47,14 @@ return BASE_URL + self.SECTION_PATH[section] def is_browser_on_page(self): - stripped_url = self.browser.url.replace(BASE_URL, "") - css_sel = self.EXPECTED_CSS[stripped_url] - return self.is_css_present(css_sel) + + # Find the appropriate css based on the URL + for url_path, css_sel in self.EXPECTED_CSS.iteritems(): + if self.browser.url.endswith(url_path): + return self.is_css_present(css_sel) + + # Could not find the CSS based on the URL + return False @classmethod def sections(cls):
417ab5241c852cdcd072143bc2444f20f2117623
tests/execution_profiles/capture_profile.py
tests/execution_profiles/capture_profile.py
import cProfile from pqhelper import capture def main(): cProfile.run('test_solution(catapult)') def test_solution(board_string): print capture.capture(board_string) skeleton = ''' ..*..*.. .gm..mg. .ms..sm. .rs..sr. .ggmmgg. .rsggsr. .rsrrsr. ssgssgss''' giant_rat = ''' ...mm... ..mrym.. .mgyrgm. mygrygym ryxssxyr rxgbbgxr xygssgyx rybssbyr''' griffon = ''' .r..s... .b.sy... .b.yys.. .r.yxg.g .g.x*b.r .g.xxb.r rybyxygy ygyxybyr''' catapult = ''' ........ ........ ..mbgm.. .mxgbrm. my*gb*gm yrrxrxxg ymxyyrmg ssxssrss''' easy = ''' ........ ........ ........ ........ .......x ....xx.r ....rr.r ..rryyry''' if __name__ == '__main__': main()
import cProfile from pqhelper import capture def main(): cProfile.run('test_solution(catapult)') def test_solution(board_string): board = capture.Board(board_string) print capture.capture(board) skeleton = ''' ..*..*.. .gm..mg. .ms..sm. .rs..sr. .ggmmgg. .rsggsr. .rsrrsr. ssgssgss''' giant_rat = ''' ...mm... ..mrym.. .mgyrgm. mygrygym ryxssxyr rxgbbgxr xygssgyx rybssbyr''' griffon = ''' .r..s... .b.sy... .b.yys.. .r.yxg.g .g.x*b.r .g.xxb.r rybyxygy ygyxybyr''' catapult = ''' ........ ........ ..mbgm.. .mxgbrm. my*gb*gm yrrxrxxg ymxyyrmg ssxssrss''' easy = ''' ........ ........ ........ ........ .......x ....xx.r ....rr.r ..rryyry''' if __name__ == '__main__': main()
Update capture profiler to new spec of providing board instead of string.
Update capture profiler to new spec of providing board instead of string.
Python
mit
kobejohn/PQHelper
--- +++ @@ -8,7 +8,8 @@ def test_solution(board_string): - print capture.capture(board_string) + board = capture.Board(board_string) + print capture.capture(board) skeleton = ''' ..*..*..
c81eb510c72511c1f692f02f7bb63ef4caa51d27
apps/concept/management/commands/update_concept_totals.py
apps/concept/management/commands/update_concept_totals.py
from optparse import make_option import sys from django.core.management.base import BaseCommand from education.models import Concept class Command(BaseCommand): args = "" help = "Update concept total_question counts (post db import)" def handle(self, *args, **options): for concept in Concept.objects.all(): concept.total_questions = concept.question_set.count() concept.save()
from optparse import make_option import sys from django.core.management.base import BaseCommand from concept.models import Concept class Command(BaseCommand): args = "" help = "Update concept total_question counts (post db import)" def handle(self, *args, **options): for concept in Concept.objects.all(): concept.total_questions = concept.question_set.count() concept.save()
Add management functions for migration
Add management functions for migration
Python
bsd-3-clause
mfitzp/smrtr,mfitzp/smrtr
--- +++ @@ -1,7 +1,7 @@ from optparse import make_option import sys from django.core.management.base import BaseCommand -from education.models import Concept +from concept.models import Concept class Command(BaseCommand): args = ""
fb2cfe4759fb98de644932af17a247428b2cc0f5
api/auth.py
api/auth.py
from django.http import HttpResponseForbidden from django.contrib.auth.models import AnonymousUser from api.models import AuthAPIKey class APIKeyAuthentication(object): def is_authenticated(self, request): params = {} for key,value in request.GET.items(): params[key.lower()] = value if params['apikey']: try: keyobj = AuthAPIKey.objects.get(key=params['apikey']) except: keyobj = None if keyobj and keyobj.active: request.user = AnonymousUser() return True return False def challenge(self): return HttpResponseForbidden('Access Denied, use a API Key')
from django.http import HttpResponseForbidden from django.contrib.auth.models import AnonymousUser from api.models import AuthAPIKey class APIKeyAuthentication(object): def is_authenticated(self, request): params = {} for key,value in request.GET.items(): params[key.lower()] = value if 'apikey' in params: try: keyobj = AuthAPIKey.objects.get(key=params['apikey']) except: keyobj = None if keyobj and keyobj.active: request.user = AnonymousUser() return True return False def challenge(self): return HttpResponseForbidden('Access Denied, use a API Key')
Fix Auth API key check causing error 500s
Fix Auth API key check causing error 500s
Python
bsd-3-clause
nikdoof/test-auth
--- +++ @@ -10,7 +10,7 @@ for key,value in request.GET.items(): params[key.lower()] = value - if params['apikey']: + if 'apikey' in params: try: keyobj = AuthAPIKey.objects.get(key=params['apikey']) except:
a1d9312e1ac6f66aaf558652d890ac2a6bd67e40
backend/loader/model/datafile.py
backend/loader/model/datafile.py
from dataitem import DataItem class DataFile(DataItem): def __init__(self, name, access, owner): super(DataFile, self).__init__(name, access, owner, "datafile") self.checksum = "" self.size = 0 self.location = "" self.mediatype = "" self.conditions = [] self.text = "" self.metatags = [] self.datadirs = []
from dataitem import DataItem class DataFile(DataItem): def __init__(self, name, access, owner): super(DataFile, self).__init__(name, access, owner, "datafile") self.checksum = "" self.size = 0 self.location = "" self.mediatype = "" self.conditions = [] self.text = "" self.metatags = [] self.datadirs = [] self.parent = ""
Add parent so we can track versions.
Add parent so we can track versions.
Python
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
--- +++ @@ -11,3 +11,4 @@ self.text = "" self.metatags = [] self.datadirs = [] + self.parent = ""
8188008cf1bd41c1cbe0452ff635dd0319dfecd9
derrida/books/urls.py
derrida/books/urls.py
from django.conf.urls import url from django.contrib.admin.views.decorators import staff_member_required from derrida.books.views import ( PublisherAutocomplete, LanguageAutocomplete, InstanceDetailView, InstanceListView ) urlpatterns = [ # TODO: come up with cleaner url patterns/names for autocomplete views url(r'^publishers/autocomplete/$', staff_member_required(PublisherAutocomplete.as_view()), name='publisher-autocomplete'), url(r'^languages/autocomplete/$', staff_member_required(LanguageAutocomplete.as_view()), name='language-autocomplete'), url(r'^(?P<pk>\d+)$', InstanceDetailView.as_view(), name='detail'), url(r'^$', InstanceListView.as_view(), name='list'), ]
from django.conf.urls import url from django.contrib.admin.views.decorators import staff_member_required from derrida.books.views import ( PublisherAutocomplete, LanguageAutocomplete, InstanceDetailView, InstanceListView ) urlpatterns = [ # TODO: come up with cleaner url patterns/names for autocomplete views url(r'^publishers/autocomplete/$', staff_member_required(PublisherAutocomplete.as_view()), name='publisher-autocomplete'), url(r'^languages/autocomplete/$', staff_member_required(LanguageAutocomplete.as_view()), name='language-autocomplete'), url(r'^(?P<pk>\d+)/$', InstanceDetailView.as_view(), name='detail'), url(r'^$', InstanceListView.as_view(), name='list'), ]
Add trailing slash to url
Add trailing slash to url
Python
apache-2.0
Princeton-CDH/derrida-django,Princeton-CDH/derrida-django,Princeton-CDH/derrida-django,Princeton-CDH/derrida-django
--- +++ @@ -13,6 +13,6 @@ name='publisher-autocomplete'), url(r'^languages/autocomplete/$', staff_member_required(LanguageAutocomplete.as_view()), name='language-autocomplete'), - url(r'^(?P<pk>\d+)$', InstanceDetailView.as_view(), name='detail'), + url(r'^(?P<pk>\d+)/$', InstanceDetailView.as_view(), name='detail'), url(r'^$', InstanceListView.as_view(), name='list'), ]
eaa17491581cbb52242fbe543dd09929f537a8bc
mysettings.py
mysettings.py
from src.markdown.makrdown import jinja_aware_markdown PREFERRED_URL_SCHEME = 'http' SERVER_NAME = 'localhost:5000' FLATPAGES_EXTENSION = '.md' FLATPAGES_HTML_RENDERER = jinja_aware_markdown FREEZER_IGNORE_404_NOT_FOUND = True FLATPAGES_AUTO_RELOAD = True GITHUB_URL = 'https://github.com/JetBrains/kotlin' TWITTER_URL = 'https://twitter.com/kotlin' EDIT_ON_GITHUB_URL = 'https://github.com/JetBrains/kotlin-web-site/edit/master/' PDF_URL = '/docs/kotlin-docs.pdf' FORUM_URL = 'http://devnet.jetbrains.com/community/kotlin' SITE_GITHUB_URL = 'http://github.com/JetBrains/kotlin-web-site' CODE_URL = 'https://github.com/JetBrains/kotlin-examples/tree/master' TEXT_USING_GRADLE = "In this tutorial we're going to be using Gradle but the same can be accomplished using either IntelliJ IDEA project structure or Maven. For details on setting up Gradle to work with Kotlin, see [Using Gradle](/docs/reference/using-gradle.html)."
from src.markdown.makrdown import jinja_aware_markdown PREFERRED_URL_SCHEME = 'http' SERVER_NAME = 'localhost:5000' FLATPAGES_EXTENSION = '.md' FLATPAGES_HTML_RENDERER = jinja_aware_markdown FREEZER_IGNORE_404_NOT_FOUND = True FLATPAGES_AUTO_RELOAD = True FREEZER_STATIC_IGNORE = ["*"] GITHUB_URL = 'https://github.com/JetBrains/kotlin' TWITTER_URL = 'https://twitter.com/kotlin' EDIT_ON_GITHUB_URL = 'https://github.com/JetBrains/kotlin-web-site/edit/master/' PDF_URL = '/docs/kotlin-docs.pdf' FORUM_URL = 'http://devnet.jetbrains.com/community/kotlin' SITE_GITHUB_URL = 'http://github.com/JetBrains/kotlin-web-site' CODE_URL = 'https://github.com/JetBrains/kotlin-examples/tree/master' TEXT_USING_GRADLE = "In this tutorial we're going to be using Gradle but the same can be accomplished using either IntelliJ IDEA project structure or Maven. For details on setting up Gradle to work with Kotlin, see [Using Gradle](/docs/reference/using-gradle.html)."
Add option to ignore static.
Add option to ignore static.
Python
apache-2.0
meilalina/kotlin-web-site,meilalina/kotlin-web-site,hltj/kotlin-web-site-cn,hltj/kotlin-web-site-cn,JetBrains/kotlin-web-site,JetBrains/kotlin-web-site,hltj/kotlin-web-site-cn,hltj/kotlin-web-site-cn,JetBrains/kotlin-web-site,JetBrains/kotlin-web-site,meilalina/kotlin-web-site,JetBrains/kotlin-web-site,meilalina/kotlin-web-site,hltj/kotlin-web-site-cn,JetBrains/kotlin-web-site,hltj/kotlin-web-site-cn
--- +++ @@ -6,6 +6,7 @@ FLATPAGES_HTML_RENDERER = jinja_aware_markdown FREEZER_IGNORE_404_NOT_FOUND = True FLATPAGES_AUTO_RELOAD = True +FREEZER_STATIC_IGNORE = ["*"] GITHUB_URL = 'https://github.com/JetBrains/kotlin' TWITTER_URL = 'https://twitter.com/kotlin' EDIT_ON_GITHUB_URL = 'https://github.com/JetBrains/kotlin-web-site/edit/master/'
c90dbc5007b5627b264493c2d16af79cff9c2af0
joku/checks.py
joku/checks.py
""" Specific checks. """ from discord.ext.commands import CheckFailure def is_owner(ctx): if not ctx.bot.owner_id == ctx.message.author.id: raise CheckFailure(message="You are not the owner.") return True
""" Specific checks. """ from discord.ext.commands import CheckFailure, check def is_owner(ctx): if not ctx.bot.owner_id == ctx.message.author.id: raise CheckFailure(message="You are not the owner.") return True def has_permissions(**perms): def predicate(ctx): if ctx.bot.owner_id == ctx.message.author.id: return True msg = ctx.message ch = msg.channel permissions = ch.permissions_for(msg.author) if all(getattr(permissions, perm, None) == value for perm, value in perms.items()): return True # Raise a custom error message raise CheckFailure(message="You do not have any of the required permissions: {}".format( ', '.join([perm.upper() for perm in perms]) )) return check(predicate)
Add better custom has_permission check.
Add better custom has_permission check.
Python
mit
MJB47/Jokusoramame,MJB47/Jokusoramame,MJB47/Jokusoramame
--- +++ @@ -1,10 +1,28 @@ """ Specific checks. """ -from discord.ext.commands import CheckFailure +from discord.ext.commands import CheckFailure, check def is_owner(ctx): if not ctx.bot.owner_id == ctx.message.author.id: raise CheckFailure(message="You are not the owner.") return True + + +def has_permissions(**perms): + def predicate(ctx): + if ctx.bot.owner_id == ctx.message.author.id: + return True + msg = ctx.message + ch = msg.channel + permissions = ch.permissions_for(msg.author) + if all(getattr(permissions, perm, None) == value for perm, value in perms.items()): + return True + + # Raise a custom error message + raise CheckFailure(message="You do not have any of the required permissions: {}".format( + ', '.join([perm.upper() for perm in perms]) + )) + + return check(predicate)
1b2f0be67a8372a652b786c8b183cd5edf1807cd
config/fuzz_pox_mesh.py
config/fuzz_pox_mesh.py
from experiment_config_lib import ControllerConfig from sts.topology import MeshTopology from sts.control_flow import Fuzzer from sts.input_traces.input_logger import InputLogger from sts.invariant_checker import InvariantChecker from sts.simulation_state import SimulationConfig # Use POX as our controller command_line = ('''./pox.py --verbose --no-cli sts.syncproto.pox_syncer ''' '''samples.topo forwarding.l2_multi ''' '''sts.util.socket_mux.pox_monkeypatcher ''' '''openflow.of_01 --address=../sts_socket_pipe''') controllers = [ControllerConfig(command_line, address="sts_socket_pipe", cwd="pox", sync="tcp:localhost:18899")] topology_class = MeshTopology topology_params = "num_switches=4" dataplane_trace = "dataplane_traces/ping_pong_same_subnet_4_switches.trace" simulation_config = SimulationConfig(controller_configs=controllers, topology_class=topology_class, topology_params=topology_params, dataplane_trace=dataplane_trace, multiplex_sockets=True) control_flow = Fuzzer(simulation_config, check_interval=1, halt_on_violation=True, input_logger=InputLogger(), invariant_check=InvariantChecker.check_liveness)
from experiment_config_lib import ControllerConfig from sts.topology import MeshTopology from sts.control_flow import Fuzzer, Interactive from sts.input_traces.input_logger import InputLogger from sts.invariant_checker import InvariantChecker from sts.simulation_state import SimulationConfig # Use POX as our controller command_line = ('''./pox.py --verbose openflow.debug ''' #sts.syncproto.pox_syncer ''' '''forwarding.l2_multi ''' #'''sts.util.socket_mux.pox_monkeypatcher ''' '''openflow.of_01 --address=__address__ --port=__port__''') controllers = [ControllerConfig(command_line, cwd="betta")] topology_class = MeshTopology topology_params = "num_switches=2" dataplane_trace = "dataplane_traces/ping_pong_same_subnet.trace" simulation_config = SimulationConfig(controller_configs=controllers, topology_class=topology_class, topology_params=topology_params, dataplane_trace=dataplane_trace, multiplex_sockets=False) control_flow = Fuzzer(simulation_config, check_interval=80, halt_on_violation=False, input_logger=InputLogger(), invariant_check=InvariantChecker.check_connectivity) #control_flow = Interactive(simulation_config, input_logger=InputLogger())
Swap back to Fuzzer, no monkey patching
Swap back to Fuzzer, no monkey patching
Python
apache-2.0
jmiserez/sts,jmiserez/sts,ucb-sts/sts,ucb-sts/sts
--- +++ @@ -1,27 +1,29 @@ from experiment_config_lib import ControllerConfig from sts.topology import MeshTopology -from sts.control_flow import Fuzzer +from sts.control_flow import Fuzzer, Interactive from sts.input_traces.input_logger import InputLogger from sts.invariant_checker import InvariantChecker from sts.simulation_state import SimulationConfig # Use POX as our controller -command_line = ('''./pox.py --verbose --no-cli sts.syncproto.pox_syncer ''' - '''samples.topo forwarding.l2_multi ''' - '''sts.util.socket_mux.pox_monkeypatcher ''' - '''openflow.of_01 --address=../sts_socket_pipe''') -controllers = [ControllerConfig(command_line, address="sts_socket_pipe", cwd="pox", sync="tcp:localhost:18899")] +command_line = ('''./pox.py --verbose openflow.debug ''' #sts.syncproto.pox_syncer ''' + '''forwarding.l2_multi ''' + #'''sts.util.socket_mux.pox_monkeypatcher ''' + '''openflow.of_01 --address=__address__ --port=__port__''') +controllers = [ControllerConfig(command_line, cwd="betta")] topology_class = MeshTopology -topology_params = "num_switches=4" -dataplane_trace = "dataplane_traces/ping_pong_same_subnet_4_switches.trace" +topology_params = "num_switches=2" +dataplane_trace = "dataplane_traces/ping_pong_same_subnet.trace" simulation_config = SimulationConfig(controller_configs=controllers, topology_class=topology_class, topology_params=topology_params, dataplane_trace=dataplane_trace, - multiplex_sockets=True) + multiplex_sockets=False) -control_flow = Fuzzer(simulation_config, check_interval=1, halt_on_violation=True, +control_flow = Fuzzer(simulation_config, check_interval=80, + halt_on_violation=False, input_logger=InputLogger(), - invariant_check=InvariantChecker.check_liveness) + invariant_check=InvariantChecker.check_connectivity) +#control_flow = Interactive(simulation_config, input_logger=InputLogger())
644fbef7030f0685be7dd056606ab23daaefdc72
app/gitlab.py
app/gitlab.py
from __future__ import absolute_import from __future__ import unicode_literals from .webhooks import WebHook from werkzeug.exceptions import BadRequest, NotImplemented EVENTS = { 'Push Hook': 'push', 'Tag Push Hook': 'tag_push', 'Issue Hook': 'issue', 'Note Hook': 'note', 'Merge Request Hook': 'merge_request' } class GitlabWebHook(WebHook): def event(self, request): gitlab_header = request.headers.get('X-Gitlab-Event', None) if not gitlab_header: raise BadRequest('Gitlab requests must provide a X-Gitlab-Event header') event = EVENTS.get(gitlab_header, None) if not event: raise NotImplemented('Header not understood %s' % githab_header) if event == 'note': if 'commit' in request.json: event = 'commit_comment' elif 'merge_request' in request.json: event = 'merge_request_comment' elif 'issue' in request.json: event = 'issue_comment' elif 'snippet' in request.json: event = 'snippet_comment' return event
from __future__ import absolute_import from __future__ import unicode_literals from .webhooks import WebHook from werkzeug.exceptions import BadRequest, NotImplemented EVENTS = { 'Push Hook': 'push', 'Tag Push Hook': 'tag_push', 'Issue Hook': 'issue', 'Note Hook': 'note', 'Merge Request Hook': 'merge_request' } class GitlabWebHook(WebHook): def event(self, request): gitlab_header = request.headers.get('X-Gitlab-Event', None) if not gitlab_header: raise BadRequest('Gitlab requests must provide a X-Gitlab-Event header') event = EVENTS.get(gitlab_header, None) if not event: raise NotImplemented('Header not understood %s' % gitlab_header) if event == 'note': if 'commit' in request.json: event = 'commit_comment' elif 'merge_request' in request.json: event = 'merge_request_comment' elif 'issue' in request.json: event = 'issue_comment' elif 'snippet' in request.json: event = 'snippet_comment' return event
Fix typo in error message variable
Fix typo in error message variable
Python
apache-2.0
pipex/gitbot,pipex/gitbot,pipex/gitbot
--- +++ @@ -21,7 +21,7 @@ event = EVENTS.get(gitlab_header, None) if not event: - raise NotImplemented('Header not understood %s' % githab_header) + raise NotImplemented('Header not understood %s' % gitlab_header) if event == 'note': if 'commit' in request.json:
abb00ac993154071776488b5dcaef32cc2982f4c
test/functional/master/test_endpoints.py
test/functional/master/test_endpoints.py
import os import yaml from test.framework.functional.base_functional_test_case import BaseFunctionalTestCase from test.functional.job_configs import BASIC_JOB class TestMasterEndpoints(BaseFunctionalTestCase): def _start_master_only_and_post_a_new_job(self): master = self.cluster.start_master() build_resp = master.post_new_build({ 'type': 'directory', 'config': yaml.safe_load(BASIC_JOB.config[os.name])['BasicJob'], 'project_directory': '/tmp', }) build_id = build_resp['build_id'] return master, build_id def test_cancel_build(self): master, build_id = self._start_master_only_and_post_a_new_job() master.cancel_build(build_id) master.block_until_build_finished(build_id) self.assert_build_has_canceled_status(build_id=build_id) def test_get_artifact_before_it_is_ready(self): master, build_id = self._start_master_only_and_post_a_new_job() # Since we didn't start any slaves so the artifacts is actually not ready. _, status_code = master.get_build_artifacts(build_id) self.assertEqual(status_code, 202) # Cancel the started build just to speed up teardown (avoid teardown timeout waiting for empty queue) master.cancel_build(build_id)
import os import tempfile import yaml from test.framework.functional.base_functional_test_case import BaseFunctionalTestCase from test.functional.job_configs import BASIC_JOB class TestMasterEndpoints(BaseFunctionalTestCase): def setUp(self): super().setUp() self._project_dir = tempfile.TemporaryDirectory() def _start_master_only_and_post_a_new_job(self): master = self.cluster.start_master() build_resp = master.post_new_build({ 'type': 'directory', 'config': yaml.safe_load(BASIC_JOB.config[os.name])['BasicJob'], 'project_directory': self._project_dir.name, }) build_id = build_resp['build_id'] return master, build_id def test_cancel_build(self): master, build_id = self._start_master_only_and_post_a_new_job() master.cancel_build(build_id) master.block_until_build_finished(build_id) self.assert_build_has_canceled_status(build_id=build_id) def test_get_artifact_before_it_is_ready(self): master, build_id = self._start_master_only_and_post_a_new_job() # Since we didn't start any slaves so the artifacts is actually not ready. _, status_code = master.get_build_artifacts(build_id) self.assertEqual(status_code, 202) # Cancel the started build just to speed up teardown (avoid teardown timeout waiting for empty queue) master.cancel_build(build_id)
Fix broken functional tests on windows
Fix broken functional tests on windows Something must have changed on the Appveyor side since this code hasn't been touched recently. The issue was that a functional test was referring to "/tmp" which is not valid on Windows. I'm surprised this worked on Windows in the first place.
Python
apache-2.0
josephharrington/ClusterRunner,box/ClusterRunner,josephharrington/ClusterRunner,nickzuber/ClusterRunner,Medium/ClusterRunner,nickzuber/ClusterRunner,box/ClusterRunner,Medium/ClusterRunner
--- +++ @@ -1,4 +1,6 @@ import os +import tempfile + import yaml from test.framework.functional.base_functional_test_case import BaseFunctionalTestCase @@ -7,12 +9,16 @@ class TestMasterEndpoints(BaseFunctionalTestCase): + def setUp(self): + super().setUp() + self._project_dir = tempfile.TemporaryDirectory() + def _start_master_only_and_post_a_new_job(self): master = self.cluster.start_master() build_resp = master.post_new_build({ 'type': 'directory', 'config': yaml.safe_load(BASIC_JOB.config[os.name])['BasicJob'], - 'project_directory': '/tmp', + 'project_directory': self._project_dir.name, }) build_id = build_resp['build_id'] return master, build_id
81833470d1eb831e27e9e34712b983efbc38a735
solar_neighbourhood/prepare_data_add_kinematics.py
solar_neighbourhood/prepare_data_add_kinematics.py
""" Add very large RV errors for stars with no known RVs. Convert to cartesian. """ import numpy as np import sys sys.path.insert(0, '..') from chronostar import tabletool from astropy.table import Table datafile = Table.read('../data/ScoCen_box_result.fits') d = tabletool.read(datafile) # Set missing radial velocities (nan) to 0 d['radial_velocity'] = np.nan_to_num(d['radial_velocity']) # Set missing radial velocity errors (nan) to 1e+10 d['radial_velocity_error'][np.isnan(d['radial_velocity_error'])] = 1e+4 print('Convert to cartesian') tabletool.convert_table_astro2cart(table=d, return_table=True) d.write('../data/ScoCen_box_result_15M_ready_for_bg_ols.fits') print('Cartesian written.', len(d))
""" Add very large RV errors for stars with no known RVs. Convert to cartesian. """ import numpy as np import sys sys.path.insert(0, '..') from chronostar import tabletool from astropy.table import Table datafile = Table.read('../data/ScoCen_box_result.fits') d = Table.read(datafile) # Set missing radial velocities (nan) to 0 d['radial_velocity'] = np.nan_to_num(d['radial_velocity']) # Set missing radial velocity errors (nan) to 1e+10 d['radial_velocity_error'][np.isnan(d['radial_velocity_error'])] = 1e+4 print('Convert to cartesian') tabletool.convert_table_astro2cart(table=d, return_table=True) d.write('../data/ScoCen_box_result_15M_ready_for_bg_ols.fits') print('Cartesian written.', len(d))
Convert entire table to cartesian
Convert entire table to cartesian
Python
mit
mikeireland/chronostar,mikeireland/chronostar,mikeireland/chronostar,mikeireland/chronostar
--- +++ @@ -10,7 +10,7 @@ from astropy.table import Table datafile = Table.read('../data/ScoCen_box_result.fits') -d = tabletool.read(datafile) +d = Table.read(datafile) # Set missing radial velocities (nan) to 0 d['radial_velocity'] = np.nan_to_num(d['radial_velocity'])
fedb3768539259568555d5a62d503c7995f4b9a2
readthedocs/oauth/utils.py
readthedocs/oauth/utils.py
import logging from .models import GithubProject, GithubOrganization log = logging.getLogger(__name__) def make_github_project(user, org, privacy, repo_json): if (repo_json['private'] is True and privacy == 'private' or repo_json['private'] is False and privacy == 'public'): project, created = GithubProject.objects.get_or_create( user=user, organization=org, full_name=repo_json['full_name'], ) project.name = repo_json['name'] project.description = repo_json['description'] project.git_url = repo_json['git_url'] project.ssh_url = repo_json['ssh_url'] project.html_url = repo_json['html_url'] project.json = repo_json project.save() return project else: log.debug('Not importing %s because mismatched type' % repo_json['name']) def make_github_organization(user, org_json): org, created = GithubOrganization.objects.get_or_create( login=org_json.get('login'), html_url=org_json.get('html_url'), name=org_json.get('name'), email=org_json.get('email'), json=org_json, ) org.users.add(user) return org
import logging from .models import GithubProject, GithubOrganization log = logging.getLogger(__name__) def make_github_project(user, org, privacy, repo_json): if (repo_json['private'] is True and privacy == 'private' or repo_json['private'] is False and privacy == 'public'): project, created = GithubProject.objects.get_or_create( full_name=repo_json['full_name'], ) if project.user != user: log.debug('Not importing %s because mismatched user' % repo_json['name']) return None if project.organization and project.organization != org: log.debug('Not importing %s because mismatched orgs' % repo_json['name']) return None project.organization=org project.name = repo_json['name'] project.description = repo_json['description'] project.git_url = repo_json['git_url'] project.ssh_url = repo_json['ssh_url'] project.html_url = repo_json['html_url'] project.json = repo_json project.save() return project else: log.debug('Not importing %s because mismatched type' % repo_json['name']) def make_github_organization(user, org_json): org, created = GithubOrganization.objects.get_or_create( login=org_json.get('login'), html_url=org_json.get('html_url'), name=org_json.get('name'), email=org_json.get('email'), json=org_json, ) org.users.add(user) return org
Handle orgs that you don’t own personally.
Handle orgs that you don’t own personally.
Python
mit
istresearch/readthedocs.org,CedarLogic/readthedocs.org,KamranMackey/readthedocs.org,SteveViss/readthedocs.org,stevepiercy/readthedocs.org,soulshake/readthedocs.org,kenshinthebattosai/readthedocs.org,takluyver/readthedocs.org,cgourlay/readthedocs.org,soulshake/readthedocs.org,attakei/readthedocs-oauth,hach-que/readthedocs.org,CedarLogic/readthedocs.org,sid-kap/readthedocs.org,davidfischer/readthedocs.org,VishvajitP/readthedocs.org,singingwolfboy/readthedocs.org,davidfischer/readthedocs.org,singingwolfboy/readthedocs.org,kenshinthebattosai/readthedocs.org,rtfd/readthedocs.org,dirn/readthedocs.org,espdev/readthedocs.org,raven47git/readthedocs.org,davidfischer/readthedocs.org,clarkperkins/readthedocs.org,mrshoki/readthedocs.org,cgourlay/readthedocs.org,atsuyim/readthedocs.org,d0ugal/readthedocs.org,raven47git/readthedocs.org,kdkeyser/readthedocs.org,dirn/readthedocs.org,michaelmcandrew/readthedocs.org,fujita-shintaro/readthedocs.org,CedarLogic/readthedocs.org,titiushko/readthedocs.org,hach-que/readthedocs.org,michaelmcandrew/readthedocs.org,techtonik/readthedocs.org,mhils/readthedocs.org,clarkperkins/readthedocs.org,clarkperkins/readthedocs.org,atsuyim/readthedocs.org,attakei/readthedocs-oauth,cgourlay/readthedocs.org,Carreau/readthedocs.org,clarkperkins/readthedocs.org,raven47git/readthedocs.org,kdkeyser/readthedocs.org,tddv/readthedocs.org,Tazer/readthedocs.org,d0ugal/readthedocs.org,sils1297/readthedocs.org,mhils/readthedocs.org,agjohnson/readthedocs.org,asampat3090/readthedocs.org,espdev/readthedocs.org,Carreau/readthedocs.org,wanghaven/readthedocs.org,mrshoki/readthedocs.org,agjohnson/readthedocs.org,GovReady/readthedocs.org,stevepiercy/readthedocs.org,wijerasa/readthedocs.org,sils1297/readthedocs.org,hach-que/readthedocs.org,wijerasa/readthedocs.org,fujita-shintaro/readthedocs.org,gjtorikian/readthedocs.org,soulshake/readthedocs.org,kenwang76/readthedocs.org,wanghaven/readthedocs.org,GovReady/readthedocs.org,stevepiercy/readthedocs.org,LukasBoersma/readthedocs.org,takluyver/readthedocs.org,attakei/readthedocs-oauth,emawind84/readthedocs.org,Carreau/readthedocs.org,michaelmcandrew/readthedocs.org,laplaceliu/readthedocs.org,dirn/readthedocs.org,safwanrahman/readthedocs.org,titiushko/readthedocs.org,kdkeyser/readthedocs.org,istresearch/readthedocs.org,rtfd/readthedocs.org,sils1297/readthedocs.org,techtonik/readthedocs.org,nikolas/readthedocs.org,LukasBoersma/readthedocs.org,sid-kap/readthedocs.org,sunnyzwh/readthedocs.org,GovReady/readthedocs.org,jerel/readthedocs.org,sils1297/readthedocs.org,nikolas/readthedocs.org,laplaceliu/readthedocs.org,emawind84/readthedocs.org,tddv/readthedocs.org,laplaceliu/readthedocs.org,d0ugal/readthedocs.org,raven47git/readthedocs.org,emawind84/readthedocs.org,d0ugal/readthedocs.org,stevepiercy/readthedocs.org,Tazer/readthedocs.org,asampat3090/readthedocs.org,soulshake/readthedocs.org,istresearch/readthedocs.org,kenshinthebattosai/readthedocs.org,attakei/readthedocs-oauth,VishvajitP/readthedocs.org,mrshoki/readthedocs.org,dirn/readthedocs.org,LukasBoersma/readthedocs.org,sunnyzwh/readthedocs.org,titiushko/readthedocs.org,nikolas/readthedocs.org,CedarLogic/readthedocs.org,royalwang/readthedocs.org,VishvajitP/readthedocs.org,kenwang76/readthedocs.org,mhils/readthedocs.org,Tazer/readthedocs.org,hach-que/readthedocs.org,jerel/readthedocs.org,safwanrahman/readthedocs.org,takluyver/readthedocs.org,GovReady/readthedocs.org,safwanrahman/readthedocs.org,kenwang76/readthedocs.org,KamranMackey/readthedocs.org,fujita-shintaro/readthedocs.org,Carreau/readthedocs.org,wanghaven/readthedocs.org,asampat3090/readthedocs.org,techtonik/readthedocs.org,istresearch/readthedocs.org,sunnyzwh/readthedocs.org,tddv/readthedocs.org,laplaceliu/readthedocs.org,nikolas/readthedocs.org,kenwang76/readthedocs.org,sid-kap/readthedocs.org,espdev/readthedocs.org,KamranMackey/readthedocs.org,michaelmcandrew/readthedocs.org,rtfd/readthedocs.org,singingwolfboy/readthedocs.org,mrshoki/readthedocs.org,emawind84/readthedocs.org,pombredanne/readthedocs.org,espdev/readthedocs.org,espdev/readthedocs.org,KamranMackey/readthedocs.org,sid-kap/readthedocs.org,kdkeyser/readthedocs.org,atsuyim/readthedocs.org,agjohnson/readthedocs.org,kenshinthebattosai/readthedocs.org,wijerasa/readthedocs.org,jerel/readthedocs.org,cgourlay/readthedocs.org,fujita-shintaro/readthedocs.org,royalwang/readthedocs.org,SteveViss/readthedocs.org,agjohnson/readthedocs.org,royalwang/readthedocs.org,atsuyim/readthedocs.org,Tazer/readthedocs.org,safwanrahman/readthedocs.org,gjtorikian/readthedocs.org,mhils/readthedocs.org,gjtorikian/readthedocs.org,wijerasa/readthedocs.org,SteveViss/readthedocs.org,singingwolfboy/readthedocs.org,pombredanne/readthedocs.org,royalwang/readthedocs.org,techtonik/readthedocs.org,titiushko/readthedocs.org,LukasBoersma/readthedocs.org,sunnyzwh/readthedocs.org,wanghaven/readthedocs.org,VishvajitP/readthedocs.org,takluyver/readthedocs.org,davidfischer/readthedocs.org,jerel/readthedocs.org,rtfd/readthedocs.org,gjtorikian/readthedocs.org,SteveViss/readthedocs.org,asampat3090/readthedocs.org,pombredanne/readthedocs.org
--- +++ @@ -8,10 +8,15 @@ if (repo_json['private'] is True and privacy == 'private' or repo_json['private'] is False and privacy == 'public'): project, created = GithubProject.objects.get_or_create( - user=user, - organization=org, full_name=repo_json['full_name'], ) + if project.user != user: + log.debug('Not importing %s because mismatched user' % repo_json['name']) + return None + if project.organization and project.organization != org: + log.debug('Not importing %s because mismatched orgs' % repo_json['name']) + return None + project.organization=org project.name = repo_json['name'] project.description = repo_json['description'] project.git_url = repo_json['git_url']
59b2d0418c787066c37904816925dad15b0b45cf
scanblog/scanning/admin.py
scanblog/scanning/admin.py
from django.contrib import admin from scanning.models import PendingScan, Document, DocumentPage, Scan, ScanPage, Transcription class ScanPageInline(admin.TabularInline): model = ScanPage class ScanAdmin(admin.ModelAdmin): model = Scan inlines = [ScanPageInline] admin.site.register(Scan, ScanAdmin) class PendingScanAdmin(admin.ModelAdmin): model = PendingScan list_display = ('author', 'editor', 'code', 'created', 'completed') search_fields = ('code',) admin.site.register(PendingScan, PendingScanAdmin) class DocumentAdmin(admin.ModelAdmin): list_display = ['title', 'author', 'status', 'created'] search_fields = ['title', 'author__profile__display_name', 'body', 'transcription__revisions__body'] date_hierarchy = 'created' list_filter = ['type', 'status', 'author', 'author__profile__managed'] admin.site.register(Document, DocumentAdmin) admin.site.register(DocumentPage) admin.site.register(Transcription)
from django.contrib import admin from scanning.models import PendingScan, Document, DocumentPage, Scan, ScanPage, Transcription class ScanPageInline(admin.TabularInline): model = ScanPage class ScanAdmin(admin.ModelAdmin): model = Scan inlines = [ScanPageInline] admin.site.register(Scan, ScanAdmin) class PendingScanAdmin(admin.ModelAdmin): model = PendingScan list_display = ('author', 'editor', 'code', 'created', 'completed') search_fields = ('code',) admin.site.register(PendingScan, PendingScanAdmin) class DocumentAdmin(admin.ModelAdmin): list_display = ['title', 'author', 'status', 'created'] search_fields = ['title', 'author__profile__display_name', 'body', 'transcription__revisions__body'] date_hierarchy = 'created' list_filter = ['type', 'status', 'author__profile__managed', 'author__profile__display_name'] admin.site.register(Document, DocumentAdmin) admin.site.register(DocumentPage) admin.site.register(Transcription)
Use author display name in document list_filter
Use author display name in document list_filter
Python
agpl-3.0
yourcelf/btb,yourcelf/btb,flexpeace/btb,flexpeace/btb,yourcelf/btb,flexpeace/btb,flexpeace/btb,yourcelf/btb,flexpeace/btb,yourcelf/btb
--- +++ @@ -20,7 +20,8 @@ search_fields = ['title', 'author__profile__display_name', 'body', 'transcription__revisions__body'] date_hierarchy = 'created' - list_filter = ['type', 'status', 'author', 'author__profile__managed'] + list_filter = ['type', 'status', 'author__profile__managed', + 'author__profile__display_name'] admin.site.register(Document, DocumentAdmin) admin.site.register(DocumentPage)
e4e10ee0ae5a18cfec0e15b7b85986b7f4fc4f9d
feder/institutions/viewsets.py
feder/institutions/viewsets.py
import django_filters from rest_framework import filters, viewsets from teryt_tree.rest_framework_ext.viewsets import custom_area_filter from .models import Institution, Tag from .serializers import InstitutionSerializer, TagSerializer class InstitutionFilter(filters.FilterSet): jst = django_filters.CharFilter(method=custom_area_filter) def __init__(self, *args, **kwargs): super(InstitutionFilter, self).__init__(*args, **kwargs) self.filters['name'].lookup_expr = 'icontains' class Meta: model = Institution fields = ['name', 'tags', 'jst', 'regon'] class InstitutionViewSet(viewsets.ModelViewSet): queryset = (Institution.objects. select_related('jst'). prefetch_related('tags'). all()) serializer_class = InstitutionSerializer filter_backends = (filters.DjangoFilterBackend,) filter_class = InstitutionFilter class TagViewSet(viewsets.ModelViewSet): queryset = Tag.objects.all() serializer_class = TagSerializer
import django_filters from rest_framework import filters, viewsets from teryt_tree.rest_framework_ext.viewsets import custom_area_filter from .models import Institution, Tag from .serializers import InstitutionSerializer, TagSerializer class InstitutionFilter(filters.FilterSet): jst = django_filters.CharFilter(method=custom_area_filter) def __init__(self, *args, **kwargs): super(InstitutionFilter, self).__init__(*args, **kwargs) self.filters['name'].lookup_expr = 'icontains' class Meta: model = Institution fields = ['name', 'tags', 'jst', 'regon'] class InstitutionViewSet(viewsets.ModelViewSet): queryset = (Institution.objects. select_related('jst'). prefetch_related('tags','parents'). all()) serializer_class = InstitutionSerializer filter_backends = (filters.DjangoFilterBackend,) filter_class = InstitutionFilter class TagViewSet(viewsets.ModelViewSet): queryset = Tag.objects.all() serializer_class = TagSerializer
Fix prefetched fields in Institutions in API
Fix prefetched fields in Institutions in API
Python
mit
watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder
--- +++ @@ -21,7 +21,7 @@ class InstitutionViewSet(viewsets.ModelViewSet): queryset = (Institution.objects. select_related('jst'). - prefetch_related('tags'). + prefetch_related('tags','parents'). all()) serializer_class = InstitutionSerializer filter_backends = (filters.DjangoFilterBackend,)
19c0e8d856049677bc7de2bc293a87a0aac306f8
httpd/keystone.py
httpd/keystone.py
import os from paste import deploy from keystone import config from keystone.common import logging LOG = logging.getLogger(__name__) CONF = config.CONF config_files = ['/etc/keystone.conf'] CONF(config_files=config_files) conf = CONF.config_file[0] name = os.path.basename(__file__) if CONF.debug: CONF.log_opt_values(logging.getLogger(CONF.prog), logging.DEBUG) options = deploy.appconfig('config:%s' % CONF.config_file[0]) application = deploy.loadapp('config:%s' % conf, name=name)
import os from paste import deploy from keystone import config from keystone.common import logging LOG = logging.getLogger(__name__) CONF = config.CONF config_files = ['/etc/keystone/keystone.conf'] CONF(project='keystone', default_config_files=config_files) conf = CONF.config_file[0] name = os.path.basename(__file__) if CONF.debug: CONF.log_opt_values(logging.getLogger(CONF.prog), logging.DEBUG) options = deploy.appconfig('config:%s' % CONF.config_file[0]) application = deploy.loadapp('config:%s' % conf, name=name)
Fix wsgi config file access for HTTPD
Fix wsgi config file access for HTTPD Bug 1051081 Change-Id: Ie1690c9b1b98ed3f5a78d935878369b7520b35c9
Python
apache-2.0
ging/keystone,cloudbau/keystone,cloudbau/keystone,JioCloud/keystone,townbull/keystone-dtrust,roopali8/keystone,maestro-hybrid-cloud/keystone,townbull/keystone-dtrust,rickerc/keystone_audit,rickerc/keystone_audit,jumpstarter-io/keystone,cloudbau/keystone,jamielennox/keystone,cbrucks/Federated_Keystone,jumpstarter-io/keystone,takeshineshiro/keystone,himanshu-setia/keystone,derekchiang/keystone,maestro-hybrid-cloud/keystone,reeshupatel/demo,idjaw/keystone,derekchiang/keystone,cernops/keystone,dstanek/keystone,citrix-openstack-build/keystone,rickerc/keystone_audit,dsiddharth/access-keys,himanshu-setia/keystone,kwss/keystone,takeshineshiro/keystone,dstanek/keystone,openstack/keystone,blueboxgroup/keystone,jumpstarter-io/keystone,JioCloud/keystone,dstanek/keystone,vivekdhayaal/keystone,reeshupatel/demo,MaheshIBM/keystone,jamielennox/keystone,mahak/keystone,rushiagr/keystone,rodrigods/keystone,ajayaa/keystone,rushiagr/keystone,idjaw/keystone,blueboxgroup/keystone,promptworks/keystone,ntt-sic/keystone,reeshupatel/demo,kwss/keystone,nuxeh/keystone,dims/keystone,nuxeh/keystone,citrix-openstack-build/keystone,rajalokan/keystone,mahak/keystone,ilay09/keystone,klmitch/keystone,ntt-sic/keystone,ilay09/keystone,dims/keystone,rajalokan/keystone,ging/keystone,dsiddharth/access-keys,dsiddharth/access-keys,vivekdhayaal/keystone,ntt-sic/keystone,cbrucks/Federated_Keystone,rajalokan/keystone,rushiagr/keystone,mahak/keystone,promptworks/keystone,rodrigods/keystone,citrix-openstack-build/keystone,promptworks/keystone,ilay09/keystone,ajayaa/keystone,jonnary/keystone,kwss/keystone,MaheshIBM/keystone,nuxeh/keystone,vivekdhayaal/keystone,klmitch/keystone,openstack/keystone,openstack/keystone,townbull/keystone-dtrust,cbrucks/Federated_Keystone,derekchiang/keystone,UTSA-ICS/keystone-kerberos,roopali8/keystone,jonnary/keystone,cernops/keystone,UTSA-ICS/keystone-kerberos
--- +++ @@ -7,8 +7,8 @@ LOG = logging.getLogger(__name__) CONF = config.CONF -config_files = ['/etc/keystone.conf'] -CONF(config_files=config_files) +config_files = ['/etc/keystone/keystone.conf'] +CONF(project='keystone', default_config_files=config_files) conf = CONF.config_file[0] name = os.path.basename(__file__)
671ca30892e3ebeb0a9140f95690853b4b92dc02
post/views.py
post/views.py
from django.core.urlresolvers import reverse from django.utils.translation import ugettext as _ from post.models import Post from jmbo.generic.views import GenericObjectDetail, GenericObjectList from jmbo.view_modifiers import DefaultViewModifier class ObjectList(GenericObjectList): def get_extra_context(self, *args, **kwargs): return {'title': _('Posts')} def get_view_modifier(self, request, *args, **kwargs): return DefaultViewModifier(request, *args, **kwargs) def get_paginate_by(self, *args, **kwargs): return 12 def get_queryset(self, *args, **kwargs): return Post.permitted.all() object_list = ObjectList() class ObjectDetail(GenericObjectDetail): def get_queryset(self, *args, **kwargs): return Post.permitted.all() def get_extra_context(self, *args, **kwargs): return {'title': 'Posts'} def get_view_modifier(self, request, *args, **kwargs): return DefaultViewModifier( request, base_url=reverse("post_object_list"), ignore_defaults=True, *args, **kwargs ) object_detail = ObjectDetail()
from django.core.urlresolvers import reverse from django.utils.translation import ugettext as _ from post.models import Post from jmbo.generic.views import GenericObjectDetail, GenericObjectList from jmbo.view_modifiers import DefaultViewModifier class ObjectList(GenericObjectList): def get_extra_context(self, *args, **kwargs): return {'title': _('Posts')} def get_view_modifier(self, request, *args, **kwargs): return DefaultViewModifier(request, *args, **kwargs) def get_paginate_by(self, *args, **kwargs): return 12 def get_queryset(self, *args, **kwargs): return Post.permitted.all() object_list = ObjectList() class ObjectDetail(GenericObjectDetail): def get_queryset(self, *args, **kwargs): return Post.permitted.all() def get_extra_context(self, *args, **kwargs): return {'title': 'Posts'} def get_view_modifier(self, request, *args, **kwargs): return DefaultViewModifier( request, base_url=reverse("object_list", args=['post', 'post']), ignore_defaults=True, *args, **kwargs ) object_detail = ObjectDetail()
Fix reverse since we deprecated post_object_list
Fix reverse since we deprecated post_object_list
Python
bsd-3-clause
praekelt/jmbo-post,praekelt/jmbo-post
--- +++ @@ -32,7 +32,7 @@ def get_view_modifier(self, request, *args, **kwargs): return DefaultViewModifier( request, - base_url=reverse("post_object_list"), + base_url=reverse("object_list", args=['post', 'post']), ignore_defaults=True, *args, **kwargs
ee3b712611ed531843134ef4ce94cb45c726c127
nap/extras/actions.py
nap/extras/actions.py
from django.http import StreamingHttpResponse from django.utils.encoding import force_text from .models import modelserialiser_factory from .simplecsv import CSV class ExportCsv(object): def __init__(self, serialiser=None, label=None, **opts): self.serialiser = serialiser self.opts = opts if label: self.short_description = label def __call__(self, admin, request, queryset): if self.serialiser is None: ser_class = modelserialiser_factory( '%sSerialiser' % admin.__class__.__name__, admin.model, **self.opts ) else: ser_class = self.serialiser def inner(ser): csv = CSV(fields=ser._fields.keys()) yield csv.write_headers() for obj in queryset: data = { key: force_text(val) for key, val in ser.object_deflate(obj).items() } yield csv.write_dict(data) response = StreamingHttpResponse(inner(ser_class()), content_type='text/csv') filename = admin.csv_ response['Content-Disposition'] = 'attachment; filename=%s' % filename return response
from django.http import StreamingHttpResponse from django.utils.encoding import force_text from .models import modelserialiser_factory from .simplecsv import CSV class ExportCsv(object): def __init__(self, serialiser=None, label=None, **opts): self.serialiser = serialiser self.opts = opts if label: self.short_description = label def __call__(self, admin, request, queryset): if self.serialiser is None: ser_class = modelserialiser_factory( '%sSerialiser' % admin.__class__.__name__, admin.model, **self.opts ) else: ser_class = self.serialiser def inner(ser): csv = CSV(fields=ser._fields.keys()) yield csv.write_headers() for obj in queryset: data = { key: force_text(val) for key, val in ser.object_deflate(obj).items() } yield csv.write_dict(data) response = StreamingHttpResponse(inner(ser_class()), content_type='text/csv') filename = self.opts.get('filename', 'export_{classname}.csv') if callable(filename): filename = filename(admin) else: filename = filename.format( classname=admin.__class__.__name__, model=admin.model._meta.module_name, app_label=admin.model._meta.app_label, ) response['Content-Disposition'] = 'attachment; filename=%s' % filename return response
Fix filename creation in csv export action
Fix filename creation in csv export action
Python
bsd-3-clause
limbera/django-nap,MarkusH/django-nap
--- +++ @@ -34,7 +34,15 @@ yield csv.write_dict(data) response = StreamingHttpResponse(inner(ser_class()), content_type='text/csv') - filename = admin.csv_ + filename = self.opts.get('filename', 'export_{classname}.csv') + if callable(filename): + filename = filename(admin) + else: + filename = filename.format( + classname=admin.__class__.__name__, + model=admin.model._meta.module_name, + app_label=admin.model._meta.app_label, + ) response['Content-Disposition'] = 'attachment; filename=%s' % filename return response
63eaf0faf56a70fadbd37f0acac6f5e61c7b19eb
checkdns.py
checkdns.py
# coding=utf8 # 31.220.16.242 # 216.58.222.46 import socket import time import webbrowser def checkdns(): print time.ctime() retorno = True try: ip = socket.gethostbyname('google.com') print ("O IP do host verificado é: " + ip) if ip == "216.58.222.46": retorno = False url = 'http://www.google.com.br/' webbrowser.open_new_tab(url) else: print "DNS ainda não atualizado. Aguardando 30s." time.sleep( 30 ) except socket.gaierror: print "Nenhum host definido para o domínio. Aguardando 30s." time.sleep( 30 ) return retorno condicao = True while condicao: condicao = checkdns()
# coding=utf8 # 31.220.16.242 # 216.58.222.46 import socket import time import webbrowser def checkdns(): print time.ctime() retorno = True try: ip = socket.gethostbyname('google.com') print ("O IP do host verificado é: " + ip) if ip == "216.58.22.46": retorno = False url = 'http://www.google.com.br/' webbrowser.open_new_tab(url) else: print "DNS ainda não atualizado. Aguardando 30s." except socket.gaierror: print "Nenhum host definido para o domínio. Aguardando 30s." return retorno condicao = True while condicao: condicao = checkdns() time.sleep( 30 )
Change sleep function to the end to do repeat everytime
Change sleep function to the end to do repeat everytime
Python
mit
felipebhz/checkdns
--- +++ @@ -14,18 +14,17 @@ try: ip = socket.gethostbyname('google.com') print ("O IP do host verificado é: " + ip) - if ip == "216.58.222.46": + if ip == "216.58.22.46": retorno = False url = 'http://www.google.com.br/' webbrowser.open_new_tab(url) else: print "DNS ainda não atualizado. Aguardando 30s." - time.sleep( 30 ) except socket.gaierror: print "Nenhum host definido para o domínio. Aguardando 30s." - time.sleep( 30 ) return retorno condicao = True while condicao: condicao = checkdns() + time.sleep( 30 )
ab78bf2c47a8bec5c1d0c5a7951dba1c98f5c28e
check_gm.py
check_gm.py
#!/usr/bin/env python3 # vi:tabstop=4:expandtab:shiftwidth=4:softtabstop=4:autoindent:smarttab import os, sys import sqlite3 import urllib.request err = False for version in range (7, 14): fname = 'tables_v1.sql' if version < 12 else 'tables.sql' url = 'https://cdn.jsdelivr.net/gh/moneymanagerex/database@v%i/%s' % (version, fname) schema = urllib.request.urlopen(url).read().decode('utf-8') db = sqlite3.connect(':memory:') db.executescript(schema) print('\nTesting reports with MMEX db schema v%i:' % version) print('-' * 40) for root, dirs, files in os.walk('.'): for sql in files: if sql=='sqlcontent.sql': try: db.executescript(open(os.path.join(root, sql)).read()) except sqlite3.Error as e: print('ERR', os.path.basename(root).ljust(40), e.args[0]) err = True else: print('OK ', os.path.basename(root)) db.rollback() db.close() if err: sys.exit(1)
#!/usr/bin/env python3 # vi:tabstop=4:expandtab:shiftwidth=4:softtabstop=4:autoindent:smarttab import os, sys import sqlite3 import urllib.request err = False for version in range (7, 14): fname = 'tables_v1.sql' if version < 12 else 'tables.sql' url = 'https://cdn.jsdelivr.net/gh/moneymanagerex/database@v%i/%s' % (version, fname) schema = urllib.request.urlopen(url).read().decode('utf-8') db = sqlite3.connect(':memory:') db.executescript(schema) print('\nTesting reports with MMEX db schema v%i:' % version) print('-' * 40) for root, dirs, files in os.walk('.'): for sql in files: if sql=='sqlcontent.sql': try: db.executescript(open(os.path.join(root, sql)).read()) except sqlite3.Error as e: print('ERR', os.path.basename(root).ljust(40), e.args[0]) err = True else: print('OK ', os.path.basename(root)) db.rollback() db.close() if err: sys.exit(1)
Revert file to moneymanager master branch.
Revert file to moneymanager master branch.
Python
mit
moneymanagerex/general-reports,moneymanagerex/general-reports
175bbd2f181d067712d38beeca9df4063654103a
nlppln/frog_to_saf.py
nlppln/frog_to_saf.py
#!/usr/bin/env python import click import os import codecs import json from xtas.tasks._frog import parse_frog, frog_to_saf @click.command() @click.argument('input_files', nargs=-1, type=click.Path(exists=True)) @click.argument('output_dir', nargs=1, type=click.Path()) def frog2saf(input_files, output_dir): if not os.path.exists(output_dir): os.makedirs(output_dir) for fi in input_files: with codecs.open(fi) as f: lines = f.readlines() lines = [line.strip() for line in lines] saf_data = frog_to_saf(parse_frog(lines)) head, tail = os.path.split(fi) out_file = os.path.join(output_dir, '{}.json'.format(tail)) with codecs.open(out_file, 'wb', encoding='utf-8') as f: json.dump(saf_data, f, indent=4) if __name__ == '__main__': frog2saf()
#!/usr/bin/env python import click import os import codecs import json from xtas.tasks._frog import parse_frog, frog_to_saf @click.command() @click.argument('input_files', nargs=-1, type=click.Path(exists=True)) @click.argument('output_dir', nargs=1, type=click.Path()) def frog2saf(input_files, output_dir): if not os.path.exists(output_dir): os.makedirs(output_dir) for fi in input_files: with codecs.open(fi) as f: lines = f.readlines() lines = [line.strip() for line in lines] saf_data = frog_to_saf(parse_frog(lines)) head, tail = os.path.split(fi) fname = tail.replace(os.path.splitext(tail)[1], '') out_file = os.path.join(output_dir, '{}.json'.format(fname)) with codecs.open(out_file, 'wb', encoding='utf-8') as f: json.dump(saf_data, f, indent=4) if __name__ == '__main__': frog2saf()
Update script to remove extension from filename
Update script to remove extension from filename Before, the script added the extension .json to whatever the file name was. Now, it removes the last extension and then appends .json.
Python
apache-2.0
WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln
--- +++ @@ -21,8 +21,9 @@ saf_data = frog_to_saf(parse_frog(lines)) head, tail = os.path.split(fi) + fname = tail.replace(os.path.splitext(tail)[1], '') - out_file = os.path.join(output_dir, '{}.json'.format(tail)) + out_file = os.path.join(output_dir, '{}.json'.format(fname)) with codecs.open(out_file, 'wb', encoding='utf-8') as f: json.dump(saf_data, f, indent=4)
7e4b66fe3df07afa431201de7a5a76d2eeb949a1
app/main.py
app/main.py
#!/usr/bin/env python from env_setup import setup_django setup_django() from env_setup import setup setup() from webapp2 import RequestHandler, Route, WSGIApplication from agar.env import on_production_server from agar.config import Config from agar.django.templates import render_template class MainApplicationConfig(Config): """ :py:class:`~agar.config.Config` settings for the ``main`` `webapp2.WSGIApplication`_. Settings are under the ``main_application`` namespace. The following settings (and defaults) are provided:: main_application_NOOP = None To override ``main`` `webapp2.WSGIApplication`_ settings, define values in the ``appengine_config.py`` file in the root of your project. """ _prefix = 'main_application' #: A no op. NOOP = None config = MainApplicationConfig.get_config() class MainHandler(RequestHandler): def get(self): render_template(self.response, 'index.html') application = WSGIApplication( [ Route('/', MainHandler, name='main'), ], debug=not on_production_server) def main(): from google.appengine.ext.webapp import template, util template.register_template_library('agar.django.templatetags') util.run_wsgi_app(application) if __name__ == '__main__': main()
#!/usr/bin/env python import env_setup; env_setup.setup(); env_setup.setup_django() from django.template import add_to_builtins add_to_builtins('agar.django.templatetags') from webapp2 import RequestHandler, Route, WSGIApplication from agar.env import on_production_server from agar.config import Config from agar.django.templates import render_template class MainApplicationConfig(Config): """ :py:class:`~agar.config.Config` settings for the ``main`` `webapp2.WSGIApplication`_. Settings are under the ``main_application`` namespace. The following settings (and defaults) are provided:: main_application_NOOP = None To override ``main`` `webapp2.WSGIApplication`_ settings, define values in the ``appengine_config.py`` file in the root of your project. """ _prefix = 'main_application' #: A no op. NOOP = None config = MainApplicationConfig.get_config() class MainHandler(RequestHandler): def get(self): render_template(self.response, 'index.html') application = WSGIApplication( [ Route('/', MainHandler, name='main'), ], debug=not on_production_server) def main(): from google.appengine.ext.webapp import template, util template.register_template_library('agar.django.templatetags') util.run_wsgi_app(application) if __name__ == '__main__': main()
Fix django custom template tag importing
Fix django custom template tag importing
Python
mit
xuru/substrate,xuru/substrate,xuru/substrate
--- +++ @@ -1,9 +1,9 @@ #!/usr/bin/env python -from env_setup import setup_django -setup_django() -from env_setup import setup -setup() +import env_setup; env_setup.setup(); env_setup.setup_django() + +from django.template import add_to_builtins +add_to_builtins('agar.django.templatetags') from webapp2 import RequestHandler, Route, WSGIApplication
aaba085cd2e97c8c23e6724da3313d42d12798f0
app/grandchallenge/annotations/validators.py
app/grandchallenge/annotations/validators.py
from rest_framework import serializers from django.conf import settings def validate_grader_is_current_retina_user(grader, context): """ This method checks if the passed grader equals the request.user that is passed in the context. Only applies to users that are in the retina_graders group. """ request = context.get("request") if request and request.user.is_authenticated: user = request.user if user.groups.filter( name=settings.RETINA_GRADERS_GROUP_NAME ).exists(): if grader != user: raise serializers.ValidationError( "User is not allowed to create annotation for other grader" )
from rest_framework import serializers from django.conf import settings def validate_grader_is_current_retina_user(grader, context): """ This method checks if the passed grader equals the request.user that is passed in the context. Only applies to users that are in the retina_graders group. """ request = context.get("request") if ( request is not None and request.user is not None and request.user.is_authenticated ): user = request.user if user.groups.filter( name=settings.RETINA_GRADERS_GROUP_NAME ).exists(): if grader != user: raise serializers.ValidationError( "User is not allowed to create annotation for other grader" )
Make sure request.user is a user
Make sure request.user is a user
Python
apache-2.0
comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django
--- +++ @@ -8,7 +8,11 @@ Only applies to users that are in the retina_graders group. """ request = context.get("request") - if request and request.user.is_authenticated: + if ( + request is not None + and request.user is not None + and request.user.is_authenticated + ): user = request.user if user.groups.filter( name=settings.RETINA_GRADERS_GROUP_NAME
ac6ce056e6b05531d81c550ae3e1e1d688ece4a0
jwt_auth/serializers.py
jwt_auth/serializers.py
from .models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(max_length=20, min_length=8, trim_whitespace=False, write_only=True) class Meta: model = User fields = ('id', 'nickname', 'username', 'email', 'password') # default `create` method call `model.objects.create` method to create new instance # override to create user correctly def create(self, validated_data): return User.objects.create_user(**validated_data) # since the password cannot be changed directly # override to update user correctly def update(self, instance, validated_data): if 'password' in validated_data: instance.set_password(validated_data['password']) instance.nickname = validated_data.get('nickname', instance.nickname) instance.save() return instance
from .models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(max_length=20, min_length=8, trim_whitespace=False, write_only=True) class Meta: model = User fields = ('id', 'nickname', 'username', 'email', 'password') # serializer's default `create` method will call `model.objects.create` # method to create new instance, override to create user correctly. def create(self, validated_data): return User.objects.create_user(**validated_data) # since the password cannot be changed directly # override to update user correctly def update(self, instance, validated_data): if 'password' in validated_data: instance.set_password(validated_data['password']) instance.nickname = validated_data.get('nickname', instance.nickname) instance.save() return instance
Make serializer commet more clear
[docs](jwt_auth): Make serializer commet more clear
Python
mit
codertx/lightil
--- +++ @@ -8,8 +8,8 @@ model = User fields = ('id', 'nickname', 'username', 'email', 'password') - # default `create` method call `model.objects.create` method to create new instance - # override to create user correctly + # serializer's default `create` method will call `model.objects.create` + # method to create new instance, override to create user correctly. def create(self, validated_data): return User.objects.create_user(**validated_data)
d64460c8bbbe045dcdf9f737562a31d84044acce
rest/setup.py
rest/setup.py
# # Copyright 2012 University of Southern California # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from distutils.core import setup setup(name="cirm-rest", description="cirm web application", version="0.1", package_dir={"": "src"}, packages=["cirmrest"], requires=["web.py", "psycopg2"], classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Topic :: Internet :: WWW/HTTP", "Topic :: Software Development :: Libraries :: Python Modules", ], )
# # Copyright 2012 University of Southern California # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from distutils.core import setup setup(name="cirm-rest", description="cirm web application", version="0.1", package_dir={"": "src"}, packages=["cirm"], requires=["web.py", "psycopg2"], classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Topic :: Internet :: WWW/HTTP", "Topic :: Software Development :: Libraries :: Python Modules", ], )
Change package name to 'cirm' to avoid confusion.
Change package name to 'cirm' to avoid confusion.
Python
apache-2.0
informatics-isi-edu/microscopy,informatics-isi-edu/microscopy,informatics-isi-edu/microscopy,informatics-isi-edu/microscopy
--- +++ @@ -20,7 +20,7 @@ description="cirm web application", version="0.1", package_dir={"": "src"}, - packages=["cirmrest"], + packages=["cirm"], requires=["web.py", "psycopg2"], classifiers=[ "Intended Audience :: Developers",
10d0b7c452c8d9d5893cfe612e0beaa738f61628
easy_pjax/__init__.py
easy_pjax/__init__.py
#-*- coding: utf-8 -*- """ Register filter so it is available for use in the `extends` template tag (The `extends` tag must come first in a template, so regular `load` is not an option). """ from __future__ import absolute_import, division, print_function, unicode_literals __version__ = "1.2.0" try: from django.template import add_to_builtins except ImportError: # import path changed in 1.8 from django.template.base import add_to_builtins add_to_builtins("easy_pjax.templatetags.pjax_tags")
#-*- coding: utf-8 -*- """ Register filter so it is available for use in the `extends` template tag (The `extends` tag must come first in a template, so regular `load` is not an option). """ from __future__ import absolute_import, division, print_function, unicode_literals __version__ = "1.2.0" has_add_to_builtins = True try: from django.template import add_to_builtins except ImportError: try: # import path changed in 1.8 from django.template.base import add_to_builtins except ImportError: has_add_to_builtins = False if has_add_to_builtins: add_to_builtins("easy_pjax.templatetags.pjax_tags")
Add to template builtins only if add_to_buitlins is available (Django <= 1.8)
Add to template builtins only if add_to_buitlins is available (Django <= 1.8)
Python
bsd-3-clause
nigma/django-easy-pjax,nigma/django-easy-pjax,nigma/django-easy-pjax
--- +++ @@ -10,11 +10,15 @@ __version__ = "1.2.0" - +has_add_to_builtins = True try: from django.template import add_to_builtins except ImportError: - # import path changed in 1.8 - from django.template.base import add_to_builtins + try: + # import path changed in 1.8 + from django.template.base import add_to_builtins + except ImportError: + has_add_to_builtins = False -add_to_builtins("easy_pjax.templatetags.pjax_tags") +if has_add_to_builtins: + add_to_builtins("easy_pjax.templatetags.pjax_tags")
b6208c1f9b6f0afca1dff40a66d2c915594b1946
blaze/io/server/tests/start_simple_server.py
blaze/io/server/tests/start_simple_server.py
""" Starts a Blaze server for tests. $ start_test_server.py /path/to/catalog_config.yaml <portnumber> """ import sys, os import blaze from blaze.io.server.app import app blaze.catalog.load_config(sys.argv[1]) app.run(port=int(sys.argv[2]), use_reloader=False)
""" Starts a Blaze server for tests. $ start_test_server.py /path/to/catalog_config.yaml <portnumber> """ import sys, os if os.name == 'nt': old_excepthook = sys.excepthook # Exclude this from our autogenerated API docs. undoc = lambda func: func @undoc def gui_excepthook(exctype, value, tb): try: import ctypes, traceback MB_ICONERROR = 0x00000010 title = u'Error starting test Blaze server' msg = u''.join(traceback.format_exception(exctype, value, tb)) ctypes.windll.user32.MessageBoxW(0, msg, title, MB_ICONERROR) finally: # Also call the old exception hook to let it do # its thing too. old_excepthook(exctype, value, tb) sys.excepthook = gui_excepthook import blaze from blaze.io.server.app import app blaze.catalog.load_config(sys.argv[1]) app.run(port=int(sys.argv[2]), use_reloader=False)
Add exception hook to help diagnose server test errors in python3 gui mode
Add exception hook to help diagnose server test errors in python3 gui mode
Python
bsd-3-clause
caseyclements/blaze,dwillmer/blaze,jcrist/blaze,mrocklin/blaze,cowlicks/blaze,ContinuumIO/blaze,jcrist/blaze,xlhtc007/blaze,FrancescAlted/blaze,aterrel/blaze,nkhuyu/blaze,AbhiAgarwal/blaze,markflorisson/blaze-core,nkhuyu/blaze,FrancescAlted/blaze,ChinaQuants/blaze,markflorisson/blaze-core,alexmojaki/blaze,alexmojaki/blaze,jdmcbr/blaze,mrocklin/blaze,AbhiAgarwal/blaze,maxalbert/blaze,dwillmer/blaze,markflorisson/blaze-core,AbhiAgarwal/blaze,scls19fr/blaze,LiaoPan/blaze,scls19fr/blaze,mwiebe/blaze,aterrel/blaze,xlhtc007/blaze,aterrel/blaze,ContinuumIO/blaze,AbhiAgarwal/blaze,ChinaQuants/blaze,jdmcbr/blaze,cpcloud/blaze,LiaoPan/blaze,maxalbert/blaze,cpcloud/blaze,cowlicks/blaze,mwiebe/blaze,mwiebe/blaze,markflorisson/blaze-core,FrancescAlted/blaze,caseyclements/blaze,mwiebe/blaze,FrancescAlted/blaze
--- +++ @@ -4,6 +4,28 @@ $ start_test_server.py /path/to/catalog_config.yaml <portnumber> """ import sys, os + +if os.name == 'nt': + old_excepthook = sys.excepthook + + # Exclude this from our autogenerated API docs. + undoc = lambda func: func + + @undoc + def gui_excepthook(exctype, value, tb): + try: + import ctypes, traceback + MB_ICONERROR = 0x00000010 + title = u'Error starting test Blaze server' + msg = u''.join(traceback.format_exception(exctype, value, tb)) + ctypes.windll.user32.MessageBoxW(0, msg, title, MB_ICONERROR) + finally: + # Also call the old exception hook to let it do + # its thing too. + old_excepthook(exctype, value, tb) + + sys.excepthook = gui_excepthook + import blaze from blaze.io.server.app import app
95bde4f783a4d11627d8bc64e24b383e945bdf01
src/web/tags.py
src/web/tags.py
# -*- coding: utf-8 -*- # vim: set fileencodings=utf-8 __docformat__ = "reStructuredText" import json import datetime from django.template.base import Library from django.utils.safestring import mark_safe register = Library() #CDN_URL = 'https://cdn.crate.io' CDN_URL = 'http://localhost:8001' def media(context, media_url): """ Get the path for a media file. """ if media_url.startswith('http://') or media_url.startswith('https://'): url = media_url elif media_url.startswith('/'): url = u'{0}{1}'.format(CDN_URL, media_url) else: url = u'{0}/media/{1}'.format(CDN_URL, media_url) return url register.simple_tag(takes_context=True)(media)
# -*- coding: utf-8 -*- # vim: set fileencodings=utf-8 __docformat__ = "reStructuredText" import json import datetime from django.template.base import Library from django.utils.safestring import mark_safe register = Library() CDN_URL = 'https://cdn.crate.io' def media(context, media_url): """ Get the path for a media file. """ if media_url.startswith('http://') or media_url.startswith('https://'): url = media_url elif media_url.startswith('/'): url = u'{0}{1}'.format(CDN_URL, media_url) else: url = u'{0}/media/{1}'.format(CDN_URL, media_url) return url register.simple_tag(takes_context=True)(media)
Revert local CDN location set by Jodok
Revert local CDN location set by Jodok
Python
apache-2.0
crate/crate-web,jomolinare/crate-web,crate/crate-web,crate/crate-web,jomolinare/crate-web,jomolinare/crate-web
--- +++ @@ -11,8 +11,7 @@ register = Library() -#CDN_URL = 'https://cdn.crate.io' -CDN_URL = 'http://localhost:8001' +CDN_URL = 'https://cdn.crate.io' def media(context, media_url): """
8d8002062a0ecbf3720870d7561670a8c7e98da2
test/stores/test_auth_tokens_store.py
test/stores/test_auth_tokens_store.py
from test.base import ApiTestCase from zou.app.stores import auth_tokens_store class CommandsTestCase(ApiTestCase): def setUp(self): super(CommandsTestCase, self).setUp() self.store = auth_tokens_store self.store.clear() def tearDown(self): self.store.clear() def test_get_and_add(self): self.assertIsNone(self.store.get("key-1")) self.store.add("key-1", "true") self.assertEquals(self.store.get("key-1"), "true") def test_delete(self): self.store.add("key-1", "true") self.store.delete("key-1") self.assertIsNone(self.store.get("key-1")) def test_is_revoked(self): self.assertTrue(self.store.is_revoked({"jti": "key-1"})) self.store.add("key-1", "true") self.assertTrue(self.store.is_revoked({"jti": "key-1"})) self.store.add("key-1", "false") self.assertFalse(self.store.is_revoked({"jti": "key-1"})) def test_keys(self): self.store.add("key-1", "true") self.store.add("key-2", "true") self.assertEquals( self.store.keys(), ["key-1", "key-2"] )
from test.base import ApiTestCase from zou.app.stores import auth_tokens_store class CommandsTestCase(ApiTestCase): def setUp(self): super(CommandsTestCase, self).setUp() self.store = auth_tokens_store self.store.clear() def tearDown(self): self.store.clear() def test_get_and_add(self): self.assertIsNone(self.store.get("key-1")) self.store.add("key-1", "true") self.assertEquals(self.store.get("key-1"), "true") def test_delete(self): self.store.add("key-1", "true") self.store.delete("key-1") self.assertIsNone(self.store.get("key-1")) def test_is_revoked(self): self.assertTrue(self.store.is_revoked({"jti": "key-1"})) self.store.add("key-1", "true") self.assertTrue(self.store.is_revoked({"jti": "key-1"})) self.store.add("key-1", "false") self.assertFalse(self.store.is_revoked({"jti": "key-1"})) def test_keys(self): self.store.add("key-1", "true") self.store.add("key-2", "true") self.assertTrue("key-1" in self.store.keys()) self.assertTrue("key-2" in self.store.keys())
Fix test for auth tokens store
Fix test for auth tokens store
Python
agpl-3.0
cgwire/zou
--- +++ @@ -33,6 +33,5 @@ def test_keys(self): self.store.add("key-1", "true") self.store.add("key-2", "true") - self.assertEquals( - self.store.keys(), ["key-1", "key-2"] - ) + self.assertTrue("key-1" in self.store.keys()) + self.assertTrue("key-2" in self.store.keys())
7ba77209687ae1bb1344cc09e3539f7e21bfe599
tests/test_utilities/test_csvstack.py
tests/test_utilities/test_csvstack.py
#!/usr/bin/env python import sys import StringIO import unittest from csvkit import CSVKitReader from csvkit.utilities.stack import CSVStack class TestCSVStack(unittest.TestCase): def test_explicit_grouping(self): # stack two CSV files args = ["--groups", "asd,sdf", "-n", "foo", "examples/dummy.csv", "examples/dummy2.csv"] output_file = StringIO.StringIO() utility = CSVStack(args, output_file) utility.main() # verify the stacked file's contents input_file = StringIO.StringIO(output_file.getvalue()) reader = CSVKitReader(input_file) self.assertEqual(reader.next(), ["foo", "a", "b", "c"]) self.assertEqual(reader.next()[0], "asd") self.assertEqual(reader.next()[0], "sdf") def test_filenames_grouping(self): # stack two CSV files args = ["--filenames", "-n", "path", "examples/dummy.csv", "examples/dummy2.csv"] output_file = StringIO.StringIO() utility = CSVStack(args, output_file) utility.main() # verify the stacked file's contents input_file = StringIO.StringIO(output_file.getvalue()) reader = CSVKitReader(input_file) self.assertEqual(reader.next(), ["foo", "a", "b", "c"]) self.assertEqual(reader.next()[0], "asd") self.assertEqual(reader.next()[0], "sdf")
#!/usr/bin/env python import sys import StringIO import unittest from csvkit import CSVKitReader from csvkit.utilities.stack import CSVStack class TestCSVStack(unittest.TestCase): def test_explicit_grouping(self): # stack two CSV files args = ["--groups", "asd,sdf", "-n", "foo", "examples/dummy.csv", "examples/dummy2.csv"] output_file = StringIO.StringIO() utility = CSVStack(args, output_file) utility.main() # verify the stacked file's contents input_file = StringIO.StringIO(output_file.getvalue()) reader = CSVKitReader(input_file) self.assertEqual(reader.next(), ["foo", "a", "b", "c"]) self.assertEqual(reader.next()[0], "asd") self.assertEqual(reader.next()[0], "sdf") def test_filenames_grouping(self): # stack two CSV files args = ["--filenames", "-n", "path", "examples/dummy.csv", "examples/dummy2.csv"] output_file = StringIO.StringIO() utility = CSVStack(args, output_file) utility.main() # verify the stacked file's contents input_file = StringIO.StringIO(output_file.getvalue()) reader = CSVKitReader(input_file) self.assertEqual(reader.next(), ["path", "a", "b", "c"]) self.assertEqual(reader.next()[0], "dummy.csv") self.assertEqual(reader.next()[0], "dummy2.csv")
Improve test of csvstack --filenames.
Improve test of csvstack --filenames.
Python
mit
unpingco/csvkit,snuggles08/csvkit,doganmeh/csvkit,aequitas/csvkit,themiurgo/csvkit,bradparks/csvkit__query_join_filter_CSV_cli,matterker/csvkit,archaeogeek/csvkit,metasoarous/csvkit,jpalvarezf/csvkit,kyeoh/csvkit,nriyer/csvkit,gepuro/csvkit,bmispelon/csvkit,KarrieK/csvkit,Tabea-K/csvkit,moradology/csvkit,tlevine/csvkit,haginara/csvkit,cypreess/csvkit,barentsen/csvkit,reubano/csvkit,wjr1985/csvkit,dannguyen/csvkit,onyxfish/csvkit,wireservice/csvkit,arowla/csvkit,elcritch/csvkit,Jobava/csvkit
--- +++ @@ -36,7 +36,7 @@ input_file = StringIO.StringIO(output_file.getvalue()) reader = CSVKitReader(input_file) - self.assertEqual(reader.next(), ["foo", "a", "b", "c"]) - self.assertEqual(reader.next()[0], "asd") - self.assertEqual(reader.next()[0], "sdf") + self.assertEqual(reader.next(), ["path", "a", "b", "c"]) + self.assertEqual(reader.next()[0], "dummy.csv") + self.assertEqual(reader.next()[0], "dummy2.csv")
585317f3a03f55f6487a98446d4a9279f91714d2
tests/test_vector2_scalar_multiplication.py
tests/test_vector2_scalar_multiplication.py
import pytest # type: ignore from hypothesis import given from hypothesis.strategies import floats from utils import vectors from ppb_vector import Vector2 @pytest.mark.parametrize("x, y, expected", [ (Vector2(6, 1), 0, Vector2(0, 0)), (Vector2(6, 1), 2, Vector2(12, 2)), (Vector2(0, 0), 3, Vector2(0, 0)), (Vector2(-1.5, 2.4), -2, Vector2(3.0, -4.8)), (Vector2(1, 2), 0.1, Vector2(0.1, 0.2)) ]) def test_scalar_multiplication(x, y, expected): assert x * y == expected @given( x=floats(min_value=-1e75, max_value=1e75), y=floats(min_value=-1e75, max_value=1e75), v=vectors(max_magnitude=1e150) ) def test_scalar_associative(x: float, y: float, v: Vector2): left = (x * y) * v right = x * (y * v) assert left.isclose(right)
import pytest # type: ignore from hypothesis import given from hypothesis.strategies import floats from utils import vectors from ppb_vector import Vector2 @pytest.mark.parametrize("x, y, expected", [ (Vector2(6, 1), 0, Vector2(0, 0)), (Vector2(6, 1), 2, Vector2(12, 2)), (Vector2(0, 0), 3, Vector2(0, 0)), (Vector2(-1.5, 2.4), -2, Vector2(3.0, -4.8)), (Vector2(1, 2), 0.1, Vector2(0.1, 0.2)) ]) def test_scalar_multiplication(x, y, expected): assert x * y == expected @given( x=floats(min_value=-1e75, max_value=1e75), y=floats(min_value=-1e75, max_value=1e75), v=vectors(max_magnitude=1e150) ) def test_scalar_associative(x: float, y: float, v: Vector2): left = (x * y) * v right = x * (y * v) assert left.isclose(right) @given( l=floats(min_value=-1e150, max_value=1e150), x=vectors(max_magnitude=1e150), y=vectors(max_magnitude=1e150), ) def test_scalar_linear(l: float, x: Vector2, y: Vector2): assert (l * (x + y)).isclose(l*x + l*y)
Add a test of the linearity of scalar multiplication
Add a test of the linearity of scalar multiplication
Python
artistic-2.0
ppb/ppb-vector,ppb/ppb-vector
--- +++ @@ -25,3 +25,11 @@ left = (x * y) * v right = x * (y * v) assert left.isclose(right) + +@given( + l=floats(min_value=-1e150, max_value=1e150), + x=vectors(max_magnitude=1e150), + y=vectors(max_magnitude=1e150), +) +def test_scalar_linear(l: float, x: Vector2, y: Vector2): + assert (l * (x + y)).isclose(l*x + l*y)
aa5259efac8f7fbe8e2afd263198feaaa45fc4c3
tingbot/platform_specific/__init__.py
tingbot/platform_specific/__init__.py
import platform def is_tingbot(): """return True if running as a tingbot. We can update this function to be more smart in future""" return platform.machine().startswith('armv71') if platform.system() == 'Darwin': from osx import fixup_env, create_main_surface, register_button_callback elif is_tingbot(): from pi import fixup_env, create_main_surface, register_button_callback else: from sdl_wrapper import fixup_env, create_main_surface, register_button_callback
import platform, os def is_tingbot(): """ Return True if running as a tingbot. """ # TB_RUN_ON_LCD is an environment variable set by tbprocessd when running tingbot apps. return 'TB_RUN_ON_LCD' in os.environ if platform.system() == 'Darwin': from osx import fixup_env, create_main_surface, register_button_callback elif is_tingbot(): from pi import fixup_env, create_main_surface, register_button_callback else: from sdl_wrapper import fixup_env, create_main_surface, register_button_callback
Change test for running on Tingbot
Change test for running on Tingbot
Python
bsd-2-clause
furbrain/tingbot-python
--- +++ @@ -1,8 +1,11 @@ -import platform +import platform, os def is_tingbot(): - """return True if running as a tingbot. We can update this function to be more smart in future""" - return platform.machine().startswith('armv71') + """ + Return True if running as a tingbot. + """ + # TB_RUN_ON_LCD is an environment variable set by tbprocessd when running tingbot apps. + return 'TB_RUN_ON_LCD' in os.environ if platform.system() == 'Darwin': from osx import fixup_env, create_main_surface, register_button_callback
16c1ae09e0288036aae87eb4337c24b23b1e6638
classify.py
classify.py
from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.neighbors import KNeighborsRegressor from sklearn.ensemble import RandomForestRegressor from sklearn.pipeline import Pipeline import numpy as np import json import sys import time from analyze import Analyzer # for some train data labelling def main(argv): group = argv[0] if len(argv) > 0 else "id" train_size = int(argv[1]) if len(argv) > 1 else 1000 train_data = [] train_labels = [] analyzer = Analyzer(group) for message, _ in analyzer.read_json(sys.stdin): label = analyzer.analyze(message)[0] train_data.append(message) train_labels.append(label) if len(train_data) >= train_size: break regressor = Pipeline([ ('tfidf', TfidfVectorizer(input='content')), ('clf', RandomForestRegressor()) #('clf', KNeighborsRegressor()) ]) regressor.fit(train_data, train_labels) for message, group in analyzer.read_json(sys.stdin): # Call predict for every message which might be slow in practice but # avoids memory hog due to not being able to use iterators if done in # one batch. prediction = regressor.predict([message])[0] if analyzer.display: # Take the color for this group of predictions c = cmp(prediction, 0) message = analyzer.colors[c] + message + analyzer.END_COLOR analyzer.output(group, message, prediction, "") if __name__ == "__main__": main(sys.argv[1:])
from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.ensemble import RandomForestRegressor from sklearn.pipeline import Pipeline import numpy as np import json import sys from analyze import Analyzer # for some train data labelling def main(argv): group = argv[0] if len(argv) > 0 else "id" train_size = int(argv[1]) if len(argv) > 1 else 1000 train_data = [] train_labels = [] analyzer = Analyzer(group) for message, _ in analyzer.read_json(sys.stdin): label = analyzer.analyze(message)[0] train_data.append(message) train_labels.append(label) if len(train_data) >= train_size: break regressor = Pipeline([ ('tfidf', TfidfVectorizer(input='content')), ('clf', RandomForestRegressor()) ]) regressor.fit(train_data, train_labels) for message, group in analyzer.read_json(sys.stdin): # Call predict for every message which might be slow in practice but # avoids memory hog due to not being able to use iterators if done in # one batch. prediction = regressor.predict([message])[0] if analyzer.display: # Take the color for this group of predictions c = cmp(prediction, 0) message = analyzer.colors[c] + message + analyzer.END_COLOR analyzer.output(group, message, prediction, "") if __name__ == "__main__": main(sys.argv[1:])
Clean up some unused imports and comments
Clean up some unused imports and comments
Python
mit
timvandermeij/sentiment-analysis,timvandermeij/sentiment-analysis
--- +++ @@ -1,11 +1,9 @@ from sklearn.feature_extraction.text import TfidfVectorizer -from sklearn.neighbors import KNeighborsRegressor from sklearn.ensemble import RandomForestRegressor from sklearn.pipeline import Pipeline import numpy as np import json import sys -import time from analyze import Analyzer # for some train data labelling def main(argv): @@ -26,7 +24,6 @@ regressor = Pipeline([ ('tfidf', TfidfVectorizer(input='content')), ('clf', RandomForestRegressor()) - #('clf', KNeighborsRegressor()) ]) regressor.fit(train_data, train_labels)
4f3d1e90ec4af618ada415f53ddd9eec42bafb38
wafer/talks/tests/test_wafer_basic_talks.py
wafer/talks/tests/test_wafer_basic_talks.py
# This tests the very basic talk stuff, to ensure some levels of sanity def test_add_talk(): """Create a user and add a talk to it""" from django.contrib.auth.models import User from wafer.talks.models import Talks user = User.objects.create_user('john', 'best@wafer.test', 'johnpassword') talk = Talks.objects.create(title="This is a test talk", abstract="This should be a long and interesting abstract, but isn't", corresponding_author_id=user.id) assert user.contact_talks.count() == 1
# This tests the very basic talk stuff, to ensure some levels of sanity def test_add_talk(): """Create a user and add a talk to it""" from django.contrib.auth.models import User from wafer.talks.models import Talks user = User.objects.create_user('john', 'best@wafer.test', 'johnpassword') talk = Talks.objects.create(title="This is a test talk", abstract="This should be a long and interesting abstract, but isn't", corresponding_author_id=user.id) assert user.contact_talks.count() == 1
Indent with 4 spaces, not 3
Indent with 4 spaces, not 3
Python
isc
CTPUG/wafer,CTPUG/wafer,CarlFK/wafer,CTPUG/wafer,CarlFK/wafer,CarlFK/wafer,CTPUG/wafer,CarlFK/wafer
--- +++ @@ -2,13 +2,13 @@ def test_add_talk(): - """Create a user and add a talk to it""" - from django.contrib.auth.models import User - from wafer.talks.models import Talks + """Create a user and add a talk to it""" + from django.contrib.auth.models import User + from wafer.talks.models import Talks - user = User.objects.create_user('john', 'best@wafer.test', 'johnpassword') - talk = Talks.objects.create(title="This is a test talk", - abstract="This should be a long and interesting abstract, but isn't", - corresponding_author_id=user.id) + user = User.objects.create_user('john', 'best@wafer.test', 'johnpassword') + talk = Talks.objects.create(title="This is a test talk", + abstract="This should be a long and interesting abstract, but isn't", + corresponding_author_id=user.id) - assert user.contact_talks.count() == 1 + assert user.contact_talks.count() == 1
3685715cd260f4f5ca392caddf7fb0c01af9ebcc
mzalendo/comments2/feeds.py
mzalendo/comments2/feeds.py
from disqus.wxr_feed import ContribCommentsWxrFeed # from comments2.models import Comment from core.models import Person # http://help.disqus.com/customer/portal/articles/472150-custom-xml-import-format class CommentWxrFeed(ContribCommentsWxrFeed): link = "/" def items(self): return Person.objects.all()[:5] # remove [:5] before generating full dump def item_pubdate(self, item): return item.created def item_description(self, item): return str(item) def item_guid(self, item): # set to none so that the output dsq:thread_identifier is empty return None def item_comments(self, item): return item.comments.all() def comment_user_name(self, comment): return str(comment.user) def comment_user_email(self, comment): return comment.user.email or str(comment.id) + '@bogus-email-address.com' def comment_user_url(self, comment): return None def comment_is_approved(self, comment): return 1
from disqus.wxr_feed import ContribCommentsWxrFeed # from comments2.models import Comment from core.models import Person, Place, Organisation # http://help.disqus.com/customer/portal/articles/472150-custom-xml-import-format class CommentWxrFeed(ContribCommentsWxrFeed): link = "/" def items(self): list = [] list.extend( Person.objects.all() ) list.extend( Organisation.objects.all() ) list.extend( Place.objects.all() ) return list def item_pubdate(self, item): return item.created def item_description(self, item): return str(item) def item_guid(self, item): # set to none so that the output dsq:thread_identifier is empty return None def item_comments(self, item): return item.comments.all() def comment_user_name(self, comment): return str(comment.user) def comment_user_email(self, comment): return comment.user.email or str(comment.id) + '@bogus-email-address.com' def comment_user_url(self, comment): return None def comment_is_approved(self, comment): return 1
Add in comments for orgs and places too, remove limit
Add in comments for orgs and places too, remove limit
Python
agpl-3.0
mysociety/pombola,Hutspace/odekro,ken-muturi/pombola,mysociety/pombola,Hutspace/odekro,patricmutwiri/pombola,geoffkilpin/pombola,patricmutwiri/pombola,mysociety/pombola,ken-muturi/pombola,ken-muturi/pombola,ken-muturi/pombola,mysociety/pombola,mysociety/pombola,patricmutwiri/pombola,geoffkilpin/pombola,geoffkilpin/pombola,Hutspace/odekro,geoffkilpin/pombola,hzj123/56th,ken-muturi/pombola,geoffkilpin/pombola,hzj123/56th,Hutspace/odekro,hzj123/56th,mysociety/pombola,patricmutwiri/pombola,hzj123/56th,hzj123/56th,ken-muturi/pombola,geoffkilpin/pombola,Hutspace/odekro,patricmutwiri/pombola,patricmutwiri/pombola,hzj123/56th
--- +++ @@ -1,6 +1,6 @@ from disqus.wxr_feed import ContribCommentsWxrFeed # from comments2.models import Comment -from core.models import Person +from core.models import Person, Place, Organisation # http://help.disqus.com/customer/portal/articles/472150-custom-xml-import-format @@ -9,7 +9,11 @@ link = "/" def items(self): - return Person.objects.all()[:5] # remove [:5] before generating full dump + list = [] + list.extend( Person.objects.all() ) + list.extend( Organisation.objects.all() ) + list.extend( Place.objects.all() ) + return list def item_pubdate(self, item): return item.created
f3da1fab9af2279182a09922aae00fcee73a92ee
goog/middleware.py
goog/middleware.py
from django.conf import settings from django.conf.urls.defaults import patterns, include import goog.urls from goog import utils class GoogDevelopmentMiddleware(object): def devmode_enabled(self, request): """Returns True iff the devmode is enabled.""" return utils.is_devmode() def process_request(self, request): # This urlconf patching is inspired by debug_toolbar. # https://github.com/robhudson/django-debug-toolbar if self.devmode_enabled(request): original_urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF) if original_urlconf != 'goog.urls': goog.urls.urlpatterns += patterns( '', ('', include(original_urlconf)), ) request.urlconf = 'goog.urls'
from django.conf import settings try: from django.conf.urls.defaults import patterns, include except ImportError: # Django >= 1.6 from django.conf.urls import patterns, include import goog.urls from goog import utils class GoogDevelopmentMiddleware(object): def devmode_enabled(self, request): """Returns True iff the devmode is enabled.""" return utils.is_devmode() def process_request(self, request): # This urlconf patching is inspired by debug_toolbar. # https://github.com/robhudson/django-debug-toolbar if self.devmode_enabled(request): original_urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF) if original_urlconf != 'goog.urls': goog.urls.urlpatterns += patterns( '', ('', include(original_urlconf)), ) request.urlconf = 'goog.urls'
Fix imports for Django >= 1.6
Fix imports for Django >= 1.6
Python
bsd-3-clause
andialbrecht/django-goog
--- +++ @@ -1,5 +1,8 @@ from django.conf import settings -from django.conf.urls.defaults import patterns, include +try: + from django.conf.urls.defaults import patterns, include +except ImportError: # Django >= 1.6 + from django.conf.urls import patterns, include import goog.urls from goog import utils
61cf4e2feb3d8920179e28719822c7fb34ea6550
3/ibm_rng.py
3/ibm_rng.py
def ibm_rng(x1, a, c, m): x = x1 while True: x = (a * x + c) % m yield x / (m-1) def main(): rng = ibm_rng(1, 65539, 0, 2**31) while True: x = next(rng) print(x) if __name__ == '__main__': main()
def ibm_rng(x1, a=65539, c=0, m=2**31): x = x1 while True: x = (a * x + c) % m yield x / (m-1) def main(): rng = ibm_rng(1, 65539, 0, 2**31) while True: x = next(rng) print(x) if __name__ == '__main__': main()
Add defaults to the ibm RNG
Add defaults to the ibm RNG
Python
mit
JelteF/statistics
--- +++ @@ -1,4 +1,4 @@ -def ibm_rng(x1, a, c, m): +def ibm_rng(x1, a=65539, c=0, m=2**31): x = x1 while True: x = (a * x + c) % m
db3cee63baf64d00b2d2ac4fcf726f287b6d7af2
app/proxy_fix.py
app/proxy_fix.py
from werkzeug.middleware.proxy_fix import ProxyFix class CustomProxyFix(object): def __init__(self, app, forwarded_proto): self.app = ProxyFix(app) self.forwarded_proto = forwarded_proto def __call__(self, environ, start_response): environ.update({ "HTTP_X_FORWARDED_PROTO": self.forwarded_proto }) return self.app(environ, start_response) def init_app(app): app.wsgi_app = CustomProxyFix(app.wsgi_app, app.config.get('HTTP_PROTOCOL', 'http'))
from werkzeug.middleware.proxy_fix import ProxyFix class CustomProxyFix(object): def __init__(self, app, forwarded_proto): self.app = ProxyFix(app, x_for=1, x_proto=1, x_host=1, x_port=0, x_prefix=0) self.forwarded_proto = forwarded_proto def __call__(self, environ, start_response): environ.update({ "HTTP_X_FORWARDED_PROTO": self.forwarded_proto }) return self.app(environ, start_response) def init_app(app): app.wsgi_app = CustomProxyFix(app.wsgi_app, app.config.get('HTTP_PROTOCOL', 'http'))
Update call to proxy fix to use new method signature
Update call to proxy fix to use new method signature Old method: ```python ProxyFix(app, num_proxies=1) ``` https://werkzeug.palletsprojects.com/en/0.14.x/contrib/fixers/#werkzeug.contrib.fixers.ProxyFix This uses forwarded values for `REMOTE_ADDR` and `HTTP_HOST`. New method: ```python ProxyFix(app, num_proxies=None, x_for=1, x_proto=0, x_host=0, x_port=0, x_prefix=0) ``` https://werkzeug.palletsprojects.com/en/0.15.x/middleware/proxy_fix/#module-werkzeug.middleware.proxy_fix Setting `x_for=1` preserves the same behaviour as `num_proxies=1`. Setting `x_proto=1` and `x_host=1` will cause `REMOTE_ADDR`, `HTTP_HOST`, `SERVER_NAME` and `SERVER_PORT` to be forwarded. So we will be forwarding `SERVER_NAME` and `SERVER_PORT` which we weren’t before, but we think this is OK.
Python
mit
alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin
--- +++ @@ -3,7 +3,7 @@ class CustomProxyFix(object): def __init__(self, app, forwarded_proto): - self.app = ProxyFix(app) + self.app = ProxyFix(app, x_for=1, x_proto=1, x_host=1, x_port=0, x_prefix=0) self.forwarded_proto = forwarded_proto def __call__(self, environ, start_response):
34c0c6c73a65da3120aa52600254afc909e9a3bc
pytach/wsgi.py
pytach/wsgi.py
import bottle from bottle import route, run from web import web import config app = application = bottle.Bottle() app.merge(web.app) config.arguments['--verbose'] = True if __name__ == '__main__': app.run(host='0.0.0.0', port=8082, debug=True)
import bottle import config from web import web app = application = bottle.Bottle() app.merge(web.app) config.arguments['--verbose'] = True
Remove unused main and unused imports
Remove unused main and unused imports
Python
mit
gotling/PyTach,gotling/PyTach,gotling/PyTach
--- +++ @@ -1,12 +1,9 @@ import bottle -from bottle import route, run + +import config from web import web -import config app = application = bottle.Bottle() app.merge(web.app) config.arguments['--verbose'] = True - -if __name__ == '__main__': - app.run(host='0.0.0.0', port=8082, debug=True)
d86bdec5d7d57fe74cb463e391798bd1e5be87ff
pombola/ghana/urls.py
pombola/ghana/urls.py
from django.conf.urls import patterns, include, url, handler404 from django.views.generic import TemplateView import django.contrib.auth.views from .views import data_upload, info_page_upload urlpatterns = patterns('', url(r'^intro$', TemplateView.as_view(template_name='intro.html')), url(r'^data/upload/mps/$', data_upload, name='data_upload'), url(r'^data/upload/info-page/$', info_page_upload, name='info_page_upload'), #auth views url(r'^accounts/login$', django.contrib.auth.views.login, name='login'), url(r'^accounts/logut$', django.contrib.auth.views.logout, name='logout'), #url(r'^accounts/register$', registration.backends.simple.urls, name='register'), )
from django.conf.urls import patterns, url, include from django.views.generic import TemplateView from .views import data_upload, info_page_upload urlpatterns = patterns('', url(r'^intro$', TemplateView.as_view(template_name='intro.html')), url(r'^data/upload/mps/$', data_upload, name='data_upload'), url(r'^data/upload/info-page/$', info_page_upload, name='info_page_upload'), url('', include('django.contrib.auth.urls')), )
Update Ghana code to match current Pombola
Update Ghana code to match current Pombola
Python
agpl-3.0
geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola
--- +++ @@ -1,7 +1,5 @@ -from django.conf.urls import patterns, include, url, handler404 +from django.conf.urls import patterns, url, include from django.views.generic import TemplateView -import django.contrib.auth.views - from .views import data_upload, info_page_upload @@ -9,11 +7,5 @@ url(r'^intro$', TemplateView.as_view(template_name='intro.html')), url(r'^data/upload/mps/$', data_upload, name='data_upload'), url(r'^data/upload/info-page/$', info_page_upload, name='info_page_upload'), - - #auth views - url(r'^accounts/login$', django.contrib.auth.views.login, name='login'), - url(r'^accounts/logut$', django.contrib.auth.views.logout, name='logout'), - #url(r'^accounts/register$', registration.backends.simple.urls, name='register'), - - + url('', include('django.contrib.auth.urls')), )
5526f8e3dca2f84fce34df5a134bada8479a2f69
netbox/ipam/models/__init__.py
netbox/ipam/models/__init__.py
from .fhrp import * from .ip import * from .services import * from .vlans import * from .vrfs import * __all__ = ( 'ASN', 'Aggregate', 'IPAddress', 'IPRange', 'FHRPGroup', 'FHRPGroupAssignment', 'Prefix', 'RIR', 'Role', 'RouteTarget', 'Service', 'ServiceTemplate', 'VLAN', 'VLANGroup', 'VRF', )
# Ensure that VRFs are imported before IPs/prefixes so dumpdata & loaddata work correctly from .fhrp import * from .vrfs import * from .ip import * from .services import * from .vlans import * __all__ = ( 'ASN', 'Aggregate', 'IPAddress', 'IPRange', 'FHRPGroup', 'FHRPGroupAssignment', 'Prefix', 'RIR', 'Role', 'RouteTarget', 'Service', 'ServiceTemplate', 'VLAN', 'VLANGroup', 'VRF', )
Fix dumpdata ordering for VRFs
Fix dumpdata ordering for VRFs
Python
apache-2.0
digitalocean/netbox,digitalocean/netbox,digitalocean/netbox,digitalocean/netbox
--- +++ @@ -1,8 +1,9 @@ +# Ensure that VRFs are imported before IPs/prefixes so dumpdata & loaddata work correctly from .fhrp import * +from .vrfs import * from .ip import * from .services import * from .vlans import * -from .vrfs import * __all__ = ( 'ASN',
0782ba56218e825dea5b76cbf030a522932bcfd6
networkx/classes/ordered.py
networkx/classes/ordered.py
""" OrderedDict variants of the default base classes. These classes are especially useful for doctests and unit tests. """ try: # Python 2.7+ from collections import OrderedDict except ImportError: # Oython 2.6 try: from ordereddict import OrderedDict except ImportError: OrderedDict = None from .graph import Graph from .multigraph import MultiGraph from .digraph import DiGraph from .multidigraph import MultiDiGraph __all__ = [] if OrderedDict is not None: __all__.extend([ 'OrderedGraph', 'OrderedDiGraph', 'OrderedMultiGraph', 'OrderedMultiDiGraph' ]) class OrderedGraph(Graph): node_dict_factory = OrderedDict adjlist_dict_factory = OrderedDict edge_attr_dict_factory = OrderedDict class OrderedDiGraph(DiGraph): node_dict_factory = OrderedDict adjlist_dict_factory = OrderedDict edge_attr_dict_factory = OrderedDict class OrderedMultiGraph(MultiGraph): node_dict_factory = OrderedDict adjlist_dict_factory = OrderedDict edge_key_dict_factory = OrderedDict edge_attr_dict_factory = OrderedDict class OrderedMultiDiGraph(MultiDiGraph): node_dict_factory = OrderedDict adjlist_dict_factory = OrderedDict edge_key_dict_factory = OrderedDict edge_attr_dict_factory = OrderedDict
""" OrderedDict variants of the default base classes. """ try: # Python 2.7+ from collections import OrderedDict except ImportError: # Oython 2.6 try: from ordereddict import OrderedDict except ImportError: OrderedDict = None from .graph import Graph from .multigraph import MultiGraph from .digraph import DiGraph from .multidigraph import MultiDiGraph __all__ = [] if OrderedDict is not None: __all__.extend([ 'OrderedGraph', 'OrderedDiGraph', 'OrderedMultiGraph', 'OrderedMultiDiGraph' ]) class OrderedGraph(Graph): node_dict_factory = OrderedDict adjlist_dict_factory = OrderedDict edge_attr_dict_factory = OrderedDict class OrderedDiGraph(DiGraph): node_dict_factory = OrderedDict adjlist_dict_factory = OrderedDict edge_attr_dict_factory = OrderedDict class OrderedMultiGraph(MultiGraph): node_dict_factory = OrderedDict adjlist_dict_factory = OrderedDict edge_key_dict_factory = OrderedDict edge_attr_dict_factory = OrderedDict class OrderedMultiDiGraph(MultiDiGraph): node_dict_factory = OrderedDict adjlist_dict_factory = OrderedDict edge_key_dict_factory = OrderedDict edge_attr_dict_factory = OrderedDict
Remove unnecessary (and debatable) comment.
Remove unnecessary (and debatable) comment.
Python
bsd-3-clause
nathania/networkx,dhimmel/networkx,RMKD/networkx,sharifulgeo/networkx,chrisnatali/networkx,goulu/networkx,farhaanbukhsh/networkx,jni/networkx,jakevdp/networkx,ionanrozenfeld/networkx,debsankha/networkx,nathania/networkx,tmilicic/networkx,kernc/networkx,ltiao/networkx,michaelpacer/networkx,bzero/networkx,dhimmel/networkx,RMKD/networkx,kernc/networkx,bzero/networkx,aureooms/networkx,ionanrozenfeld/networkx,sharifulgeo/networkx,yashu-seth/networkx,bzero/networkx,OrkoHunter/networkx,blublud/networkx,harlowja/networkx,ghdk/networkx,dmoliveira/networkx,dhimmel/networkx,beni55/networkx,sharifulgeo/networkx,blublud/networkx,RMKD/networkx,farhaanbukhsh/networkx,nathania/networkx,jni/networkx,farhaanbukhsh/networkx,aureooms/networkx,jfinkels/networkx,Sixshaman/networkx,harlowja/networkx,debsankha/networkx,blublud/networkx,jakevdp/networkx,andnovar/networkx,dmoliveira/networkx,wasade/networkx,debsankha/networkx,SanketDG/networkx,chrisnatali/networkx,NvanAdrichem/networkx,chrisnatali/networkx,ionanrozenfeld/networkx,dmoliveira/networkx,kernc/networkx,JamesClough/networkx,jcurbelo/networkx,ghdk/networkx,jakevdp/networkx,jni/networkx,aureooms/networkx,cmtm/networkx,harlowja/networkx,ghdk/networkx
--- +++ @@ -1,7 +1,5 @@ """ OrderedDict variants of the default base classes. - -These classes are especially useful for doctests and unit tests. """ try:
603c36aec2a4704bb4cf41c224194a5f83f9babe
sale_payment_method_automatic_workflow/__openerp__.py
sale_payment_method_automatic_workflow/__openerp__.py
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2015 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## {'name': 'Sale Payment Method - Automatic Reconcile', 'version': '1.0', 'author': ['Camptocamp', 'Akretion'], 'license': 'AGPL-3', 'category': 'Generic Modules/Others', 'depends': ['sale_payment_method', 'sale_automatic_workflow'], 'website': 'http://www.camptocamp.com', 'data': [], 'test': [], 'installable': True, 'auto_install': False, }
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2015 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## {'name': 'Sale Payment Method - Automatic Reconcile', 'version': '1.0', 'author': ['Camptocamp', 'Akretion'], 'license': 'AGPL-3', 'category': 'Generic Modules/Others', 'depends': ['sale_payment_method', 'sale_automatic_workflow'], 'website': 'http://www.camptocamp.com', 'data': [], 'test': [], 'installable': True, 'auto_install': True, }
Set the module as auto_install
Set the module as auto_install So it installs when both sale_payment_method and sale_automatic_workflow are installed. This module acts as the glue between them
Python
agpl-3.0
BT-ojossen/e-commerce,Antiun/e-commerce,raycarnes/e-commerce,jt-xx/e-commerce,gurneyalex/e-commerce,BT-ojossen/e-commerce,Endika/e-commerce,damdam-s/e-commerce,vauxoo-dev/e-commerce,charbeljc/e-commerce,brain-tec/e-commerce,BT-jmichaud/e-commerce,Endika/e-commerce,brain-tec/e-commerce,JayVora-SerpentCS/e-commerce,fevxie/e-commerce,JayVora-SerpentCS/e-commerce,jt-xx/e-commerce,Antiun/e-commerce,raycarnes/e-commerce,cloud9UG/e-commerce,vauxoo-dev/e-commerce,BT-fgarbely/e-commerce
--- +++ @@ -30,5 +30,5 @@ 'data': [], 'test': [], 'installable': True, - 'auto_install': False, + 'auto_install': True, }
4a6060f476aebac163dbac8f9822539596379c0a
welt2000/__init__.py
welt2000/__init__.py
from flask import Flask, request, session from flask.ext.babel import Babel from babel.core import negotiate_locale from welt2000.__about__ import ( __title__, __summary__, __uri__, __version__, __author__, __email__, __license__, ) # noqa app = Flask(__name__) app.secret_key = '1234567890' babel = Babel(app) translations = ['en'] translations.extend(map(str, babel.list_translations())) @app.template_global() @babel.localeselector def get_locale(): lang = session.get('lang') if lang and lang in translations: return lang preferred = map(lambda l: l[0], request.accept_languages) return negotiate_locale(preferred, translations) from welt2000 import views # noqa
from flask import Flask, request, session, current_app from flask.ext.babel import Babel from babel.core import negotiate_locale from welt2000.__about__ import ( __title__, __summary__, __uri__, __version__, __author__, __email__, __license__, ) # noqa app = Flask(__name__) app.secret_key = '1234567890' babel = Babel(app) @app.template_global() @babel.localeselector def get_locale(): available = ['en'] available.extend(map(str, current_app.babel_instance.list_translations())) lang = session.get('lang') if lang and lang in available: return lang preferred = map(lambda l: l[0], request.accept_languages) return negotiate_locale(preferred, available) from welt2000 import views # noqa
Use current_app.babel_instance instead of babel
app: Use current_app.babel_instance instead of babel That way we can use Babel.init_app() later
Python
mit
Turbo87/welt2000,Turbo87/welt2000
--- +++ @@ -1,4 +1,4 @@ -from flask import Flask, request, session +from flask import Flask, request, session, current_app from flask.ext.babel import Babel from babel.core import negotiate_locale @@ -13,19 +13,19 @@ babel = Babel(app) -translations = ['en'] -translations.extend(map(str, babel.list_translations())) - @app.template_global() @babel.localeselector def get_locale(): + available = ['en'] + available.extend(map(str, current_app.babel_instance.list_translations())) + lang = session.get('lang') - if lang and lang in translations: + if lang and lang in available: return lang preferred = map(lambda l: l[0], request.accept_languages) - return negotiate_locale(preferred, translations) + return negotiate_locale(preferred, available) from welt2000 import views # noqa
6f0740fbd94acc2398f0628552a6329c2a90a348
greengraph/command.py
greengraph/command.py
from argparse import ArgumentParser from matplotlib import pyplot as plt from graph import Greengraph def process(): parser = ArgumentParser( description="Produce graph quantifying the amount of green land between two locations") parser.add_argument("--start", required=True, help="The starting location ") parser.add_argument("--end", required=True, help="The ending location") parser.add_argument("--steps", help="The number of steps between the starting and ending locations, defaults to 10") parser.add_argument("--out", help="The output filename, defaults to graph.png") arguments = parser.parse_args() mygraph = Greengraph(arguments.start, arguments.end) if arguments.steps: data = mygraph.green_between(arguments.steps) else: data = mygraph.green_between(10) plt.plot(data) # TODO add a title and axis labels to this graph if arguments.out: plt.savefig(arguments.out) else: plt.savefig("graph.png") if __name__ == "__main__": process()
from argparse import ArgumentParser from matplotlib import pyplot as plt from graph import Greengraph def process(): parser = ArgumentParser( description="Produce graph quantifying the amount of green land between two locations") parser.add_argument("--start", required=True, nargs="+", help="The starting location ") parser.add_argument("--end", required=True, nargs="+", help="The ending location") parser.add_argument("--steps", help="The number of steps between the starting and ending locations, defaults to 10") parser.add_argument("--out", help="The output filename, defaults to graph.png") arguments = parser.parse_args() #mygraph = Greengraph(arguments.start, arguments.end) if arguments.steps: data = mygraph.green_between(arguments.steps) else: data = mygraph.green_between(10) plt.plot(data) # TODO add a title and axis labels to this graph if arguments.out: plt.savefig(arguments.out) else: plt.savefig("graph.png") print arguments.start print arguments.end if __name__ == "__main__": process()
Allow start and end arguments to take inputs of multiple words such as 'New York'
Allow start and end arguments to take inputs of multiple words such as 'New York'
Python
mit
MikeVasmer/GreenGraphCoursework
--- +++ @@ -6,9 +6,9 @@ def process(): parser = ArgumentParser( description="Produce graph quantifying the amount of green land between two locations") - parser.add_argument("--start", required=True, + parser.add_argument("--start", required=True, nargs="+", help="The starting location ") - parser.add_argument("--end", required=True, + parser.add_argument("--end", required=True, nargs="+", help="The ending location") parser.add_argument("--steps", help="The number of steps between the starting and ending locations, defaults to 10") @@ -16,7 +16,7 @@ help="The output filename, defaults to graph.png") arguments = parser.parse_args() - mygraph = Greengraph(arguments.start, arguments.end) + #mygraph = Greengraph(arguments.start, arguments.end) if arguments.steps: data = mygraph.green_between(arguments.steps) else: @@ -27,6 +27,8 @@ plt.savefig(arguments.out) else: plt.savefig("graph.png") + print arguments.start + print arguments.end if __name__ == "__main__": process()
4bb8a61cde27575865cdd2b7df5afcb5d6860523
fmriprep/interfaces/tests/test_reports.py
fmriprep/interfaces/tests/test_reports.py
import pytest from ..reports import get_world_pedir @pytest.mark.parametrize("orientation,pe_dir,expected", [ ('RAS', 'j', 'Posterior-Anterior'), ('RAS', 'j-', 'Anterior-Posterior'), ('RAS', 'i', 'Left-Right'), ('RAS', 'i-', 'Right-Left'), ('RAS', 'k', 'Inferior-Superior'), ('RAS', 'k-', 'Superior-Inferior'), ('LAS', 'j', 'Posterior-Anterior'), ('LAS', 'i-', 'Left-Right'), ('LAS', 'k-', 'Superior-Inferior'), ('LPI', 'j', 'Anterior-Posterior'), ('LPI', 'i-', 'Left-Right'), ('LPI', 'k-', 'Inferior-Superior'), ]) def test_get_world_pedir(tmpdir, orientation, pe_dir, expected): assert get_world_pedir(orientation, pe_dir) == expected
import pytest from ..reports import get_world_pedir @pytest.mark.parametrize("orientation,pe_dir,expected", [ ('RAS', 'j', 'Posterior-Anterior'), ('RAS', 'j-', 'Anterior-Posterior'), ('RAS', 'i', 'Left-Right'), ('RAS', 'i-', 'Right-Left'), ('RAS', 'k', 'Inferior-Superior'), ('RAS', 'k-', 'Superior-Inferior'), ('LAS', 'j', 'Posterior-Anterior'), ('LAS', 'i-', 'Left-Right'), ('LAS', 'k-', 'Superior-Inferior'), ('LPI', 'j', 'Anterior-Posterior'), ('LPI', 'i-', 'Left-Right'), ('LPI', 'k-', 'Inferior-Superior'), ('SLP', 'k-', 'Posterior-Anterior'), ('SLP', 'k', 'Anterior-Posterior'), ('SLP', 'j-', 'Left-Right'), ('SLP', 'j', 'Right-Left'), ('SLP', 'i', 'Inferior-Superior'), ('SLP', 'i-', 'Superior-Inferior'), ]) def test_get_world_pedir(tmpdir, orientation, pe_dir, expected): assert get_world_pedir(orientation, pe_dir) == expected
Add weird SLP orientation to get_world_pedir
TEST: Add weird SLP orientation to get_world_pedir
Python
bsd-3-clause
oesteban/fmriprep,poldracklab/preprocessing-workflow,oesteban/fmriprep,poldracklab/preprocessing-workflow,oesteban/fmriprep
--- +++ @@ -16,6 +16,12 @@ ('LPI', 'j', 'Anterior-Posterior'), ('LPI', 'i-', 'Left-Right'), ('LPI', 'k-', 'Inferior-Superior'), + ('SLP', 'k-', 'Posterior-Anterior'), + ('SLP', 'k', 'Anterior-Posterior'), + ('SLP', 'j-', 'Left-Right'), + ('SLP', 'j', 'Right-Left'), + ('SLP', 'i', 'Inferior-Superior'), + ('SLP', 'i-', 'Superior-Inferior'), ]) def test_get_world_pedir(tmpdir, orientation, pe_dir, expected): assert get_world_pedir(orientation, pe_dir) == expected
95ea1d7d6564bcbb2e3b8d2ba254ccd2c1c38436
mamba/__init__.py
mamba/__init__.py
__version__ = '0.9.2' def description(message): pass def _description(message): pass def it(message): pass def _it(message): pass def context(message): pass def _context(message): pass def before(): pass def after(): pass
__version__ = '0.9.2' def description(message): pass def _description(message): pass def fdescription(message): pass def it(message): pass def _it(message): pass def fit(message): pass def context(message): pass def _context(message): pass def fcontext(message): pass def before(): pass def after(): pass
Add import for focused stuff
Add import for focused stuff
Python
mit
nestorsalceda/mamba
--- +++ @@ -9,11 +9,19 @@ pass +def fdescription(message): + pass + + def it(message): pass def _it(message): + pass + + +def fit(message): pass @@ -25,6 +33,10 @@ pass +def fcontext(message): + pass + + def before(): pass
29e491c5505d2068b46eb489044455968e53ab70
test/400-bay-water.py
test/400-bay-water.py
assert_has_feature( 14, 2623, 6318, 'water', { 'kind': 'bay', 'label_placement': 'yes' })
# osm_id: 43950409 name: San Pablo Bay assert_has_feature( 14, 2623, 6318, 'water', { 'kind': 'bay', 'label_placement': 'yes' }) # osm_id: 360566115 name: Byron strait assert_has_feature( 14, 15043, 8311, 'water', { 'kind': 'strait', 'label_placement': 'yes' }) # osm_id: -1451065 name: Horsens Fjord assert_has_feature( 14, 8645, 5114, 'water', { 'kind': 'fjord', 'label_placement': 'yes' })
Add tests for strait and fjord
Add tests for strait and fjord
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
--- +++ @@ -1,3 +1,14 @@ +# osm_id: 43950409 name: San Pablo Bay assert_has_feature( 14, 2623, 6318, 'water', { 'kind': 'bay', 'label_placement': 'yes' }) + +# osm_id: 360566115 name: Byron strait +assert_has_feature( + 14, 15043, 8311, 'water', + { 'kind': 'strait', 'label_placement': 'yes' }) + +# osm_id: -1451065 name: Horsens Fjord +assert_has_feature( + 14, 8645, 5114, 'water', + { 'kind': 'fjord', 'label_placement': 'yes' })
cdf545cf9385a0490590cd0162141025a1301c09
track/config.py
track/config.py
import configargparse DEFAULT_CONFIG_FILES=[ './track.cfg', '~/.track.cfg', ] # Bit of a cheat... not actually an object constructor, just a 'make me an object' method def ArgParser(): return configargparse.ArgParser( ignore_unknown_config_file_keys =True, allow_abbrev =True, default_config_files =DEFAULT_CONFIG_FILES, formatter_class =configargparse.ArgumentDefaultsHelpFormatter, config_file_parser_class =configargparse.DefaultConfigFileParser, # INI format args_for_setting_config_path =['-c', '--cfg'], args_for_writing_out_config_file=['-w', '--cfg-write'], )
import configargparse DEFAULT_CONFIG_FILES=[ './track.cfg', '~/.track.cfg', ] # Bit of a cheat... not actually an object constructor, just a 'make me an object' method def ArgParser(): return configargparse.ArgParser( ignore_unknown_config_file_keys =True, allow_abbrev =True, default_config_files =DEFAULT_CONFIG_FILES, # formatter_class =configargparse.ArgumentDefaultsHelpFormatter, formatter_class =configargparse.RawDescriptionHelpFormatter, config_file_parser_class =configargparse.DefaultConfigFileParser, # INI format args_for_setting_config_path =['-c', '--cfg'], args_for_writing_out_config_file=['-w', '--cfg-write'], )
Use argparse formatter RawDescriptionHelpFormatter, maybe temporarily
Use argparse formatter RawDescriptionHelpFormatter, maybe temporarily
Python
mit
bgottula/track,bgottula/track
--- +++ @@ -13,7 +13,8 @@ ignore_unknown_config_file_keys =True, allow_abbrev =True, default_config_files =DEFAULT_CONFIG_FILES, - formatter_class =configargparse.ArgumentDefaultsHelpFormatter, +# formatter_class =configargparse.ArgumentDefaultsHelpFormatter, + formatter_class =configargparse.RawDescriptionHelpFormatter, config_file_parser_class =configargparse.DefaultConfigFileParser, # INI format args_for_setting_config_path =['-c', '--cfg'], args_for_writing_out_config_file=['-w', '--cfg-write'],
148d4c44a9eb63016b469c6bf317a3dbe9ed7918
permuta/permutations.py
permuta/permutations.py
from .misc import DancingLinks from .permutation import Permutation import random class Permutations(object): def __init__(self, n): assert 0 <= n self.n = n def __iter__(self): left = DancingLinks(range(1, self.n+1)) res = [] def gen(): if len(left) == 0: yield Permutation(list(res)) else: cur = left.front while cur is not None: left.erase(cur) res.append(cur.value) for p in gen(): yield p res.pop() left.restore(cur) cur = cur.next return gen() def random_element(self): p = [ i+1 for i in range(self.n) ] for i in range(self.n-1, -1, -1): j = random.randint(0, i) p[i],p[j] = p[j],p[i] return Permutation(p) def __str__(self): return 'The set of Permutations of length %d' % self.n def __repr__(self): return 'Permutations(%d)' % self.n
from .misc import DancingLinks from .permutation import Permutation import random class Permutations(object): """Class for iterating through all Permutations of length n""" def __init__(self, n): """Returns an object giving all permutations of length n""" assert 0 <= n self.n = n def __iter__(self): """Iterates through permutations of length n in lexical order""" left = DancingLinks(range(1, self.n+1)) res = [] def gen(): if len(left) == 0: yield Permutation(list(res)) else: cur = left.front while cur is not None: left.erase(cur) res.append(cur.value) for p in gen(): yield p res.pop() left.restore(cur) cur = cur.next return gen() def random_element(self): """Returns a random permutation of length n""" p = [i+1 for i in range(self.n)] for i in range(self.n-1, -1, -1): j = random.randint(0, i) p[i], p[j] = p[j], p[i] return Permutation(p) def __str__(self): return 'The set of Permutations of length %d' % self.n def __repr__(self): return 'Permutations(%d)' % self.n
Add documentation for Permutations class
Add documentation for Permutations class
Python
bsd-3-clause
PermutaTriangle/Permuta
--- +++ @@ -2,15 +2,20 @@ from .permutation import Permutation import random + class Permutations(object): + """Class for iterating through all Permutations of length n""" + def __init__(self, n): + """Returns an object giving all permutations of length n""" assert 0 <= n self.n = n def __iter__(self): - + """Iterates through permutations of length n in lexical order""" left = DancingLinks(range(1, self.n+1)) res = [] + def gen(): if len(left) == 0: yield Permutation(list(res)) @@ -28,10 +33,11 @@ return gen() def random_element(self): - p = [ i+1 for i in range(self.n) ] + """Returns a random permutation of length n""" + p = [i+1 for i in range(self.n)] for i in range(self.n-1, -1, -1): j = random.randint(0, i) - p[i],p[j] = p[j],p[i] + p[i], p[j] = p[j], p[i] return Permutation(p) def __str__(self): @@ -39,4 +45,3 @@ def __repr__(self): return 'Permutations(%d)' % self.n -
86791effb26c33514bbc6713f67a903e8d9e5295
scripts/c19.py
scripts/c19.py
from __future__ import print_function import sys from pyspark.sql import SparkSession from pyspark.sql.functions import lit, col, coalesce if __name__ == "__main__": if len(sys.argv) != 3: print("Usage: c19.py <input> <output>", file=sys.stderr) exit(-1) spark = SparkSession.builder.appName('Select c19').getOrCreate() raw = spark.read.option('mergeSchema','true').load(sys.argv[1]) df = raw.filter(col('date') < '1900') opens = df.filter(col('open') == 'true')\ .select('series', 'date', lit(1).alias('inopen')).distinct() df.join(opens, ['series', 'date'], 'left_outer')\ .filter((col('open') == 'true') | col('inopen').isNull())\ .drop('inopen')\ .dropDuplicates(['id'])\ .write.save(sys.argv[2]) spark.stop()
from __future__ import print_function import sys from pyspark.sql import SparkSession from pyspark.sql.functions import col, struct, max if __name__ == "__main__": if len(sys.argv) != 3: print("Usage: c19.py <input> <output>", file=sys.stderr) exit(-1) spark = SparkSession.builder.appName('Select c19').getOrCreate() raw = spark.read.option('mergeSchema','true').load(sys.argv[1]) df = raw.filter(col('date') < '1900') spark.conf.set('spark.sql.shuffle.partitions', df.rdd.getNumPartitions() * 2) issues = df.groupBy('series', 'date')\ .agg(max(struct('open', 'corpus'))['corpus'].alias('corpus')) df.join(issues, ['series', 'date', 'corpus'], 'inner')\ .write.save(sys.argv[2]) spark.stop()
Choose a single corpus for a given series,date pair.
Choose a single corpus for a given series,date pair.
Python
apache-2.0
ViralTexts/vt-passim,ViralTexts/vt-passim,ViralTexts/vt-passim
--- +++ @@ -3,7 +3,7 @@ import sys from pyspark.sql import SparkSession -from pyspark.sql.functions import lit, col, coalesce +from pyspark.sql.functions import col, struct, max if __name__ == "__main__": if len(sys.argv) != 3: @@ -13,13 +13,12 @@ raw = spark.read.option('mergeSchema','true').load(sys.argv[1]) df = raw.filter(col('date') < '1900') - opens = df.filter(col('open') == 'true')\ - .select('series', 'date', lit(1).alias('inopen')).distinct() + spark.conf.set('spark.sql.shuffle.partitions', df.rdd.getNumPartitions() * 2) - df.join(opens, ['series', 'date'], 'left_outer')\ - .filter((col('open') == 'true') | col('inopen').isNull())\ - .drop('inopen')\ - .dropDuplicates(['id'])\ + issues = df.groupBy('series', 'date')\ + .agg(max(struct('open', 'corpus'))['corpus'].alias('corpus')) + + df.join(issues, ['series', 'date', 'corpus'], 'inner')\ .write.save(sys.argv[2]) spark.stop()
54c48073dfb8ffd418efe234c0c107f7a5c303a9
svg/templatetags/svg.py
svg/templatetags/svg.py
import logging import os from django import template from django.conf import settings from django.contrib.staticfiles import finders from django.utils.safestring import mark_safe from svg.exceptions import SVGNotFound logger = logging.getLogger(__name__) register = template.Library() @register.simple_tag def svg(filename): path = finders.find(os.path.join('svg', '%s.svg' % filename), all=True) if not path: message = "SVG 'svg/%s.svg' not found" % filename if settings.DEBUG: raise SVGNotFound(message) else: logger.warning(message) return '' if isinstance(path, (list, tuple)): path = path[0] with open(path) as svg_file: svg = mark_safe(svg_file.read()) return svg
from __future__ import absolute_import import logging import os from django import template from django.conf import settings from django.contrib.staticfiles import finders from django.utils.safestring import mark_safe from svg.exceptions import SVGNotFound logger = logging.getLogger(__name__) register = template.Library() @register.simple_tag def svg(filename): path = finders.find(os.path.join('svg', '%s.svg' % filename), all=True) if not path: message = "SVG 'svg/%s.svg' not found" % filename if settings.DEBUG: raise SVGNotFound(message) else: logger.warning(message) return '' if isinstance(path, (list, tuple)): path = path[0] with open(path) as svg_file: svg = mark_safe(svg_file.read()) return svg
Fix failing imports in Python 2
Fix failing imports in Python 2
Python
mit
mixxorz/django-inline-svg
--- +++ @@ -1,3 +1,4 @@ +from __future__ import absolute_import import logging import os
7b4531ec867982ba2f660a2a08e85dbae457083e
users/models.py
users/models.py
import hashlib import urllib.parse as urllib from django.contrib.auth.models import User from django.db import models # extension to django's User class which has authentication details # as well as some basic info such as name class Member(models.Model): def gravatar(self, size=128): default = "https://pbs.twimg.com/media/Civ9AUkVAAAwihS.jpg" h = hashlib.md5( self.equiv_user.email.encode('utf8').lower() ).hexdigest() q = urllib.urlencode({ # 'd':default, 'd': 'identicon', 's': str(size), }) return 'https://www.gravatar.com/avatar/{}?{}'.format(h, q) equiv_user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.equiv_user.username bio = models.CharField(max_length=4096, blank=True) signature = models.CharField(max_length=1024, blank=True) def notification_count(self): return len(self.notifications_owned.filter(is_unread=True)) official_photo_url = models.CharField(max_length=512, null=True, blank=True) def is_exec(self): return len(self.execrole_set.all()) > 0
import hashlib import urllib.parse as urllib from django.contrib.auth.models import User from django.db import models # extension to django's User class which has authentication details # as well as some basic info such as name class Member(models.Model): def gravatar(self, size=128): default = "https://pbs.twimg.com/media/Civ9AUkVAAAwihS.jpg" h = hashlib.md5( self.equiv_user.email.encode('utf8').lower() ).hexdigest() q = urllib.urlencode({ # 'd':default, 'd': 'identicon', 's': str(size), }) return 'https://www.gravatar.com/avatar/{}?{}'.format(h, q) equiv_user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.equiv_user.username bio = models.TextField(max_length=4096, blank=True) signature = models.TextField(max_length=1024, blank=True) def notification_count(self): return len(self.notifications_owned.filter(is_unread=True)) official_photo_url = models.CharField(max_length=512, null=True, blank=True) def is_exec(self): return len(self.execrole_set.all()) > 0
Fix new line stripping in admin site
Fix new line stripping in admin site Closes #87
Python
isc
ashbc/tgrsite,ashbc/tgrsite,ashbc/tgrsite
--- +++ @@ -26,8 +26,8 @@ def __str__(self): return self.equiv_user.username - bio = models.CharField(max_length=4096, blank=True) - signature = models.CharField(max_length=1024, blank=True) + bio = models.TextField(max_length=4096, blank=True) + signature = models.TextField(max_length=1024, blank=True) def notification_count(self): return len(self.notifications_owned.filter(is_unread=True))
390fa07c191d79290b1ef83c268f38431f68093a
tests/clients/simple.py
tests/clients/simple.py
# -*- coding: utf-8 -*- from base import jsonrpyc class MyClass(object): def one(self): return 1 def twice(self, n): return n * 2 def arglen(self, *args, **kwargs): return len(args) + len(kwargs) if __name__ == "__main__": rpc = jsonrpyc.RPC(MyClass())
# -*- coding: utf-8 -*- import os import sys base = os.path.dirname(os.path.abspath(__file__)) sys.path.append(base) from base import jsonrpyc class MyClass(object): def one(self): return 1 def twice(self, n): return n * 2 def arglen(self, *args, **kwargs): return len(args) + len(kwargs) if __name__ == "__main__": rpc = jsonrpyc.RPC(MyClass())
Fix import in test client.
Fix import in test client.
Python
mit
riga/jsonrpyc
--- +++ @@ -1,5 +1,11 @@ # -*- coding: utf-8 -*- + +import os +import sys + +base = os.path.dirname(os.path.abspath(__file__)) +sys.path.append(base) from base import jsonrpyc
73d0be7a432340b4ecd140ad1cc8792d3f049779
tests/factories/user.py
tests/factories/user.py
# -*- coding: utf-8 -*- # Copyright (c) 2016 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. import factory from factory.faker import Faker from pycroft.model.user import User from .base import BaseFactory from .facilities import RoomFactory from .finance import AccountFactory class UserFactory(BaseFactory): class Meta: model = User login = Faker('user_name') name = Faker('name') registered_at = Faker('date_time') password = Faker('password') email = Faker('email') account = factory.SubFactory(AccountFactory, type="USER_ASSET") room = factory.SubFactory(RoomFactory) address = factory.LazyAttribute(lambda o: o.room.address) class UserWithHostFactory(UserFactory): host = factory.RelatedFactory('tests.factories.host.HostFactory', 'owner')
# -*- coding: utf-8 -*- # Copyright (c) 2016 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. import factory from factory.faker import Faker from pycroft.model.user import User from .base import BaseFactory from .facilities import RoomFactory from .finance import AccountFactory class UserFactory(BaseFactory): class Meta: model = User login = Faker('user_name') name = Faker('name') registered_at = Faker('date_time') password = Faker('password') email = Faker('email') account = factory.SubFactory(AccountFactory, type="USER_ASSET") room = factory.SubFactory(RoomFactory) address = factory.SelfAttribute('room.address') class UserWithHostFactory(UserFactory): host = factory.RelatedFactory('tests.factories.host.HostFactory', 'owner')
Use SelfAttribute instead of explicit lambda
Use SelfAttribute instead of explicit lambda
Python
apache-2.0
agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft
--- +++ @@ -21,7 +21,7 @@ email = Faker('email') account = factory.SubFactory(AccountFactory, type="USER_ASSET") room = factory.SubFactory(RoomFactory) - address = factory.LazyAttribute(lambda o: o.room.address) + address = factory.SelfAttribute('room.address') class UserWithHostFactory(UserFactory):
2c37ed091baf12e53885bfa06fdb835bb8de1218
tests/skipif_markers.py
tests/skipif_markers.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ skipif_markers -------------- Contains pytest skipif markers to be used in the suite. """ import pytest import os try: os.environ[u'TRAVIS'] except KeyError: travis = False else: travis = True try: os.environ[u'DISABLE_NETWORK_TESTS'] except KeyError: no_network = False else: no_network = True # For some reason pytest incorrectly uses the first reason text regardless of # which condition matches. Using a unified message for now # travis_reason = 'Works locally with tox but fails on Travis.' # no_network_reason = 'Needs a network connection to GitHub.' reason = 'Fails on Travis or else there is no network connection to GitHub' skipif_travis = pytest.mark.skipif(travis, reason=reason) skipif_no_network = pytest.mark.skipif(no_network, reason=reason)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ skipif_markers -------------- Contains pytest skipif markers to be used in the suite. """ import pytest import os try: os.environ[u'TRAVIS'] except KeyError: travis = False else: travis = True try: os.environ[u'DISABLE_NETWORK_TESTS'] except KeyError: no_network = False else: no_network = True # For some reason pytest incorrectly uses the first reason text regardless of # which condition matches. Using a unified message for now # travis_reason = 'Works locally with tox but fails on Travis.' # no_network_reason = 'Needs a network connection to GitHub.' reason = ( 'Fails on Travis or else there is no network connection to ' 'GitHub/Bitbucket.' ) skipif_travis = pytest.mark.skipif(travis, reason=reason) skipif_no_network = pytest.mark.skipif(no_network, reason=reason)
Add Bitbucket to skipif marker reason
Add Bitbucket to skipif marker reason
Python
bsd-3-clause
pjbull/cookiecutter,atlassian/cookiecutter,sp1rs/cookiecutter,0k/cookiecutter,cichm/cookiecutter,takeflight/cookiecutter,atlassian/cookiecutter,kkujawinski/cookiecutter,foodszhang/cookiecutter,christabor/cookiecutter,ramiroluz/cookiecutter,cguardia/cookiecutter,tylerdave/cookiecutter,benthomasson/cookiecutter,Springerle/cookiecutter,nhomar/cookiecutter,vincentbernat/cookiecutter,stevepiercy/cookiecutter,kkujawinski/cookiecutter,jhermann/cookiecutter,luzfcb/cookiecutter,drgarcia1986/cookiecutter,ramiroluz/cookiecutter,willingc/cookiecutter,audreyr/cookiecutter,terryjbates/cookiecutter,dajose/cookiecutter,christabor/cookiecutter,ionelmc/cookiecutter,nhomar/cookiecutter,foodszhang/cookiecutter,venumech/cookiecutter,tylerdave/cookiecutter,luzfcb/cookiecutter,hackebrot/cookiecutter,michaeljoseph/cookiecutter,lgp171188/cookiecutter,0k/cookiecutter,janusnic/cookiecutter,lgp171188/cookiecutter,vintasoftware/cookiecutter,ionelmc/cookiecutter,Springerle/cookiecutter,cichm/cookiecutter,pjbull/cookiecutter,agconti/cookiecutter,jhermann/cookiecutter,Vauxoo/cookiecutter,agconti/cookiecutter,willingc/cookiecutter,lucius-feng/cookiecutter,hackebrot/cookiecutter,moi65/cookiecutter,moi65/cookiecutter,Vauxoo/cookiecutter,stevepiercy/cookiecutter,dajose/cookiecutter,audreyr/cookiecutter,lucius-feng/cookiecutter,venumech/cookiecutter,takeflight/cookiecutter,drgarcia1986/cookiecutter,terryjbates/cookiecutter,janusnic/cookiecutter,sp1rs/cookiecutter,vincentbernat/cookiecutter,cguardia/cookiecutter,benthomasson/cookiecutter,michaeljoseph/cookiecutter,vintasoftware/cookiecutter
--- +++ @@ -30,7 +30,10 @@ # which condition matches. Using a unified message for now # travis_reason = 'Works locally with tox but fails on Travis.' # no_network_reason = 'Needs a network connection to GitHub.' -reason = 'Fails on Travis or else there is no network connection to GitHub' +reason = ( + 'Fails on Travis or else there is no network connection to ' + 'GitHub/Bitbucket.' +) skipif_travis = pytest.mark.skipif(travis, reason=reason) skipif_no_network = pytest.mark.skipif(no_network, reason=reason)
44dac786339716ad8cc05f6790b73b5fc47be812
config/jinja2.py
config/jinja2.py
from django.urls import reverse from django.utils import translation from django.template.backends.jinja2 import Jinja2 from jinja2 import Environment class FoodsavingJinja2(Jinja2): app_dirname = 'templates' def environment(**options): env = Environment(extensions=['jinja2.ext.i18n',], **options) env.globals.update({ 'url': reverse, }) env.install_gettext_translations(translation) env.install_null_translations() return env
from django.urls import reverse from django.utils import translation from django.template.backends.jinja2 import Jinja2 from jinja2 import Environment class FoodsavingJinja2(Jinja2): app_dirname = 'templates' def environment(**options): env = Environment(extensions=['jinja2.ext.i18n'], **options) env.globals.update({ 'url': reverse, }) env.install_gettext_translations(translation) env.install_null_translations() return env
Remove extra comma to avoid flake8 test failure in CircleCI
Remove extra comma to avoid flake8 test failure in CircleCI
Python
agpl-3.0
yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/yunity-core
--- +++ @@ -9,7 +9,7 @@ def environment(**options): - env = Environment(extensions=['jinja2.ext.i18n',], **options) + env = Environment(extensions=['jinja2.ext.i18n'], **options) env.globals.update({ 'url': reverse, })
6e67a9e8eedd959d9d0193e746a375099e9784ef
toodlepip/consoles.py
toodlepip/consoles.py
class Console(object): def __init__(self, shell, stdout): self._shell = shell self._stdout = stdout def run(self, description, command, **kwargs): return self.run_all(description, [command], **kwargs) def run_all(self, description, commands, quiet=False, cwd=None): stdout = None if quiet else self._stdout # TODO: Test printing description # TODO: detect terminal self._stdout.write('\033[1m') self._stdout.write(description) self._stdout.write("\n") self._stdout.write('\033[0m') self._stdout.flush() for command in commands: # TODO: print command result = self._shell.run( command, stdout=stdout, stderr=stdout, cwd=cwd, allow_error=True ) if result.return_code != 0: return Result(result.return_code) return Result(0) class Result(object): def __init__(self, return_code): self.return_code = return_code
class Console(object): def __init__(self, shell, stdout): self._shell = shell self._stdout = stdout def run(self, description, command, **kwargs): return self.run_all(description, [command], **kwargs) def run_all(self, description, commands, quiet=False, cwd=None): stdout = None if quiet else self._stdout # TODO: Test printing description # TODO: detect terminal self._stdout.write(b'\033[1m') self._stdout.write(description.encode("utf8")) self._stdout.write(b"\n") self._stdout.write(b'\033[0m') self._stdout.flush() for command in commands: # TODO: print command result = self._shell.run( command, stdout=stdout, stderr=stdout, cwd=cwd, allow_error=True ) if result.return_code != 0: return Result(result.return_code) return Result(0) class Result(object): def __init__(self, return_code): self.return_code = return_code
Use bytes instead of str where appropriate for Python 3
Use bytes instead of str where appropriate for Python 3
Python
bsd-2-clause
mwilliamson/toodlepip
--- +++ @@ -10,10 +10,10 @@ stdout = None if quiet else self._stdout # TODO: Test printing description # TODO: detect terminal - self._stdout.write('\033[1m') - self._stdout.write(description) - self._stdout.write("\n") - self._stdout.write('\033[0m') + self._stdout.write(b'\033[1m') + self._stdout.write(description.encode("utf8")) + self._stdout.write(b"\n") + self._stdout.write(b'\033[0m') self._stdout.flush() for command in commands: # TODO: print command
1df8efb63333e89777820a96d78d5a59252b303d
tests/test_config.py
tests/test_config.py
import unittest import figgypy.config import sys import os class TestConfig(unittest.TestCase): def test_config_load(self): os.environ['FIGGY_GPG_HOME']='tests/resources/test-keys' c = figgypy.config.Config('tests/resources/test-config.yaml') self.assertEqual(c.db['host'], 'db.heck.ya') self.assertEqual(c.db['pass'], 'test password') if __name__ == '__main__': unittest.main()
import unittest import figgypy.config import sys import os class TestConfig(unittest.TestCase): def test_config_load_with_gpg(self): os.environ['FIGGY_GPG_HOME']='tests/resources/test-keys' c = figgypy.config.Config('tests/resources/test-config.yaml') self.assertEqual(c.db['host'], 'db.heck.ya') self.assertEqual(c.db['pass'], 'test password') if __name__ == '__main__': unittest.main()
Rename test specific to with gpg
Rename test specific to with gpg
Python
mit
theherk/figgypy
--- +++ @@ -5,7 +5,7 @@ import os class TestConfig(unittest.TestCase): - def test_config_load(self): + def test_config_load_with_gpg(self): os.environ['FIGGY_GPG_HOME']='tests/resources/test-keys' c = figgypy.config.Config('tests/resources/test-config.yaml') self.assertEqual(c.db['host'], 'db.heck.ya')
66eddf04efd46fb3dbeae34c4d82f673a88be70f
tests/test_person.py
tests/test_person.py
from copy import copy from unittest import TestCase from address_book import Person class PersonTestCase(TestCase): def test_get_groups(self): pass def test_add_address(self): basic_address = ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'] person = Person( 'John', 'Doe', copy(basic_address), ['+79834772053'], ['john@gmail.com'] ) person.add_address('new address') self.assertEqual( person.addresses, basic_address + ['new address'] ) def test_add_phone(self): pass def test_add_email(self): pass
from copy import copy from unittest import TestCase from address_book import Person class PersonTestCase(TestCase): def test_get_groups(self): pass def test_add_address(self): basic_address = ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'] person = Person( 'John', 'Doe', copy(basic_address), ['+79834772053'], ['john@gmail.com'] ) person.add_address('new address') self.assertEqual( person.addresses, basic_address + ['new address'] ) def test_add_phone(self): basic_phone = ['+79237778492'] person = Person( 'John', 'Doe', copy(basic_phone), ['+79834772053'], ['john@gmail.com'] ) person.add_phone('+79234478810') self.assertEqual( person.addresses, basic_phone + ['+79234478810'] ) def test_add_email(self): pass
Test the ability to add phone to the person
Test the ability to add phone to the person
Python
mit
dizpers/python-address-book-assignment
--- +++ @@ -26,7 +26,19 @@ ) def test_add_phone(self): - pass + basic_phone = ['+79237778492'] + person = Person( + 'John', + 'Doe', + copy(basic_phone), + ['+79834772053'], + ['john@gmail.com'] + ) + person.add_phone('+79234478810') + self.assertEqual( + person.addresses, + basic_phone + ['+79234478810'] + ) def test_add_email(self): pass
3e84dcb7b449db89ca6ce2b91b34a5e8f8428b39
core/markdown.py
core/markdown.py
from markdown.extensions import nl2br, sane_lists, fenced_code from pymdownx import magiclink from mdx_unimoji import UnimojiExtension import utils.markdown markdown_extensions = [ magiclink.MagiclinkExtension(), nl2br.Nl2BrExtension(), utils.markdown.ExtendedLinkExtension(), sane_lists.SaneListExtension(), fenced_code.FencedCodeExtension(), utils.markdown.CuddledListExtension(), UnimojiExtension() ] content_allowed_tags = ( # text 'p', 'em', 'strong', 'br', 'a', 'img', # citation 'blockquote', 'cite', # headings 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', # lists 'ol', 'ul', 'li', # code 'pre', 'code' ) content_allowed_attributes = { '*': ['id', 'title'], 'a': ['href', 'title', 'data-component', 'data-grouplink-ref'], 'code': ['class'], 'img': ['src', 'alt'] }
from markdown.extensions import nl2br, sane_lists, fenced_code from pymdownx import magiclink from mdx_unimoji import UnimojiExtension import utils.markdown markdown_extensions = [ magiclink.MagiclinkExtension(), nl2br.Nl2BrExtension(), utils.markdown.ExtendedLinkExtension(), sane_lists.SaneListExtension(), fenced_code.FencedCodeExtension(), utils.markdown.CuddledListExtension(), UnimojiExtension() ] content_allowed_tags = ( # text 'p', 'em', 'strong', 'br', 'a', 'img', 'sub', 'sup', # citation 'blockquote', 'cite', # headings 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', # lists 'ol', 'ul', 'li', # code 'pre', 'code' ) content_allowed_attributes = { '*': ['id', 'title'], 'a': ['href', 'title', 'data-component', 'data-grouplink-ref'], 'code': ['class'], 'img': ['src', 'alt'] }
Allow sub- and superscript tags
Allow sub- and superscript tags
Python
agpl-3.0
stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten
--- +++ @@ -15,7 +15,7 @@ content_allowed_tags = ( # text - 'p', 'em', 'strong', 'br', 'a', 'img', + 'p', 'em', 'strong', 'br', 'a', 'img', 'sub', 'sup', # citation 'blockquote', 'cite', # headings
458d61ffb5161394f8080cea59716b2f9cb492f3
nbgrader_config.py
nbgrader_config.py
c = get_config() c.CourseDirectory.db_assignments = [dict(name="1", duedate="2019-12-09 17:00:00 UTC")] c.CourseDirectory.db_students = [ dict(id="foo", first_name="foo", last_name="foo") ] c.ClearSolutions.code_stub = {'python': '##### Implement this part of the code #####\nraise NotImplementedError()'}
c = get_config() c.CourseDirectory.db_assignments = [dict(name="1", duedate="2019-12-09 17:00:00 UTC")] c.CourseDirectory.db_students = [ dict(id="foo", first_name="foo", last_name="foo") ] c.ClearSolutions.code_stub = {'python': '''##### Implement this part of the code ##### raise NotImplementedError("Code not implemented, follow the instructions.")'''}
Add error message for not implemented error
Add error message for not implemented error
Python
mit
pbutenee/ml-tutorial,pbutenee/ml-tutorial
--- +++ @@ -3,4 +3,5 @@ c.CourseDirectory.db_students = [ dict(id="foo", first_name="foo", last_name="foo") ] -c.ClearSolutions.code_stub = {'python': '##### Implement this part of the code #####\nraise NotImplementedError()'} +c.ClearSolutions.code_stub = {'python': '''##### Implement this part of the code ##### +raise NotImplementedError("Code not implemented, follow the instructions.")'''}
7c77a7b14432a85447ff74e7aa017ca56c86e662
oidc_apis/views.py
oidc_apis/views.py
from django.http import JsonResponse from django.views.decorators.http import require_http_methods from oidc_provider.lib.utils.oauth2 import protected_resource_view from .api_tokens import get_api_tokens_by_access_token @require_http_methods(['GET', 'POST']) @protected_resource_view(['openid']) def get_api_tokens_view(request, token, *args, **kwargs): """ Get the authorized API Tokens. :type token: oidc_provider.models.Token :rtype: JsonResponse """ api_tokens = get_api_tokens_by_access_token(token, request=request) response = JsonResponse(api_tokens, status=200) response['Access-Control-Allow-Origin'] = '*' response['Cache-Control'] = 'no-store' response['Pragma'] = 'no-cache' return response
from django.http import JsonResponse from django.views.decorators.http import require_http_methods from oidc_provider.lib.utils.oauth2 import protected_resource_view from django.views.decorators.csrf import csrf_exempt from .api_tokens import get_api_tokens_by_access_token @csrf_exempt @require_http_methods(['GET', 'POST']) @protected_resource_view(['openid']) def get_api_tokens_view(request, token, *args, **kwargs): """ Get the authorized API Tokens. :type token: oidc_provider.models.Token :rtype: JsonResponse """ api_tokens = get_api_tokens_by_access_token(token, request=request) response = JsonResponse(api_tokens, status=200) response['Access-Control-Allow-Origin'] = '*' response['Cache-Control'] = 'no-store' response['Pragma'] = 'no-cache' return response
Make api-tokens view exempt from CSRF checks
Make api-tokens view exempt from CSRF checks
Python
mit
mikkokeskinen/tunnistamo,mikkokeskinen/tunnistamo
--- +++ @@ -1,10 +1,12 @@ from django.http import JsonResponse from django.views.decorators.http import require_http_methods from oidc_provider.lib.utils.oauth2 import protected_resource_view +from django.views.decorators.csrf import csrf_exempt from .api_tokens import get_api_tokens_by_access_token +@csrf_exempt @require_http_methods(['GET', 'POST']) @protected_resource_view(['openid']) def get_api_tokens_view(request, token, *args, **kwargs):
f26c2059ff6e2a595097ef7a03efe149f9e253eb
iterator.py
iterator.py
import os, re, requests rootdir = '_posts' for subdir, dirs, files in os.walk(rootdir): for file in files: filename = os.path.join(subdir, file) f = open(filename, "r") contents = f.readlines() f.close() # Find first image for key, line in enumerate(contents): src = re.search('\!\[.*?\]\((.*?)\)', line) if src: wordpress_src = re.search('/blog/images/wordpress/(.*)', src.group(1)) if wordpress_src: image_src = wordpress_src.group(1) path = 'images/wordpress/'+image_src print 'Retrieving ' + path + '...' if not os.path.isfile(path): print path f = open(path, "w") f.write(requests.get("http://blog.stackoverflow.com/wp-content/uploads/" + wordpress_src.group(1)).content) f.close() continue f = open(filename, "w") contents = "".join(contents) f.write(contents) f.close()
import os, re, requests rootdir = '_posts' for subdir, dirs, files in os.walk(rootdir): for file in files: filename = os.path.join(subdir, file) f = open(filename, "r") contents = f.readlines() f.close() # Find first image if re.search('podcast', filename): if re.search('^hero: ', contents[6]): print filename contents.insert(6, 'hero: /blog/images/category/podcasts.jpg\n') f = file.open(filename, "w") f.write("".join(contents)) f.close()
Add default images for podcasts if necessary
Add default images for podcasts if necessary
Python
mit
up1/blog-1,up1/blog-1,up1/blog-1
--- +++ @@ -10,22 +10,10 @@ f.close() # Find first image - for key, line in enumerate(contents): - src = re.search('\!\[.*?\]\((.*?)\)', line) - if src: - wordpress_src = re.search('/blog/images/wordpress/(.*)', src.group(1)) - if wordpress_src: - image_src = wordpress_src.group(1) - path = 'images/wordpress/'+image_src - print 'Retrieving ' + path + '...' - if not os.path.isfile(path): - print path - f = open(path, "w") - f.write(requests.get("http://blog.stackoverflow.com/wp-content/uploads/" + wordpress_src.group(1)).content) - f.close() - - continue - f = open(filename, "w") - contents = "".join(contents) - f.write(contents) - f.close() + if re.search('podcast', filename): + if re.search('^hero: ', contents[6]): + print filename + contents.insert(6, 'hero: /blog/images/category/podcasts.jpg\n') + f = file.open(filename, "w") + f.write("".join(contents)) + f.close()
3f70ead379b7f586313d01d5ab617fd5368f8ce3
cthulhubot/management/commands/restart_masters.py
cthulhubot/management/commands/restart_masters.py
from django.core.management.base import BaseCommand from cthulhubot.models import Buildmaster class Command(BaseCommand): help = 'Restart all Buildmaster processes' args = "" def handle(self, *fixture_labels, **options): verbosity = int(options.get('verbosity', 1)) commit = int(options.get('commit', 1)) if verbosity > 1: print 'Restarting buildmasters...' for b in Buildmaster.objects.all(): if verbosity > 1: print 'Handling buildmaster %s for project %s' % (str(b.id), str(b.project.name)) try: b.stop() except: print 'Failed to stop master' try: b.start() except: print 'Failed to start master'
from traceback import print_exc from django.core.management.base import BaseCommand from cthulhubot.models import Buildmaster class Command(BaseCommand): help = 'Restart all Buildmaster processes' args = "" def handle(self, *fixture_labels, **options): verbosity = int(options.get('verbosity', 1)) commit = int(options.get('commit', 1)) if verbosity > 1: print 'Restarting buildmasters...' for b in Buildmaster.objects.all(): if verbosity > 1: print 'Handling buildmaster %s for project %s' % (str(b.id), str(b.project.name)) try: b.stop() except: print 'Failed to stop master' print_exc() try: b.start() except: print 'Failed to start master' print_exc()
Print traceback if startup fails
Print traceback if startup fails
Python
bsd-3-clause
centrumholdings/cthulhubot
--- +++ @@ -1,3 +1,4 @@ +from traceback import print_exc from django.core.management.base import BaseCommand from cthulhubot.models import Buildmaster @@ -20,8 +21,10 @@ b.stop() except: print 'Failed to stop master' + print_exc() try: b.start() except: print 'Failed to start master' + print_exc()
355040c346ee26f763561529422b951e312e3db2
profile/files/openstack/horizon/overrides.py
profile/files/openstack/horizon/overrides.py
# Disable Floating IPs from openstack_dashboard.dashboards.project.access_and_security import tabs from openstack_dashboard.dashboards.project.instances import tables import horizon NO = lambda *x: False tabs.FloatingIPsTab.allowed = NO tabs.APIAccessTab.allowed = NO tables.AssociateIP.allowed = NO tables.SimpleAssociateIP.allowed = NO tables.SimpleDisassociateIP.allowed = NO project_dashboard = horizon.get_dashboard("project") # Completely remove panel Network->Routers routers_panel = project_dashboard.get_panel("routers") project_dashboard.unregister(routers_panel.__class__) # Completely remove panel Network->Networks networks_panel = project_dashboard.get_panel("networks") project_dashboard.unregister(networks_panel.__class__) # Disable Floating IPs # Remove "Volume Consistency Groups" tab from openstack_dashboard.dashboards.project.volumes import tabs tabs.CGroupsTab.allowed = NO
# Disable Floating IPs from openstack_dashboard.dashboards.project.access_and_security import tabs from openstack_dashboard.dashboards.project.instances import tables import horizon NO = lambda *x: False tabs.FloatingIPsTab.allowed = NO tabs.APIAccessTab.allowed = NO tables.AssociateIP.allowed = NO tables.SimpleAssociateIP.allowed = NO tables.SimpleDisassociateIP.allowed = NO project_dashboard = horizon.get_dashboard("project") # Completely remove panel Network->Routers routers_panel = project_dashboard.get_panel("routers") project_dashboard.unregister(routers_panel.__class__) # Completely remove panel Network->Networks networks_panel = project_dashboard.get_panel("networks") project_dashboard.unregister(networks_panel.__class__) # Disable Floating IPs # Completely remove panel Network->Network Topology topology_panel = project_dashboard.get_panel("network_topology") project_dashboard.unregister(topology_panel.__class__) # Remove "Volume Consistency Groups" tab from openstack_dashboard.dashboards.project.volumes import tabs tabs.CGroupsTab.allowed = NO
Remove non-working network topology panel
Remove non-working network topology panel
Python
apache-2.0
eckhart/himlar,tanzr/himlar,TorLdre/himlar,mikaeld66/himlar,norcams/himlar,raykrist/himlar,eckhart/himlar,norcams/himlar,TorLdre/himlar,norcams/himlar,norcams/himlar,raykrist/himlar,mikaeld66/himlar,eckhart/himlar,TorLdre/himlar,tanzr/himlar,mikaeld66/himlar,tanzr/himlar,TorLdre/himlar,mikaeld66/himlar,eckhart/himlar,norcams/himlar,mikaeld66/himlar,raykrist/himlar,raykrist/himlar,TorLdre/himlar,tanzr/himlar,tanzr/himlar,raykrist/himlar
--- +++ @@ -21,6 +21,10 @@ networks_panel = project_dashboard.get_panel("networks") project_dashboard.unregister(networks_panel.__class__) # Disable Floating IPs +# Completely remove panel Network->Network Topology +topology_panel = project_dashboard.get_panel("network_topology") +project_dashboard.unregister(topology_panel.__class__) + # Remove "Volume Consistency Groups" tab from openstack_dashboard.dashboards.project.volumes import tabs tabs.CGroupsTab.allowed = NO
dc229325a7a527c2d2143b105b47899140018e32
darkoob/social/admin.py
darkoob/social/admin.py
from django.contrib import admin from models import UserProfile class UserProfileAdmin(admin.ModelAdmin): list_display = ('user',) # list_display = ('user','sex') # search_fields = ('user',) # list_filter = ('sex',ist_display = ('user','sex') # search_fields = ('user',) # list_filter = ('sex','birthplace')'birthplace') admin.site.register(UserProfile,UserProfileAdmin)
from django.contrib import admin from models import UserProfile class UserProfileAdmin(admin.ModelAdmin): list_display = ('user', 'sex') search_fields = ('user',) admin.site.register(UserProfile,UserProfileAdmin)
Add UserProfile Model To Django Admin Website
Add UserProfile Model To Django Admin Website
Python
mit
s1na/darkoob,s1na/darkoob,s1na/darkoob
--- +++ @@ -2,12 +2,7 @@ from models import UserProfile class UserProfileAdmin(admin.ModelAdmin): - list_display = ('user',) - # list_display = ('user','sex') - # search_fields = ('user',) - # list_filter = ('sex',ist_display = ('user','sex') - # search_fields = ('user',) - # list_filter = ('sex','birthplace')'birthplace') - - + list_display = ('user', 'sex') + search_fields = ('user',) + admin.site.register(UserProfile,UserProfileAdmin)
3db23515437a0073cc374d5064f496c1d84e1bb7
HotCIDR/setup.py
HotCIDR/setup.py
from distutils.core import setup setup( name='HotCIDR', version='0.1.0', author='ViaSat', author_email='stephan.kemper@viasat.com', packages=['hotcidr', 'hotcidr.test'], scripts=['bin/hc-apply', 'bin/hc-audit', 'bin/hc-validate', 'bin/hc-fetch', 'bin/hc-deleteexpired','bin/hc-setupall'], #url='http://pypi.python.org/pypi/HotCIDR', license='LICENSE.txt', description="Firewall rule management and automation tools", #long_description=open('README.txt').read(), install_requires=[ "GitPython >= 0.3.2", "MySQL-python >= 1.2.5", "PyYAML >= 3.10", "boto >= 2.31.1", "inflect >= 0.2.4", "netaddr >= 0.7.12", "requests >= 0.14.0", "toposort >= 1.1", ], )
from distutils.core import setup setup( name='HotCIDR', version='0.1.0', author='ViaSat', author_email='stephan.kemper@viasat.com', packages=['hotcidr', 'hotcidr.test'], scripts=['bin/hc-apply', 'bin/hc-audit', 'bin/hc-validate', 'bin/hc-fetch', 'bin/hc-deleteexpired','bin/hc-setupall'], #url='http://pypi.python.org/pypi/HotCIDR', license='LICENSE.txt', description="Firewall rule management and automation tools", #long_description=open('README.txt').read(), install_requires=[ "GitPython >= 0.3.2.RC1", "MySQL-python >= 1.2.5", "PyYAML >= 3.10", "boto >= 2.28.0", "inflect >= 0.2.4", "netaddr >= 0.7.11", "requests >= 0.14.0", "toposort >= 1.0", ], )
Update dependencies to actual version numbers
Update dependencies to actual version numbers
Python
apache-2.0
ViaSat/hotcidr
--- +++ @@ -12,13 +12,13 @@ description="Firewall rule management and automation tools", #long_description=open('README.txt').read(), install_requires=[ - "GitPython >= 0.3.2", + "GitPython >= 0.3.2.RC1", "MySQL-python >= 1.2.5", "PyYAML >= 3.10", - "boto >= 2.31.1", + "boto >= 2.28.0", "inflect >= 0.2.4", - "netaddr >= 0.7.12", + "netaddr >= 0.7.11", "requests >= 0.14.0", - "toposort >= 1.1", + "toposort >= 1.0", ], )
76709e594bd863476c4111185d98ca2551c460d3
ds_graph.py
ds_graph.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function class Graph(object): """Graph class.""" pass def main(): pass if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function class Vertex(object): """Vertex class. It uses a dict to keep track of the vertices which it's connected. """ class Graph(object): """Graph class. It contains a dict to map vertex name to vertex objects. """ pass def main(): pass if __name__ == '__main__': main()
Add Vertex class and doc strings for 2 classes
Add Vertex class and doc strings for 2 classes
Python
bsd-2-clause
bowen0701/algorithms_data_structures
--- +++ @@ -3,8 +3,18 @@ from __future__ import print_function +class Vertex(object): + """Vertex class. + + It uses a dict to keep track of the vertices which it's connected. + """ + + class Graph(object): - """Graph class.""" + """Graph class. + + It contains a dict to map vertex name to vertex objects. + """ pass
181c094a8918bc386771aaf2d7c99d4cc011a3a5
selenium/tests/basic.py
selenium/tests/basic.py
# # Basic test to check that the catlog loads in IE # def run(driver): driver.get('https://demo.geomoose.org/master/desktop/') if not 'GeoMoose' in driver.title: raise Exception('Unable to load geomoose demo!') # ensure the catalog rendered elem = driver.find_element_by_id('catalog') layers = elem.find_elements_by_class_name('layer') if len(layers) != 17: raise Exception('Layers did not render!')
# # Basic test to check that the catlog loads in IE # def run(driver): driver.get('https://demo.geomoose.org/master/desktop/') if not 'GeoMoose' in driver.title: raise Exception('Unable to load geomoose demo!') # ensure the catalog rendered elem = driver.find_element_by_id('catalog') layers = elem.find_elements_by_class_name('layer') if len(layers) < 10: raise Exception('Layers did not render!')
Fix selenium layer count check.
Fix selenium layer count check. Was hard coded to 17, but sometimes the mapbook changes. Allow to pass when > 10, so this isn't so fragile. The main goal is to see if IE11 works at all. More detailed tests can follow if needed. ref: #391
Python
mit
geomoose/gm3,geomoose/gm3,geomoose/gm3
--- +++ @@ -12,5 +12,5 @@ elem = driver.find_element_by_id('catalog') layers = elem.find_elements_by_class_name('layer') - if len(layers) != 17: + if len(layers) < 10: raise Exception('Layers did not render!')
01c571a3767339caf81dca61c6525f9c9bcf66fd
formlibrary/migrations/0005_auto_20171204_0203.py
formlibrary/migrations/0005_auto_20171204_0203.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-12-04 10:03 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): dependencies = [ ('workflow', '0007_auto_20171204_0203'), ('formlibrary', '0004_customform_created_by'), ] operations = [ migrations.AddField( model_name='customform', name='form_uuid', field=models.CharField(default=uuid.uuid4, max_length=255, unique=True, verbose_name='CustomForm UUID'), ), migrations.AddField( model_name='customform', name='silo_id', field=models.IntegerField(default=0), ), migrations.AddField( model_name='customform', name='workflowlevel1', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='workflow.WorkflowLevel1'), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-12-04 10:03 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): dependencies = [ ('workflow', '0007_auto_20171204_0203'), ('formlibrary', '0004_customform_created_by'), ] operations = [ migrations.AddField( model_name='customform', name='form_uuid', field=models.CharField(default='', max_length=255, verbose_name='CustomForm UUID'), ), migrations.AlterField( model_name='customform', name='form_uuid', field=models.CharField(default=uuid.uuid4, max_length=255, unique=True, verbose_name='CustomForm UUID'), ), migrations.AddField( model_name='customform', name='silo_id', field=models.IntegerField(default=0), ), migrations.AddField( model_name='customform', name='workflowlevel1', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='workflow.WorkflowLevel1'), ), ]
Fix the CustomForm migration script
Fix the CustomForm migration script
Python
apache-2.0
toladata/TolaActivity,toladata/TolaActivity,toladata/TolaActivity,toladata/TolaActivity
--- +++ @@ -18,6 +18,11 @@ migrations.AddField( model_name='customform', name='form_uuid', + field=models.CharField(default='', max_length=255, verbose_name='CustomForm UUID'), + ), + migrations.AlterField( + model_name='customform', + name='form_uuid', field=models.CharField(default=uuid.uuid4, max_length=255, unique=True, verbose_name='CustomForm UUID'), ), migrations.AddField(
ec441eb63a785ad1ab15356f60f812a57a726788
lib/Subcommands/Pull.py
lib/Subcommands/Pull.py
from lib.Wrappers.ArgumentParser import ArgumentParser from lib.DockerManagerFactory import DockerManagerFactory class Pull: def __init__(self, manager_factory=None): self.manager_factory = manager_factory or DockerManagerFactory() def execute(self, *args): arguments = self._parse_arguments(*args) manager = self.manager_factory.get_manager(arguments.version) manager.pull(arguments.components) def _parse_arguments(self, command_name, *args): parser = ArgumentParser(description='Pulls the desired containers', prog='eyeos ' + command_name) parser.add_argument('-v', '--version', metavar='VERSION', type=str, help='pull the version VERSION', default=ArgumentParser.DEFAULT_VERSION) # parser.add_argument('-n', '--node', metavar='NODE', type=str, default=['all'], action='append', # help='pull in NODE only (this flag can be specified multiple times)') parser.add_argument('components', metavar='COMPONENT', nargs='*', default=ArgumentParser.DEFAULT_COMPONENTS, help='which component(s) to pull') args = parser.parse_args(args) return args
import os from lib.DockerComposeExecutor import DockerComposeExecutor from lib.Tools import paths class Pull: def __init__(self, manager_factory=None): pass def execute(self, *args): file_path = os.getcwd() + '/environments/compose_files/latest/docker-compose-all.yml' docker_compose = DockerComposeExecutor(file_path) docker_compose.exec('pull')
Refactor the 'pull' subcommand to use DockerComposeExecutor
Refactor the 'pull' subcommand to use DockerComposeExecutor The pull subcommand was not working because it depended on an unimplemented class DockerManagerFactory.
Python
agpl-3.0
Open365/Open365,Open365/Open365
--- +++ @@ -1,24 +1,15 @@ -from lib.Wrappers.ArgumentParser import ArgumentParser -from lib.DockerManagerFactory import DockerManagerFactory +import os + +from lib.DockerComposeExecutor import DockerComposeExecutor +from lib.Tools import paths class Pull: def __init__(self, manager_factory=None): - self.manager_factory = manager_factory or DockerManagerFactory() + pass def execute(self, *args): - arguments = self._parse_arguments(*args) - manager = self.manager_factory.get_manager(arguments.version) - manager.pull(arguments.components) + file_path = os.getcwd() + '/environments/compose_files/latest/docker-compose-all.yml' + docker_compose = DockerComposeExecutor(file_path) + docker_compose.exec('pull') - def _parse_arguments(self, command_name, *args): - parser = ArgumentParser(description='Pulls the desired containers', - prog='eyeos ' + command_name) - parser.add_argument('-v', '--version', metavar='VERSION', type=str, - help='pull the version VERSION', default=ArgumentParser.DEFAULT_VERSION) - # parser.add_argument('-n', '--node', metavar='NODE', type=str, default=['all'], action='append', - # help='pull in NODE only (this flag can be specified multiple times)') - parser.add_argument('components', metavar='COMPONENT', nargs='*', default=ArgumentParser.DEFAULT_COMPONENTS, - help='which component(s) to pull') - args = parser.parse_args(args) - return args
b03f32dc74785154ccb01f354a30457c53b1526f
tests/templates/components/test_radios_with_images.py
tests/templates/components/test_radios_with_images.py
import json def test_govuk_frontend_jinja_overrides_on_design_system_v3(): with open("package.json") as package_file: package_json = json.load(package_file) assert package_json["dependencies"]["govuk-frontend"].startswith("3."), ( "After upgrading the Design System, manually validate that " "`app/templates/govuk_frontend_jinja_overrides/templates/components/*/template.njk`" "are all structurally-correct and up-to-date macros. If not, update the macros or retire them and update the " "rendering process." )
import json def test_govuk_frontend_jinja_overrides_on_design_system_v3(): with open("package.json") as package_file: package_json = json.load(package_file) assert package_json["dependencies"]["govuk-frontend"].startswith("3."), ( "After upgrading the Design System, manually validate that " "`app/templates/govuk_frontend_jinja_overrides/templates/components/*/template.html`" "are all structurally-correct and up-to-date macros. If not, update the macros or retire them and update the " "rendering process." )
Fix test description: njk -> html
Fix test description: njk -> html
Python
mit
alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin
--- +++ @@ -7,7 +7,7 @@ assert package_json["dependencies"]["govuk-frontend"].startswith("3."), ( "After upgrading the Design System, manually validate that " - "`app/templates/govuk_frontend_jinja_overrides/templates/components/*/template.njk`" + "`app/templates/govuk_frontend_jinja_overrides/templates/components/*/template.html`" "are all structurally-correct and up-to-date macros. If not, update the macros or retire them and update the " "rendering process." )
9db16e16db9131806d76a1f6875dfba33a7d452b
smile_model_graph/__openerp__.py
smile_model_graph/__openerp__.py
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 Smile (<http://www.smile.fr>). All Rights Reserved # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { "name": "Objects Graph", "version": "0.1", "depends": ["base"], "author": "Smile", "license": 'AGPL-3', "description": """ Generate Objects Graph Suggestions & Feedback to: corentin.pouhet-brunerie@smile.fr """, "website": "http://www.smile.fr", "category": "Hidden", "sequence": 32, "data": [ "wizard/ir_model_graph_wizard_view.xml", ], "demo": [], 'test': [], "auto_install": True, "installable": True, "application": False, }
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 Smile (<http://www.smile.fr>). All Rights Reserved # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { "name": "Models Graph", "version": "0.1", "depends": ["base"], "author": "Smile", "license": 'AGPL-3', "description": """ Generate Models Graph Suggestions & Feedback to: corentin.pouhet-brunerie@smile.fr """, "website": "http://www.smile.fr", "category": "Hidden", "sequence": 32, "data": [ "wizard/ir_model_graph_wizard_view.xml", ], "demo": [], 'test': [], "auto_install": True, "installable": True, "application": False, }
Rename Objects to Models in module description
[IMP] Rename Objects to Models in module description
Python
agpl-3.0
tiexinliu/odoo_addons,chadyred/odoo_addons,chadyred/odoo_addons,ovnicraft/odoo_addons,bmya/odoo_addons,odoocn/odoo_addons,odoocn/odoo_addons,tiexinliu/odoo_addons,chadyred/odoo_addons,odoocn/odoo_addons,ovnicraft/odoo_addons,bmya/odoo_addons,ovnicraft/odoo_addons,bmya/odoo_addons,tiexinliu/odoo_addons
--- +++ @@ -20,13 +20,13 @@ ############################################################################## { - "name": "Objects Graph", + "name": "Models Graph", "version": "0.1", "depends": ["base"], "author": "Smile", "license": 'AGPL-3', "description": """ - Generate Objects Graph + Generate Models Graph Suggestions & Feedback to: corentin.pouhet-brunerie@smile.fr """,
7a14c03e0864ca51993d2f05eabd2319c495ba90
recipyGui/views.py
recipyGui/views.py
from flask import Blueprint, request, redirect, render_template, url_for from flask.views import MethodView from recipyGui import recipyGui, mongo from forms import SearchForm runs = Blueprint('runs', __name__, template_folder='templates') @recipyGui.route('/') def index(): form = SearchForm() query = request.args.get('query', '') if not query: # Return all runs, ordered by date (oldest run first) runs = [r for r in mongo.db.recipies.find({}).sort('date', -1)] else: # Search runs using the query string q = { '$text': { '$search': query} } runs = [r for r in mongo.db.recipies.find(q)] print 'runs:', runs print 'query:', query return render_template('runs/list.html', runs=runs, query=query, form=form) #class ListView(MethodView): # def get(self): # runs = Run.objects.all() # print runs # return render_template('runs/list.html', runs=runs) # Register urls #runs.add_url_rule('/', view_func=ListView.as_view('list'))
from flask import Blueprint, request, redirect, render_template, url_for from flask.views import MethodView from recipyGui import recipyGui, mongo from forms import SearchForm runs = Blueprint('runs', __name__, template_folder='templates') @recipyGui.route('/') def index(): form = SearchForm() query = request.args.get('query', '') if not query: # Return all runs, ordered by date (oldest run first) runs = [r for r in mongo.db.recipies.find({}).sort('date', -1)] else: # Search runs using the query string q = { '$text': { '$search': query} } score = { 'score': { '$meta': 'textScore' } } score_sort = [('score', {'$meta': 'textScore'})] runs = [r for r in mongo.db.recipies.find(q, score).sort(score_sort)] print 'runs:', runs print 'query:', query return render_template('runs/list.html', runs=runs, query=query, form=form) #class ListView(MethodView): # def get(self): # runs = Run.objects.all() # print runs # return render_template('runs/list.html', runs=runs) # Register urls #runs.add_url_rule('/', view_func=ListView.as_view('list'))
Sort runs by text score
Sort runs by text score Search results for runs are sorted by text score.
Python
apache-2.0
recipy/recipy-gui,musically-ut/recipy,github4ry/recipy,github4ry/recipy,recipy/recipy,MichielCottaar/recipy,recipy/recipy-gui,MBARIMike/recipy,recipy/recipy,MBARIMike/recipy,bsipocz/recipy,bsipocz/recipy,MichielCottaar/recipy,musically-ut/recipy
--- +++ @@ -17,7 +17,9 @@ else: # Search runs using the query string q = { '$text': { '$search': query} } - runs = [r for r in mongo.db.recipies.find(q)] + score = { 'score': { '$meta': 'textScore' } } + score_sort = [('score', {'$meta': 'textScore'})] + runs = [r for r in mongo.db.recipies.find(q, score).sort(score_sort)] print 'runs:', runs print 'query:', query
4e94612f7fad4b231de9c1a4044259be6079a982
fabtasks.py
fabtasks.py
# -*- coding: utf-8 -*- from fabric.api import task, run def _generate_password(): import string from random import sample chars = string.letters + string.digits return ''.join(sample(chars, 8)) def create_mysql_instance(mysql_user, mysql_password, instance_code): user = instance_code password = _generate_password() cmd = "/usr/bin/mysql -h localhost -u '%s' '--password=%s' -P %s -e \"create database %s; grant all on %s.* to '%s'@'%%' identified by '%s'\"" % ( mysql_user, mysql_password, 3306, user, user, user, password,) return run(cmd) # Local Variables: ** # comment-column: 56 ** # indent-tabs-mode: nil ** # python-indent: 4 ** # End: **
# -*- coding: utf-8 -*- from fabric.api import run def _generate_password(): import string from random import sample chars = string.letters + string.digits return ''.join(sample(chars, 8)) def create_mysql_instance(mysql_user, mysql_password, instance_code): user = instance_code password = _generate_password() cmd_create_database = "/usr/bin/mysql -h localhost -u '%s' '--password=%s' -P %s -e \"create database %s;\"" % ( mysql_user, mysql_password, 3306, user,) cmd_create_user = "/usr/bin/mysql -h localhost -u '%s' '--password=%s' -P %s -e \"grant all on %s.* to '%s'@'%%' identified by '%s';\"" % ( mysql_user, mysql_password, 3306, user, user, password,) run(cmd_create_database) run(cmd_create_user) # Local Variables: ** # comment-column: 56 ** # indent-tabs-mode: nil ** # python-indent: 4 ** # End: **
Split create database and create user into to individual commands
Split create database and create user into to individual commands
Python
mit
goncha/fablib
--- +++ @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -from fabric.api import task, run +from fabric.api import run def _generate_password(): import string @@ -12,10 +12,15 @@ def create_mysql_instance(mysql_user, mysql_password, instance_code): user = instance_code password = _generate_password() - cmd = "/usr/bin/mysql -h localhost -u '%s' '--password=%s' -P %s -e \"create database %s; grant all on %s.* to '%s'@'%%' identified by '%s'\"" % ( + cmd_create_database = "/usr/bin/mysql -h localhost -u '%s' '--password=%s' -P %s -e \"create database %s;\"" % ( mysql_user, mysql_password, 3306, - user, user, user, password,) - return run(cmd) + user,) + cmd_create_user = "/usr/bin/mysql -h localhost -u '%s' '--password=%s' -P %s -e \"grant all on %s.* to '%s'@'%%' identified by '%s';\"" % ( + mysql_user, mysql_password, 3306, + user, user, password,) + + run(cmd_create_database) + run(cmd_create_user)
25777afb24441f54edab1f9daa1bfc7a25c6d0ad
tests/test_regex_parser.py
tests/test_regex_parser.py
import unittest # Ensuring that the proper path is found; there must be a better way import os import sys sys.path.insert(0, os.path.normpath(os.path.join(os.getcwd(), ".."))) # other imports proceed from parsers.regex_parser import BaseParser from src import svg class TestBaseParser(unittest.TestCase): ''' description ''' def setUp(self): self.p = BaseParser() def test__init__(self): self.assertEqual(self.p.directive_name, 'regex_parser') def test_get_svg_defs(self): '''get_svg_defs is really a dummy function; the test is just here so as to ensure there are no major changes done inadvertentdly''' self.assertEqual(str(self.p.get_svg_defs)[0], "<") def test_parse_single_line(self): pass if __name__ == '__main__': unittest.main()
import unittest # Ensuring that the proper path is found; there must be a better way import os import sys sys.path.insert(0, os.path.normpath(os.path.join(os.getcwd(), ".."))) # other imports proceed from parsers.regex_parser import BaseParser from src import svg class TestBaseParser(unittest.TestCase): ''' description ''' def setUp(self): self.p = BaseParser() def test__init__(self): self.assertEqual(self.p.directive_name, 'regex_parser') def test_get_svg_defs(self): '''get_svg_defs is really a dummy function; the test is just here so as to ensure there are no major changes done inadvertentdly''' self.assertEqual(str(self.p.get_svg_defs)[0], "<") def test_parse_single_line(self): self.assertEqual(self.p.parse_single_line(" this is good"), ("good", ())) self.assertEqual(self.p.parse_single_line("this is bad"), (None, "this is bad")) def test_draw_warning(self): lines = ["Dummy1", "Dummy2"] self.assert_("Warning" in str(self.p.draw_warning(lines))) self.assert_("Dummy" in str(self.p.draw_warning(lines))) def test_create_picture(self): good_lines = ["This is good", "More good stuff", "All goodness"] self.assert_("Drawing" in str(self.p.create_picture(good_lines))) if __name__ == '__main__': unittest.main()
Work on unit test for regex_parser (preparing to refactor).
Work on unit test for regex_parser (preparing to refactor).
Python
bsd-3-clause
aroberge/docpicture,aroberge/docpicture
--- +++ @@ -22,6 +22,17 @@ self.assertEqual(str(self.p.get_svg_defs)[0], "<") def test_parse_single_line(self): - pass + self.assertEqual(self.p.parse_single_line(" this is good"), ("good", ())) + self.assertEqual(self.p.parse_single_line("this is bad"), (None, "this is bad")) + + def test_draw_warning(self): + lines = ["Dummy1", "Dummy2"] + self.assert_("Warning" in str(self.p.draw_warning(lines))) + self.assert_("Dummy" in str(self.p.draw_warning(lines))) + + def test_create_picture(self): + good_lines = ["This is good", "More good stuff", "All goodness"] + self.assert_("Drawing" in str(self.p.create_picture(good_lines))) + if __name__ == '__main__': unittest.main()
e10743d9973f479a4d9816f4aafeaacaffa1bd4d
tests/test_spam_filters.py
tests/test_spam_filters.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals """ Unit tests for spam filters. """ import unittest from django.conf import settings from django.test import TestCase try: import honeypot except ImportError: honeypot = None from envelope.spam_filters import check_honeypot # mocking form and request, no need to use the real things here class FakeForm(object): pass class FakeRequest(object): def __init__(self): self.method = 'POST' self.POST = {} class CheckHoneypotTestCase(TestCase): """ Unit tests for ``check_honeypot`` spam filter. """ def setUp(self): self.form = FakeForm() self.request = FakeRequest() self.honeypot = getattr(settings, 'HONEYPOT_FIELD_NAME', 'email2') def test_empty_honeypot(self): """ Empty honeypot field is a valid situation. """ self.request.POST[self.honeypot] = '' self.assertTrue(check_honeypot(self.request, self.form)) @unittest.skipIf(honeypot is None, "django-honeypot is not installed") def test_filled_honeypot(self): """ A value in the honeypot field is an indicator of a bot request. """ self.request.POST[self.honeypot] = 'Hi, this is a bot' self.assertFalse(check_honeypot(self.request, self.form))
# -*- coding: utf-8 -*- from __future__ import unicode_literals """ Unit tests for spam filters. """ import unittest from django.conf import settings try: import honeypot except ImportError: honeypot = None from envelope.spam_filters import check_honeypot # mocking form and request, no need to use the real things here class FakeForm(object): pass class FakeRequest(object): def __init__(self): self.method = 'POST' self.POST = {} class CheckHoneypotTestCase(unittest.TestCase): """ Unit tests for ``check_honeypot`` spam filter. """ def setUp(self): self.form = FakeForm() self.request = FakeRequest() self.honeypot = getattr(settings, 'HONEYPOT_FIELD_NAME', 'email2') def test_empty_honeypot(self): """ Empty honeypot field is a valid situation. """ self.request.POST[self.honeypot] = '' self.assertTrue(check_honeypot(self.request, self.form)) @unittest.skipIf(honeypot is None, "django-honeypot is not installed") def test_filled_honeypot(self): """ A value in the honeypot field is an indicator of a bot request. """ self.request.POST[self.honeypot] = 'Hi, this is a bot' self.assertFalse(check_honeypot(self.request, self.form))
Use simple TestCase in spam filter tests.
Use simple TestCase in spam filter tests.
Python
mit
zsiciarz/django-envelope,r4ts0n/django-envelope,zsiciarz/django-envelope,r4ts0n/django-envelope
--- +++ @@ -9,7 +9,6 @@ import unittest from django.conf import settings -from django.test import TestCase try: import honeypot @@ -30,13 +29,12 @@ self.POST = {} -class CheckHoneypotTestCase(TestCase): +class CheckHoneypotTestCase(unittest.TestCase): """ Unit tests for ``check_honeypot`` spam filter. """ def setUp(self): - self.form = FakeForm() self.request = FakeRequest() self.honeypot = getattr(settings, 'HONEYPOT_FIELD_NAME', 'email2')
b37e9d1cc315e04d763b646bb028612b86768d37
migrations/versions/360_add_pass_fail_returned.py
migrations/versions/360_add_pass_fail_returned.py
""" Add columns to supplier_frameworks to indicate Pass/Fail and whether a Framework Agreement has been returned. Revision ID: 360_add_pass_fail_returned Revises: 340 Create Date: 2015-10-23 16:25:02.068155 """ # revision identifiers, used by Alembic. revision = '360_add_pass_fail_returned' down_revision = '340' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('supplier_frameworks', sa.Column('agreement_returned', sa.Boolean(), nullable=True)) op.add_column('supplier_frameworks', sa.Column('on_framework', sa.Boolean(), nullable=True)) def downgrade(): op.drop_column('supplier_frameworks', 'on_framework') op.drop_column('supplier_frameworks', 'agreement_returned')
""" Add columns to supplier_frameworks to indicate Pass/Fail and whether a Framework Agreement has been returned. Revision ID: 360_add_pass_fail_returned Revises: 350_migrate_interested_suppliers Create Date: 2015-10-23 16:25:02.068155 """ # revision identifiers, used by Alembic. revision = '360_add_pass_fail_returned' down_revision = '350_migrate_interested_suppliers' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('supplier_frameworks', sa.Column('agreement_returned', sa.Boolean(), nullable=True)) op.add_column('supplier_frameworks', sa.Column('on_framework', sa.Boolean(), nullable=True)) def downgrade(): op.drop_column('supplier_frameworks', 'on_framework') op.drop_column('supplier_frameworks', 'agreement_returned')
Update migration sequence after rebase
Update migration sequence after rebase
Python
mit
alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api
--- +++ @@ -3,14 +3,14 @@ been returned. Revision ID: 360_add_pass_fail_returned -Revises: 340 +Revises: 350_migrate_interested_suppliers Create Date: 2015-10-23 16:25:02.068155 """ # revision identifiers, used by Alembic. revision = '360_add_pass_fail_returned' -down_revision = '340' +down_revision = '350_migrate_interested_suppliers' from alembic import op import sqlalchemy as sa
7187dbb7ca378726e2b58dc052dbc150582f9a24
src/summon.py
src/summon.py
#! /usr/bin/env python2 from __future__ import print_function ''' summon.py A simple wrapper for OS-dependent file launchers. Copyright 2013 Julian Gonggrijp Licensed under the Red Spider Project License. See the License.txt that shipped with your copy of this software for details. ''' import sys import subprocess if sys.platform.startswith('win32'): summoning_command = ['start'] elif sys.platform.startswith('darwin'): summoning_command = ['open'] else: # linux assumed summoning_command = ['xdg-open'] def main (argv = None): if not argv: print(usage_msg) else: for filename in argv: subprocess.call(summoning_command + [filename]) usage_msg = ''' Call me with a space-separated list of file paths and I'll summon them for you. ''' if __name__ == '__main__': main(sys.argv[1:])
#! /usr/bin/env python2 from __future__ import print_function ''' summon.py A simple wrapper for OS-dependent file launchers. Copyright 2013 Julian Gonggrijp Licensed under the Red Spider Project License. See the License.txt that shipped with your copy of this software for details. ''' import sys import subprocess useshell = False if sys.platform.startswith('win32'): summoning_command = ['start'] useshell = True elif sys.platform.startswith('darwin'): summoning_command = ['open'] else: # linux assumed summoning_command = ['xdg-open'] def main (argv = None): if not argv: print(usage_msg) else: for filename in argv: subprocess.call(summoning_command + [filename], shell = useshell) usage_msg = ''' Call me with a space-separated list of file paths and I'll summon them for you. ''' if __name__ == '__main__': main(sys.argv[1:])
Use shell in subprocess.call for Windows.
Use shell in subprocess.call for Windows.
Python
mit
the-xkcd-community/the-red-spider-project,the-xkcd-community/the-red-spider-project,the-xkcd-community/the-red-spider-project,the-xkcd-community/the-red-spider-project,the-xkcd-community/the-red-spider-project,the-xkcd-community/the-red-spider-project,the-xkcd-community/the-red-spider-project,the-xkcd-community/the-red-spider-project,the-xkcd-community/the-red-spider-project,the-xkcd-community/the-red-spider-project,the-xkcd-community/the-red-spider-project
--- +++ @@ -12,8 +12,10 @@ import sys import subprocess +useshell = False if sys.platform.startswith('win32'): summoning_command = ['start'] + useshell = True elif sys.platform.startswith('darwin'): summoning_command = ['open'] else: # linux assumed @@ -24,7 +26,7 @@ print(usage_msg) else: for filename in argv: - subprocess.call(summoning_command + [filename]) + subprocess.call(summoning_command + [filename], shell = useshell) usage_msg = ''' Call me with a space-separated list of file paths and I'll summon
d22f77a8e1a54d373f426589364b95f742b70b3f
irc/util.py
irc/util.py
# from jaraco.util.itertools def always_iterable(item): """ Given an object, always return an iterable. If the item is not already iterable, return a tuple containing only the item. >>> always_iterable([1,2,3]) [1, 2, 3] >>> always_iterable('foo') ('foo',) >>> always_iterable(None) (None,) >>> always_iterable(xrange(10)) xrange(10) """ if isinstance(item, basestring) or not hasattr(item, '__iter__'): item = item, return item def total_seconds(td): """ Python 2.7 adds a total_seconds method to timedelta objects. See http://docs.python.org/library/datetime.html#datetime.timedelta.total_seconds >>> import datetime >>> total_seconds(datetime.timedelta(hours=24)) 86400.0 """ try: result = td.total_seconds() except AttributeError: seconds = td.seconds + td.days * 24 * 3600 result = (td.microseconds + seconds * 10**6) / 10**6 return result
# from jaraco.util.itertools def always_iterable(item): """ Given an object, always return an iterable. If the item is not already iterable, return a tuple containing only the item. >>> always_iterable([1,2,3]) [1, 2, 3] >>> always_iterable('foo') ('foo',) >>> always_iterable(None) (None,) >>> always_iterable(xrange(10)) xrange(10) """ if isinstance(item, basestring) or not hasattr(item, '__iter__'): item = item, return item def total_seconds(td): """ Python 2.7 adds a total_seconds method to timedelta objects. See http://docs.python.org/library/datetime.html#datetime.timedelta.total_seconds >>> import datetime >>> total_seconds(datetime.timedelta(hours=24)) 86400.0 """ try: result = td.total_seconds() except AttributeError: seconds = td.seconds + td.days * 24 * 3600 result = float((td.microseconds + seconds * 10**6) / 10**6) return result
Use float so test passes on Python 2.6
Use float so test passes on Python 2.6
Python
mit
jaraco/irc
--- +++ @@ -30,5 +30,5 @@ result = td.total_seconds() except AttributeError: seconds = td.seconds + td.days * 24 * 3600 - result = (td.microseconds + seconds * 10**6) / 10**6 + result = float((td.microseconds + seconds * 10**6) / 10**6) return result
d6a817949c51462af7d95d542ece667547b23cce
cbagent/collectors/ps.py
cbagent/collectors/ps.py
from cbagent.collectors import Collector from cbagent.collectors.libstats.psstats import PSStats class PS(Collector): COLLECTOR = "atop" # Legacy KNOWN_PROCESSES = ("beam.smp", "memcached", "indexer", "projector", "cbq-engine") def __init__(self, settings): super(PS, self).__init__(settings) self.nodes = settings.hostnames or list(self.get_nodes()) if hasattr(settings, "monitor_clients") and settings.monitor_clients\ and settings.master_node in settings.monitor_clients: self.nodes = settings.monitor_clients self.KNOWN_PROCESSES = ("backup", "cbbackupwrapper", ) if hasattr(settings, "fts_server"): self.KNOWN_PROCESSES = ("beam.smp", "memcached", "cbft",) self.ps = PSStats(hosts=self.nodes, user=self.ssh_username, password=self.ssh_password) def update_metadata(self): self.mc.add_cluster() for node in self.nodes: self.mc.add_server(node) def sample(self): for process in self.KNOWN_PROCESSES: for node, stats in self.ps.get_samples(process).items(): if stats: self.update_metric_metadata(stats.keys(), server=node) self.store.append(stats, cluster=self.cluster, server=node, collector=self.COLLECTOR)
from cbagent.collectors import Collector from cbagent.collectors.libstats.psstats import PSStats class PS(Collector): COLLECTOR = "atop" # Legacy KNOWN_PROCESSES = ("beam.smp", "memcached", "indexer", "projector", "cbq-engine") def __init__(self, settings): super(PS, self).__init__(settings) self.nodes = settings.hostnames or list(self.get_nodes()) if hasattr(settings, "monitor_clients") and settings.monitor_clients\ and settings.master_node in settings.monitor_clients: self.nodes = settings.monitor_clients self.KNOWN_PROCESSES = ("backup", "cbbackupwrapper", ) if hasattr(settings, "fts_server") and settings.fts_server: self.KNOWN_PROCESSES = ("beam.smp", "memcached", "cbft",) self.ps = PSStats(hosts=self.nodes, user=self.ssh_username, password=self.ssh_password) def update_metadata(self): self.mc.add_cluster() for node in self.nodes: self.mc.add_server(node) def sample(self): for process in self.KNOWN_PROCESSES: for node, stats in self.ps.get_samples(process).items(): if stats: self.update_metric_metadata(stats.keys(), server=node) self.store.append(stats, cluster=self.cluster, server=node, collector=self.COLLECTOR)
Fix condition for FTS stats collection
CBPS-186: Fix condition for FTS stats collection Currently, stats collection for processes such as indexer and cbq-engine is disabled due to a wrong "if" statement. The "settings object" always has "fts_server" attribute. We should check its boolean value instead. Change-Id: I017f4758f3603e674f094af27b6293716796418a Reviewed-on: http://review.couchbase.org/67781 Tested-by: buildbot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com> Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com>
Python
apache-2.0
pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner
--- +++ @@ -18,7 +18,7 @@ self.nodes = settings.monitor_clients self.KNOWN_PROCESSES = ("backup", "cbbackupwrapper", ) - if hasattr(settings, "fts_server"): + if hasattr(settings, "fts_server") and settings.fts_server: self.KNOWN_PROCESSES = ("beam.smp", "memcached", "cbft",) self.ps = PSStats(hosts=self.nodes,
ac7fefd3a2058e2e9773d7e458f8fad6112fc33c
dev/lint.py
dev/lint.py
# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import os import flake8 if flake8.__version_info__ < (3,): from flake8.engine import get_style_guide else: from flake8.api.legacy import get_style_guide cur_dir = os.path.dirname(__file__) config_file = os.path.join(cur_dir, '..', 'tox.ini') def run(): """ Runs flake8 lint :return: A bool - if flake8 did not find any errors """ print('Running flake8') flake8_style = get_style_guide(config_file=config_file) paths = [] for root, _, filenames in os.walk('asn1crypto'): for filename in filenames: if not filename.endswith('.py'): continue paths.append(os.path.join(root, filename)) report = flake8_style.check_files(paths) success = report.total_errors == 0 if success: print('OK') return success
# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import os import flake8 if not hasattr(flake8, '__version_info__') or flake8.__version_info__ < (3,): from flake8.engine import get_style_guide else: from flake8.api.legacy import get_style_guide cur_dir = os.path.dirname(__file__) config_file = os.path.join(cur_dir, '..', 'tox.ini') def run(): """ Runs flake8 lint :return: A bool - if flake8 did not find any errors """ print('Running flake8') flake8_style = get_style_guide(config_file=config_file) paths = [] for root, _, filenames in os.walk('asn1crypto'): for filename in filenames: if not filename.endswith('.py'): continue paths.append(os.path.join(root, filename)) report = flake8_style.check_files(paths) success = report.total_errors == 0 if success: print('OK') return success
Fix support for flake8 v2
Fix support for flake8 v2
Python
mit
wbond/asn1crypto
--- +++ @@ -4,7 +4,7 @@ import os import flake8 -if flake8.__version_info__ < (3,): +if not hasattr(flake8, '__version_info__') or flake8.__version_info__ < (3,): from flake8.engine import get_style_guide else: from flake8.api.legacy import get_style_guide
49999de7ac753f57e3c25d9d36c1806f3ec3a0ee
omnirose/curve/forms.py
omnirose/curve/forms.py
from django import forms from django.forms.models import formset_factory, BaseModelFormSet from django.forms.widgets import NumberInput from .models import Reading class ReadingForm(forms.Form): ships_head = forms.FloatField(required=False, widget=NumberInput(attrs={'style': "width: 5em;"})) deviation = forms.FloatField(required=False, widget=NumberInput(attrs={'style': "width: 5em;"})) ReadingFormSet = formset_factory(form=ReadingForm)
from django import forms from django.forms.models import formset_factory, BaseModelFormSet from django.forms.widgets import NumberInput from .models import Reading class DegreeInput(NumberInput): """Set the default style""" def __init__(self, attrs=None): if attrs is None: attrs = {} attrs['style'] = "width: 5em;" super(DegreeInput, self).__init__(attrs) """Strip decimal points if not needed""" def _format_value(self, value): return u"%g" % value class ReadingForm(forms.Form): ships_head = forms.FloatField( required=False, widget=DegreeInput() ) deviation = forms.FloatField( required=False, widget=DegreeInput() ) ReadingFormSet = formset_factory(form=ReadingForm)
Customize degree widget so that if formats floats more elegantly
Customize degree widget so that if formats floats more elegantly
Python
agpl-3.0
OmniRose/omnirose-website,OmniRose/omnirose-website,OmniRose/omnirose-website
--- +++ @@ -4,8 +4,30 @@ from .models import Reading +class DegreeInput(NumberInput): + + """Set the default style""" + def __init__(self, attrs=None): + if attrs is None: + attrs = {} + attrs['style'] = "width: 5em;" + + super(DegreeInput, self).__init__(attrs) + + """Strip decimal points if not needed""" + def _format_value(self, value): + return u"%g" % value + + class ReadingForm(forms.Form): - ships_head = forms.FloatField(required=False, widget=NumberInput(attrs={'style': "width: 5em;"})) - deviation = forms.FloatField(required=False, widget=NumberInput(attrs={'style': "width: 5em;"})) + ships_head = forms.FloatField( + required=False, + widget=DegreeInput() + ) + + deviation = forms.FloatField( + required=False, + widget=DegreeInput() + ) ReadingFormSet = formset_factory(form=ReadingForm)
2b464c9be11ad8aa0de62bca4424fed7d4d3e2b3
configurator/__init__.py
configurator/__init__.py
"""Adaptive configuration dialogs. Attributes: __version__: The current version string. """ import os import subprocess def _get_version(version=None): # overwritten by setup.py if version is None: pkg_dir = os.path.dirname(__file__) src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir)) git_dir = os.path.join(src_dir, ".git") git_args = ("git", "--work-tree", src_dir, "--git-dir", git_dir, "describe", "--tags", "--dirty") with open(os.devnull, "w") as devnull: output = subprocess.check_output(git_args) version = output.decode("utf-8").strip() return version __version__ = _get_version()
"""Adaptive configuration dialogs. Attributes: __version__: The current version string. """ import os import subprocess def _get_version(version=None): # overwritten by setup.py if version is None: pkg_dir = os.path.dirname(__file__) src_dir = os.path.abspath(os.path.join(pkg_dir, os.pardir)) git_dir = os.path.join(src_dir, ".git") git_args = ("git", "--work-tree", src_dir, "--git-dir", git_dir, "describe", "--tags", "--dirty") with open(os.devnull, "w") as devnull: output = subprocess.check_output(git_args, stderr=devnull) version = output.decode("utf-8").strip() return version __version__ = _get_version()
Enable back git output redirection in _get_version
Enable back git output redirection in _get_version
Python
apache-2.0
yasserglez/configurator,yasserglez/configurator
--- +++ @@ -16,7 +16,7 @@ git_args = ("git", "--work-tree", src_dir, "--git-dir", git_dir, "describe", "--tags", "--dirty") with open(os.devnull, "w") as devnull: - output = subprocess.check_output(git_args) + output = subprocess.check_output(git_args, stderr=devnull) version = output.decode("utf-8").strip() return version
3dc9e45448211a5bd36c1f4e495eddef6e0e485e
scaffolder/commands/list.py
scaffolder/commands/list.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from optparse import make_option from optparse import OptionParser from scaffolder.core.commands import BaseCommand from scaffolder.core.template import TemplateManager class TemplateCommand(BaseCommand): option_list = BaseCommand.option_list + ( make_option( "-u", "--url", dest="url", default='default', help='Database router id.', metavar="DATABASE" ), ) def __init__(self, name, help='', aliases=(), stdout=None, stderr=None): help = 'Template command help entry' parser = OptionParser( version=self.get_version(), option_list=self.get_option_list(), usage='\n %prog {0} [OPTIONS] FILE...'.format(name) ) aliases = ('tmp',) BaseCommand.__init__(self, name, parser=parser, help=help, aliases=aliases) def run(self, *args, **options): url = options.get('url') debug = options.get('debug') manger = TemplateManager() manger.list() print "Execute template {0}, {1}".format(url, debug)
#!/usr/bin/env python # -*- coding: utf-8 -*- from optparse import make_option from optparse import OptionParser from scaffolder.core.commands import BaseCommand from scaffolder.core.template import TemplateManager class ListCommand(BaseCommand): def __init__(self, name, help='', aliases=(), stdout=None, stderr=None): help = 'Template command help entry' parser = OptionParser( version=self.get_version(), option_list=self.get_option_list(), usage='\n %prog {0} [OPTIONS]'.format(name) ) aliases = ('tmp',) BaseCommand.__init__(self, name, parser=parser, help=help, aliases=aliases) def run(self, *args, **options): manger = TemplateManager() manger.list() def get_default_option(self): return []
Remove options, the command does not take options.
ListCommand: Remove options, the command does not take options.
Python
mit
goliatone/minions
--- +++ @@ -6,32 +6,21 @@ from scaffolder.core.commands import BaseCommand from scaffolder.core.template import TemplateManager -class TemplateCommand(BaseCommand): - option_list = BaseCommand.option_list + ( - make_option( - "-u", - "--url", - dest="url", - default='default', - help='Database router id.', - metavar="DATABASE" - ), - ) +class ListCommand(BaseCommand): def __init__(self, name, help='', aliases=(), stdout=None, stderr=None): help = 'Template command help entry' parser = OptionParser( version=self.get_version(), option_list=self.get_option_list(), - usage='\n %prog {0} [OPTIONS] FILE...'.format(name) + usage='\n %prog {0} [OPTIONS]'.format(name) ) aliases = ('tmp',) BaseCommand.__init__(self, name, parser=parser, help=help, aliases=aliases) def run(self, *args, **options): - url = options.get('url') - debug = options.get('debug') manger = TemplateManager() manger.list() - print "Execute template {0}, {1}".format(url, debug) + def get_default_option(self): + return []
48beff57b1c98db24a83ee0c4fdb3f3b436978be
pyface/__init__.py
pyface/__init__.py
#------------------------------------------------------------------------------ # Copyright (c) 2005-2013, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt # Thanks for using Enthought open source! # # Author: Enthought, Inc. # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ """ Reusable MVC-based components for Traits-based applications. Part of the TraitsGUI project of the Enthought Tool Suite. """ try: from ._version import full_version as __version__ except ImportError: __version__ = 'not-built' __requires__ = [ 'traits', ]
#------------------------------------------------------------------------------ # Copyright (c) 2005-2013, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt # Thanks for using Enthought open source! # # Author: Enthought, Inc. # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ """ Reusable MVC-based components for Traits-based applications. Part of the TraitsGUI project of the Enthought Tool Suite. """ try: from pyface._version import full_version as __version__ except ImportError: __version__ = 'not-built' __requires__ = [ 'traits', ]
Use absolute import to get the package version.
Use absolute import to get the package version.
Python
bsd-3-clause
geggo/pyface,geggo/pyface,brett-patterson/pyface
--- +++ @@ -16,7 +16,7 @@ """ try: - from ._version import full_version as __version__ + from pyface._version import full_version as __version__ except ImportError: __version__ = 'not-built'
6d5ebbebd558a716afeda1933f45f0dfbef41bb4
tests/smolder_tests.py
tests/smolder_tests.py
#!/usr/bin/env python2 import smolder import nose import json import os from nose.tools import assert_raises from imp import reload THIS_DIR = os.path.dirname(os.path.realpath(__file__)) def test_noop_test(): assert smolder.noop_test() def test_github_status(): myfile = open(THIS_DIR + '/github_status.json') test_json = json.load(myfile) for test in test_json['tests']: smolder.http_test(test, 'status.github.com', False) reload(smolder) assert smolder.failed_tests == 0 def test_github_status_response_time_expect_fail(): myfile = open(THIS_DIR + '/harsh_github_status.json') test_json = json.load(myfile) for test in test_json['tests']: smolder.http_test(test, 'status.github.com', False) reload(smolder) assert smolder.failed_tests > 0 def test_tcp_test(): smolder.tcp_test('127.0.0.1', 22) #Are you running an ssh server? def test_fail_tcp_test(): assert_raises(Exception, smolder.tcp_test, '127.0.0.1', 4242)
#!/usr/bin/env python2 import smolder import json import os from nose.tools import assert_raises from imp import reload THIS_DIR = os.path.dirname(os.path.realpath(__file__)) def test_noop_test(): assert smolder.noop_test() def test_github_status(): myfile = open(THIS_DIR + '/github_status.json') test_json = json.load(myfile) for test in test_json['tests']: smolder.http_test(test, 'status.github.com', False) reload(smolder) assert smolder.failed_tests == 0 def test_github_status_response_time_expect_fail(): myfile = open(THIS_DIR + '/harsh_github_status.json') test_json = json.load(myfile) for test in test_json['tests']: smolder.http_test(test, 'status.github.com', False) reload(smolder) assert smolder.failed_tests > 0 def test_tcp_test(): smolder.tcp_test('127.0.0.1', 22) #Are you running an ssh server? def test_fail_tcp_test(): assert_raises(Exception, smolder.tcp_test, '127.0.0.1', 4242)
Clean up imports in smolder tests
Clean up imports in smolder tests
Python
bsd-3-clause
sky-shiny/smolder,sky-shiny/smolder
--- +++ @@ -1,6 +1,5 @@ #!/usr/bin/env python2 import smolder -import nose import json import os from nose.tools import assert_raises