commit stringlengths 40 40 | old_file stringlengths 4 118 | new_file stringlengths 4 118 | old_contents stringlengths 0 2.94k | new_contents stringlengths 1 4.43k | subject stringlengths 15 444 | message stringlengths 16 3.45k | lang stringclasses 1 value | license stringclasses 13 values | repos stringlengths 5 43.2k | prompt stringlengths 17 4.58k | response stringlengths 1 4.43k | prompt_tagged stringlengths 58 4.62k | response_tagged stringlengths 1 4.43k | text stringlengths 132 7.29k | text_tagged stringlengths 173 7.33k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
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 | 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)Add upload file size limit | 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) | <commit_before>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)<commit_msg>Add upload file size limit<commit_after> | 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) | 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)Add upload file size limitfrom __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) | <commit_before>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)<commit_msg>Add upload file size limit<commit_after>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) |
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 | 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)
Enable command-line args for configuration | 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)
| <commit_before>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)
<commit_msg>Enable command-line args for configuration<commit_after> | 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)
| 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)
Enable command-line args for configurationfrom 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)
| <commit_before>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)
<commit_msg>Enable command-line args for configuration<commit_after>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)
|
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 | 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
Remove unused imports and sort | 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
| <commit_before>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
<commit_msg>Remove unused imports and sort<commit_after> | 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
| 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
Remove unused imports and sortimport 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
| <commit_before>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
<commit_msg>Remove unused imports and sort<commit_after>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
|
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 | #!/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 | #!/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
| <commit_before>#!/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
<commit_msg>Change prompt to a diamond<commit_after> | #!/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#!/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
| <commit_before>#!/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
<commit_msg>Change prompt to a diamond<commit_after>#!/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
|
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 | 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()
Add comment on dist of first function | 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()
| <commit_before>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()
<commit_msg>Add comment on dist of first function<commit_after> | 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()
| 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()
Add comment on dist of first functionimport 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()
| <commit_before>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()
<commit_msg>Add comment on dist of first function<commit_after>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()
|
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 | #!/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')
Add Minecraft Wiki link to version item | #!/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')
| <commit_before>#!/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')
<commit_msg>Add Minecraft Wiki link to version item<commit_after> | #!/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')
| #!/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')
Add Minecraft Wiki link to version item#!/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')
| <commit_before>#!/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')
<commit_msg>Add Minecraft Wiki link to version item<commit_after>#!/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')
|
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 | """ 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 | """ 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;
}
"""
| <commit_before>""" 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;
}
"""
<commit_msg>Fix CSS problem when Flexx is enbedded in page-app<commit_after> | """ 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""" 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;
}
"""
| <commit_before>""" 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;
}
"""
<commit_msg>Fix CSS problem when Flexx is enbedded in page-app<commit_after>""" 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;
}
"""
|
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 | #
# 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())
Update Arch package to 2.7 | #
# 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())
| <commit_before>#
# 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())
<commit_msg>Update Arch package to 2.7<commit_after> | #
# 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())
| #
# 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())
Update Arch package to 2.7#
# 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())
| <commit_before>#
# 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())
<commit_msg>Update Arch package to 2.7<commit_after>#
# 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())
|
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 | 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')
Update upstream version of vo | 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')
| <commit_before>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')
<commit_msg>Update upstream version of vo<commit_after> | 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')
| 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')
Update upstream version of vofrom 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')
| <commit_before>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')
<commit_msg>Update upstream version of vo<commit_after>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')
|
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 | #!/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()
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. | #!/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()
| <commit_before>#!/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()
<commit_msg>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.<commit_after> | #!/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()
| #!/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()
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.#!/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()
| <commit_before>#!/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()
<commit_msg>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.<commit_after>#!/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()
|
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 | # 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
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 | # 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
| <commit_before># 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
<commit_msg>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<commit_after> | # 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
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# 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
| <commit_before># 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
<commit_msg>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<commit_after># 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
|
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 | from django.contrib import admin
# Register your models here.
Add `Post`, `Tag` models to Admin | from django.contrib import admin
from .models import Post, Tag
admin.site.register(Post)
admin.site.register(Tag)
| <commit_before>from django.contrib import admin
# Register your models here.
<commit_msg>Add `Post`, `Tag` models to Admin<commit_after> | from django.contrib import admin
from .models import Post, Tag
admin.site.register(Post)
admin.site.register(Tag)
| from django.contrib import admin
# Register your models here.
Add `Post`, `Tag` models to Adminfrom django.contrib import admin
from .models import Post, Tag
admin.site.register(Post)
admin.site.register(Tag)
| <commit_before>from django.contrib import admin
# Register your models here.
<commit_msg>Add `Post`, `Tag` models to Admin<commit_after>from django.contrib import admin
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 | 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()
Fix for test failure introduced by basic auth changes | 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()
| <commit_before>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()
<commit_msg>Fix for test failure introduced by basic auth changes<commit_after> | 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()
| 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()
Fix for test failure introduced by basic auth changesfrom 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()
| <commit_before>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()
<commit_msg>Fix for test failure introduced by basic auth changes<commit_after>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()
|
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 | 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()Update capture profiler to new spec of providing board instead of string. | 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() | <commit_before>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()<commit_msg>Update capture profiler to new spec of providing board instead of string.<commit_after> | 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() | 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()Update capture profiler to new spec of providing board instead of string.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() | <commit_before>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()<commit_msg>Update capture profiler to new spec of providing board instead of string.<commit_after>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() |
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 | 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()
Add management functions for migration | 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()
| <commit_before>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()
<commit_msg>Add management functions for migration<commit_after> | 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()
| 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()
Add management functions for migrationfrom 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()
| <commit_before>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()
<commit_msg>Add management functions for migration<commit_after>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()
|
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 | 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')
Fix Auth API key check causing error 500s | 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')
| <commit_before>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')
<commit_msg>Fix Auth API key check causing error 500s<commit_after> | 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')
| 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')
Fix Auth API key check causing error 500sfrom 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')
| <commit_before>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')
<commit_msg>Fix Auth API key check causing error 500s<commit_after>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')
|
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 | 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 = []
Add parent so we can track versions. | 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 = ""
| <commit_before>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 = []
<commit_msg>Add parent so we can track versions.<commit_after> | 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 = ""
| 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 = []
Add parent so we can track versions.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 = ""
| <commit_before>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 = []
<commit_msg>Add parent so we can track versions.<commit_after>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 = ""
|
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 | 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 | 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'),
]
| <commit_before>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'),
]
<commit_msg>Add trailing slash to url<commit_after> | 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 urlfrom 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'),
]
| <commit_before>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'),
]
<commit_msg>Add trailing slash to url<commit_after>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'),
]
|
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 | 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)."Add option to ignore static. | 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)." | <commit_before>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)."<commit_msg>Add option to ignore static.<commit_after> | 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)." | 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)."Add option to ignore static.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)." | <commit_before>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)."<commit_msg>Add option to ignore static.<commit_after>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)." |
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 | """
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
Add better custom has_permission check. | """
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)
| <commit_before>"""
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
<commit_msg>Add better custom has_permission check.<commit_after> | """
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)
| """
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
Add better custom has_permission check."""
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)
| <commit_before>"""
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
<commit_msg>Add better custom has_permission check.<commit_after>"""
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)
|
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 | 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)
Swap back to Fuzzer, no monkey patching | 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())
| <commit_before>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)
<commit_msg>Swap back to Fuzzer, no monkey patching<commit_after> | 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())
| 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)
Swap back to Fuzzer, no monkey patchingfrom 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())
| <commit_before>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)
<commit_msg>Swap back to Fuzzer, no monkey patching<commit_after>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())
|
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 | 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
Fix typo in error message variable | 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
| <commit_before>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
<commit_msg>Fix typo in error message variable<commit_after> | 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
| 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
Fix typo in error message variablefrom __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
| <commit_before>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
<commit_msg>Fix typo in error message variable<commit_after>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
|
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 | 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)
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. | 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)
| <commit_before>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)
<commit_msg>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.<commit_after> | 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)
| 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)
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.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)
| <commit_before>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)
<commit_msg>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.<commit_after>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)
|
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 | """
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))Convert entire table to cartesian | """
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)) | <commit_before>"""
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))<commit_msg>Convert entire table to cartesian<commit_after> | """
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)) | """
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))Convert entire table to cartesian"""
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)) | <commit_before>"""
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))<commit_msg>Convert entire table to cartesian<commit_after>"""
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)) |
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 | 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
Handle orgs that you don’t own personally. | 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
| <commit_before>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
<commit_msg>Handle orgs that you don’t own personally.<commit_after> | 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
| 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
Handle orgs that you don’t own personally.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
| <commit_before>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
<commit_msg>Handle orgs that you don’t own personally.<commit_after>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
|
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 | 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)
Use author display name in document list_filter | 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)
| <commit_before>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)
<commit_msg>Use author display name in document list_filter<commit_after> | 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)
| 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)
Use author display name in document list_filterfrom 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)
| <commit_before>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)
<commit_msg>Use author display name in document list_filter<commit_after>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)
|
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 | 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
Fix prefetched fields in Institutions in API | 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
| <commit_before>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
<commit_msg>Fix prefetched fields in Institutions in API<commit_after> | 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
| 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
Fix prefetched fields in Institutions in APIimport 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
| <commit_before>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
<commit_msg>Fix prefetched fields in Institutions in API<commit_after>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
|
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 | 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)
Fix wsgi config file access for HTTPD
Bug 1051081
Change-Id: Ie1690c9b1b98ed3f5a78d935878369b7520b35c9 | 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)
| <commit_before>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)
<commit_msg>Fix wsgi config file access for HTTPD
Bug 1051081
Change-Id: Ie1690c9b1b98ed3f5a78d935878369b7520b35c9<commit_after> | 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)
| 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)
Fix wsgi config file access for HTTPD
Bug 1051081
Change-Id: Ie1690c9b1b98ed3f5a78d935878369b7520b35c9import 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)
| <commit_before>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)
<commit_msg>Fix wsgi config file access for HTTPD
Bug 1051081
Change-Id: Ie1690c9b1b98ed3f5a78d935878369b7520b35c9<commit_after>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)
|
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 | 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()
Fix reverse since we deprecated post_object_list | 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()
| <commit_before>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()
<commit_msg>Fix reverse since we deprecated post_object_list<commit_after> | 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()
| 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()
Fix reverse since we deprecated post_object_listfrom 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()
| <commit_before>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()
<commit_msg>Fix reverse since we deprecated post_object_list<commit_after>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()
|
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 |
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
Fix filename creation in csv export action |
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
| <commit_before>
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
<commit_msg>Fix filename creation in csv export action<commit_after> |
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
|
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
Fix filename creation in csv export action
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
| <commit_before>
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
<commit_msg>Fix filename creation in csv export action<commit_after>
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
|
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 | # 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()Change sleep function to the end to do repeat everytime | # 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 ) | <commit_before># 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()<commit_msg>Change sleep function to the end to do repeat everytime<commit_after> | # 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 ) | # 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()Change sleep function to the end to do repeat everytime# 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 ) | <commit_before># 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()<commit_msg>Change sleep function to the end to do repeat everytime<commit_after># 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 ) |
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 | #!/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. | #!/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)
| <commit_before>#!/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)<commit_msg>Revert file to moneymanager master branch.<commit_after> | #!/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.#!/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)
| <commit_before>#!/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)<commit_msg>Revert file to moneymanager master branch.<commit_after>#!/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)
|
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 | #!/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()
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. | #!/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()
| <commit_before>#!/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()
<commit_msg>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.<commit_after> | #!/usr/bin/env python
import click
import os
import codecs
import json
from xtas.tasks._frog import parse_frog, frog_to_saf
@click.command()
@click.argument('input_files', nargs=-1, type=click.Path(exists=True))
@click.argument('output_dir', nargs=1, type=click.Path())
def frog2saf(input_files, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for fi in input_files:
with codecs.open(fi) as f:
lines = f.readlines()
lines = [line.strip() for line in lines]
saf_data = frog_to_saf(parse_frog(lines))
head, tail = os.path.split(fi)
fname = tail.replace(os.path.splitext(tail)[1], '')
out_file = os.path.join(output_dir, '{}.json'.format(fname))
with codecs.open(out_file, 'wb', encoding='utf-8') as f:
json.dump(saf_data, f, indent=4)
if __name__ == '__main__':
frog2saf()
| #!/usr/bin/env python
import click
import os
import codecs
import json
from xtas.tasks._frog import parse_frog, frog_to_saf
@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()
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.#!/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()
| <commit_before>#!/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()
<commit_msg>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.<commit_after>#!/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()
|
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 | #!/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()
Fix django custom template tag importing | #!/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()
| <commit_before>#!/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()
<commit_msg>Fix django custom template tag importing<commit_after> | #!/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()
| #!/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()
Fix django custom template tag importing#!/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()
| <commit_before>#!/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()
<commit_msg>Fix django custom template tag importing<commit_after>#!/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()
|
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 | 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"
)
Make sure request.user is a user | 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"
)
| <commit_before>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"
)
<commit_msg>Make sure request.user is a user<commit_after> | 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"
)
| 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"
)
Make sure request.user is a userfrom 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"
)
| <commit_before>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"
)
<commit_msg>Make sure request.user is a user<commit_after>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"
)
|
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 | 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
[docs](jwt_auth): Make serializer commet more clear | 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
| <commit_before>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
<commit_msg>[docs](jwt_auth): Make serializer commet more clear<commit_after> | 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
| 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
[docs](jwt_auth): Make serializer commet more clearfrom .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
| <commit_before>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
<commit_msg>[docs](jwt_auth): Make serializer commet more clear<commit_after>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
|
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 | #
# 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",
],
)
Change package name to 'cirm' to avoid confusion. | #
# 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",
],
)
| <commit_before>#
# 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",
],
)
<commit_msg>Change package name to 'cirm' to avoid confusion.<commit_after> | #
# 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",
],
)
| #
# 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",
],
)
Change package name to 'cirm' to avoid confusion.#
# 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",
],
)
| <commit_before>#
# 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",
],
)
<commit_msg>Change package name to 'cirm' to avoid confusion.<commit_after>#
# 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",
],
)
|
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 | #-*- 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")
Add to template builtins only if add_to_buitlins is available (Django <= 1.8) | #-*- 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")
| <commit_before>#-*- 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")
<commit_msg>Add to template builtins only if add_to_buitlins is available (Django <= 1.8)<commit_after> | #-*- 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")
| #-*- 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")
Add to template builtins only if add_to_buitlins is available (Django <= 1.8)#-*- 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")
| <commit_before>#-*- 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")
<commit_msg>Add to template builtins only if add_to_buitlins is available (Django <= 1.8)<commit_after>#-*- 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")
|
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 | """
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)
Add exception hook to help diagnose server test errors in python3 gui mode | """
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)
| <commit_before>"""
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)
<commit_msg>Add exception hook to help diagnose server test errors in python3 gui mode<commit_after> | """
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)
| """
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)
Add exception hook to help diagnose server test errors in python3 gui mode"""
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)
| <commit_before>"""
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)
<commit_msg>Add exception hook to help diagnose server test errors in python3 gui mode<commit_after>"""
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)
|
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 | # -*- 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)
Revert local CDN location set by Jodok | # -*- 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)
| <commit_before># -*- 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)
<commit_msg>Revert local CDN location set by Jodok<commit_after> | # -*- 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)
| # -*- 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)
Revert local CDN location set by Jodok# -*- 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)
| <commit_before># -*- 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)
<commit_msg>Revert local CDN location set by Jodok<commit_after># -*- 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)
|
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 | 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"]
)
Fix test for auth tokens store | 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())
| <commit_before>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"]
)
<commit_msg>Fix test for auth tokens store<commit_after> | 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())
| 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"]
)
Fix test for auth tokens storefrom 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())
| <commit_before>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"]
)
<commit_msg>Fix test for auth tokens store<commit_after>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())
|
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 | #!/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")
Improve test of csvstack --filenames. | #!/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")
| <commit_before>#!/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")
<commit_msg>Improve test of csvstack --filenames.<commit_after> | #!/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")
| #!/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")
Improve test of csvstack --filenames.#!/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")
| <commit_before>#!/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")
<commit_msg>Improve test of csvstack --filenames.<commit_after>#!/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")
|
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 | 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)
Add a test of the linearity of scalar multiplication | 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)
| <commit_before>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)
<commit_msg>Add a test of the linearity of scalar multiplication<commit_after> | 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)
| 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)
Add a test of the linearity of scalar multiplicationimport 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)
| <commit_before>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)
<commit_msg>Add a test of the linearity of scalar multiplication<commit_after>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)
|
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 | 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
Change test for running on Tingbot | 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
| <commit_before>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
<commit_msg>Change test for running on Tingbot<commit_after> | 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
| 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
Change test for running on Tingbotimport 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
| <commit_before>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
<commit_msg>Change test for running on Tingbot<commit_after>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
|
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 | 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:])
Clean up some unused imports and comments | 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:])
| <commit_before>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:])
<commit_msg>Clean up some unused imports and comments<commit_after> | 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:])
| 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:])
Clean up some unused imports and commentsfrom 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:])
| <commit_before>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:])
<commit_msg>Clean up some unused imports and comments<commit_after>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:])
|
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 | # 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 | # 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
| <commit_before># 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
<commit_msg>Indent with 4 spaces, not 3<commit_after> | # 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# 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
| <commit_before># 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
<commit_msg>Indent with 4 spaces, not 3<commit_after># 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
|
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 | 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 1Add in comments for orgs and places too, remove limit | 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 | <commit_before>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<commit_msg>Add in comments for orgs and places too, remove limit<commit_after> | 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 | 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 1Add in comments for orgs and places too, remove limitfrom 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 | <commit_before>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<commit_msg>Add in comments for orgs and places too, remove limit<commit_after>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 |
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 | 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'
Fix imports for Django >= 1.6 | 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'
| <commit_before>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'
<commit_msg>Fix imports for Django >= 1.6<commit_after> | 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'
| 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'
Fix imports for Django >= 1.6from 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'
| <commit_before>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'
<commit_msg>Fix imports for Django >= 1.6<commit_after>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'
|
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 | 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()
Add defaults to the ibm RNG | 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()
| <commit_before>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()
<commit_msg>Add defaults to the ibm RNG<commit_after> | 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()
| 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()
Add defaults to the ibm RNGdef 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()
| <commit_before>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()
<commit_msg>Add defaults to the ibm RNG<commit_after>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()
|
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 | 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'))
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. | 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'))
| <commit_before>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'))
<commit_msg>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.<commit_after> | 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'))
| 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'))
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.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'))
| <commit_before>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'))
<commit_msg>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.<commit_after>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'))
|
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 | 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)
Remove unused main and unused imports | import bottle
import config
from web import web
app = application = bottle.Bottle()
app.merge(web.app)
config.arguments['--verbose'] = True
| <commit_before>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)
<commit_msg>Remove unused main and unused imports<commit_after> | import bottle
import config
from web import web
app = application = bottle.Bottle()
app.merge(web.app)
config.arguments['--verbose'] = True
| 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)
Remove unused main and unused importsimport bottle
import config
from web import web
app = application = bottle.Bottle()
app.merge(web.app)
config.arguments['--verbose'] = True
| <commit_before>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)
<commit_msg>Remove unused main and unused imports<commit_after>import bottle
import config
from web import web
app = application = bottle.Bottle()
app.merge(web.app)
config.arguments['--verbose'] = 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 | 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'),
)
Update Ghana code to match current Pombola | 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')),
)
| <commit_before>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'),
)
<commit_msg>Update Ghana code to match current Pombola<commit_after> | 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')),
)
| 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'),
)
Update Ghana code to match current Pombolafrom 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')),
)
| <commit_before>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'),
)
<commit_msg>Update Ghana code to match current Pombola<commit_after>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')),
)
|
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 | 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',
)
Fix dumpdata ordering for VRFs | # 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',
)
| <commit_before>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',
)
<commit_msg>Fix dumpdata ordering for VRFs<commit_after> | # 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',
)
| 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',
)
Fix dumpdata ordering for VRFs# 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',
)
| <commit_before>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',
)
<commit_msg>Fix dumpdata ordering for VRFs<commit_after># 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',
)
|
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 | """
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
Remove unnecessary (and debatable) comment. | """
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
| <commit_before>"""
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
<commit_msg>Remove unnecessary (and debatable) comment.<commit_after> | """
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
| """
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
Remove unnecessary (and debatable) comment."""
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
| <commit_before>"""
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
<commit_msg>Remove unnecessary (and debatable) comment.<commit_after>"""
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
|
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 | # -*- 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,
}
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 | # -*- 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,
}
| <commit_before># -*- 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,
}
<commit_msg>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<commit_after> | # -*- 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,
}
| # -*- 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,
}
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# -*- 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,
}
| <commit_before># -*- 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,
}
<commit_msg>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<commit_after># -*- 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,
}
|
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 | 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
app: Use current_app.babel_instance instead of babel
That way we can use Babel.init_app() later | 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
| <commit_before>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
<commit_msg>app: Use current_app.babel_instance instead of babel
That way we can use Babel.init_app() later<commit_after> | 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
| 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
app: Use current_app.babel_instance instead of babel
That way we can use Babel.init_app() laterfrom 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
| <commit_before>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
<commit_msg>app: Use current_app.babel_instance instead of babel
That way we can use Babel.init_app() later<commit_after>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
|
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 | 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()
Allow start and end arguments to take inputs of multiple words such as 'New York' | 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()
| <commit_before>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()
<commit_msg>Allow start and end arguments to take inputs of multiple words such as 'New York'<commit_after> | 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()
| 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()
Allow start and end arguments to take inputs of multiple words such as 'New York'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()
| <commit_before>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()
<commit_msg>Allow start and end arguments to take inputs of multiple words such as 'New York'<commit_after>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()
|
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 | 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
TEST: Add weird SLP orientation to get_world_pedir | 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
| <commit_before>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
<commit_msg>TEST: Add weird SLP orientation to get_world_pedir<commit_after> | 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
| 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
TEST: Add weird SLP orientation to get_world_pedirimport 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
| <commit_before>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
<commit_msg>TEST: Add weird SLP orientation to get_world_pedir<commit_after>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
|
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 | __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
Add import for focused stuff | __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
| <commit_before>__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
<commit_msg>Add import for focused stuff<commit_after> | __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
| __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
Add import for focused stuff__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
| <commit_before>__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
<commit_msg>Add import for focused stuff<commit_after>__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
|
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 | assert_has_feature(
14, 2623, 6318, 'water',
{ 'kind': 'bay', 'label_placement': 'yes' })
Add tests for strait and fjord | # 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' })
| <commit_before>assert_has_feature(
14, 2623, 6318, 'water',
{ 'kind': 'bay', 'label_placement': 'yes' })
<commit_msg>Add tests for strait and fjord<commit_after> | # 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' })
| assert_has_feature(
14, 2623, 6318, 'water',
{ 'kind': 'bay', 'label_placement': 'yes' })
Add tests for strait and fjord# 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' })
| <commit_before>assert_has_feature(
14, 2623, 6318, 'water',
{ 'kind': 'bay', 'label_placement': 'yes' })
<commit_msg>Add tests for strait and fjord<commit_after># 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 | 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'],
)
Use argparse formatter RawDescriptionHelpFormatter, maybe temporarily | 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'],
)
| <commit_before>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'],
)
<commit_msg>Use argparse formatter RawDescriptionHelpFormatter, maybe temporarily<commit_after> | 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'],
)
| 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'],
)
Use argparse formatter RawDescriptionHelpFormatter, maybe temporarilyimport 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'],
)
| <commit_before>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'],
)
<commit_msg>Use argparse formatter RawDescriptionHelpFormatter, maybe temporarily<commit_after>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'],
)
|
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 | 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
Add documentation for Permutations class | 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
| <commit_before>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
<commit_msg>Add documentation for Permutations class<commit_after> | 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
| 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
Add documentation for Permutations classfrom .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
| <commit_before>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
<commit_msg>Add documentation for Permutations class<commit_after>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
|
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 | 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()
Choose a single corpus for a given series,date pair. | 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()
| <commit_before>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()
<commit_msg>Choose a single corpus for a given series,date pair.<commit_after> | 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()
| 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()
Choose a single corpus for a given series,date pair.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()
| <commit_before>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()
<commit_msg>Choose a single corpus for a given series,date pair.<commit_after>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()
|
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 | 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 | 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
| <commit_before>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
<commit_msg>Fix failing imports in Python 2<commit_after> | 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
| 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 2from __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
| <commit_before>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
<commit_msg>Fix failing imports in Python 2<commit_after>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
|
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 | 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
Fix new line stripping in admin site
Closes #87 | 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
| <commit_before>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
<commit_msg>Fix new line stripping in admin site
Closes #87<commit_after> | 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
| 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
Fix new line stripping in admin site
Closes #87import 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
| <commit_before>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
<commit_msg>Fix new line stripping in admin site
Closes #87<commit_after>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
|
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 | # -*- 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())
Fix import in test client. | # -*- 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())
| <commit_before># -*- 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())
<commit_msg>Fix import in test client.<commit_after> | # -*- 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())
| # -*- 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())
Fix import in test client.# -*- 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())
| <commit_before># -*- 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())
<commit_msg>Fix import in test client.<commit_after># -*- 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())
|
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 | # -*- 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')
Use SelfAttribute instead of explicit lambda | # -*- 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')
| <commit_before># -*- 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')
<commit_msg>Use SelfAttribute instead of explicit lambda<commit_after> | # -*- 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')
| # -*- 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')
Use SelfAttribute instead of explicit lambda# -*- 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')
| <commit_before># -*- 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')
<commit_msg>Use SelfAttribute instead of explicit lambda<commit_after># -*- 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')
|
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 | #!/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)
Add Bitbucket to skipif marker 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)
| <commit_before>#!/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)
<commit_msg>Add Bitbucket to skipif marker reason<commit_after> | #!/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)
| #!/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)
Add Bitbucket to skipif marker 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)
| <commit_before>#!/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)
<commit_msg>Add Bitbucket to skipif marker reason<commit_after>#!/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)
|
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 | 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 | 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
| <commit_before>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
<commit_msg>Remove extra comma to avoid flake8 test failure in CircleCI<commit_after> | 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 CircleCIfrom 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
| <commit_before>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
<commit_msg>Remove extra comma to avoid flake8 test failure in CircleCI<commit_after>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
|
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 | 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
Use bytes instead of str where appropriate for Python 3 | 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
| <commit_before>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
<commit_msg>Use bytes instead of str where appropriate for Python 3<commit_after> | 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
| 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
Use bytes instead of str where appropriate for Python 3class 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
| <commit_before>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
<commit_msg>Use bytes instead of str where appropriate for Python 3<commit_after>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
|
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 | 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()
Rename test specific to with gpg | 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()
| <commit_before>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()
<commit_msg>Rename test specific to with gpg<commit_after> | 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()
| 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()
Rename test specific to with gpgimport 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()
| <commit_before>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()
<commit_msg>Rename test specific to with gpg<commit_after>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()
|
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 | 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):
passTest the ability to add phone to the person | 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 | <commit_before>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<commit_msg>Test the ability to add phone to the person<commit_after> | 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 | 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):
passTest the ability to add phone to the personfrom 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 | <commit_before>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<commit_msg>Test the ability to add phone to the person<commit_after>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 |
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 | 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']
}
Allow sub- and superscript tags | 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']
}
| <commit_before>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']
}
<commit_msg>Allow sub- and superscript tags<commit_after> | 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']
}
| 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']
}
Allow sub- and superscript tagsfrom 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']
}
| <commit_before>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']
}
<commit_msg>Allow sub- and superscript tags<commit_after>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']
}
|
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 | 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()'}
Add error message for not implemented error | 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.")'''}
| <commit_before>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()'}
<commit_msg>Add error message for not implemented error<commit_after> | 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.")'''}
| 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()'}
Add error message for not implemented errorc = 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.")'''}
| <commit_before>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()'}
<commit_msg>Add error message for not implemented error<commit_after>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.")'''}
|
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 | 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
Make api-tokens view exempt from CSRF checks | 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
| <commit_before>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
<commit_msg>Make api-tokens view exempt from CSRF checks<commit_after> | 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
| 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
Make api-tokens view exempt from CSRF checksfrom 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
| <commit_before>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
<commit_msg>Make api-tokens view exempt from CSRF checks<commit_after>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
|
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 | 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()Add default images for podcasts if necessary | 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()
| <commit_before>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()<commit_msg>Add default images for podcasts if necessary<commit_after> | 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()
| 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()Add default images for podcasts if necessaryimport 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()
| <commit_before>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()<commit_msg>Add default images for podcasts if necessary<commit_after>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()
|
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 | 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'
Print traceback if startup fails | 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()
| <commit_before>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'
<commit_msg>Print traceback if startup fails<commit_after> | 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()
| 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'
Print traceback if startup failsfrom 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()
| <commit_before>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'
<commit_msg>Print traceback if startup fails<commit_after>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()
|
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 | # 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
Remove non-working network topology panel | # 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
| <commit_before># 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
<commit_msg>Remove non-working network topology panel<commit_after> | # 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
| # 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
Remove non-working network topology panel# 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
| <commit_before># 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
<commit_msg>Remove non-working network topology panel<commit_after># 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
|
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 | 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)
Add UserProfile Model To Django Admin Website | 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)
| <commit_before>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)
<commit_msg>Add UserProfile Model To Django Admin Website<commit_after> | 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)
| 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)
Add UserProfile Model To Django Admin Websitefrom django.contrib import admin
from models import UserProfile
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'sex')
search_fields = ('user',)
admin.site.register(UserProfile,UserProfileAdmin)
| <commit_before>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)
<commit_msg>Add UserProfile Model To Django Admin Website<commit_after>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)
|
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 | 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",
],
)
Update dependencies to actual version numbers | 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",
],
)
| <commit_before>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",
],
)
<commit_msg>Update dependencies to actual version numbers<commit_after> | 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",
],
)
| 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",
],
)
Update dependencies to actual version numbersfrom 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",
],
)
| <commit_before>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",
],
)
<commit_msg>Update dependencies to actual version numbers<commit_after>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",
],
)
|
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 | 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()
Add Vertex class and doc strings for 2 classes | 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()
| <commit_before>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()
<commit_msg>Add Vertex class and doc strings for 2 classes<commit_after> | 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()
| 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()
Add Vertex class and doc strings for 2 classesfrom __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()
| <commit_before>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()
<commit_msg>Add Vertex class and doc strings for 2 classes<commit_after>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()
|
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 | #
# 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!')
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 | #
# 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!')
| <commit_before>#
# 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!')
<commit_msg>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<commit_after> | #
# 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!')
| #
# 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!')
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#
# 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!')
| <commit_before>#
# 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!')
<commit_msg>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<commit_after>#
# 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!')
|
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 | # -*- 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'),
),
]
Fix the CustomForm migration script | # -*- 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'),
),
]
| <commit_before># -*- 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'),
),
]
<commit_msg>Fix the CustomForm migration script<commit_after> | # -*- 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'),
),
]
| # -*- 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'),
),
]
Fix the CustomForm migration script# -*- 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'),
),
]
| <commit_before># -*- 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'),
),
]
<commit_msg>Fix the CustomForm migration script<commit_after># -*- 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'),
),
]
|
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 | 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
Refactor the 'pull' subcommand to use DockerComposeExecutor
The pull subcommand was not working because it depended on an
unimplemented class DockerManagerFactory. | 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')
| <commit_before>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
<commit_msg>Refactor the 'pull' subcommand to use DockerComposeExecutor
The pull subcommand was not working because it depended on an
unimplemented class DockerManagerFactory.<commit_after> | 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')
| 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
Refactor the 'pull' subcommand to use DockerComposeExecutor
The pull subcommand was not working because it depended on an
unimplemented class DockerManagerFactory.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')
| <commit_before>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
<commit_msg>Refactor the 'pull' subcommand to use DockerComposeExecutor
The pull subcommand was not working because it depended on an
unimplemented class DockerManagerFactory.<commit_after>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')
|
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 | 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."
)
Fix test description: njk -> html | 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."
)
| <commit_before>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."
)
<commit_msg>Fix test description: njk -> html<commit_after> | 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."
)
| 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."
)
Fix test description: njk -> htmlimport 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."
)
| <commit_before>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."
)
<commit_msg>Fix test description: njk -> html<commit_after>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."
)
|
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 | # -*- 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,
}
[IMP] Rename Objects to Models in module description | # -*- 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,
}
| <commit_before># -*- 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,
}
<commit_msg>[IMP] Rename Objects to Models in module description<commit_after> | # -*- 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,
}
| # -*- 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,
}
[IMP] Rename Objects to Models in module description# -*- 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,
}
| <commit_before># -*- 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,
}
<commit_msg>[IMP] Rename Objects to Models in module description<commit_after># -*- 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,
}
|
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 | 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'))
Sort runs by text score
Search results for runs are sorted by text score. | 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'))
| <commit_before>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'))
<commit_msg>Sort runs by text score
Search results for runs are sorted by text score.<commit_after> | 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'))
| 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'))
Sort runs by text score
Search results for runs are sorted by text score.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'))
| <commit_before>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'))
<commit_msg>Sort runs by text score
Search results for runs are sorted by text score.<commit_after>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'))
|
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 | # -*- 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: **
Split create database and create user into to individual commands | # -*- 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: **
| <commit_before># -*- 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: **
<commit_msg>Split create database and create user into to individual commands<commit_after> | # -*- 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: **
| # -*- 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: **
Split create database and create user into to individual commands# -*- 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: **
| <commit_before># -*- 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: **
<commit_msg>Split create database and create user into to individual commands<commit_after># -*- 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: **
|
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 | 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()Work on unit test for regex_parser (preparing to refactor). | 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() | <commit_before>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()<commit_msg>Work on unit test for regex_parser (preparing to refactor).<commit_after> | 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() | 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()Work on unit test for regex_parser (preparing to refactor).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() | <commit_before>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()<commit_msg>Work on unit test for regex_parser (preparing to refactor).<commit_after>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() |
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 | # -*- 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))
Use simple TestCase in spam filter tests. | # -*- 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))
| <commit_before># -*- 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))
<commit_msg>Use simple TestCase in spam filter tests.<commit_after> | # -*- 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))
| # -*- 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))
Use simple TestCase in spam filter tests.# -*- 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))
| <commit_before># -*- 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))
<commit_msg>Use simple TestCase in spam filter tests.<commit_after># -*- 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))
|
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 | """ 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')
Update migration sequence after rebase | """ 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')
| <commit_before>""" 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')
<commit_msg>Update migration sequence after rebase<commit_after> | """ 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')
| """ 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')
Update migration sequence after rebase""" 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')
| <commit_before>""" 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')
<commit_msg>Update migration sequence after rebase<commit_after>""" 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')
|
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 | #! /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:])
Use shell in subprocess.call for Windows. | #! /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:])
| <commit_before>#! /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:])
<commit_msg>Use shell in subprocess.call for Windows.<commit_after> | #! /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:])
| #! /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:])
Use shell in subprocess.call for Windows.#! /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:])
| <commit_before>#! /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:])
<commit_msg>Use shell in subprocess.call for Windows.<commit_after>#! /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:])
|
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 | # 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
Use float so test passes on Python 2.6 | # 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
| <commit_before># 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
<commit_msg>Use float so test passes on Python 2.6<commit_after> | # 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
| # 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
Use float so test passes on Python 2.6# 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
| <commit_before># 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
<commit_msg>Use float so test passes on Python 2.6<commit_after># 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
|
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 | 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)
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> | 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)
| <commit_before>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)
<commit_msg>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><commit_after> | 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)
| 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)
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>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)
| <commit_before>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)
<commit_msg>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><commit_after>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)
|
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 | # 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
Fix support for flake8 v2 | # 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
| <commit_before># 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
<commit_msg>Fix support for flake8 v2<commit_after> | # 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
| # 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
Fix support for flake8 v2# 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
| <commit_before># 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
<commit_msg>Fix support for flake8 v2<commit_after># 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
|
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 | 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)
Customize degree widget so that if formats floats more elegantly | 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)
| <commit_before>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)
<commit_msg>Customize degree widget so that if formats floats more elegantly<commit_after> | 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)
| 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)
Customize degree widget so that if formats floats more elegantlyfrom 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)
| <commit_before>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)
<commit_msg>Customize degree widget so that if formats floats more elegantly<commit_after>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)
|
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 | """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()
Enable back git output redirection in _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()
| <commit_before>"""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()
<commit_msg>Enable back git output redirection in _get_version<commit_after> | """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()
| """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()
Enable back git output redirection in _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()
| <commit_before>"""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()
<commit_msg>Enable back git output redirection in _get_version<commit_after>"""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()
|
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 | #!/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)
ListCommand: Remove options, the command does not take options. | #!/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 []
| <commit_before>#!/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)
<commit_msg>ListCommand: Remove options, the command does not take options.<commit_after> | #!/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 []
| #!/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)
ListCommand: Remove options, the command does not take options.#!/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 []
| <commit_before>#!/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)
<commit_msg>ListCommand: Remove options, the command does not take options.<commit_after>#!/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 []
|
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 | #------------------------------------------------------------------------------
# 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',
]
Use absolute import to get the package version. | #------------------------------------------------------------------------------
# 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',
]
| <commit_before>#------------------------------------------------------------------------------
# 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',
]
<commit_msg>Use absolute import to get the package version.<commit_after> | #------------------------------------------------------------------------------
# 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',
]
| #------------------------------------------------------------------------------
# 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',
]
Use absolute import to get the package version.#------------------------------------------------------------------------------
# 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',
]
| <commit_before>#------------------------------------------------------------------------------
# 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',
]
<commit_msg>Use absolute import to get the package version.<commit_after>#------------------------------------------------------------------------------
# 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',
]
|
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 | #!/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)
Clean up imports in smolder tests | #!/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)
| <commit_before>#!/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)
<commit_msg>Clean up imports in smolder tests<commit_after> | #!/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)
| #!/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)
Clean up imports in smolder tests#!/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)
| <commit_before>#!/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)
<commit_msg>Clean up imports in smolder tests<commit_after>#!/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)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.