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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5834127e59b1da93bd814575cd7cbba391e253c8 | run_borealis.py | run_borealis.py | from borealis import BotBorealis
try:
print("Welcome to BOREALIS.")
print("Initializing BOREALIS and its subcomponents.")
bot = BotBorealis("config.yml")
print("Initialization completed. Readying subcomponents.")
bot.setup()
print("Subcomponents ready. All systems functional.")
print("Starting BOREALIS.")
bot.start_borealis()
except Exception as e:
print("Danger! Exception caught!")
print(e)
print("BOREALIS has been shut down.")
print("Check the log for further details.")
input("Press Enter to exit.")
| from borealis import BotBorealis
import time
while True:
bot = None
try:
print("Welcome to BOREALIS.")
print("Initializing BOREALIS and its subcomponents.")
bot = BotBorealis("config.yml")
print("Initialization completed. Readying subcomponents.")
bot.setup()
print("Subcomponents ready. All systems functional.")
print("Starting BOREALIS.")
bot.start_borealis()
except Exception as e:
print("Danger! Exception caught!")
print(e)
print("Deleting bot!")
# Delete the bot, run it again.
del bot
# Sleep for a bit before restarting!
time.sleep(60)
print("Restarting loop.\n\n\n")
# Should never get here, but just in case.
print("We somehow exited the main loop. :ree:")
input("Press Enter to exit.")
| Implement recovery Bot will now automatically restart after an exception is caught. | Implement recovery
Bot will now automatically restart after an exception is caught.
| Python | agpl-3.0 | Aurorastation/BOREALISbot2 | from borealis import BotBorealis
try:
print("Welcome to BOREALIS.")
print("Initializing BOREALIS and its subcomponents.")
bot = BotBorealis("config.yml")
print("Initialization completed. Readying subcomponents.")
bot.setup()
print("Subcomponents ready. All systems functional.")
print("Starting BOREALIS.")
bot.start_borealis()
except Exception as e:
print("Danger! Exception caught!")
print(e)
print("BOREALIS has been shut down.")
print("Check the log for further details.")
input("Press Enter to exit.")
Implement recovery
Bot will now automatically restart after an exception is caught. | from borealis import BotBorealis
import time
while True:
bot = None
try:
print("Welcome to BOREALIS.")
print("Initializing BOREALIS and its subcomponents.")
bot = BotBorealis("config.yml")
print("Initialization completed. Readying subcomponents.")
bot.setup()
print("Subcomponents ready. All systems functional.")
print("Starting BOREALIS.")
bot.start_borealis()
except Exception as e:
print("Danger! Exception caught!")
print(e)
print("Deleting bot!")
# Delete the bot, run it again.
del bot
# Sleep for a bit before restarting!
time.sleep(60)
print("Restarting loop.\n\n\n")
# Should never get here, but just in case.
print("We somehow exited the main loop. :ree:")
input("Press Enter to exit.")
| <commit_before>from borealis import BotBorealis
try:
print("Welcome to BOREALIS.")
print("Initializing BOREALIS and its subcomponents.")
bot = BotBorealis("config.yml")
print("Initialization completed. Readying subcomponents.")
bot.setup()
print("Subcomponents ready. All systems functional.")
print("Starting BOREALIS.")
bot.start_borealis()
except Exception as e:
print("Danger! Exception caught!")
print(e)
print("BOREALIS has been shut down.")
print("Check the log for further details.")
input("Press Enter to exit.")
<commit_msg>Implement recovery
Bot will now automatically restart after an exception is caught.<commit_after> | from borealis import BotBorealis
import time
while True:
bot = None
try:
print("Welcome to BOREALIS.")
print("Initializing BOREALIS and its subcomponents.")
bot = BotBorealis("config.yml")
print("Initialization completed. Readying subcomponents.")
bot.setup()
print("Subcomponents ready. All systems functional.")
print("Starting BOREALIS.")
bot.start_borealis()
except Exception as e:
print("Danger! Exception caught!")
print(e)
print("Deleting bot!")
# Delete the bot, run it again.
del bot
# Sleep for a bit before restarting!
time.sleep(60)
print("Restarting loop.\n\n\n")
# Should never get here, but just in case.
print("We somehow exited the main loop. :ree:")
input("Press Enter to exit.")
| from borealis import BotBorealis
try:
print("Welcome to BOREALIS.")
print("Initializing BOREALIS and its subcomponents.")
bot = BotBorealis("config.yml")
print("Initialization completed. Readying subcomponents.")
bot.setup()
print("Subcomponents ready. All systems functional.")
print("Starting BOREALIS.")
bot.start_borealis()
except Exception as e:
print("Danger! Exception caught!")
print(e)
print("BOREALIS has been shut down.")
print("Check the log for further details.")
input("Press Enter to exit.")
Implement recovery
Bot will now automatically restart after an exception is caught.from borealis import BotBorealis
import time
while True:
bot = None
try:
print("Welcome to BOREALIS.")
print("Initializing BOREALIS and its subcomponents.")
bot = BotBorealis("config.yml")
print("Initialization completed. Readying subcomponents.")
bot.setup()
print("Subcomponents ready. All systems functional.")
print("Starting BOREALIS.")
bot.start_borealis()
except Exception as e:
print("Danger! Exception caught!")
print(e)
print("Deleting bot!")
# Delete the bot, run it again.
del bot
# Sleep for a bit before restarting!
time.sleep(60)
print("Restarting loop.\n\n\n")
# Should never get here, but just in case.
print("We somehow exited the main loop. :ree:")
input("Press Enter to exit.")
| <commit_before>from borealis import BotBorealis
try:
print("Welcome to BOREALIS.")
print("Initializing BOREALIS and its subcomponents.")
bot = BotBorealis("config.yml")
print("Initialization completed. Readying subcomponents.")
bot.setup()
print("Subcomponents ready. All systems functional.")
print("Starting BOREALIS.")
bot.start_borealis()
except Exception as e:
print("Danger! Exception caught!")
print(e)
print("BOREALIS has been shut down.")
print("Check the log for further details.")
input("Press Enter to exit.")
<commit_msg>Implement recovery
Bot will now automatically restart after an exception is caught.<commit_after>from borealis import BotBorealis
import time
while True:
bot = None
try:
print("Welcome to BOREALIS.")
print("Initializing BOREALIS and its subcomponents.")
bot = BotBorealis("config.yml")
print("Initialization completed. Readying subcomponents.")
bot.setup()
print("Subcomponents ready. All systems functional.")
print("Starting BOREALIS.")
bot.start_borealis()
except Exception as e:
print("Danger! Exception caught!")
print(e)
print("Deleting bot!")
# Delete the bot, run it again.
del bot
# Sleep for a bit before restarting!
time.sleep(60)
print("Restarting loop.\n\n\n")
# Should never get here, but just in case.
print("We somehow exited the main loop. :ree:")
input("Press Enter to exit.")
|
fb54f741783ddefd0f452216b96808dea52c055e | sai/__init__.py | sai/__init__.py | import os
import logging
from flask import Flask, abort, g
from config import config
from api_v1 import bp as api_v1_bp
from ui import bp as ui_bp
app = Flask(__name__)
app.config.from_object(config)
app.register_blueprint(api_v1_bp, url_prefix='/api/v1')
app.register_blueprint(ui_bp, url_path='/')
@app.before_request
def globalize():
g.mongo, g.db = mongo, db
@app.before_first_request
def set_root_path():
root_path = app.config.get('root_path')
if not root_path:
root_path = os.path.dirname(app.root_path)
app.config['root_path'] = root_path
playbooks_path = app.config.get('playbooks_path')
if not playbooks_path:
playbooks_path = os.path.join(root_path, 'playbooks')
app.config['playbooks_path'] = playbooks_path
@app.before_first_request
def logger():
if not app.debug:
app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)
@app.errorhandler(500)
def internal_server_error(e):
app.logger.exception(e)
return abort(500)
| import os
import logging
from flask import Flask, abort, g
from config import config
from api_v1 import bp as api_v1_bp
from ui import bp as ui_bp
app = Flask(__name__)
app.config.from_object(config)
app.register_blueprint(api_v1_bp, url_prefix='/api/v1')
app.register_blueprint(ui_bp, url_path='/')
@app.before_first_request
def set_root_path():
root_path = app.config.get('root_path')
if not root_path:
root_path = os.path.dirname(app.root_path)
app.config['root_path'] = root_path
playbooks_path = app.config.get('playbooks_path')
if not playbooks_path:
playbooks_path = os.path.join(root_path, 'playbooks')
app.config['playbooks_path'] = playbooks_path
@app.before_first_request
def logger():
if not app.debug:
app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)
@app.errorhandler(500)
def internal_server_error(e):
app.logger.exception(e)
return abort(500)
| Remove remaining reference to mongo | Remove remaining reference to mongo
| Python | apache-2.0 | sivel/sai | import os
import logging
from flask import Flask, abort, g
from config import config
from api_v1 import bp as api_v1_bp
from ui import bp as ui_bp
app = Flask(__name__)
app.config.from_object(config)
app.register_blueprint(api_v1_bp, url_prefix='/api/v1')
app.register_blueprint(ui_bp, url_path='/')
@app.before_request
def globalize():
g.mongo, g.db = mongo, db
@app.before_first_request
def set_root_path():
root_path = app.config.get('root_path')
if not root_path:
root_path = os.path.dirname(app.root_path)
app.config['root_path'] = root_path
playbooks_path = app.config.get('playbooks_path')
if not playbooks_path:
playbooks_path = os.path.join(root_path, 'playbooks')
app.config['playbooks_path'] = playbooks_path
@app.before_first_request
def logger():
if not app.debug:
app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)
@app.errorhandler(500)
def internal_server_error(e):
app.logger.exception(e)
return abort(500)
Remove remaining reference to mongo | import os
import logging
from flask import Flask, abort, g
from config import config
from api_v1 import bp as api_v1_bp
from ui import bp as ui_bp
app = Flask(__name__)
app.config.from_object(config)
app.register_blueprint(api_v1_bp, url_prefix='/api/v1')
app.register_blueprint(ui_bp, url_path='/')
@app.before_first_request
def set_root_path():
root_path = app.config.get('root_path')
if not root_path:
root_path = os.path.dirname(app.root_path)
app.config['root_path'] = root_path
playbooks_path = app.config.get('playbooks_path')
if not playbooks_path:
playbooks_path = os.path.join(root_path, 'playbooks')
app.config['playbooks_path'] = playbooks_path
@app.before_first_request
def logger():
if not app.debug:
app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)
@app.errorhandler(500)
def internal_server_error(e):
app.logger.exception(e)
return abort(500)
| <commit_before>import os
import logging
from flask import Flask, abort, g
from config import config
from api_v1 import bp as api_v1_bp
from ui import bp as ui_bp
app = Flask(__name__)
app.config.from_object(config)
app.register_blueprint(api_v1_bp, url_prefix='/api/v1')
app.register_blueprint(ui_bp, url_path='/')
@app.before_request
def globalize():
g.mongo, g.db = mongo, db
@app.before_first_request
def set_root_path():
root_path = app.config.get('root_path')
if not root_path:
root_path = os.path.dirname(app.root_path)
app.config['root_path'] = root_path
playbooks_path = app.config.get('playbooks_path')
if not playbooks_path:
playbooks_path = os.path.join(root_path, 'playbooks')
app.config['playbooks_path'] = playbooks_path
@app.before_first_request
def logger():
if not app.debug:
app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)
@app.errorhandler(500)
def internal_server_error(e):
app.logger.exception(e)
return abort(500)
<commit_msg>Remove remaining reference to mongo<commit_after> | import os
import logging
from flask import Flask, abort, g
from config import config
from api_v1 import bp as api_v1_bp
from ui import bp as ui_bp
app = Flask(__name__)
app.config.from_object(config)
app.register_blueprint(api_v1_bp, url_prefix='/api/v1')
app.register_blueprint(ui_bp, url_path='/')
@app.before_first_request
def set_root_path():
root_path = app.config.get('root_path')
if not root_path:
root_path = os.path.dirname(app.root_path)
app.config['root_path'] = root_path
playbooks_path = app.config.get('playbooks_path')
if not playbooks_path:
playbooks_path = os.path.join(root_path, 'playbooks')
app.config['playbooks_path'] = playbooks_path
@app.before_first_request
def logger():
if not app.debug:
app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)
@app.errorhandler(500)
def internal_server_error(e):
app.logger.exception(e)
return abort(500)
| import os
import logging
from flask import Flask, abort, g
from config import config
from api_v1 import bp as api_v1_bp
from ui import bp as ui_bp
app = Flask(__name__)
app.config.from_object(config)
app.register_blueprint(api_v1_bp, url_prefix='/api/v1')
app.register_blueprint(ui_bp, url_path='/')
@app.before_request
def globalize():
g.mongo, g.db = mongo, db
@app.before_first_request
def set_root_path():
root_path = app.config.get('root_path')
if not root_path:
root_path = os.path.dirname(app.root_path)
app.config['root_path'] = root_path
playbooks_path = app.config.get('playbooks_path')
if not playbooks_path:
playbooks_path = os.path.join(root_path, 'playbooks')
app.config['playbooks_path'] = playbooks_path
@app.before_first_request
def logger():
if not app.debug:
app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)
@app.errorhandler(500)
def internal_server_error(e):
app.logger.exception(e)
return abort(500)
Remove remaining reference to mongoimport os
import logging
from flask import Flask, abort, g
from config import config
from api_v1 import bp as api_v1_bp
from ui import bp as ui_bp
app = Flask(__name__)
app.config.from_object(config)
app.register_blueprint(api_v1_bp, url_prefix='/api/v1')
app.register_blueprint(ui_bp, url_path='/')
@app.before_first_request
def set_root_path():
root_path = app.config.get('root_path')
if not root_path:
root_path = os.path.dirname(app.root_path)
app.config['root_path'] = root_path
playbooks_path = app.config.get('playbooks_path')
if not playbooks_path:
playbooks_path = os.path.join(root_path, 'playbooks')
app.config['playbooks_path'] = playbooks_path
@app.before_first_request
def logger():
if not app.debug:
app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)
@app.errorhandler(500)
def internal_server_error(e):
app.logger.exception(e)
return abort(500)
| <commit_before>import os
import logging
from flask import Flask, abort, g
from config import config
from api_v1 import bp as api_v1_bp
from ui import bp as ui_bp
app = Flask(__name__)
app.config.from_object(config)
app.register_blueprint(api_v1_bp, url_prefix='/api/v1')
app.register_blueprint(ui_bp, url_path='/')
@app.before_request
def globalize():
g.mongo, g.db = mongo, db
@app.before_first_request
def set_root_path():
root_path = app.config.get('root_path')
if not root_path:
root_path = os.path.dirname(app.root_path)
app.config['root_path'] = root_path
playbooks_path = app.config.get('playbooks_path')
if not playbooks_path:
playbooks_path = os.path.join(root_path, 'playbooks')
app.config['playbooks_path'] = playbooks_path
@app.before_first_request
def logger():
if not app.debug:
app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)
@app.errorhandler(500)
def internal_server_error(e):
app.logger.exception(e)
return abort(500)
<commit_msg>Remove remaining reference to mongo<commit_after>import os
import logging
from flask import Flask, abort, g
from config import config
from api_v1 import bp as api_v1_bp
from ui import bp as ui_bp
app = Flask(__name__)
app.config.from_object(config)
app.register_blueprint(api_v1_bp, url_prefix='/api/v1')
app.register_blueprint(ui_bp, url_path='/')
@app.before_first_request
def set_root_path():
root_path = app.config.get('root_path')
if not root_path:
root_path = os.path.dirname(app.root_path)
app.config['root_path'] = root_path
playbooks_path = app.config.get('playbooks_path')
if not playbooks_path:
playbooks_path = os.path.join(root_path, 'playbooks')
app.config['playbooks_path'] = playbooks_path
@app.before_first_request
def logger():
if not app.debug:
app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)
@app.errorhandler(500)
def internal_server_error(e):
app.logger.exception(e)
return abort(500)
|
64d109e975eb42bc06bb6b5e1deb26536e6f1def | tests/test_KociembaSolver.py | tests/test_KociembaSolver.py | from src.Move import Move
from src.NaiveCube import NaiveCube
from src.Cubie imort Cube
from src.Solver import Kociemba
import timeout_decorator
import unittest
class TestKociembaSolver(unittest.TestCase):
@timeout_decorator.timeout(300)
def _test_solution(self, c):
solver = Kociemba.KociembaSolver(c)
return solver.solution()
def test_solution(self):
for i in range(100):
c = Cube()
cr = Cube()
c.shuffle(i)
solution = self._test_solution(c)
for s in solution:
c.move(s)
# Align faces
while cr.cubies['F'].facings['F'] != c.cubies['F'].facings['F']:
c.move(Move('Y'))
for cubie in cr.cubies:
for facing in cr.cubies[cubie].facings:
self.assertEqual(cr.cubies[cubie].facings[facing], c.cubies[cubie].facings[facing])
def test_timeout(self):
c = Cube()
nc = NaiveCube()
nc.set_cube("orgyyybbbwgobbbyrywowwrwrwyrorogboogwygyorrwobrggwgbgy")
c.from_naive_cube(nc)
with self.assertRaises(Kociemba.Search.TimeoutError):
solver = Kociemba.KociembaSolver(c)
solver.solution(timeOut = 1) | from src.Move import Move
from src.NaiveCube import NaiveCube
from src.Cubie imort Cube
from src.Solver import Kociemba
import timeout_decorator
import unittest
class TestKociembaSolver(unittest.TestCase):
@timeout_decorator.timeout(300)
def _test_solution(self, c):
solver = Kociemba.KociembaSolver(c)
return solver.solution()
def test_solution(self):
for i in range(20):
c = Cube()
cr = Cube()
c.shuffle(i)
solution = self._test_solution(c)
for s in solution:
c.move(s)
# Align faces
while cr.cubies['F'].facings['F'] != c.cubies['F'].facings['F']:
c.move(Move('Y'))
for cubie in cr.cubies:
for facing in cr.cubies[cubie].facings:
self.assertEqual(cr.cubies[cubie].facings[facing], c.cubies[cubie].facings[facing])
def test_timeout(self):
c = Cube()
nc = NaiveCube()
nc.set_cube("orgyyybbbwgobbbyrywowwrwrwyrorogboogwygyorrwobrggwgbgy")
c.from_naive_cube(nc)
with self.assertRaises(Kociemba.Search.TimeoutError):
solver = Kociemba.KociembaSolver(c)
solver.solution(timeOut = 1)
| Reduce the number of test for Kociemba Solver | Reduce the number of test for Kociemba Solver
| Python | mit | Wiston999/python-rubik | from src.Move import Move
from src.NaiveCube import NaiveCube
from src.Cubie imort Cube
from src.Solver import Kociemba
import timeout_decorator
import unittest
class TestKociembaSolver(unittest.TestCase):
@timeout_decorator.timeout(300)
def _test_solution(self, c):
solver = Kociemba.KociembaSolver(c)
return solver.solution()
def test_solution(self):
for i in range(100):
c = Cube()
cr = Cube()
c.shuffle(i)
solution = self._test_solution(c)
for s in solution:
c.move(s)
# Align faces
while cr.cubies['F'].facings['F'] != c.cubies['F'].facings['F']:
c.move(Move('Y'))
for cubie in cr.cubies:
for facing in cr.cubies[cubie].facings:
self.assertEqual(cr.cubies[cubie].facings[facing], c.cubies[cubie].facings[facing])
def test_timeout(self):
c = Cube()
nc = NaiveCube()
nc.set_cube("orgyyybbbwgobbbyrywowwrwrwyrorogboogwygyorrwobrggwgbgy")
c.from_naive_cube(nc)
with self.assertRaises(Kociemba.Search.TimeoutError):
solver = Kociemba.KociembaSolver(c)
solver.solution(timeOut = 1)Reduce the number of test for Kociemba Solver | from src.Move import Move
from src.NaiveCube import NaiveCube
from src.Cubie imort Cube
from src.Solver import Kociemba
import timeout_decorator
import unittest
class TestKociembaSolver(unittest.TestCase):
@timeout_decorator.timeout(300)
def _test_solution(self, c):
solver = Kociemba.KociembaSolver(c)
return solver.solution()
def test_solution(self):
for i in range(20):
c = Cube()
cr = Cube()
c.shuffle(i)
solution = self._test_solution(c)
for s in solution:
c.move(s)
# Align faces
while cr.cubies['F'].facings['F'] != c.cubies['F'].facings['F']:
c.move(Move('Y'))
for cubie in cr.cubies:
for facing in cr.cubies[cubie].facings:
self.assertEqual(cr.cubies[cubie].facings[facing], c.cubies[cubie].facings[facing])
def test_timeout(self):
c = Cube()
nc = NaiveCube()
nc.set_cube("orgyyybbbwgobbbyrywowwrwrwyrorogboogwygyorrwobrggwgbgy")
c.from_naive_cube(nc)
with self.assertRaises(Kociemba.Search.TimeoutError):
solver = Kociemba.KociembaSolver(c)
solver.solution(timeOut = 1)
| <commit_before>from src.Move import Move
from src.NaiveCube import NaiveCube
from src.Cubie imort Cube
from src.Solver import Kociemba
import timeout_decorator
import unittest
class TestKociembaSolver(unittest.TestCase):
@timeout_decorator.timeout(300)
def _test_solution(self, c):
solver = Kociemba.KociembaSolver(c)
return solver.solution()
def test_solution(self):
for i in range(100):
c = Cube()
cr = Cube()
c.shuffle(i)
solution = self._test_solution(c)
for s in solution:
c.move(s)
# Align faces
while cr.cubies['F'].facings['F'] != c.cubies['F'].facings['F']:
c.move(Move('Y'))
for cubie in cr.cubies:
for facing in cr.cubies[cubie].facings:
self.assertEqual(cr.cubies[cubie].facings[facing], c.cubies[cubie].facings[facing])
def test_timeout(self):
c = Cube()
nc = NaiveCube()
nc.set_cube("orgyyybbbwgobbbyrywowwrwrwyrorogboogwygyorrwobrggwgbgy")
c.from_naive_cube(nc)
with self.assertRaises(Kociemba.Search.TimeoutError):
solver = Kociemba.KociembaSolver(c)
solver.solution(timeOut = 1)<commit_msg>Reduce the number of test for Kociemba Solver<commit_after> | from src.Move import Move
from src.NaiveCube import NaiveCube
from src.Cubie imort Cube
from src.Solver import Kociemba
import timeout_decorator
import unittest
class TestKociembaSolver(unittest.TestCase):
@timeout_decorator.timeout(300)
def _test_solution(self, c):
solver = Kociemba.KociembaSolver(c)
return solver.solution()
def test_solution(self):
for i in range(20):
c = Cube()
cr = Cube()
c.shuffle(i)
solution = self._test_solution(c)
for s in solution:
c.move(s)
# Align faces
while cr.cubies['F'].facings['F'] != c.cubies['F'].facings['F']:
c.move(Move('Y'))
for cubie in cr.cubies:
for facing in cr.cubies[cubie].facings:
self.assertEqual(cr.cubies[cubie].facings[facing], c.cubies[cubie].facings[facing])
def test_timeout(self):
c = Cube()
nc = NaiveCube()
nc.set_cube("orgyyybbbwgobbbyrywowwrwrwyrorogboogwygyorrwobrggwgbgy")
c.from_naive_cube(nc)
with self.assertRaises(Kociemba.Search.TimeoutError):
solver = Kociemba.KociembaSolver(c)
solver.solution(timeOut = 1)
| from src.Move import Move
from src.NaiveCube import NaiveCube
from src.Cubie imort Cube
from src.Solver import Kociemba
import timeout_decorator
import unittest
class TestKociembaSolver(unittest.TestCase):
@timeout_decorator.timeout(300)
def _test_solution(self, c):
solver = Kociemba.KociembaSolver(c)
return solver.solution()
def test_solution(self):
for i in range(100):
c = Cube()
cr = Cube()
c.shuffle(i)
solution = self._test_solution(c)
for s in solution:
c.move(s)
# Align faces
while cr.cubies['F'].facings['F'] != c.cubies['F'].facings['F']:
c.move(Move('Y'))
for cubie in cr.cubies:
for facing in cr.cubies[cubie].facings:
self.assertEqual(cr.cubies[cubie].facings[facing], c.cubies[cubie].facings[facing])
def test_timeout(self):
c = Cube()
nc = NaiveCube()
nc.set_cube("orgyyybbbwgobbbyrywowwrwrwyrorogboogwygyorrwobrggwgbgy")
c.from_naive_cube(nc)
with self.assertRaises(Kociemba.Search.TimeoutError):
solver = Kociemba.KociembaSolver(c)
solver.solution(timeOut = 1)Reduce the number of test for Kociemba Solverfrom src.Move import Move
from src.NaiveCube import NaiveCube
from src.Cubie imort Cube
from src.Solver import Kociemba
import timeout_decorator
import unittest
class TestKociembaSolver(unittest.TestCase):
@timeout_decorator.timeout(300)
def _test_solution(self, c):
solver = Kociemba.KociembaSolver(c)
return solver.solution()
def test_solution(self):
for i in range(20):
c = Cube()
cr = Cube()
c.shuffle(i)
solution = self._test_solution(c)
for s in solution:
c.move(s)
# Align faces
while cr.cubies['F'].facings['F'] != c.cubies['F'].facings['F']:
c.move(Move('Y'))
for cubie in cr.cubies:
for facing in cr.cubies[cubie].facings:
self.assertEqual(cr.cubies[cubie].facings[facing], c.cubies[cubie].facings[facing])
def test_timeout(self):
c = Cube()
nc = NaiveCube()
nc.set_cube("orgyyybbbwgobbbyrywowwrwrwyrorogboogwygyorrwobrggwgbgy")
c.from_naive_cube(nc)
with self.assertRaises(Kociemba.Search.TimeoutError):
solver = Kociemba.KociembaSolver(c)
solver.solution(timeOut = 1)
| <commit_before>from src.Move import Move
from src.NaiveCube import NaiveCube
from src.Cubie imort Cube
from src.Solver import Kociemba
import timeout_decorator
import unittest
class TestKociembaSolver(unittest.TestCase):
@timeout_decorator.timeout(300)
def _test_solution(self, c):
solver = Kociemba.KociembaSolver(c)
return solver.solution()
def test_solution(self):
for i in range(100):
c = Cube()
cr = Cube()
c.shuffle(i)
solution = self._test_solution(c)
for s in solution:
c.move(s)
# Align faces
while cr.cubies['F'].facings['F'] != c.cubies['F'].facings['F']:
c.move(Move('Y'))
for cubie in cr.cubies:
for facing in cr.cubies[cubie].facings:
self.assertEqual(cr.cubies[cubie].facings[facing], c.cubies[cubie].facings[facing])
def test_timeout(self):
c = Cube()
nc = NaiveCube()
nc.set_cube("orgyyybbbwgobbbyrywowwrwrwyrorogboogwygyorrwobrggwgbgy")
c.from_naive_cube(nc)
with self.assertRaises(Kociemba.Search.TimeoutError):
solver = Kociemba.KociembaSolver(c)
solver.solution(timeOut = 1)<commit_msg>Reduce the number of test for Kociemba Solver<commit_after>from src.Move import Move
from src.NaiveCube import NaiveCube
from src.Cubie imort Cube
from src.Solver import Kociemba
import timeout_decorator
import unittest
class TestKociembaSolver(unittest.TestCase):
@timeout_decorator.timeout(300)
def _test_solution(self, c):
solver = Kociemba.KociembaSolver(c)
return solver.solution()
def test_solution(self):
for i in range(20):
c = Cube()
cr = Cube()
c.shuffle(i)
solution = self._test_solution(c)
for s in solution:
c.move(s)
# Align faces
while cr.cubies['F'].facings['F'] != c.cubies['F'].facings['F']:
c.move(Move('Y'))
for cubie in cr.cubies:
for facing in cr.cubies[cubie].facings:
self.assertEqual(cr.cubies[cubie].facings[facing], c.cubies[cubie].facings[facing])
def test_timeout(self):
c = Cube()
nc = NaiveCube()
nc.set_cube("orgyyybbbwgobbbyrywowwrwrwyrorogboogwygyorrwobrggwgbgy")
c.from_naive_cube(nc)
with self.assertRaises(Kociemba.Search.TimeoutError):
solver = Kociemba.KociembaSolver(c)
solver.solution(timeOut = 1)
|
50f3233a8560120cc0c55b02849f1b586cf1aa27 | languages_plus/utils.py | languages_plus/utils.py | from django.core.exceptions import ObjectDoesNotExist
from countries_plus.models import Country
from .models import Language, CultureCode
def associate_countries_and_languages():
for country in Country.objects.all():
langs = country.languages.strip(',')
if langs:
codes = langs.split(",")
for code in codes:
if '-' in code:
lang_code, country_code = code.split('-')
try:
language = Language.objects.get(iso_639_1=lang_code)
except ObjectDoesNotExist:
print("Cannot find language identified by code %s" % lang_code)
continue
try:
country = Country.objects.get(iso=country_code)
except ObjectDoesNotExist:
print("Cannot find country identified by code %s" % country_code)
continue
country.language_set.add(language)
CultureCode.objects.get_or_create(code=code, language=language, country=country)
else:
try:
language = Language.objects.get_by_code(code)
country.language_set.add(language)
except ObjectDoesNotExist:
print("Cannot find language identified by code %s" % code)
continue
else:
print ("No langauges found for country %s" % country)
| from django.core.exceptions import ObjectDoesNotExist
from countries_plus.models import Country
from .models import Language, CultureCode
def associate_countries_and_languages():
for country in Country.objects.all():
langs = ''
try:
langs = country.languages.strip(',')
if langs:
codes = langs.split(",")
for code in codes:
if '-' in code:
lang_code, country_code = code.split('-')
try:
language = Language.objects.get(iso_639_1=lang_code)
except ObjectDoesNotExist:
print("Cannot find language identified by code %s" % lang_code)
continue
try:
country = Country.objects.get(iso=country_code)
except ObjectDoesNotExist:
print("Cannot find country identified by code %s" % country_code)
continue
country.language_set.add(language)
CultureCode.objects.get_or_create(code=code, language=language, country=country)
else:
try:
language = Language.objects.get_by_code(code)
country.language_set.add(language)
except ObjectDoesNotExist:
print("Cannot find language identified by code %s" % code)
continue
else:
print ("No langauges found for country %s" % country)
| Fix a crash if a country has no languages spoken | Fix a crash if a country has no languages spoken
| Python | mit | cordery/django-languages-plus | from django.core.exceptions import ObjectDoesNotExist
from countries_plus.models import Country
from .models import Language, CultureCode
def associate_countries_and_languages():
for country in Country.objects.all():
langs = country.languages.strip(',')
if langs:
codes = langs.split(",")
for code in codes:
if '-' in code:
lang_code, country_code = code.split('-')
try:
language = Language.objects.get(iso_639_1=lang_code)
except ObjectDoesNotExist:
print("Cannot find language identified by code %s" % lang_code)
continue
try:
country = Country.objects.get(iso=country_code)
except ObjectDoesNotExist:
print("Cannot find country identified by code %s" % country_code)
continue
country.language_set.add(language)
CultureCode.objects.get_or_create(code=code, language=language, country=country)
else:
try:
language = Language.objects.get_by_code(code)
country.language_set.add(language)
except ObjectDoesNotExist:
print("Cannot find language identified by code %s" % code)
continue
else:
print ("No langauges found for country %s" % country)
Fix a crash if a country has no languages spoken | from django.core.exceptions import ObjectDoesNotExist
from countries_plus.models import Country
from .models import Language, CultureCode
def associate_countries_and_languages():
for country in Country.objects.all():
langs = ''
try:
langs = country.languages.strip(',')
if langs:
codes = langs.split(",")
for code in codes:
if '-' in code:
lang_code, country_code = code.split('-')
try:
language = Language.objects.get(iso_639_1=lang_code)
except ObjectDoesNotExist:
print("Cannot find language identified by code %s" % lang_code)
continue
try:
country = Country.objects.get(iso=country_code)
except ObjectDoesNotExist:
print("Cannot find country identified by code %s" % country_code)
continue
country.language_set.add(language)
CultureCode.objects.get_or_create(code=code, language=language, country=country)
else:
try:
language = Language.objects.get_by_code(code)
country.language_set.add(language)
except ObjectDoesNotExist:
print("Cannot find language identified by code %s" % code)
continue
else:
print ("No langauges found for country %s" % country)
| <commit_before>from django.core.exceptions import ObjectDoesNotExist
from countries_plus.models import Country
from .models import Language, CultureCode
def associate_countries_and_languages():
for country in Country.objects.all():
langs = country.languages.strip(',')
if langs:
codes = langs.split(",")
for code in codes:
if '-' in code:
lang_code, country_code = code.split('-')
try:
language = Language.objects.get(iso_639_1=lang_code)
except ObjectDoesNotExist:
print("Cannot find language identified by code %s" % lang_code)
continue
try:
country = Country.objects.get(iso=country_code)
except ObjectDoesNotExist:
print("Cannot find country identified by code %s" % country_code)
continue
country.language_set.add(language)
CultureCode.objects.get_or_create(code=code, language=language, country=country)
else:
try:
language = Language.objects.get_by_code(code)
country.language_set.add(language)
except ObjectDoesNotExist:
print("Cannot find language identified by code %s" % code)
continue
else:
print ("No langauges found for country %s" % country)
<commit_msg>Fix a crash if a country has no languages spoken<commit_after> | from django.core.exceptions import ObjectDoesNotExist
from countries_plus.models import Country
from .models import Language, CultureCode
def associate_countries_and_languages():
for country in Country.objects.all():
langs = ''
try:
langs = country.languages.strip(',')
if langs:
codes = langs.split(",")
for code in codes:
if '-' in code:
lang_code, country_code = code.split('-')
try:
language = Language.objects.get(iso_639_1=lang_code)
except ObjectDoesNotExist:
print("Cannot find language identified by code %s" % lang_code)
continue
try:
country = Country.objects.get(iso=country_code)
except ObjectDoesNotExist:
print("Cannot find country identified by code %s" % country_code)
continue
country.language_set.add(language)
CultureCode.objects.get_or_create(code=code, language=language, country=country)
else:
try:
language = Language.objects.get_by_code(code)
country.language_set.add(language)
except ObjectDoesNotExist:
print("Cannot find language identified by code %s" % code)
continue
else:
print ("No langauges found for country %s" % country)
| from django.core.exceptions import ObjectDoesNotExist
from countries_plus.models import Country
from .models import Language, CultureCode
def associate_countries_and_languages():
for country in Country.objects.all():
langs = country.languages.strip(',')
if langs:
codes = langs.split(",")
for code in codes:
if '-' in code:
lang_code, country_code = code.split('-')
try:
language = Language.objects.get(iso_639_1=lang_code)
except ObjectDoesNotExist:
print("Cannot find language identified by code %s" % lang_code)
continue
try:
country = Country.objects.get(iso=country_code)
except ObjectDoesNotExist:
print("Cannot find country identified by code %s" % country_code)
continue
country.language_set.add(language)
CultureCode.objects.get_or_create(code=code, language=language, country=country)
else:
try:
language = Language.objects.get_by_code(code)
country.language_set.add(language)
except ObjectDoesNotExist:
print("Cannot find language identified by code %s" % code)
continue
else:
print ("No langauges found for country %s" % country)
Fix a crash if a country has no languages spokenfrom django.core.exceptions import ObjectDoesNotExist
from countries_plus.models import Country
from .models import Language, CultureCode
def associate_countries_and_languages():
for country in Country.objects.all():
langs = ''
try:
langs = country.languages.strip(',')
if langs:
codes = langs.split(",")
for code in codes:
if '-' in code:
lang_code, country_code = code.split('-')
try:
language = Language.objects.get(iso_639_1=lang_code)
except ObjectDoesNotExist:
print("Cannot find language identified by code %s" % lang_code)
continue
try:
country = Country.objects.get(iso=country_code)
except ObjectDoesNotExist:
print("Cannot find country identified by code %s" % country_code)
continue
country.language_set.add(language)
CultureCode.objects.get_or_create(code=code, language=language, country=country)
else:
try:
language = Language.objects.get_by_code(code)
country.language_set.add(language)
except ObjectDoesNotExist:
print("Cannot find language identified by code %s" % code)
continue
else:
print ("No langauges found for country %s" % country)
| <commit_before>from django.core.exceptions import ObjectDoesNotExist
from countries_plus.models import Country
from .models import Language, CultureCode
def associate_countries_and_languages():
for country in Country.objects.all():
langs = country.languages.strip(',')
if langs:
codes = langs.split(",")
for code in codes:
if '-' in code:
lang_code, country_code = code.split('-')
try:
language = Language.objects.get(iso_639_1=lang_code)
except ObjectDoesNotExist:
print("Cannot find language identified by code %s" % lang_code)
continue
try:
country = Country.objects.get(iso=country_code)
except ObjectDoesNotExist:
print("Cannot find country identified by code %s" % country_code)
continue
country.language_set.add(language)
CultureCode.objects.get_or_create(code=code, language=language, country=country)
else:
try:
language = Language.objects.get_by_code(code)
country.language_set.add(language)
except ObjectDoesNotExist:
print("Cannot find language identified by code %s" % code)
continue
else:
print ("No langauges found for country %s" % country)
<commit_msg>Fix a crash if a country has no languages spoken<commit_after>from django.core.exceptions import ObjectDoesNotExist
from countries_plus.models import Country
from .models import Language, CultureCode
def associate_countries_and_languages():
for country in Country.objects.all():
langs = ''
try:
langs = country.languages.strip(',')
if langs:
codes = langs.split(",")
for code in codes:
if '-' in code:
lang_code, country_code = code.split('-')
try:
language = Language.objects.get(iso_639_1=lang_code)
except ObjectDoesNotExist:
print("Cannot find language identified by code %s" % lang_code)
continue
try:
country = Country.objects.get(iso=country_code)
except ObjectDoesNotExist:
print("Cannot find country identified by code %s" % country_code)
continue
country.language_set.add(language)
CultureCode.objects.get_or_create(code=code, language=language, country=country)
else:
try:
language = Language.objects.get_by_code(code)
country.language_set.add(language)
except ObjectDoesNotExist:
print("Cannot find language identified by code %s" % code)
continue
else:
print ("No langauges found for country %s" % country)
|
780a330e1f185d7c19953edb5bc1767582501197 | tests/test_card.py | tests/test_card.py | """
Created on Dec 04, 2016
@author: john papa
Copyright 2016 John Papa. All rights reserved.
This work is licensed under the MIT License.
"""
import unittest
from cards.card import Card
class Test_Card(unittest.TestCase):
def setUp(self):
self._suit = "clubs"
self._rank = "10"
self._card = ConcreteCard(suit=self._suit, rank=self._rank)
def tearDown(self):
pass
def test_card_is_abstract_class(self):
""" Test that the Card class is an abstract base class """
with self.assertRaises(TypeError):
Card()
def test_rank(self):
""" Test 'rank' property returns correct rank. """
card = self._card
self.assertEqual(card.rank, self._rank)
def test_suit(self):
""" Test 'suit' property returns correct suit. """
card = self._card
self.assertEqual(card.suit, self._suit)
class ConcreteCard(Card):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@property
def value(self):
pass
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| """
Created on Dec 04, 2016
@author: john papa
Copyright 2016 John Papa. All rights reserved.
This work is licensed under the MIT License.
"""
import unittest
from cards.card import Card
class Test_Card(unittest.TestCase):
def setUp(self):
self._suit = "clubs"
self._rank = "10"
self._card = ConcreteCard(suit=self._suit, rank=self._rank)
def tearDown(self):
pass
def test_card_is_abstract_class(self):
""" Test that the Card class is an abstract base class """
with self.assertRaises(TypeError):
Card()
def test_rank(self):
""" Test 'rank' property returns correct rank. """
card = self._card
self.assertEqual(card.rank, self._rank)
def test_suit(self):
""" Test 'suit' property returns correct suit. """
card = self._card
self.assertEqual(card.suit, self._suit)
class ConcreteCard(Card):
def __init__(self, suit, rank):
super().__init__(suit, rank)
@property
def value(self):
pass
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| Change ConcreteCard test class params. | Change ConcreteCard test class params.
| Python | mit | johnpapa2/twenty-one,johnpapa2/twenty-one | """
Created on Dec 04, 2016
@author: john papa
Copyright 2016 John Papa. All rights reserved.
This work is licensed under the MIT License.
"""
import unittest
from cards.card import Card
class Test_Card(unittest.TestCase):
def setUp(self):
self._suit = "clubs"
self._rank = "10"
self._card = ConcreteCard(suit=self._suit, rank=self._rank)
def tearDown(self):
pass
def test_card_is_abstract_class(self):
""" Test that the Card class is an abstract base class """
with self.assertRaises(TypeError):
Card()
def test_rank(self):
""" Test 'rank' property returns correct rank. """
card = self._card
self.assertEqual(card.rank, self._rank)
def test_suit(self):
""" Test 'suit' property returns correct suit. """
card = self._card
self.assertEqual(card.suit, self._suit)
class ConcreteCard(Card):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@property
def value(self):
pass
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
Change ConcreteCard test class params. | """
Created on Dec 04, 2016
@author: john papa
Copyright 2016 John Papa. All rights reserved.
This work is licensed under the MIT License.
"""
import unittest
from cards.card import Card
class Test_Card(unittest.TestCase):
def setUp(self):
self._suit = "clubs"
self._rank = "10"
self._card = ConcreteCard(suit=self._suit, rank=self._rank)
def tearDown(self):
pass
def test_card_is_abstract_class(self):
""" Test that the Card class is an abstract base class """
with self.assertRaises(TypeError):
Card()
def test_rank(self):
""" Test 'rank' property returns correct rank. """
card = self._card
self.assertEqual(card.rank, self._rank)
def test_suit(self):
""" Test 'suit' property returns correct suit. """
card = self._card
self.assertEqual(card.suit, self._suit)
class ConcreteCard(Card):
def __init__(self, suit, rank):
super().__init__(suit, rank)
@property
def value(self):
pass
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| <commit_before>"""
Created on Dec 04, 2016
@author: john papa
Copyright 2016 John Papa. All rights reserved.
This work is licensed under the MIT License.
"""
import unittest
from cards.card import Card
class Test_Card(unittest.TestCase):
def setUp(self):
self._suit = "clubs"
self._rank = "10"
self._card = ConcreteCard(suit=self._suit, rank=self._rank)
def tearDown(self):
pass
def test_card_is_abstract_class(self):
""" Test that the Card class is an abstract base class """
with self.assertRaises(TypeError):
Card()
def test_rank(self):
""" Test 'rank' property returns correct rank. """
card = self._card
self.assertEqual(card.rank, self._rank)
def test_suit(self):
""" Test 'suit' property returns correct suit. """
card = self._card
self.assertEqual(card.suit, self._suit)
class ConcreteCard(Card):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@property
def value(self):
pass
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
<commit_msg>Change ConcreteCard test class params.<commit_after> | """
Created on Dec 04, 2016
@author: john papa
Copyright 2016 John Papa. All rights reserved.
This work is licensed under the MIT License.
"""
import unittest
from cards.card import Card
class Test_Card(unittest.TestCase):
def setUp(self):
self._suit = "clubs"
self._rank = "10"
self._card = ConcreteCard(suit=self._suit, rank=self._rank)
def tearDown(self):
pass
def test_card_is_abstract_class(self):
""" Test that the Card class is an abstract base class """
with self.assertRaises(TypeError):
Card()
def test_rank(self):
""" Test 'rank' property returns correct rank. """
card = self._card
self.assertEqual(card.rank, self._rank)
def test_suit(self):
""" Test 'suit' property returns correct suit. """
card = self._card
self.assertEqual(card.suit, self._suit)
class ConcreteCard(Card):
def __init__(self, suit, rank):
super().__init__(suit, rank)
@property
def value(self):
pass
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| """
Created on Dec 04, 2016
@author: john papa
Copyright 2016 John Papa. All rights reserved.
This work is licensed under the MIT License.
"""
import unittest
from cards.card import Card
class Test_Card(unittest.TestCase):
def setUp(self):
self._suit = "clubs"
self._rank = "10"
self._card = ConcreteCard(suit=self._suit, rank=self._rank)
def tearDown(self):
pass
def test_card_is_abstract_class(self):
""" Test that the Card class is an abstract base class """
with self.assertRaises(TypeError):
Card()
def test_rank(self):
""" Test 'rank' property returns correct rank. """
card = self._card
self.assertEqual(card.rank, self._rank)
def test_suit(self):
""" Test 'suit' property returns correct suit. """
card = self._card
self.assertEqual(card.suit, self._suit)
class ConcreteCard(Card):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@property
def value(self):
pass
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
Change ConcreteCard test class params."""
Created on Dec 04, 2016
@author: john papa
Copyright 2016 John Papa. All rights reserved.
This work is licensed under the MIT License.
"""
import unittest
from cards.card import Card
class Test_Card(unittest.TestCase):
def setUp(self):
self._suit = "clubs"
self._rank = "10"
self._card = ConcreteCard(suit=self._suit, rank=self._rank)
def tearDown(self):
pass
def test_card_is_abstract_class(self):
""" Test that the Card class is an abstract base class """
with self.assertRaises(TypeError):
Card()
def test_rank(self):
""" Test 'rank' property returns correct rank. """
card = self._card
self.assertEqual(card.rank, self._rank)
def test_suit(self):
""" Test 'suit' property returns correct suit. """
card = self._card
self.assertEqual(card.suit, self._suit)
class ConcreteCard(Card):
def __init__(self, suit, rank):
super().__init__(suit, rank)
@property
def value(self):
pass
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| <commit_before>"""
Created on Dec 04, 2016
@author: john papa
Copyright 2016 John Papa. All rights reserved.
This work is licensed under the MIT License.
"""
import unittest
from cards.card import Card
class Test_Card(unittest.TestCase):
def setUp(self):
self._suit = "clubs"
self._rank = "10"
self._card = ConcreteCard(suit=self._suit, rank=self._rank)
def tearDown(self):
pass
def test_card_is_abstract_class(self):
""" Test that the Card class is an abstract base class """
with self.assertRaises(TypeError):
Card()
def test_rank(self):
""" Test 'rank' property returns correct rank. """
card = self._card
self.assertEqual(card.rank, self._rank)
def test_suit(self):
""" Test 'suit' property returns correct suit. """
card = self._card
self.assertEqual(card.suit, self._suit)
class ConcreteCard(Card):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@property
def value(self):
pass
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
<commit_msg>Change ConcreteCard test class params.<commit_after>"""
Created on Dec 04, 2016
@author: john papa
Copyright 2016 John Papa. All rights reserved.
This work is licensed under the MIT License.
"""
import unittest
from cards.card import Card
class Test_Card(unittest.TestCase):
def setUp(self):
self._suit = "clubs"
self._rank = "10"
self._card = ConcreteCard(suit=self._suit, rank=self._rank)
def tearDown(self):
pass
def test_card_is_abstract_class(self):
""" Test that the Card class is an abstract base class """
with self.assertRaises(TypeError):
Card()
def test_rank(self):
""" Test 'rank' property returns correct rank. """
card = self._card
self.assertEqual(card.rank, self._rank)
def test_suit(self):
""" Test 'suit' property returns correct suit. """
card = self._card
self.assertEqual(card.suit, self._suit)
class ConcreteCard(Card):
def __init__(self, suit, rank):
super().__init__(suit, rank)
@property
def value(self):
pass
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
|
e264224ee69cb37a02f28a6c78a231dd6d41db58 | examples/web_rewrite_headers_middleware.py | examples/web_rewrite_headers_middleware.py | #!/usr/bin/env python3
"""
Example for rewriting response headers by middleware.
"""
import asyncio
from aiohttp.web import Application, Response
@asyncio.coroutine
def handler(request):
return Response(text="Everything is fine")
@asyncio.coroutine
def middleware_factory(app, next_handler):
@asyncio.coroutine
def middleware(request):
response = yield from next_handler(request)
if not response.started:
response.headers['SERVER'] = "Secured Server Software"
return response
return middleware
@asyncio.coroutine
def init(loop):
app = Application(loop=loop, middlewares=[middleware_factory])
app.router.add_route('GET', '/', handler)
requests_handler = app.make_handler()
srv = yield from loop.create_server(requests_handler, '127.0.0.1', 8080)
print("Server started at http://127.0.0.1:8080")
return srv, requests_handler
loop = asyncio.get_event_loop()
srv, requests_handler = loop.run_until_complete(init(loop))
try:
loop.run_forever()
except KeyboardInterrupt:
loop.run_until_complete(requests_handler.finish_connections())
| #!/usr/bin/env python3
"""
Example for rewriting response headers by middleware.
"""
import asyncio
from aiohttp.web import Application, Response, HTTPException
@asyncio.coroutine
def handler(request):
return Response(text="Everything is fine")
@asyncio.coroutine
def middleware_factory(app, next_handler):
@asyncio.coroutine
def middleware(request):
try:
response = yield from next_handler(request)
except HTTPException as exc:
response = exc
if not response.started:
response.headers['SERVER'] = "Secured Server Software"
return response
return middleware
@asyncio.coroutine
def init(loop):
app = Application(loop=loop, middlewares=[middleware_factory])
app.router.add_route('GET', '/', handler)
requests_handler = app.make_handler()
srv = yield from loop.create_server(requests_handler, '127.0.0.1', 8080)
print("Server started at http://127.0.0.1:8080")
return srv, requests_handler
loop = asyncio.get_event_loop()
srv, requests_handler = loop.run_until_complete(init(loop))
try:
loop.run_forever()
except KeyboardInterrupt:
loop.run_until_complete(requests_handler.finish_connections())
| Fix example for rewriting response headers in middleware to set headers for exceptions like 404 Not Found | Fix example for rewriting response headers in middleware to set headers for exceptions like 404 Not Found
| Python | apache-2.0 | alex-eri/aiohttp-1,jettify/aiohttp,hellysmile/aiohttp,z2v/aiohttp,juliatem/aiohttp,rutsky/aiohttp,AlexLisovoy/aiohttp,KeepSafe/aiohttp,mind1master/aiohttp,rutsky/aiohttp,Eyepea/aiohttp,jojurajan/aiohttp,mind1master/aiohttp,jashandeep-sohi/aiohttp,mind1master/aiohttp,alexsdutton/aiohttp,elastic-coders/aiohttp,pathcl/aiohttp,elastic-coders/aiohttp,singulared/aiohttp,vaskalas/aiohttp,alex-eri/aiohttp-1,z2v/aiohttp,juliatem/aiohttp,alexsdutton/aiohttp,danielnelson/aiohttp,KeepSafe/aiohttp,singulared/aiohttp,vasylbo/aiohttp,iksteen/aiohttp,decentfox/aiohttp,noodle-learns-programming/aiohttp,noplay/aiohttp,KeepSafe/aiohttp,vaskalas/aiohttp,Srogozins/aiohttp,Insoleet/aiohttp,jettify/aiohttp,esaezgil/aiohttp,panda73111/aiohttp,arthurdarcet/aiohttp,hellysmile/aiohttp,flying-sheep/aiohttp,vedun/aiohttp,decentfox/aiohttp,arthurdarcet/aiohttp,noplay/aiohttp,elastic-coders/aiohttp,jashandeep-sohi/aiohttp,decentfox/aiohttp,panda73111/aiohttp,esaezgil/aiohttp,avanov/aiohttp,rutsky/aiohttp,AraHaanOrg/aiohttp,jojurajan/aiohttp,vaskalas/aiohttp,panda73111/aiohttp,morgan-del/aiohttp,alunduil/aiohttp,moden-py/aiohttp,pfreixes/aiohttp,sterwill/aiohttp,singulared/aiohttp,andyaguiar/aiohttp,AraHaanOrg/aiohttp,jettify/aiohttp,esaezgil/aiohttp,playpauseandstop/aiohttp,AlexLisovoy/aiohttp,pfreixes/aiohttp,moden-py/aiohttp,z2v/aiohttp,alex-eri/aiohttp-1,iksteen/aiohttp,jashandeep-sohi/aiohttp,moden-py/aiohttp,arthurdarcet/aiohttp | #!/usr/bin/env python3
"""
Example for rewriting response headers by middleware.
"""
import asyncio
from aiohttp.web import Application, Response
@asyncio.coroutine
def handler(request):
return Response(text="Everything is fine")
@asyncio.coroutine
def middleware_factory(app, next_handler):
@asyncio.coroutine
def middleware(request):
response = yield from next_handler(request)
if not response.started:
response.headers['SERVER'] = "Secured Server Software"
return response
return middleware
@asyncio.coroutine
def init(loop):
app = Application(loop=loop, middlewares=[middleware_factory])
app.router.add_route('GET', '/', handler)
requests_handler = app.make_handler()
srv = yield from loop.create_server(requests_handler, '127.0.0.1', 8080)
print("Server started at http://127.0.0.1:8080")
return srv, requests_handler
loop = asyncio.get_event_loop()
srv, requests_handler = loop.run_until_complete(init(loop))
try:
loop.run_forever()
except KeyboardInterrupt:
loop.run_until_complete(requests_handler.finish_connections())
Fix example for rewriting response headers in middleware to set headers for exceptions like 404 Not Found | #!/usr/bin/env python3
"""
Example for rewriting response headers by middleware.
"""
import asyncio
from aiohttp.web import Application, Response, HTTPException
@asyncio.coroutine
def handler(request):
return Response(text="Everything is fine")
@asyncio.coroutine
def middleware_factory(app, next_handler):
@asyncio.coroutine
def middleware(request):
try:
response = yield from next_handler(request)
except HTTPException as exc:
response = exc
if not response.started:
response.headers['SERVER'] = "Secured Server Software"
return response
return middleware
@asyncio.coroutine
def init(loop):
app = Application(loop=loop, middlewares=[middleware_factory])
app.router.add_route('GET', '/', handler)
requests_handler = app.make_handler()
srv = yield from loop.create_server(requests_handler, '127.0.0.1', 8080)
print("Server started at http://127.0.0.1:8080")
return srv, requests_handler
loop = asyncio.get_event_loop()
srv, requests_handler = loop.run_until_complete(init(loop))
try:
loop.run_forever()
except KeyboardInterrupt:
loop.run_until_complete(requests_handler.finish_connections())
| <commit_before>#!/usr/bin/env python3
"""
Example for rewriting response headers by middleware.
"""
import asyncio
from aiohttp.web import Application, Response
@asyncio.coroutine
def handler(request):
return Response(text="Everything is fine")
@asyncio.coroutine
def middleware_factory(app, next_handler):
@asyncio.coroutine
def middleware(request):
response = yield from next_handler(request)
if not response.started:
response.headers['SERVER'] = "Secured Server Software"
return response
return middleware
@asyncio.coroutine
def init(loop):
app = Application(loop=loop, middlewares=[middleware_factory])
app.router.add_route('GET', '/', handler)
requests_handler = app.make_handler()
srv = yield from loop.create_server(requests_handler, '127.0.0.1', 8080)
print("Server started at http://127.0.0.1:8080")
return srv, requests_handler
loop = asyncio.get_event_loop()
srv, requests_handler = loop.run_until_complete(init(loop))
try:
loop.run_forever()
except KeyboardInterrupt:
loop.run_until_complete(requests_handler.finish_connections())
<commit_msg>Fix example for rewriting response headers in middleware to set headers for exceptions like 404 Not Found<commit_after> | #!/usr/bin/env python3
"""
Example for rewriting response headers by middleware.
"""
import asyncio
from aiohttp.web import Application, Response, HTTPException
@asyncio.coroutine
def handler(request):
return Response(text="Everything is fine")
@asyncio.coroutine
def middleware_factory(app, next_handler):
@asyncio.coroutine
def middleware(request):
try:
response = yield from next_handler(request)
except HTTPException as exc:
response = exc
if not response.started:
response.headers['SERVER'] = "Secured Server Software"
return response
return middleware
@asyncio.coroutine
def init(loop):
app = Application(loop=loop, middlewares=[middleware_factory])
app.router.add_route('GET', '/', handler)
requests_handler = app.make_handler()
srv = yield from loop.create_server(requests_handler, '127.0.0.1', 8080)
print("Server started at http://127.0.0.1:8080")
return srv, requests_handler
loop = asyncio.get_event_loop()
srv, requests_handler = loop.run_until_complete(init(loop))
try:
loop.run_forever()
except KeyboardInterrupt:
loop.run_until_complete(requests_handler.finish_connections())
| #!/usr/bin/env python3
"""
Example for rewriting response headers by middleware.
"""
import asyncio
from aiohttp.web import Application, Response
@asyncio.coroutine
def handler(request):
return Response(text="Everything is fine")
@asyncio.coroutine
def middleware_factory(app, next_handler):
@asyncio.coroutine
def middleware(request):
response = yield from next_handler(request)
if not response.started:
response.headers['SERVER'] = "Secured Server Software"
return response
return middleware
@asyncio.coroutine
def init(loop):
app = Application(loop=loop, middlewares=[middleware_factory])
app.router.add_route('GET', '/', handler)
requests_handler = app.make_handler()
srv = yield from loop.create_server(requests_handler, '127.0.0.1', 8080)
print("Server started at http://127.0.0.1:8080")
return srv, requests_handler
loop = asyncio.get_event_loop()
srv, requests_handler = loop.run_until_complete(init(loop))
try:
loop.run_forever()
except KeyboardInterrupt:
loop.run_until_complete(requests_handler.finish_connections())
Fix example for rewriting response headers in middleware to set headers for exceptions like 404 Not Found#!/usr/bin/env python3
"""
Example for rewriting response headers by middleware.
"""
import asyncio
from aiohttp.web import Application, Response, HTTPException
@asyncio.coroutine
def handler(request):
return Response(text="Everything is fine")
@asyncio.coroutine
def middleware_factory(app, next_handler):
@asyncio.coroutine
def middleware(request):
try:
response = yield from next_handler(request)
except HTTPException as exc:
response = exc
if not response.started:
response.headers['SERVER'] = "Secured Server Software"
return response
return middleware
@asyncio.coroutine
def init(loop):
app = Application(loop=loop, middlewares=[middleware_factory])
app.router.add_route('GET', '/', handler)
requests_handler = app.make_handler()
srv = yield from loop.create_server(requests_handler, '127.0.0.1', 8080)
print("Server started at http://127.0.0.1:8080")
return srv, requests_handler
loop = asyncio.get_event_loop()
srv, requests_handler = loop.run_until_complete(init(loop))
try:
loop.run_forever()
except KeyboardInterrupt:
loop.run_until_complete(requests_handler.finish_connections())
| <commit_before>#!/usr/bin/env python3
"""
Example for rewriting response headers by middleware.
"""
import asyncio
from aiohttp.web import Application, Response
@asyncio.coroutine
def handler(request):
return Response(text="Everything is fine")
@asyncio.coroutine
def middleware_factory(app, next_handler):
@asyncio.coroutine
def middleware(request):
response = yield from next_handler(request)
if not response.started:
response.headers['SERVER'] = "Secured Server Software"
return response
return middleware
@asyncio.coroutine
def init(loop):
app = Application(loop=loop, middlewares=[middleware_factory])
app.router.add_route('GET', '/', handler)
requests_handler = app.make_handler()
srv = yield from loop.create_server(requests_handler, '127.0.0.1', 8080)
print("Server started at http://127.0.0.1:8080")
return srv, requests_handler
loop = asyncio.get_event_loop()
srv, requests_handler = loop.run_until_complete(init(loop))
try:
loop.run_forever()
except KeyboardInterrupt:
loop.run_until_complete(requests_handler.finish_connections())
<commit_msg>Fix example for rewriting response headers in middleware to set headers for exceptions like 404 Not Found<commit_after>#!/usr/bin/env python3
"""
Example for rewriting response headers by middleware.
"""
import asyncio
from aiohttp.web import Application, Response, HTTPException
@asyncio.coroutine
def handler(request):
return Response(text="Everything is fine")
@asyncio.coroutine
def middleware_factory(app, next_handler):
@asyncio.coroutine
def middleware(request):
try:
response = yield from next_handler(request)
except HTTPException as exc:
response = exc
if not response.started:
response.headers['SERVER'] = "Secured Server Software"
return response
return middleware
@asyncio.coroutine
def init(loop):
app = Application(loop=loop, middlewares=[middleware_factory])
app.router.add_route('GET', '/', handler)
requests_handler = app.make_handler()
srv = yield from loop.create_server(requests_handler, '127.0.0.1', 8080)
print("Server started at http://127.0.0.1:8080")
return srv, requests_handler
loop = asyncio.get_event_loop()
srv, requests_handler = loop.run_until_complete(init(loop))
try:
loop.run_forever()
except KeyboardInterrupt:
loop.run_until_complete(requests_handler.finish_connections())
|
b75a9eab312a2ac787e4b0e44115f8bad4508418 | route/__init__.py | route/__init__.py | class Route(object):
def __init__(self, ip, domain):
self.ip = ip
self.domain = domain
def __str__(self):
return self.domain
def query(self):
""" search domain routing info """
pass
def register(self):
""" register domain nginx reverse proxy """
pass
def __del__(self):
del self
| from route.db import db_session
from route.models import Domain
import os
import subprocess
class Route(object):
def __init__(self, ip, domain):
self.ip = ip
self.domain = domain
def __str__(self):
return self.domain
def search(self, option, value):
""" search domain routing info """
d = Domain
if option == "ip":
d.filter(Domain.ip == value)
elif option == "domain":
d.filter(Domain.domain == value)
elif option == "user":
d.filter(Domain.user == value)
return d.all()
def register(self, user):
""" register domain nginx reverse proxy """
self.write_file()
self.restart_nginx()
db_session.add(Domain(ip, domain, user))
db_session.commit()
def restart_nginx(self):
def write_file(self):
data = "server {\n"\
"\tlisten 443 ssl;\n"\
"\tserver_name {}\n\n".format(self.domain)\
"\tlocation / {\n"\
"\t\tproxy_redirect off;\n"\
"\t\tproxy_pass_header Server;\n"\
"\t\tproxy_set_header Host $http_host;\n"\
"\t\tproxy_set_header X-Real-IP $remote_addr;\n"\
"\t\tproxy_set_header X-Scheme $scheme;\n"\
"\t\tproxy_pass http://{};\n".format(self.ip)\
"\t}\n"\
"}\n\n"\
"server {\n"\
"\tlisten 80;\n"\
"\tserver_name {}\n\n".format(self.domain)\
"\tlocation / {\n"\
"\t\trewrite ^(.*) https://$host$1 permanent;\n"\
"\t}\n"\
"}\n"
with open("/etc/nginx/sites-available/{}".format(self.domain), "a") as f:
f.write(data)
os.symlink("/etc/nginx/sites-available/{}".format(self.domain), "/etc/nginx/sites-enabled/{}".format(self.domain))
def __del__(self):
del self
| Add register, restart, write to handle nginx | Add register, restart, write to handle nginx
| Python | apache-2.0 | bunseokbot/proxy_register,bunseokbot/proxy_register | class Route(object):
def __init__(self, ip, domain):
self.ip = ip
self.domain = domain
def __str__(self):
return self.domain
def query(self):
""" search domain routing info """
pass
def register(self):
""" register domain nginx reverse proxy """
pass
def __del__(self):
del self
Add register, restart, write to handle nginx | from route.db import db_session
from route.models import Domain
import os
import subprocess
class Route(object):
def __init__(self, ip, domain):
self.ip = ip
self.domain = domain
def __str__(self):
return self.domain
def search(self, option, value):
""" search domain routing info """
d = Domain
if option == "ip":
d.filter(Domain.ip == value)
elif option == "domain":
d.filter(Domain.domain == value)
elif option == "user":
d.filter(Domain.user == value)
return d.all()
def register(self, user):
""" register domain nginx reverse proxy """
self.write_file()
self.restart_nginx()
db_session.add(Domain(ip, domain, user))
db_session.commit()
def restart_nginx(self):
def write_file(self):
data = "server {\n"\
"\tlisten 443 ssl;\n"\
"\tserver_name {}\n\n".format(self.domain)\
"\tlocation / {\n"\
"\t\tproxy_redirect off;\n"\
"\t\tproxy_pass_header Server;\n"\
"\t\tproxy_set_header Host $http_host;\n"\
"\t\tproxy_set_header X-Real-IP $remote_addr;\n"\
"\t\tproxy_set_header X-Scheme $scheme;\n"\
"\t\tproxy_pass http://{};\n".format(self.ip)\
"\t}\n"\
"}\n\n"\
"server {\n"\
"\tlisten 80;\n"\
"\tserver_name {}\n\n".format(self.domain)\
"\tlocation / {\n"\
"\t\trewrite ^(.*) https://$host$1 permanent;\n"\
"\t}\n"\
"}\n"
with open("/etc/nginx/sites-available/{}".format(self.domain), "a") as f:
f.write(data)
os.symlink("/etc/nginx/sites-available/{}".format(self.domain), "/etc/nginx/sites-enabled/{}".format(self.domain))
def __del__(self):
del self
| <commit_before>class Route(object):
def __init__(self, ip, domain):
self.ip = ip
self.domain = domain
def __str__(self):
return self.domain
def query(self):
""" search domain routing info """
pass
def register(self):
""" register domain nginx reverse proxy """
pass
def __del__(self):
del self
<commit_msg>Add register, restart, write to handle nginx<commit_after> | from route.db import db_session
from route.models import Domain
import os
import subprocess
class Route(object):
def __init__(self, ip, domain):
self.ip = ip
self.domain = domain
def __str__(self):
return self.domain
def search(self, option, value):
""" search domain routing info """
d = Domain
if option == "ip":
d.filter(Domain.ip == value)
elif option == "domain":
d.filter(Domain.domain == value)
elif option == "user":
d.filter(Domain.user == value)
return d.all()
def register(self, user):
""" register domain nginx reverse proxy """
self.write_file()
self.restart_nginx()
db_session.add(Domain(ip, domain, user))
db_session.commit()
def restart_nginx(self):
def write_file(self):
data = "server {\n"\
"\tlisten 443 ssl;\n"\
"\tserver_name {}\n\n".format(self.domain)\
"\tlocation / {\n"\
"\t\tproxy_redirect off;\n"\
"\t\tproxy_pass_header Server;\n"\
"\t\tproxy_set_header Host $http_host;\n"\
"\t\tproxy_set_header X-Real-IP $remote_addr;\n"\
"\t\tproxy_set_header X-Scheme $scheme;\n"\
"\t\tproxy_pass http://{};\n".format(self.ip)\
"\t}\n"\
"}\n\n"\
"server {\n"\
"\tlisten 80;\n"\
"\tserver_name {}\n\n".format(self.domain)\
"\tlocation / {\n"\
"\t\trewrite ^(.*) https://$host$1 permanent;\n"\
"\t}\n"\
"}\n"
with open("/etc/nginx/sites-available/{}".format(self.domain), "a") as f:
f.write(data)
os.symlink("/etc/nginx/sites-available/{}".format(self.domain), "/etc/nginx/sites-enabled/{}".format(self.domain))
def __del__(self):
del self
| class Route(object):
def __init__(self, ip, domain):
self.ip = ip
self.domain = domain
def __str__(self):
return self.domain
def query(self):
""" search domain routing info """
pass
def register(self):
""" register domain nginx reverse proxy """
pass
def __del__(self):
del self
Add register, restart, write to handle nginxfrom route.db import db_session
from route.models import Domain
import os
import subprocess
class Route(object):
def __init__(self, ip, domain):
self.ip = ip
self.domain = domain
def __str__(self):
return self.domain
def search(self, option, value):
""" search domain routing info """
d = Domain
if option == "ip":
d.filter(Domain.ip == value)
elif option == "domain":
d.filter(Domain.domain == value)
elif option == "user":
d.filter(Domain.user == value)
return d.all()
def register(self, user):
""" register domain nginx reverse proxy """
self.write_file()
self.restart_nginx()
db_session.add(Domain(ip, domain, user))
db_session.commit()
def restart_nginx(self):
def write_file(self):
data = "server {\n"\
"\tlisten 443 ssl;\n"\
"\tserver_name {}\n\n".format(self.domain)\
"\tlocation / {\n"\
"\t\tproxy_redirect off;\n"\
"\t\tproxy_pass_header Server;\n"\
"\t\tproxy_set_header Host $http_host;\n"\
"\t\tproxy_set_header X-Real-IP $remote_addr;\n"\
"\t\tproxy_set_header X-Scheme $scheme;\n"\
"\t\tproxy_pass http://{};\n".format(self.ip)\
"\t}\n"\
"}\n\n"\
"server {\n"\
"\tlisten 80;\n"\
"\tserver_name {}\n\n".format(self.domain)\
"\tlocation / {\n"\
"\t\trewrite ^(.*) https://$host$1 permanent;\n"\
"\t}\n"\
"}\n"
with open("/etc/nginx/sites-available/{}".format(self.domain), "a") as f:
f.write(data)
os.symlink("/etc/nginx/sites-available/{}".format(self.domain), "/etc/nginx/sites-enabled/{}".format(self.domain))
def __del__(self):
del self
| <commit_before>class Route(object):
def __init__(self, ip, domain):
self.ip = ip
self.domain = domain
def __str__(self):
return self.domain
def query(self):
""" search domain routing info """
pass
def register(self):
""" register domain nginx reverse proxy """
pass
def __del__(self):
del self
<commit_msg>Add register, restart, write to handle nginx<commit_after>from route.db import db_session
from route.models import Domain
import os
import subprocess
class Route(object):
def __init__(self, ip, domain):
self.ip = ip
self.domain = domain
def __str__(self):
return self.domain
def search(self, option, value):
""" search domain routing info """
d = Domain
if option == "ip":
d.filter(Domain.ip == value)
elif option == "domain":
d.filter(Domain.domain == value)
elif option == "user":
d.filter(Domain.user == value)
return d.all()
def register(self, user):
""" register domain nginx reverse proxy """
self.write_file()
self.restart_nginx()
db_session.add(Domain(ip, domain, user))
db_session.commit()
def restart_nginx(self):
def write_file(self):
data = "server {\n"\
"\tlisten 443 ssl;\n"\
"\tserver_name {}\n\n".format(self.domain)\
"\tlocation / {\n"\
"\t\tproxy_redirect off;\n"\
"\t\tproxy_pass_header Server;\n"\
"\t\tproxy_set_header Host $http_host;\n"\
"\t\tproxy_set_header X-Real-IP $remote_addr;\n"\
"\t\tproxy_set_header X-Scheme $scheme;\n"\
"\t\tproxy_pass http://{};\n".format(self.ip)\
"\t}\n"\
"}\n\n"\
"server {\n"\
"\tlisten 80;\n"\
"\tserver_name {}\n\n".format(self.domain)\
"\tlocation / {\n"\
"\t\trewrite ^(.*) https://$host$1 permanent;\n"\
"\t}\n"\
"}\n"
with open("/etc/nginx/sites-available/{}".format(self.domain), "a") as f:
f.write(data)
os.symlink("/etc/nginx/sites-available/{}".format(self.domain), "/etc/nginx/sites-enabled/{}".format(self.domain))
def __del__(self):
del self
|
90cd7a194ce1294d6b14b819b10ca62e3d058cb9 | auslib/test/web/test_dockerflow.py | auslib/test/web/test_dockerflow.py | import mock
from auslib.test.web.test_client import ClientTestBase
class TestDockerflowEndpoints(ClientTestBase):
def testVersion(self):
ret = self.client.get("/__version__")
self.assertEquals(ret.data, """
{
"source":"https://github.com/mozilla/balrog",
"version":"1.0",
"commit":"abcdef123456"
}
""")
def testHeartbeat(self):
with mock.patch("auslib.global_state.dbo.rules.countRules") as cr:
ret = self.client.get("/__heartbeat__")
self.assertEqual(ret.status_code, 200)
self.assertEqual(cr.call_count, 1)
def testLbHeartbeat(self):
ret = self.client.get("/__lbheartbeat__")
self.assertEqual(ret.status_code, 200)
| import mock
from auslib.test.web.test_client import ClientTestBase
class TestDockerflowEndpoints(ClientTestBase):
def testVersion(self):
ret = self.client.get("/__version__")
self.assertEquals(ret.data, """
{
"source":"https://github.com/mozilla/balrog",
"version":"1.0",
"commit":"abcdef123456"
}
""")
def testHeartbeat(self):
with mock.patch("auslib.global_state.dbo.rules.countRules") as cr:
ret = self.client.get("/__heartbeat__")
self.assertEqual(ret.status_code, 200)
self.assertEqual(cr.call_count, 1)
def testHeartbeatWithException(self):
with mock.patch("auslib.global_state.dbo.rules.countRules") as cr:
cr.side_effect = Exception("kabom!")
# Because there's no web server between us and the endpoint, we recieve
# the Exception directly instead of a 500 error
self.assertRaises(Exception, self.client.get, "/__heartbeat__")
self.assertEqual(cr.call_count, 1)
def testLbHeartbeat(self):
ret = self.client.get("/__lbheartbeat__")
self.assertEqual(ret.status_code, 200)
| Add test to make sure public facing app raises exception when it hits an error. | Add test to make sure public facing app raises exception when it hits an error.
| Python | mpl-2.0 | aksareen/balrog,nurav/balrog,nurav/balrog,mozbhearsum/balrog,tieu/balrog,mozbhearsum/balrog,aksareen/balrog,testbhearsum/balrog,testbhearsum/balrog,nurav/balrog,aksareen/balrog,tieu/balrog,nurav/balrog,tieu/balrog,mozbhearsum/balrog,tieu/balrog,testbhearsum/balrog,mozbhearsum/balrog,aksareen/balrog,testbhearsum/balrog | import mock
from auslib.test.web.test_client import ClientTestBase
class TestDockerflowEndpoints(ClientTestBase):
def testVersion(self):
ret = self.client.get("/__version__")
self.assertEquals(ret.data, """
{
"source":"https://github.com/mozilla/balrog",
"version":"1.0",
"commit":"abcdef123456"
}
""")
def testHeartbeat(self):
with mock.patch("auslib.global_state.dbo.rules.countRules") as cr:
ret = self.client.get("/__heartbeat__")
self.assertEqual(ret.status_code, 200)
self.assertEqual(cr.call_count, 1)
def testLbHeartbeat(self):
ret = self.client.get("/__lbheartbeat__")
self.assertEqual(ret.status_code, 200)
Add test to make sure public facing app raises exception when it hits an error. | import mock
from auslib.test.web.test_client import ClientTestBase
class TestDockerflowEndpoints(ClientTestBase):
def testVersion(self):
ret = self.client.get("/__version__")
self.assertEquals(ret.data, """
{
"source":"https://github.com/mozilla/balrog",
"version":"1.0",
"commit":"abcdef123456"
}
""")
def testHeartbeat(self):
with mock.patch("auslib.global_state.dbo.rules.countRules") as cr:
ret = self.client.get("/__heartbeat__")
self.assertEqual(ret.status_code, 200)
self.assertEqual(cr.call_count, 1)
def testHeartbeatWithException(self):
with mock.patch("auslib.global_state.dbo.rules.countRules") as cr:
cr.side_effect = Exception("kabom!")
# Because there's no web server between us and the endpoint, we recieve
# the Exception directly instead of a 500 error
self.assertRaises(Exception, self.client.get, "/__heartbeat__")
self.assertEqual(cr.call_count, 1)
def testLbHeartbeat(self):
ret = self.client.get("/__lbheartbeat__")
self.assertEqual(ret.status_code, 200)
| <commit_before>import mock
from auslib.test.web.test_client import ClientTestBase
class TestDockerflowEndpoints(ClientTestBase):
def testVersion(self):
ret = self.client.get("/__version__")
self.assertEquals(ret.data, """
{
"source":"https://github.com/mozilla/balrog",
"version":"1.0",
"commit":"abcdef123456"
}
""")
def testHeartbeat(self):
with mock.patch("auslib.global_state.dbo.rules.countRules") as cr:
ret = self.client.get("/__heartbeat__")
self.assertEqual(ret.status_code, 200)
self.assertEqual(cr.call_count, 1)
def testLbHeartbeat(self):
ret = self.client.get("/__lbheartbeat__")
self.assertEqual(ret.status_code, 200)
<commit_msg>Add test to make sure public facing app raises exception when it hits an error.<commit_after> | import mock
from auslib.test.web.test_client import ClientTestBase
class TestDockerflowEndpoints(ClientTestBase):
def testVersion(self):
ret = self.client.get("/__version__")
self.assertEquals(ret.data, """
{
"source":"https://github.com/mozilla/balrog",
"version":"1.0",
"commit":"abcdef123456"
}
""")
def testHeartbeat(self):
with mock.patch("auslib.global_state.dbo.rules.countRules") as cr:
ret = self.client.get("/__heartbeat__")
self.assertEqual(ret.status_code, 200)
self.assertEqual(cr.call_count, 1)
def testHeartbeatWithException(self):
with mock.patch("auslib.global_state.dbo.rules.countRules") as cr:
cr.side_effect = Exception("kabom!")
# Because there's no web server between us and the endpoint, we recieve
# the Exception directly instead of a 500 error
self.assertRaises(Exception, self.client.get, "/__heartbeat__")
self.assertEqual(cr.call_count, 1)
def testLbHeartbeat(self):
ret = self.client.get("/__lbheartbeat__")
self.assertEqual(ret.status_code, 200)
| import mock
from auslib.test.web.test_client import ClientTestBase
class TestDockerflowEndpoints(ClientTestBase):
def testVersion(self):
ret = self.client.get("/__version__")
self.assertEquals(ret.data, """
{
"source":"https://github.com/mozilla/balrog",
"version":"1.0",
"commit":"abcdef123456"
}
""")
def testHeartbeat(self):
with mock.patch("auslib.global_state.dbo.rules.countRules") as cr:
ret = self.client.get("/__heartbeat__")
self.assertEqual(ret.status_code, 200)
self.assertEqual(cr.call_count, 1)
def testLbHeartbeat(self):
ret = self.client.get("/__lbheartbeat__")
self.assertEqual(ret.status_code, 200)
Add test to make sure public facing app raises exception when it hits an error.import mock
from auslib.test.web.test_client import ClientTestBase
class TestDockerflowEndpoints(ClientTestBase):
def testVersion(self):
ret = self.client.get("/__version__")
self.assertEquals(ret.data, """
{
"source":"https://github.com/mozilla/balrog",
"version":"1.0",
"commit":"abcdef123456"
}
""")
def testHeartbeat(self):
with mock.patch("auslib.global_state.dbo.rules.countRules") as cr:
ret = self.client.get("/__heartbeat__")
self.assertEqual(ret.status_code, 200)
self.assertEqual(cr.call_count, 1)
def testHeartbeatWithException(self):
with mock.patch("auslib.global_state.dbo.rules.countRules") as cr:
cr.side_effect = Exception("kabom!")
# Because there's no web server between us and the endpoint, we recieve
# the Exception directly instead of a 500 error
self.assertRaises(Exception, self.client.get, "/__heartbeat__")
self.assertEqual(cr.call_count, 1)
def testLbHeartbeat(self):
ret = self.client.get("/__lbheartbeat__")
self.assertEqual(ret.status_code, 200)
| <commit_before>import mock
from auslib.test.web.test_client import ClientTestBase
class TestDockerflowEndpoints(ClientTestBase):
def testVersion(self):
ret = self.client.get("/__version__")
self.assertEquals(ret.data, """
{
"source":"https://github.com/mozilla/balrog",
"version":"1.0",
"commit":"abcdef123456"
}
""")
def testHeartbeat(self):
with mock.patch("auslib.global_state.dbo.rules.countRules") as cr:
ret = self.client.get("/__heartbeat__")
self.assertEqual(ret.status_code, 200)
self.assertEqual(cr.call_count, 1)
def testLbHeartbeat(self):
ret = self.client.get("/__lbheartbeat__")
self.assertEqual(ret.status_code, 200)
<commit_msg>Add test to make sure public facing app raises exception when it hits an error.<commit_after>import mock
from auslib.test.web.test_client import ClientTestBase
class TestDockerflowEndpoints(ClientTestBase):
def testVersion(self):
ret = self.client.get("/__version__")
self.assertEquals(ret.data, """
{
"source":"https://github.com/mozilla/balrog",
"version":"1.0",
"commit":"abcdef123456"
}
""")
def testHeartbeat(self):
with mock.patch("auslib.global_state.dbo.rules.countRules") as cr:
ret = self.client.get("/__heartbeat__")
self.assertEqual(ret.status_code, 200)
self.assertEqual(cr.call_count, 1)
def testHeartbeatWithException(self):
with mock.patch("auslib.global_state.dbo.rules.countRules") as cr:
cr.side_effect = Exception("kabom!")
# Because there's no web server between us and the endpoint, we recieve
# the Exception directly instead of a 500 error
self.assertRaises(Exception, self.client.get, "/__heartbeat__")
self.assertEqual(cr.call_count, 1)
def testLbHeartbeat(self):
ret = self.client.get("/__lbheartbeat__")
self.assertEqual(ret.status_code, 200)
|
9b255d781e3b0aefa708e1366810d14700384d10 | satyr/__init__.py | satyr/__init__.py | from __future__ import absolute_import, division, print_function
import logging
import pkg_resources as _pkg_resources
from .scheduler import QueueScheduler
from .executor import OneOffExecutor
from .messages import PythonTask, PythonTaskStatus # important to register classes
logging.basicConfig(level=logging.DEBUG,
format='%(relativeCreated)6d %(threadName)s %(message)s')
__version__ = _pkg_resources.get_distribution('satyr').version
__all__ = ('QueueScheduler',
'OneOffExecutor',
'PythonTask',
'PythonTaskStatus')
| from __future__ import absolute_import, division, print_function
import logging
import pkg_resources as _pkg_resources
from .scheduler import QueueScheduler
from .executor import OneOffExecutor
from .messages import PythonTask, PythonTaskStatus # important to register classes
logging.basicConfig(level=logging.INFO,
format='%(relativeCreated)6d %(threadName)s %(message)s')
__version__ = _pkg_resources.get_distribution('satyr').version
__all__ = ('QueueScheduler',
'OneOffExecutor',
'PythonTask',
'PythonTaskStatus')
| Set default logging level to INFO | Set default logging level to INFO
| Python | apache-2.0 | lensacom/satyr | from __future__ import absolute_import, division, print_function
import logging
import pkg_resources as _pkg_resources
from .scheduler import QueueScheduler
from .executor import OneOffExecutor
from .messages import PythonTask, PythonTaskStatus # important to register classes
logging.basicConfig(level=logging.DEBUG,
format='%(relativeCreated)6d %(threadName)s %(message)s')
__version__ = _pkg_resources.get_distribution('satyr').version
__all__ = ('QueueScheduler',
'OneOffExecutor',
'PythonTask',
'PythonTaskStatus')
Set default logging level to INFO | from __future__ import absolute_import, division, print_function
import logging
import pkg_resources as _pkg_resources
from .scheduler import QueueScheduler
from .executor import OneOffExecutor
from .messages import PythonTask, PythonTaskStatus # important to register classes
logging.basicConfig(level=logging.INFO,
format='%(relativeCreated)6d %(threadName)s %(message)s')
__version__ = _pkg_resources.get_distribution('satyr').version
__all__ = ('QueueScheduler',
'OneOffExecutor',
'PythonTask',
'PythonTaskStatus')
| <commit_before>from __future__ import absolute_import, division, print_function
import logging
import pkg_resources as _pkg_resources
from .scheduler import QueueScheduler
from .executor import OneOffExecutor
from .messages import PythonTask, PythonTaskStatus # important to register classes
logging.basicConfig(level=logging.DEBUG,
format='%(relativeCreated)6d %(threadName)s %(message)s')
__version__ = _pkg_resources.get_distribution('satyr').version
__all__ = ('QueueScheduler',
'OneOffExecutor',
'PythonTask',
'PythonTaskStatus')
<commit_msg>Set default logging level to INFO<commit_after> | from __future__ import absolute_import, division, print_function
import logging
import pkg_resources as _pkg_resources
from .scheduler import QueueScheduler
from .executor import OneOffExecutor
from .messages import PythonTask, PythonTaskStatus # important to register classes
logging.basicConfig(level=logging.INFO,
format='%(relativeCreated)6d %(threadName)s %(message)s')
__version__ = _pkg_resources.get_distribution('satyr').version
__all__ = ('QueueScheduler',
'OneOffExecutor',
'PythonTask',
'PythonTaskStatus')
| from __future__ import absolute_import, division, print_function
import logging
import pkg_resources as _pkg_resources
from .scheduler import QueueScheduler
from .executor import OneOffExecutor
from .messages import PythonTask, PythonTaskStatus # important to register classes
logging.basicConfig(level=logging.DEBUG,
format='%(relativeCreated)6d %(threadName)s %(message)s')
__version__ = _pkg_resources.get_distribution('satyr').version
__all__ = ('QueueScheduler',
'OneOffExecutor',
'PythonTask',
'PythonTaskStatus')
Set default logging level to INFOfrom __future__ import absolute_import, division, print_function
import logging
import pkg_resources as _pkg_resources
from .scheduler import QueueScheduler
from .executor import OneOffExecutor
from .messages import PythonTask, PythonTaskStatus # important to register classes
logging.basicConfig(level=logging.INFO,
format='%(relativeCreated)6d %(threadName)s %(message)s')
__version__ = _pkg_resources.get_distribution('satyr').version
__all__ = ('QueueScheduler',
'OneOffExecutor',
'PythonTask',
'PythonTaskStatus')
| <commit_before>from __future__ import absolute_import, division, print_function
import logging
import pkg_resources as _pkg_resources
from .scheduler import QueueScheduler
from .executor import OneOffExecutor
from .messages import PythonTask, PythonTaskStatus # important to register classes
logging.basicConfig(level=logging.DEBUG,
format='%(relativeCreated)6d %(threadName)s %(message)s')
__version__ = _pkg_resources.get_distribution('satyr').version
__all__ = ('QueueScheduler',
'OneOffExecutor',
'PythonTask',
'PythonTaskStatus')
<commit_msg>Set default logging level to INFO<commit_after>from __future__ import absolute_import, division, print_function
import logging
import pkg_resources as _pkg_resources
from .scheduler import QueueScheduler
from .executor import OneOffExecutor
from .messages import PythonTask, PythonTaskStatus # important to register classes
logging.basicConfig(level=logging.INFO,
format='%(relativeCreated)6d %(threadName)s %(message)s')
__version__ = _pkg_resources.get_distribution('satyr').version
__all__ = ('QueueScheduler',
'OneOffExecutor',
'PythonTask',
'PythonTaskStatus')
|
bcef6c233fd607d160bc9042c7957abcea1e43cd | ycml/transformers/base.py | ycml/transformers/base.py | import logging
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from ..utils import Timer
__all__ = ['PureTransformer', 'identity']
logger = logging.getLogger(__name__)
# Helper class. A transformer that only does transformation and does not need to fit any internal parameters.
class PureTransformer(BaseEstimator, TransformerMixin):
def __init__(self, nparray=True, **kwargs):
super(PureTransformer, self).__init__(**kwargs)
self.nparray = nparray
#end def
def fit(self, X, y=None, **fit_params): return self
def transform(self, X, **kwargs):
timer = Timer()
transformed = self._transform(X, **kwargs)
if self.nparray: transformed = np.array(transformed)
logger.debug('Done <{}> transformation{}.'.format(type(self).__name__, timer))
return transformed
#end def
def _transform(self, X, y=None):
return [self.transform_one(row) for row in X]
#end def
def transform_one(self, x):
raise NotImplementedError('transform_one method needs to be implemented.')
#end class
def identity(x): return x
| import logging
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from ..utils import Timer
__all__ = ['PureTransformer', 'identity']
logger = logging.getLogger(__name__)
# Helper class. A transformer that only does transformation and does not need to fit any internal parameters.
class PureTransformer(BaseEstimator, TransformerMixin):
def __init__(self, nparray=True, **kwargs):
super(PureTransformer, self).__init__(**kwargs)
self.nparray = nparray
#end def
def fit(self, X, y=None, **fit_params): return self
def transform(self, X, **kwargs):
timer = Timer()
transformed = self._transform(X, **kwargs)
if self.nparray:
transformed = np.array(transformed)
if transformed.ndim == 1:
transformed = transformed.reshape(transformed.shape[0], 1)
#end if
logger.debug('Done <{}> transformation{}.'.format(type(self).__name__, timer))
return transformed
#end def
def _transform(self, X, y=None):
return [self.transform_one(row) for row in X]
#end def
def transform_one(self, x):
raise NotImplementedError('transform_one method needs to be implemented.')
#end class
def identity(x): return x
| Reshape transformers to 2D matrix | Reshape transformers to 2D matrix
| Python | apache-2.0 | skylander86/ycml | import logging
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from ..utils import Timer
__all__ = ['PureTransformer', 'identity']
logger = logging.getLogger(__name__)
# Helper class. A transformer that only does transformation and does not need to fit any internal parameters.
class PureTransformer(BaseEstimator, TransformerMixin):
def __init__(self, nparray=True, **kwargs):
super(PureTransformer, self).__init__(**kwargs)
self.nparray = nparray
#end def
def fit(self, X, y=None, **fit_params): return self
def transform(self, X, **kwargs):
timer = Timer()
transformed = self._transform(X, **kwargs)
if self.nparray: transformed = np.array(transformed)
logger.debug('Done <{}> transformation{}.'.format(type(self).__name__, timer))
return transformed
#end def
def _transform(self, X, y=None):
return [self.transform_one(row) for row in X]
#end def
def transform_one(self, x):
raise NotImplementedError('transform_one method needs to be implemented.')
#end class
def identity(x): return x
Reshape transformers to 2D matrix | import logging
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from ..utils import Timer
__all__ = ['PureTransformer', 'identity']
logger = logging.getLogger(__name__)
# Helper class. A transformer that only does transformation and does not need to fit any internal parameters.
class PureTransformer(BaseEstimator, TransformerMixin):
def __init__(self, nparray=True, **kwargs):
super(PureTransformer, self).__init__(**kwargs)
self.nparray = nparray
#end def
def fit(self, X, y=None, **fit_params): return self
def transform(self, X, **kwargs):
timer = Timer()
transformed = self._transform(X, **kwargs)
if self.nparray:
transformed = np.array(transformed)
if transformed.ndim == 1:
transformed = transformed.reshape(transformed.shape[0], 1)
#end if
logger.debug('Done <{}> transformation{}.'.format(type(self).__name__, timer))
return transformed
#end def
def _transform(self, X, y=None):
return [self.transform_one(row) for row in X]
#end def
def transform_one(self, x):
raise NotImplementedError('transform_one method needs to be implemented.')
#end class
def identity(x): return x
| <commit_before>import logging
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from ..utils import Timer
__all__ = ['PureTransformer', 'identity']
logger = logging.getLogger(__name__)
# Helper class. A transformer that only does transformation and does not need to fit any internal parameters.
class PureTransformer(BaseEstimator, TransformerMixin):
def __init__(self, nparray=True, **kwargs):
super(PureTransformer, self).__init__(**kwargs)
self.nparray = nparray
#end def
def fit(self, X, y=None, **fit_params): return self
def transform(self, X, **kwargs):
timer = Timer()
transformed = self._transform(X, **kwargs)
if self.nparray: transformed = np.array(transformed)
logger.debug('Done <{}> transformation{}.'.format(type(self).__name__, timer))
return transformed
#end def
def _transform(self, X, y=None):
return [self.transform_one(row) for row in X]
#end def
def transform_one(self, x):
raise NotImplementedError('transform_one method needs to be implemented.')
#end class
def identity(x): return x
<commit_msg>Reshape transformers to 2D matrix<commit_after> | import logging
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from ..utils import Timer
__all__ = ['PureTransformer', 'identity']
logger = logging.getLogger(__name__)
# Helper class. A transformer that only does transformation and does not need to fit any internal parameters.
class PureTransformer(BaseEstimator, TransformerMixin):
def __init__(self, nparray=True, **kwargs):
super(PureTransformer, self).__init__(**kwargs)
self.nparray = nparray
#end def
def fit(self, X, y=None, **fit_params): return self
def transform(self, X, **kwargs):
timer = Timer()
transformed = self._transform(X, **kwargs)
if self.nparray:
transformed = np.array(transformed)
if transformed.ndim == 1:
transformed = transformed.reshape(transformed.shape[0], 1)
#end if
logger.debug('Done <{}> transformation{}.'.format(type(self).__name__, timer))
return transformed
#end def
def _transform(self, X, y=None):
return [self.transform_one(row) for row in X]
#end def
def transform_one(self, x):
raise NotImplementedError('transform_one method needs to be implemented.')
#end class
def identity(x): return x
| import logging
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from ..utils import Timer
__all__ = ['PureTransformer', 'identity']
logger = logging.getLogger(__name__)
# Helper class. A transformer that only does transformation and does not need to fit any internal parameters.
class PureTransformer(BaseEstimator, TransformerMixin):
def __init__(self, nparray=True, **kwargs):
super(PureTransformer, self).__init__(**kwargs)
self.nparray = nparray
#end def
def fit(self, X, y=None, **fit_params): return self
def transform(self, X, **kwargs):
timer = Timer()
transformed = self._transform(X, **kwargs)
if self.nparray: transformed = np.array(transformed)
logger.debug('Done <{}> transformation{}.'.format(type(self).__name__, timer))
return transformed
#end def
def _transform(self, X, y=None):
return [self.transform_one(row) for row in X]
#end def
def transform_one(self, x):
raise NotImplementedError('transform_one method needs to be implemented.')
#end class
def identity(x): return x
Reshape transformers to 2D matriximport logging
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from ..utils import Timer
__all__ = ['PureTransformer', 'identity']
logger = logging.getLogger(__name__)
# Helper class. A transformer that only does transformation and does not need to fit any internal parameters.
class PureTransformer(BaseEstimator, TransformerMixin):
def __init__(self, nparray=True, **kwargs):
super(PureTransformer, self).__init__(**kwargs)
self.nparray = nparray
#end def
def fit(self, X, y=None, **fit_params): return self
def transform(self, X, **kwargs):
timer = Timer()
transformed = self._transform(X, **kwargs)
if self.nparray:
transformed = np.array(transformed)
if transformed.ndim == 1:
transformed = transformed.reshape(transformed.shape[0], 1)
#end if
logger.debug('Done <{}> transformation{}.'.format(type(self).__name__, timer))
return transformed
#end def
def _transform(self, X, y=None):
return [self.transform_one(row) for row in X]
#end def
def transform_one(self, x):
raise NotImplementedError('transform_one method needs to be implemented.')
#end class
def identity(x): return x
| <commit_before>import logging
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from ..utils import Timer
__all__ = ['PureTransformer', 'identity']
logger = logging.getLogger(__name__)
# Helper class. A transformer that only does transformation and does not need to fit any internal parameters.
class PureTransformer(BaseEstimator, TransformerMixin):
def __init__(self, nparray=True, **kwargs):
super(PureTransformer, self).__init__(**kwargs)
self.nparray = nparray
#end def
def fit(self, X, y=None, **fit_params): return self
def transform(self, X, **kwargs):
timer = Timer()
transformed = self._transform(X, **kwargs)
if self.nparray: transformed = np.array(transformed)
logger.debug('Done <{}> transformation{}.'.format(type(self).__name__, timer))
return transformed
#end def
def _transform(self, X, y=None):
return [self.transform_one(row) for row in X]
#end def
def transform_one(self, x):
raise NotImplementedError('transform_one method needs to be implemented.')
#end class
def identity(x): return x
<commit_msg>Reshape transformers to 2D matrix<commit_after>import logging
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from ..utils import Timer
__all__ = ['PureTransformer', 'identity']
logger = logging.getLogger(__name__)
# Helper class. A transformer that only does transformation and does not need to fit any internal parameters.
class PureTransformer(BaseEstimator, TransformerMixin):
def __init__(self, nparray=True, **kwargs):
super(PureTransformer, self).__init__(**kwargs)
self.nparray = nparray
#end def
def fit(self, X, y=None, **fit_params): return self
def transform(self, X, **kwargs):
timer = Timer()
transformed = self._transform(X, **kwargs)
if self.nparray:
transformed = np.array(transformed)
if transformed.ndim == 1:
transformed = transformed.reshape(transformed.shape[0], 1)
#end if
logger.debug('Done <{}> transformation{}.'.format(type(self).__name__, timer))
return transformed
#end def
def _transform(self, X, y=None):
return [self.transform_one(row) for row in X]
#end def
def transform_one(self, x):
raise NotImplementedError('transform_one method needs to be implemented.')
#end class
def identity(x): return x
|
c7daef487fee51b68d410d2f4be3fd16068c7d5a | tests/export/test_task_types_to_csv.py | tests/export/test_task_types_to_csv.py | from tests.base import ApiDBTestCase
class TasksCsvExportTestCase(ApiDBTestCase):
def setUp(self):
super(TasksCsvExportTestCase, self).setUp()
self.generate_fixture_project_status()
self.generate_fixture_project()
self.generate_fixture_asset_type()
self.generate_fixture_department()
self.generate_fixture_task_type()
def test_get_output_files(self):
csv_task_types = self.get_raw("export/csv/task-types.csv")
expected_result = """Department;Name\r
Animation;Animation\r
Modeling;Shaders\r
"""
self.assertEqual(csv_task_types, expected_result)
| from tests.base import ApiDBTestCase
class TasksCsvExportTestCase(ApiDBTestCase):
def setUp(self):
super(TasksCsvExportTestCase, self).setUp()
self.generate_fixture_project_status()
self.generate_fixture_project()
self.generate_fixture_asset_type()
self.generate_fixture_department()
self.generate_fixture_task_type()
def test_get_output_files(self):
csv_task_types = self.get_raw("export/csv/task-types.csv")
expected_result = """Department;Name\r
Animation;Animation\r
Animation;Layout\r
Modeling;Shaders\r
"""
self.assertEqual(csv_task_types, expected_result)
| Fix task type export test | Fix task type export test
| Python | agpl-3.0 | cgwire/zou | from tests.base import ApiDBTestCase
class TasksCsvExportTestCase(ApiDBTestCase):
def setUp(self):
super(TasksCsvExportTestCase, self).setUp()
self.generate_fixture_project_status()
self.generate_fixture_project()
self.generate_fixture_asset_type()
self.generate_fixture_department()
self.generate_fixture_task_type()
def test_get_output_files(self):
csv_task_types = self.get_raw("export/csv/task-types.csv")
expected_result = """Department;Name\r
Animation;Animation\r
Modeling;Shaders\r
"""
self.assertEqual(csv_task_types, expected_result)
Fix task type export test | from tests.base import ApiDBTestCase
class TasksCsvExportTestCase(ApiDBTestCase):
def setUp(self):
super(TasksCsvExportTestCase, self).setUp()
self.generate_fixture_project_status()
self.generate_fixture_project()
self.generate_fixture_asset_type()
self.generate_fixture_department()
self.generate_fixture_task_type()
def test_get_output_files(self):
csv_task_types = self.get_raw("export/csv/task-types.csv")
expected_result = """Department;Name\r
Animation;Animation\r
Animation;Layout\r
Modeling;Shaders\r
"""
self.assertEqual(csv_task_types, expected_result)
| <commit_before>from tests.base import ApiDBTestCase
class TasksCsvExportTestCase(ApiDBTestCase):
def setUp(self):
super(TasksCsvExportTestCase, self).setUp()
self.generate_fixture_project_status()
self.generate_fixture_project()
self.generate_fixture_asset_type()
self.generate_fixture_department()
self.generate_fixture_task_type()
def test_get_output_files(self):
csv_task_types = self.get_raw("export/csv/task-types.csv")
expected_result = """Department;Name\r
Animation;Animation\r
Modeling;Shaders\r
"""
self.assertEqual(csv_task_types, expected_result)
<commit_msg>Fix task type export test<commit_after> | from tests.base import ApiDBTestCase
class TasksCsvExportTestCase(ApiDBTestCase):
def setUp(self):
super(TasksCsvExportTestCase, self).setUp()
self.generate_fixture_project_status()
self.generate_fixture_project()
self.generate_fixture_asset_type()
self.generate_fixture_department()
self.generate_fixture_task_type()
def test_get_output_files(self):
csv_task_types = self.get_raw("export/csv/task-types.csv")
expected_result = """Department;Name\r
Animation;Animation\r
Animation;Layout\r
Modeling;Shaders\r
"""
self.assertEqual(csv_task_types, expected_result)
| from tests.base import ApiDBTestCase
class TasksCsvExportTestCase(ApiDBTestCase):
def setUp(self):
super(TasksCsvExportTestCase, self).setUp()
self.generate_fixture_project_status()
self.generate_fixture_project()
self.generate_fixture_asset_type()
self.generate_fixture_department()
self.generate_fixture_task_type()
def test_get_output_files(self):
csv_task_types = self.get_raw("export/csv/task-types.csv")
expected_result = """Department;Name\r
Animation;Animation\r
Modeling;Shaders\r
"""
self.assertEqual(csv_task_types, expected_result)
Fix task type export testfrom tests.base import ApiDBTestCase
class TasksCsvExportTestCase(ApiDBTestCase):
def setUp(self):
super(TasksCsvExportTestCase, self).setUp()
self.generate_fixture_project_status()
self.generate_fixture_project()
self.generate_fixture_asset_type()
self.generate_fixture_department()
self.generate_fixture_task_type()
def test_get_output_files(self):
csv_task_types = self.get_raw("export/csv/task-types.csv")
expected_result = """Department;Name\r
Animation;Animation\r
Animation;Layout\r
Modeling;Shaders\r
"""
self.assertEqual(csv_task_types, expected_result)
| <commit_before>from tests.base import ApiDBTestCase
class TasksCsvExportTestCase(ApiDBTestCase):
def setUp(self):
super(TasksCsvExportTestCase, self).setUp()
self.generate_fixture_project_status()
self.generate_fixture_project()
self.generate_fixture_asset_type()
self.generate_fixture_department()
self.generate_fixture_task_type()
def test_get_output_files(self):
csv_task_types = self.get_raw("export/csv/task-types.csv")
expected_result = """Department;Name\r
Animation;Animation\r
Modeling;Shaders\r
"""
self.assertEqual(csv_task_types, expected_result)
<commit_msg>Fix task type export test<commit_after>from tests.base import ApiDBTestCase
class TasksCsvExportTestCase(ApiDBTestCase):
def setUp(self):
super(TasksCsvExportTestCase, self).setUp()
self.generate_fixture_project_status()
self.generate_fixture_project()
self.generate_fixture_asset_type()
self.generate_fixture_department()
self.generate_fixture_task_type()
def test_get_output_files(self):
csv_task_types = self.get_raw("export/csv/task-types.csv")
expected_result = """Department;Name\r
Animation;Animation\r
Animation;Layout\r
Modeling;Shaders\r
"""
self.assertEqual(csv_task_types, expected_result)
|
b77d4a534f5f6435f0f60c0a082b9ae02673d574 | tests/twisted/connect/network-error.py | tests/twisted/connect/network-error.py |
"""
Connection is disconnected because server closes its TCP stream abruptly.
"""
from gabbletest import exec_test
from servicetest import EventPattern
import constants as cs
import sys
def test(q, bus, conn, stream):
conn.Connect()
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTING, cs.CSR_REQUESTED])
q.expect('stream-authenticated')
q.expect('dbus-signal', signal='PresenceUpdate',
args=[{1L: (0L, {u'available': {}})}])
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTED, cs.CSR_REQUESTED])
# server closes its stream
stream.transport.loseConnection()
# Gabble disconnect and close its connection
q.expect('dbus-signal',
signal='NameOwnerChanged',
predicate=lambda e: cs.CONN + '.gabble.jabber' in str(e.args[0])
and str(e.args[1]) != ''
and str(e.args[2]) == '')
if __name__ == '__main__':
exec_test(test)
|
"""
Connection is disconnected because server closes its TCP stream abruptly.
"""
from gabbletest import exec_test
from servicetest import EventPattern
import constants as cs
import sys
def test(q, bus, conn, stream):
conn.Connect()
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTING, cs.CSR_REQUESTED])
q.expect('stream-authenticated')
q.expect('dbus-signal', signal='PresenceUpdate',
args=[{1L: (0L, {u'available': {}})}])
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTED, cs.CSR_REQUESTED])
# server closes its stream
stream.transport.loseConnection()
# Gabble disconnect and close its connection
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_DISCONNECTED, cs.CSR_NONE_SPECIFIED])
q.expect('dbus-signal',
signal='NameOwnerChanged',
predicate=lambda e: cs.CONN + '.gabble.jabber' in str(e.args[0])
and str(e.args[1]) != ''
and str(e.args[2]) == '')
if __name__ == '__main__':
exec_test(test)
| Make sure state change signal to 'disconnected' is also sent. | Make sure state change signal to 'disconnected' is also sent.
| Python | lgpl-2.1 | Ziemin/telepathy-gabble,jku/telepathy-gabble,mlundblad/telepathy-gabble,Ziemin/telepathy-gabble,jku/telepathy-gabble,Ziemin/telepathy-gabble,Ziemin/telepathy-gabble,jku/telepathy-gabble,mlundblad/telepathy-gabble,mlundblad/telepathy-gabble |
"""
Connection is disconnected because server closes its TCP stream abruptly.
"""
from gabbletest import exec_test
from servicetest import EventPattern
import constants as cs
import sys
def test(q, bus, conn, stream):
conn.Connect()
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTING, cs.CSR_REQUESTED])
q.expect('stream-authenticated')
q.expect('dbus-signal', signal='PresenceUpdate',
args=[{1L: (0L, {u'available': {}})}])
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTED, cs.CSR_REQUESTED])
# server closes its stream
stream.transport.loseConnection()
# Gabble disconnect and close its connection
q.expect('dbus-signal',
signal='NameOwnerChanged',
predicate=lambda e: cs.CONN + '.gabble.jabber' in str(e.args[0])
and str(e.args[1]) != ''
and str(e.args[2]) == '')
if __name__ == '__main__':
exec_test(test)
Make sure state change signal to 'disconnected' is also sent. |
"""
Connection is disconnected because server closes its TCP stream abruptly.
"""
from gabbletest import exec_test
from servicetest import EventPattern
import constants as cs
import sys
def test(q, bus, conn, stream):
conn.Connect()
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTING, cs.CSR_REQUESTED])
q.expect('stream-authenticated')
q.expect('dbus-signal', signal='PresenceUpdate',
args=[{1L: (0L, {u'available': {}})}])
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTED, cs.CSR_REQUESTED])
# server closes its stream
stream.transport.loseConnection()
# Gabble disconnect and close its connection
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_DISCONNECTED, cs.CSR_NONE_SPECIFIED])
q.expect('dbus-signal',
signal='NameOwnerChanged',
predicate=lambda e: cs.CONN + '.gabble.jabber' in str(e.args[0])
and str(e.args[1]) != ''
and str(e.args[2]) == '')
if __name__ == '__main__':
exec_test(test)
| <commit_before>
"""
Connection is disconnected because server closes its TCP stream abruptly.
"""
from gabbletest import exec_test
from servicetest import EventPattern
import constants as cs
import sys
def test(q, bus, conn, stream):
conn.Connect()
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTING, cs.CSR_REQUESTED])
q.expect('stream-authenticated')
q.expect('dbus-signal', signal='PresenceUpdate',
args=[{1L: (0L, {u'available': {}})}])
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTED, cs.CSR_REQUESTED])
# server closes its stream
stream.transport.loseConnection()
# Gabble disconnect and close its connection
q.expect('dbus-signal',
signal='NameOwnerChanged',
predicate=lambda e: cs.CONN + '.gabble.jabber' in str(e.args[0])
and str(e.args[1]) != ''
and str(e.args[2]) == '')
if __name__ == '__main__':
exec_test(test)
<commit_msg>Make sure state change signal to 'disconnected' is also sent.<commit_after> |
"""
Connection is disconnected because server closes its TCP stream abruptly.
"""
from gabbletest import exec_test
from servicetest import EventPattern
import constants as cs
import sys
def test(q, bus, conn, stream):
conn.Connect()
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTING, cs.CSR_REQUESTED])
q.expect('stream-authenticated')
q.expect('dbus-signal', signal='PresenceUpdate',
args=[{1L: (0L, {u'available': {}})}])
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTED, cs.CSR_REQUESTED])
# server closes its stream
stream.transport.loseConnection()
# Gabble disconnect and close its connection
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_DISCONNECTED, cs.CSR_NONE_SPECIFIED])
q.expect('dbus-signal',
signal='NameOwnerChanged',
predicate=lambda e: cs.CONN + '.gabble.jabber' in str(e.args[0])
and str(e.args[1]) != ''
and str(e.args[2]) == '')
if __name__ == '__main__':
exec_test(test)
|
"""
Connection is disconnected because server closes its TCP stream abruptly.
"""
from gabbletest import exec_test
from servicetest import EventPattern
import constants as cs
import sys
def test(q, bus, conn, stream):
conn.Connect()
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTING, cs.CSR_REQUESTED])
q.expect('stream-authenticated')
q.expect('dbus-signal', signal='PresenceUpdate',
args=[{1L: (0L, {u'available': {}})}])
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTED, cs.CSR_REQUESTED])
# server closes its stream
stream.transport.loseConnection()
# Gabble disconnect and close its connection
q.expect('dbus-signal',
signal='NameOwnerChanged',
predicate=lambda e: cs.CONN + '.gabble.jabber' in str(e.args[0])
and str(e.args[1]) != ''
and str(e.args[2]) == '')
if __name__ == '__main__':
exec_test(test)
Make sure state change signal to 'disconnected' is also sent.
"""
Connection is disconnected because server closes its TCP stream abruptly.
"""
from gabbletest import exec_test
from servicetest import EventPattern
import constants as cs
import sys
def test(q, bus, conn, stream):
conn.Connect()
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTING, cs.CSR_REQUESTED])
q.expect('stream-authenticated')
q.expect('dbus-signal', signal='PresenceUpdate',
args=[{1L: (0L, {u'available': {}})}])
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTED, cs.CSR_REQUESTED])
# server closes its stream
stream.transport.loseConnection()
# Gabble disconnect and close its connection
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_DISCONNECTED, cs.CSR_NONE_SPECIFIED])
q.expect('dbus-signal',
signal='NameOwnerChanged',
predicate=lambda e: cs.CONN + '.gabble.jabber' in str(e.args[0])
and str(e.args[1]) != ''
and str(e.args[2]) == '')
if __name__ == '__main__':
exec_test(test)
| <commit_before>
"""
Connection is disconnected because server closes its TCP stream abruptly.
"""
from gabbletest import exec_test
from servicetest import EventPattern
import constants as cs
import sys
def test(q, bus, conn, stream):
conn.Connect()
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTING, cs.CSR_REQUESTED])
q.expect('stream-authenticated')
q.expect('dbus-signal', signal='PresenceUpdate',
args=[{1L: (0L, {u'available': {}})}])
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTED, cs.CSR_REQUESTED])
# server closes its stream
stream.transport.loseConnection()
# Gabble disconnect and close its connection
q.expect('dbus-signal',
signal='NameOwnerChanged',
predicate=lambda e: cs.CONN + '.gabble.jabber' in str(e.args[0])
and str(e.args[1]) != ''
and str(e.args[2]) == '')
if __name__ == '__main__':
exec_test(test)
<commit_msg>Make sure state change signal to 'disconnected' is also sent.<commit_after>
"""
Connection is disconnected because server closes its TCP stream abruptly.
"""
from gabbletest import exec_test
from servicetest import EventPattern
import constants as cs
import sys
def test(q, bus, conn, stream):
conn.Connect()
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTING, cs.CSR_REQUESTED])
q.expect('stream-authenticated')
q.expect('dbus-signal', signal='PresenceUpdate',
args=[{1L: (0L, {u'available': {}})}])
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTED, cs.CSR_REQUESTED])
# server closes its stream
stream.transport.loseConnection()
# Gabble disconnect and close its connection
q.expect('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_DISCONNECTED, cs.CSR_NONE_SPECIFIED])
q.expect('dbus-signal',
signal='NameOwnerChanged',
predicate=lambda e: cs.CONN + '.gabble.jabber' in str(e.args[0])
and str(e.args[1]) != ''
and str(e.args[2]) == '')
if __name__ == '__main__':
exec_test(test)
|
d1614d3747f72c1f32e74afb6e4b98eb476c7266 | utils/layers_test.py | utils/layers_test.py | # Lint as: python3
"""Tests for spectral."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import os
import layers
class LayersTest(tf.test.TestCase):
def test_conv_transpose_shape(self):
inputs = np.random.normal(size=(10, 5, 2)).astype(np.float32)
conv_transpose = layers.Conv1DTranspose(
filters=2, kernel_size=1, strides=1
)
outputs = conv_transpose(inputs)
self.assertShapeEqual(inputs, outputs)
if __name__ == '__main__':
os.environ["CUDA_VISIBLE_DEVICES"] = ''
tf.test.main()
| # Lint as: python3
"""Tests for spectral."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import os
import layers
class LayersTest(tf.test.TestCase):
def test_conv_transpose_shape(self):
inputs = np.random.normal(size=(10, 5, 2)).astype(np.float32)
conv_transpose = layers.Conv1DTranspose(
filters=2, kernel_size=1, strides=1
)
outputs = conv_transpose(inputs)
self.assertShapeEqual(inputs, outputs)
def test_conv_transpose_shape_upscale(self):
inputs = np.random.normal(size=(10, 5, 2)).astype(np.float32)
conv_transpose = layers.Conv1DTranspose(
filters=2, kernel_size=1, strides=2
)
outputs = conv_transpose(inputs)
self.assertEqual((10, 10, 2), outputs.shape)
if __name__ == '__main__':
os.environ["CUDA_VISIBLE_DEVICES"] = ''
tf.test.main()
| Add Second Shape Test for Layers Util | Add Second Shape Test for Layers Util
| Python | apache-2.0 | googleinterns/audio_synthesis | # Lint as: python3
"""Tests for spectral."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import os
import layers
class LayersTest(tf.test.TestCase):
def test_conv_transpose_shape(self):
inputs = np.random.normal(size=(10, 5, 2)).astype(np.float32)
conv_transpose = layers.Conv1DTranspose(
filters=2, kernel_size=1, strides=1
)
outputs = conv_transpose(inputs)
self.assertShapeEqual(inputs, outputs)
if __name__ == '__main__':
os.environ["CUDA_VISIBLE_DEVICES"] = ''
tf.test.main()
Add Second Shape Test for Layers Util | # Lint as: python3
"""Tests for spectral."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import os
import layers
class LayersTest(tf.test.TestCase):
def test_conv_transpose_shape(self):
inputs = np.random.normal(size=(10, 5, 2)).astype(np.float32)
conv_transpose = layers.Conv1DTranspose(
filters=2, kernel_size=1, strides=1
)
outputs = conv_transpose(inputs)
self.assertShapeEqual(inputs, outputs)
def test_conv_transpose_shape_upscale(self):
inputs = np.random.normal(size=(10, 5, 2)).astype(np.float32)
conv_transpose = layers.Conv1DTranspose(
filters=2, kernel_size=1, strides=2
)
outputs = conv_transpose(inputs)
self.assertEqual((10, 10, 2), outputs.shape)
if __name__ == '__main__':
os.environ["CUDA_VISIBLE_DEVICES"] = ''
tf.test.main()
| <commit_before># Lint as: python3
"""Tests for spectral."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import os
import layers
class LayersTest(tf.test.TestCase):
def test_conv_transpose_shape(self):
inputs = np.random.normal(size=(10, 5, 2)).astype(np.float32)
conv_transpose = layers.Conv1DTranspose(
filters=2, kernel_size=1, strides=1
)
outputs = conv_transpose(inputs)
self.assertShapeEqual(inputs, outputs)
if __name__ == '__main__':
os.environ["CUDA_VISIBLE_DEVICES"] = ''
tf.test.main()
<commit_msg>Add Second Shape Test for Layers Util<commit_after> | # Lint as: python3
"""Tests for spectral."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import os
import layers
class LayersTest(tf.test.TestCase):
def test_conv_transpose_shape(self):
inputs = np.random.normal(size=(10, 5, 2)).astype(np.float32)
conv_transpose = layers.Conv1DTranspose(
filters=2, kernel_size=1, strides=1
)
outputs = conv_transpose(inputs)
self.assertShapeEqual(inputs, outputs)
def test_conv_transpose_shape_upscale(self):
inputs = np.random.normal(size=(10, 5, 2)).astype(np.float32)
conv_transpose = layers.Conv1DTranspose(
filters=2, kernel_size=1, strides=2
)
outputs = conv_transpose(inputs)
self.assertEqual((10, 10, 2), outputs.shape)
if __name__ == '__main__':
os.environ["CUDA_VISIBLE_DEVICES"] = ''
tf.test.main()
| # Lint as: python3
"""Tests for spectral."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import os
import layers
class LayersTest(tf.test.TestCase):
def test_conv_transpose_shape(self):
inputs = np.random.normal(size=(10, 5, 2)).astype(np.float32)
conv_transpose = layers.Conv1DTranspose(
filters=2, kernel_size=1, strides=1
)
outputs = conv_transpose(inputs)
self.assertShapeEqual(inputs, outputs)
if __name__ == '__main__':
os.environ["CUDA_VISIBLE_DEVICES"] = ''
tf.test.main()
Add Second Shape Test for Layers Util# Lint as: python3
"""Tests for spectral."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import os
import layers
class LayersTest(tf.test.TestCase):
def test_conv_transpose_shape(self):
inputs = np.random.normal(size=(10, 5, 2)).astype(np.float32)
conv_transpose = layers.Conv1DTranspose(
filters=2, kernel_size=1, strides=1
)
outputs = conv_transpose(inputs)
self.assertShapeEqual(inputs, outputs)
def test_conv_transpose_shape_upscale(self):
inputs = np.random.normal(size=(10, 5, 2)).astype(np.float32)
conv_transpose = layers.Conv1DTranspose(
filters=2, kernel_size=1, strides=2
)
outputs = conv_transpose(inputs)
self.assertEqual((10, 10, 2), outputs.shape)
if __name__ == '__main__':
os.environ["CUDA_VISIBLE_DEVICES"] = ''
tf.test.main()
| <commit_before># Lint as: python3
"""Tests for spectral."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import os
import layers
class LayersTest(tf.test.TestCase):
def test_conv_transpose_shape(self):
inputs = np.random.normal(size=(10, 5, 2)).astype(np.float32)
conv_transpose = layers.Conv1DTranspose(
filters=2, kernel_size=1, strides=1
)
outputs = conv_transpose(inputs)
self.assertShapeEqual(inputs, outputs)
if __name__ == '__main__':
os.environ["CUDA_VISIBLE_DEVICES"] = ''
tf.test.main()
<commit_msg>Add Second Shape Test for Layers Util<commit_after># Lint as: python3
"""Tests for spectral."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import os
import layers
class LayersTest(tf.test.TestCase):
def test_conv_transpose_shape(self):
inputs = np.random.normal(size=(10, 5, 2)).astype(np.float32)
conv_transpose = layers.Conv1DTranspose(
filters=2, kernel_size=1, strides=1
)
outputs = conv_transpose(inputs)
self.assertShapeEqual(inputs, outputs)
def test_conv_transpose_shape_upscale(self):
inputs = np.random.normal(size=(10, 5, 2)).astype(np.float32)
conv_transpose = layers.Conv1DTranspose(
filters=2, kernel_size=1, strides=2
)
outputs = conv_transpose(inputs)
self.assertEqual((10, 10, 2), outputs.shape)
if __name__ == '__main__':
os.environ["CUDA_VISIBLE_DEVICES"] = ''
tf.test.main()
|
2450955e2beb14e4c6ba0394e4bcd64e2ce2e4ec | wordcloud/views.py | wordcloud/views.py | import json
import os
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from .wordcloud import popular_words
@cache_page(60*60*4)
def wordcloud(request, max_entries=30):
""" Return tag cloud JSON results"""
max_entries = int(max_entries)
leaf_name = 'wordcloud-{0}.json'.format(max_entries)
cache_path = os.path.join(
settings.MEDIA_ROOT, 'wordcloud_cache', leaf_name
)
if os.path.exists(cache_path):
response = HttpResponse()
response['Content-Type'] = 'application/json'
response['X-Sendfile'] = cache_path.encode('utf-8')
return response
content = json.dumps(popular_words(max_entries=max_entries))
return HttpResponse(
content,
content_type='application/json',
)
| import json
import os
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from .wordcloud import popular_words
@cache_page(60*60*4)
def wordcloud(request, max_entries=30):
""" Return tag cloud JSON results"""
max_entries = int(max_entries)
leaf_name = 'wordcloud-{0}.json'.format(max_entries)
cache_path = os.path.join(
settings.MEDIA_ROOT, 'wordcloud_cache', leaf_name
)
if os.path.exists(cache_path):
response = HttpResponse(json.dumps({
'error':
("If you can see this, then X-SendFile isn't configured "
"correctly in your webserver. (If you're using Nginx, you'll "
"have to change the code to add a X-Accel-Redirect header - "
"this hasn't currently been tested.)")
}))
response['Content-Type'] = 'application/json'
response['X-Sendfile'] = cache_path.encode('utf-8')
return response
content = json.dumps(popular_words(max_entries=max_entries))
return HttpResponse(
content,
content_type='application/json',
)
| Add diagnostic output for when X-SendFile is misconfigured | Add diagnostic output for when X-SendFile is misconfigured
| Python | agpl-3.0 | mysociety/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,mysociety/pombola | import json
import os
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from .wordcloud import popular_words
@cache_page(60*60*4)
def wordcloud(request, max_entries=30):
""" Return tag cloud JSON results"""
max_entries = int(max_entries)
leaf_name = 'wordcloud-{0}.json'.format(max_entries)
cache_path = os.path.join(
settings.MEDIA_ROOT, 'wordcloud_cache', leaf_name
)
if os.path.exists(cache_path):
response = HttpResponse()
response['Content-Type'] = 'application/json'
response['X-Sendfile'] = cache_path.encode('utf-8')
return response
content = json.dumps(popular_words(max_entries=max_entries))
return HttpResponse(
content,
content_type='application/json',
)
Add diagnostic output for when X-SendFile is misconfigured | import json
import os
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from .wordcloud import popular_words
@cache_page(60*60*4)
def wordcloud(request, max_entries=30):
""" Return tag cloud JSON results"""
max_entries = int(max_entries)
leaf_name = 'wordcloud-{0}.json'.format(max_entries)
cache_path = os.path.join(
settings.MEDIA_ROOT, 'wordcloud_cache', leaf_name
)
if os.path.exists(cache_path):
response = HttpResponse(json.dumps({
'error':
("If you can see this, then X-SendFile isn't configured "
"correctly in your webserver. (If you're using Nginx, you'll "
"have to change the code to add a X-Accel-Redirect header - "
"this hasn't currently been tested.)")
}))
response['Content-Type'] = 'application/json'
response['X-Sendfile'] = cache_path.encode('utf-8')
return response
content = json.dumps(popular_words(max_entries=max_entries))
return HttpResponse(
content,
content_type='application/json',
)
| <commit_before>import json
import os
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from .wordcloud import popular_words
@cache_page(60*60*4)
def wordcloud(request, max_entries=30):
""" Return tag cloud JSON results"""
max_entries = int(max_entries)
leaf_name = 'wordcloud-{0}.json'.format(max_entries)
cache_path = os.path.join(
settings.MEDIA_ROOT, 'wordcloud_cache', leaf_name
)
if os.path.exists(cache_path):
response = HttpResponse()
response['Content-Type'] = 'application/json'
response['X-Sendfile'] = cache_path.encode('utf-8')
return response
content = json.dumps(popular_words(max_entries=max_entries))
return HttpResponse(
content,
content_type='application/json',
)
<commit_msg>Add diagnostic output for when X-SendFile is misconfigured<commit_after> | import json
import os
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from .wordcloud import popular_words
@cache_page(60*60*4)
def wordcloud(request, max_entries=30):
""" Return tag cloud JSON results"""
max_entries = int(max_entries)
leaf_name = 'wordcloud-{0}.json'.format(max_entries)
cache_path = os.path.join(
settings.MEDIA_ROOT, 'wordcloud_cache', leaf_name
)
if os.path.exists(cache_path):
response = HttpResponse(json.dumps({
'error':
("If you can see this, then X-SendFile isn't configured "
"correctly in your webserver. (If you're using Nginx, you'll "
"have to change the code to add a X-Accel-Redirect header - "
"this hasn't currently been tested.)")
}))
response['Content-Type'] = 'application/json'
response['X-Sendfile'] = cache_path.encode('utf-8')
return response
content = json.dumps(popular_words(max_entries=max_entries))
return HttpResponse(
content,
content_type='application/json',
)
| import json
import os
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from .wordcloud import popular_words
@cache_page(60*60*4)
def wordcloud(request, max_entries=30):
""" Return tag cloud JSON results"""
max_entries = int(max_entries)
leaf_name = 'wordcloud-{0}.json'.format(max_entries)
cache_path = os.path.join(
settings.MEDIA_ROOT, 'wordcloud_cache', leaf_name
)
if os.path.exists(cache_path):
response = HttpResponse()
response['Content-Type'] = 'application/json'
response['X-Sendfile'] = cache_path.encode('utf-8')
return response
content = json.dumps(popular_words(max_entries=max_entries))
return HttpResponse(
content,
content_type='application/json',
)
Add diagnostic output for when X-SendFile is misconfiguredimport json
import os
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from .wordcloud import popular_words
@cache_page(60*60*4)
def wordcloud(request, max_entries=30):
""" Return tag cloud JSON results"""
max_entries = int(max_entries)
leaf_name = 'wordcloud-{0}.json'.format(max_entries)
cache_path = os.path.join(
settings.MEDIA_ROOT, 'wordcloud_cache', leaf_name
)
if os.path.exists(cache_path):
response = HttpResponse(json.dumps({
'error':
("If you can see this, then X-SendFile isn't configured "
"correctly in your webserver. (If you're using Nginx, you'll "
"have to change the code to add a X-Accel-Redirect header - "
"this hasn't currently been tested.)")
}))
response['Content-Type'] = 'application/json'
response['X-Sendfile'] = cache_path.encode('utf-8')
return response
content = json.dumps(popular_words(max_entries=max_entries))
return HttpResponse(
content,
content_type='application/json',
)
| <commit_before>import json
import os
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from .wordcloud import popular_words
@cache_page(60*60*4)
def wordcloud(request, max_entries=30):
""" Return tag cloud JSON results"""
max_entries = int(max_entries)
leaf_name = 'wordcloud-{0}.json'.format(max_entries)
cache_path = os.path.join(
settings.MEDIA_ROOT, 'wordcloud_cache', leaf_name
)
if os.path.exists(cache_path):
response = HttpResponse()
response['Content-Type'] = 'application/json'
response['X-Sendfile'] = cache_path.encode('utf-8')
return response
content = json.dumps(popular_words(max_entries=max_entries))
return HttpResponse(
content,
content_type='application/json',
)
<commit_msg>Add diagnostic output for when X-SendFile is misconfigured<commit_after>import json
import os
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from .wordcloud import popular_words
@cache_page(60*60*4)
def wordcloud(request, max_entries=30):
""" Return tag cloud JSON results"""
max_entries = int(max_entries)
leaf_name = 'wordcloud-{0}.json'.format(max_entries)
cache_path = os.path.join(
settings.MEDIA_ROOT, 'wordcloud_cache', leaf_name
)
if os.path.exists(cache_path):
response = HttpResponse(json.dumps({
'error':
("If you can see this, then X-SendFile isn't configured "
"correctly in your webserver. (If you're using Nginx, you'll "
"have to change the code to add a X-Accel-Redirect header - "
"this hasn't currently been tested.)")
}))
response['Content-Type'] = 'application/json'
response['X-Sendfile'] = cache_path.encode('utf-8')
return response
content = json.dumps(popular_words(max_entries=max_entries))
return HttpResponse(
content,
content_type='application/json',
)
|
4955e830d3130a6ae86d4a1c37db23777ee792d7 | go_http/__init__.py | go_http/__init__.py | """Vumi Go HTTP API client library."""
from .send import HttpApiSender, LoggingSender
__version__ = "0.3.1a0"
__all__ = [
'HttpApiSender', 'LoggingSender',
]
| """Vumi Go HTTP API client library."""
from .send import HttpApiSender, LoggingSender
from .account import AccountApiClient
__version__ = "0.3.1a0"
__all__ = [
'HttpApiSender', 'LoggingSender',
'AccountApiClient',
]
| Add AccountApiClient to top-level package. | Add AccountApiClient to top-level package.
| Python | bsd-3-clause | praekelt/go-http-api,praekelt/go-http-api | """Vumi Go HTTP API client library."""
from .send import HttpApiSender, LoggingSender
__version__ = "0.3.1a0"
__all__ = [
'HttpApiSender', 'LoggingSender',
]
Add AccountApiClient to top-level package. | """Vumi Go HTTP API client library."""
from .send import HttpApiSender, LoggingSender
from .account import AccountApiClient
__version__ = "0.3.1a0"
__all__ = [
'HttpApiSender', 'LoggingSender',
'AccountApiClient',
]
| <commit_before>"""Vumi Go HTTP API client library."""
from .send import HttpApiSender, LoggingSender
__version__ = "0.3.1a0"
__all__ = [
'HttpApiSender', 'LoggingSender',
]
<commit_msg>Add AccountApiClient to top-level package.<commit_after> | """Vumi Go HTTP API client library."""
from .send import HttpApiSender, LoggingSender
from .account import AccountApiClient
__version__ = "0.3.1a0"
__all__ = [
'HttpApiSender', 'LoggingSender',
'AccountApiClient',
]
| """Vumi Go HTTP API client library."""
from .send import HttpApiSender, LoggingSender
__version__ = "0.3.1a0"
__all__ = [
'HttpApiSender', 'LoggingSender',
]
Add AccountApiClient to top-level package."""Vumi Go HTTP API client library."""
from .send import HttpApiSender, LoggingSender
from .account import AccountApiClient
__version__ = "0.3.1a0"
__all__ = [
'HttpApiSender', 'LoggingSender',
'AccountApiClient',
]
| <commit_before>"""Vumi Go HTTP API client library."""
from .send import HttpApiSender, LoggingSender
__version__ = "0.3.1a0"
__all__ = [
'HttpApiSender', 'LoggingSender',
]
<commit_msg>Add AccountApiClient to top-level package.<commit_after>"""Vumi Go HTTP API client library."""
from .send import HttpApiSender, LoggingSender
from .account import AccountApiClient
__version__ = "0.3.1a0"
__all__ = [
'HttpApiSender', 'LoggingSender',
'AccountApiClient',
]
|
e37e964bf9d2819c0234303d31ed2839c317be04 | openquake/engine/tests/export/core_test.py | openquake/engine/tests/export/core_test.py |
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake 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.
#
# OpenQuake 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 Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
from openquake.commonlib import nrml
def number_of(elem_name, tree):
"""
Given an element name (including the namespaces prefix, if applicable),
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
return len(tree.xpath(expr, namespaces=nrml.PARSE_NS_MAP))
class BaseExportTestCase(unittest.TestCase):
def _test_exported_file(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isabs(filename))
self.assertTrue(os.path.getsize(filename) > 0)
|
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake 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.
#
# OpenQuake 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 Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
from openquake.commonlib import nrml
def number_of(elem_name, tree):
"""
Given an element name (including the namespaces prefix, if applicable),
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
return len(tree.xpath(expr, namespaces={'nrml': nrml.NRML05}))
class BaseExportTestCase(unittest.TestCase):
def _test_exported_file(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isabs(filename))
self.assertTrue(os.path.getsize(filename) > 0)
| Fix a broken export test | Fix a broken export test
| Python | agpl-3.0 | gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine |
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake 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.
#
# OpenQuake 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 Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
from openquake.commonlib import nrml
def number_of(elem_name, tree):
"""
Given an element name (including the namespaces prefix, if applicable),
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
return len(tree.xpath(expr, namespaces=nrml.PARSE_NS_MAP))
class BaseExportTestCase(unittest.TestCase):
def _test_exported_file(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isabs(filename))
self.assertTrue(os.path.getsize(filename) > 0)
Fix a broken export test |
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake 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.
#
# OpenQuake 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 Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
from openquake.commonlib import nrml
def number_of(elem_name, tree):
"""
Given an element name (including the namespaces prefix, if applicable),
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
return len(tree.xpath(expr, namespaces={'nrml': nrml.NRML05}))
class BaseExportTestCase(unittest.TestCase):
def _test_exported_file(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isabs(filename))
self.assertTrue(os.path.getsize(filename) > 0)
| <commit_before>
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake 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.
#
# OpenQuake 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 Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
from openquake.commonlib import nrml
def number_of(elem_name, tree):
"""
Given an element name (including the namespaces prefix, if applicable),
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
return len(tree.xpath(expr, namespaces=nrml.PARSE_NS_MAP))
class BaseExportTestCase(unittest.TestCase):
def _test_exported_file(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isabs(filename))
self.assertTrue(os.path.getsize(filename) > 0)
<commit_msg>Fix a broken export test<commit_after> |
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake 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.
#
# OpenQuake 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 Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
from openquake.commonlib import nrml
def number_of(elem_name, tree):
"""
Given an element name (including the namespaces prefix, if applicable),
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
return len(tree.xpath(expr, namespaces={'nrml': nrml.NRML05}))
class BaseExportTestCase(unittest.TestCase):
def _test_exported_file(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isabs(filename))
self.assertTrue(os.path.getsize(filename) > 0)
|
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake 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.
#
# OpenQuake 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 Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
from openquake.commonlib import nrml
def number_of(elem_name, tree):
"""
Given an element name (including the namespaces prefix, if applicable),
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
return len(tree.xpath(expr, namespaces=nrml.PARSE_NS_MAP))
class BaseExportTestCase(unittest.TestCase):
def _test_exported_file(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isabs(filename))
self.assertTrue(os.path.getsize(filename) > 0)
Fix a broken export test
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake 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.
#
# OpenQuake 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 Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
from openquake.commonlib import nrml
def number_of(elem_name, tree):
"""
Given an element name (including the namespaces prefix, if applicable),
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
return len(tree.xpath(expr, namespaces={'nrml': nrml.NRML05}))
class BaseExportTestCase(unittest.TestCase):
def _test_exported_file(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isabs(filename))
self.assertTrue(os.path.getsize(filename) > 0)
| <commit_before>
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake 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.
#
# OpenQuake 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 Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
from openquake.commonlib import nrml
def number_of(elem_name, tree):
"""
Given an element name (including the namespaces prefix, if applicable),
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
return len(tree.xpath(expr, namespaces=nrml.PARSE_NS_MAP))
class BaseExportTestCase(unittest.TestCase):
def _test_exported_file(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isabs(filename))
self.assertTrue(os.path.getsize(filename) > 0)
<commit_msg>Fix a broken export test<commit_after>
# Copyright (c) 2010-2014, GEM Foundation.
#
# OpenQuake 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.
#
# OpenQuake 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 Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import os
import unittest
from openquake.commonlib import nrml
def number_of(elem_name, tree):
"""
Given an element name (including the namespaces prefix, if applicable),
return the number of occurrences of the element in a given XML document.
"""
expr = '//%s' % elem_name
return len(tree.xpath(expr, namespaces={'nrml': nrml.NRML05}))
class BaseExportTestCase(unittest.TestCase):
def _test_exported_file(self, filename):
self.assertTrue(os.path.exists(filename))
self.assertTrue(os.path.isabs(filename))
self.assertTrue(os.path.getsize(filename) > 0)
|
546a4681aa54ba183e956d220e98ef67ae6de691 | user/decorators.py | user/decorators.py | from django.conf import settings
from django.contrib.auth import get_user
from django.shortcuts import redirect
def custom_login_required(view):
# view argument must be a function
def new_view(request, *args, **kwargs):
user = get_user(request)
if user.is_authenticated():
return view(request, *args, **kwargs)
else:
url = '{}?next={}'.format(
settings.LOGIN_URL,
request.path)
return redirect(url)
return new_view
| from functools import wraps
from django.conf import settings
from django.contrib.auth import get_user
from django.shortcuts import redirect
from django.utils.decorators import \
available_attrs
def custom_login_required(view):
# view argument must be a function
@wraps(view, assigned=available_attrs(view))
def new_view(request, *args, **kwargs):
user = get_user(request)
if user.is_authenticated():
return view(request, *args, **kwargs)
else:
url = '{}?next={}'.format(
settings.LOGIN_URL,
request.path)
return redirect(url)
return new_view
| Use functools.wraps to copy view signature. | Ch20: Use functools.wraps to copy view signature.
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 | from django.conf import settings
from django.contrib.auth import get_user
from django.shortcuts import redirect
def custom_login_required(view):
# view argument must be a function
def new_view(request, *args, **kwargs):
user = get_user(request)
if user.is_authenticated():
return view(request, *args, **kwargs)
else:
url = '{}?next={}'.format(
settings.LOGIN_URL,
request.path)
return redirect(url)
return new_view
Ch20: Use functools.wraps to copy view signature. | from functools import wraps
from django.conf import settings
from django.contrib.auth import get_user
from django.shortcuts import redirect
from django.utils.decorators import \
available_attrs
def custom_login_required(view):
# view argument must be a function
@wraps(view, assigned=available_attrs(view))
def new_view(request, *args, **kwargs):
user = get_user(request)
if user.is_authenticated():
return view(request, *args, **kwargs)
else:
url = '{}?next={}'.format(
settings.LOGIN_URL,
request.path)
return redirect(url)
return new_view
| <commit_before>from django.conf import settings
from django.contrib.auth import get_user
from django.shortcuts import redirect
def custom_login_required(view):
# view argument must be a function
def new_view(request, *args, **kwargs):
user = get_user(request)
if user.is_authenticated():
return view(request, *args, **kwargs)
else:
url = '{}?next={}'.format(
settings.LOGIN_URL,
request.path)
return redirect(url)
return new_view
<commit_msg>Ch20: Use functools.wraps to copy view signature.<commit_after> | from functools import wraps
from django.conf import settings
from django.contrib.auth import get_user
from django.shortcuts import redirect
from django.utils.decorators import \
available_attrs
def custom_login_required(view):
# view argument must be a function
@wraps(view, assigned=available_attrs(view))
def new_view(request, *args, **kwargs):
user = get_user(request)
if user.is_authenticated():
return view(request, *args, **kwargs)
else:
url = '{}?next={}'.format(
settings.LOGIN_URL,
request.path)
return redirect(url)
return new_view
| from django.conf import settings
from django.contrib.auth import get_user
from django.shortcuts import redirect
def custom_login_required(view):
# view argument must be a function
def new_view(request, *args, **kwargs):
user = get_user(request)
if user.is_authenticated():
return view(request, *args, **kwargs)
else:
url = '{}?next={}'.format(
settings.LOGIN_URL,
request.path)
return redirect(url)
return new_view
Ch20: Use functools.wraps to copy view signature.from functools import wraps
from django.conf import settings
from django.contrib.auth import get_user
from django.shortcuts import redirect
from django.utils.decorators import \
available_attrs
def custom_login_required(view):
# view argument must be a function
@wraps(view, assigned=available_attrs(view))
def new_view(request, *args, **kwargs):
user = get_user(request)
if user.is_authenticated():
return view(request, *args, **kwargs)
else:
url = '{}?next={}'.format(
settings.LOGIN_URL,
request.path)
return redirect(url)
return new_view
| <commit_before>from django.conf import settings
from django.contrib.auth import get_user
from django.shortcuts import redirect
def custom_login_required(view):
# view argument must be a function
def new_view(request, *args, **kwargs):
user = get_user(request)
if user.is_authenticated():
return view(request, *args, **kwargs)
else:
url = '{}?next={}'.format(
settings.LOGIN_URL,
request.path)
return redirect(url)
return new_view
<commit_msg>Ch20: Use functools.wraps to copy view signature.<commit_after>from functools import wraps
from django.conf import settings
from django.contrib.auth import get_user
from django.shortcuts import redirect
from django.utils.decorators import \
available_attrs
def custom_login_required(view):
# view argument must be a function
@wraps(view, assigned=available_attrs(view))
def new_view(request, *args, **kwargs):
user = get_user(request)
if user.is_authenticated():
return view(request, *args, **kwargs)
else:
url = '{}?next={}'.format(
settings.LOGIN_URL,
request.path)
return redirect(url)
return new_view
|
7fc3867e7b8a01854116b43d9961e1063c051006 | mmmpaste/helpers.py | mmmpaste/helpers.py | from flask import request
def get_ip():
if not request.headers.get("X-Forwarded-For"):
return request.remote_addr
return request.headers.get("X-Forwarded-For")
| from flask import request
def get_ip():
if not request.headers.get("X-Forwarded-For"):
return request.remote_addr
return request.headers.get("X-Forwarded-For")[0]
| Select the first IP address from the X-Forwarded-For list. | Select the first IP address from the X-Forwarded-For list.
| Python | bsd-2-clause | ryanc/mmmpaste,ryanc/mmmpaste | from flask import request
def get_ip():
if not request.headers.get("X-Forwarded-For"):
return request.remote_addr
return request.headers.get("X-Forwarded-For")
Select the first IP address from the X-Forwarded-For list. | from flask import request
def get_ip():
if not request.headers.get("X-Forwarded-For"):
return request.remote_addr
return request.headers.get("X-Forwarded-For")[0]
| <commit_before>from flask import request
def get_ip():
if not request.headers.get("X-Forwarded-For"):
return request.remote_addr
return request.headers.get("X-Forwarded-For")
<commit_msg>Select the first IP address from the X-Forwarded-For list.<commit_after> | from flask import request
def get_ip():
if not request.headers.get("X-Forwarded-For"):
return request.remote_addr
return request.headers.get("X-Forwarded-For")[0]
| from flask import request
def get_ip():
if not request.headers.get("X-Forwarded-For"):
return request.remote_addr
return request.headers.get("X-Forwarded-For")
Select the first IP address from the X-Forwarded-For list.from flask import request
def get_ip():
if not request.headers.get("X-Forwarded-For"):
return request.remote_addr
return request.headers.get("X-Forwarded-For")[0]
| <commit_before>from flask import request
def get_ip():
if not request.headers.get("X-Forwarded-For"):
return request.remote_addr
return request.headers.get("X-Forwarded-For")
<commit_msg>Select the first IP address from the X-Forwarded-For list.<commit_after>from flask import request
def get_ip():
if not request.headers.get("X-Forwarded-For"):
return request.remote_addr
return request.headers.get("X-Forwarded-For")[0]
|
a778a41c8deb6fd9812e405143e34679122c18db | website/addons/base/utils.py | website/addons/base/utils.py | from os.path import basename
from website import settings
def serialize_addon_config(config, user):
lookup = config.template_lookup
return {
'addon_short_name': config.short_name,
'addon_full_name': config.full_name,
'node_settings_template': lookup.get_template(basename(config.node_settings_template)),
'user_settings_template': lookup.get_template(basename(config.user_settings_template)),
'is_enabled': user.get_addon(config.short_name) is not None,
}
def get_addons_by_config_type(config_type, user):
addons = [addon for addon in settings.ADDONS_AVAILABLE if config_type in addon.configs]
addon_settings = []
for addon_config in sorted(addons, key=lambda cfg: cfg.full_name.lower()):
# short_name = addon_config.short_name
config = serialize_addon_config(addon_config, user)
'''
user_settings = user.get_addon(short_name)
if user_settings:
user_settings = user_settings.to_json(user)
config.update({
'user_settings': user_settings or {}
})
'''
addon_settings.append(config)
return addon_settings
| from os.path import basename
from website import settings
def serialize_addon_config(config, user):
lookup = config.template_lookup
user_addon = user.get_addon(config.short_name)
ret = {
'addon_short_name': config.short_name,
'addon_full_name': config.full_name,
'node_settings_template': lookup.get_template(basename(config.node_settings_template)),
'user_settings_template': lookup.get_template(basename(config.user_settings_template)),
'is_enabled': user_addon is not None,
}
ret.update(user_addon.to_json(user) if user_addon else {})
return ret
def get_addons_by_config_type(config_type, user):
addons = [addon for addon in settings.ADDONS_AVAILABLE if config_type in addon.configs]
return [serialize_addon_config(addon_config, user) for addon_config in sorted(addons, key=lambda cfg: cfg.full_name.lower())]
| Add user_settings to serialized addon settings | Add user_settings to serialized addon settings
| Python | apache-2.0 | ZobairAlijan/osf.io,leb2dg/osf.io,doublebits/osf.io,mluo613/osf.io,jolene-esposito/osf.io,alexschiller/osf.io,mattclark/osf.io,laurenrevere/osf.io,jolene-esposito/osf.io,SSJohns/osf.io,billyhunt/osf.io,pattisdr/osf.io,samanehsan/osf.io,DanielSBrown/osf.io,cslzchen/osf.io,caseyrygt/osf.io,zachjanicki/osf.io,Nesiehr/osf.io,TomHeatwole/osf.io,reinaH/osf.io,danielneis/osf.io,cldershem/osf.io,cldershem/osf.io,mluo613/osf.io,MerlinZhang/osf.io,petermalcolm/osf.io,doublebits/osf.io,amyshi188/osf.io,SSJohns/osf.io,brandonPurvis/osf.io,asanfilippo7/osf.io,baylee-d/osf.io,mfraezz/osf.io,Nesiehr/osf.io,ticklemepierce/osf.io,samanehsan/osf.io,sloria/osf.io,samchrisinger/osf.io,kch8qx/osf.io,ckc6cz/osf.io,ckc6cz/osf.io,leb2dg/osf.io,emetsger/osf.io,cwisecarver/osf.io,hmoco/osf.io,hmoco/osf.io,erinspace/osf.io,doublebits/osf.io,aaxelb/osf.io,Ghalko/osf.io,jmcarp/osf.io,DanielSBrown/osf.io,bdyetton/prettychart,bdyetton/prettychart,TomHeatwole/osf.io,zachjanicki/osf.io,doublebits/osf.io,Nesiehr/osf.io,brianjgeiger/osf.io,acshi/osf.io,cslzchen/osf.io,jnayak1/osf.io,RomanZWang/osf.io,acshi/osf.io,sbt9uc/osf.io,danielneis/osf.io,crcresearch/osf.io,zamattiac/osf.io,monikagrabowska/osf.io,cslzchen/osf.io,erinspace/osf.io,rdhyee/osf.io,alexschiller/osf.io,mluke93/osf.io,alexschiller/osf.io,chennan47/osf.io,ckc6cz/osf.io,zamattiac/osf.io,zamattiac/osf.io,jolene-esposito/osf.io,caseyrollins/osf.io,haoyuchen1992/osf.io,arpitar/osf.io,SSJohns/osf.io,TomBaxter/osf.io,zachjanicki/osf.io,kch8qx/osf.io,lyndsysimon/osf.io,samchrisinger/osf.io,saradbowman/osf.io,acshi/osf.io,TomHeatwole/osf.io,kwierman/osf.io,wearpants/osf.io,laurenrevere/osf.io,felliott/osf.io,baylee-d/osf.io,petermalcolm/osf.io,SSJohns/osf.io,reinaH/osf.io,monikagrabowska/osf.io,amyshi188/osf.io,bdyetton/prettychart,TomHeatwole/osf.io,icereval/osf.io,haoyuchen1992/osf.io,RomanZWang/osf.io,TomBaxter/osf.io,sbt9uc/osf.io,jnayak1/osf.io,amyshi188/osf.io,emetsger/osf.io,DanielSBrown/osf.io,MerlinZhang/osf.io,cwisecarver/osf.io,Ghalko/osf.io,laurenrevere/osf.io,cslzchen/osf.io,leb2dg/osf.io,cosenal/osf.io,erinspace/osf.io,hmoco/osf.io,chrisseto/osf.io,felliott/osf.io,alexschiller/osf.io,KAsante95/osf.io,felliott/osf.io,ticklemepierce/osf.io,pattisdr/osf.io,reinaH/osf.io,icereval/osf.io,ticklemepierce/osf.io,brandonPurvis/osf.io,billyhunt/osf.io,brianjgeiger/osf.io,MerlinZhang/osf.io,abought/osf.io,mfraezz/osf.io,acshi/osf.io,HarryRybacki/osf.io,sbt9uc/osf.io,icereval/osf.io,danielneis/osf.io,CenterForOpenScience/osf.io,kch8qx/osf.io,emetsger/osf.io,zachjanicki/osf.io,GageGaskins/osf.io,rdhyee/osf.io,CenterForOpenScience/osf.io,jmcarp/osf.io,cwisecarver/osf.io,petermalcolm/osf.io,monikagrabowska/osf.io,Johnetordoff/osf.io,binoculars/osf.io,njantrania/osf.io,TomBaxter/osf.io,caseyrollins/osf.io,haoyuchen1992/osf.io,billyhunt/osf.io,RomanZWang/osf.io,mattclark/osf.io,mfraezz/osf.io,mluke93/osf.io,ZobairAlijan/osf.io,dplorimer/osf,caneruguz/osf.io,Nesiehr/osf.io,lyndsysimon/osf.io,njantrania/osf.io,kwierman/osf.io,haoyuchen1992/osf.io,rdhyee/osf.io,alexschiller/osf.io,HarryRybacki/osf.io,emetsger/osf.io,HarryRybacki/osf.io,chrisseto/osf.io,HalcyonChimera/osf.io,reinaH/osf.io,chrisseto/osf.io,ckc6cz/osf.io,mluo613/osf.io,wearpants/osf.io,mluo613/osf.io,chennan47/osf.io,caseyrygt/osf.io,leb2dg/osf.io,kwierman/osf.io,dplorimer/osf,HalcyonChimera/osf.io,KAsante95/osf.io,cwisecarver/osf.io,GageGaskins/osf.io,kch8qx/osf.io,samanehsan/osf.io,binoculars/osf.io,binoculars/osf.io,saradbowman/osf.io,jmcarp/osf.io,amyshi188/osf.io,ZobairAlijan/osf.io,Ghalko/osf.io,doublebits/osf.io,HalcyonChimera/osf.io,brandonPurvis/osf.io,abought/osf.io,HalcyonChimera/osf.io,petermalcolm/osf.io,kch8qx/osf.io,hmoco/osf.io,adlius/osf.io,asanfilippo7/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,njantrania/osf.io,rdhyee/osf.io,DanielSBrown/osf.io,abought/osf.io,samanehsan/osf.io,pattisdr/osf.io,billyhunt/osf.io,dplorimer/osf,billyhunt/osf.io,KAsante95/osf.io,adlius/osf.io,caneruguz/osf.io,samchrisinger/osf.io,brandonPurvis/osf.io,CenterForOpenScience/osf.io,dplorimer/osf,mluke93/osf.io,sloria/osf.io,crcresearch/osf.io,jnayak1/osf.io,danielneis/osf.io,cldershem/osf.io,abought/osf.io,cosenal/osf.io,caneruguz/osf.io,CenterForOpenScience/osf.io,crcresearch/osf.io,sbt9uc/osf.io,caseyrygt/osf.io,Ghalko/osf.io,mattclark/osf.io,sloria/osf.io,ZobairAlijan/osf.io,wearpants/osf.io,caseyrygt/osf.io,chennan47/osf.io,aaxelb/osf.io,cosenal/osf.io,baylee-d/osf.io,asanfilippo7/osf.io,asanfilippo7/osf.io,jnayak1/osf.io,GageGaskins/osf.io,GageGaskins/osf.io,GageGaskins/osf.io,jmcarp/osf.io,lyndsysimon/osf.io,mluke93/osf.io,HarryRybacki/osf.io,KAsante95/osf.io,adlius/osf.io,zamattiac/osf.io,kwierman/osf.io,samchrisinger/osf.io,chrisseto/osf.io,brianjgeiger/osf.io,arpitar/osf.io,brandonPurvis/osf.io,RomanZWang/osf.io,cldershem/osf.io,arpitar/osf.io,caneruguz/osf.io,wearpants/osf.io,Johnetordoff/osf.io,njantrania/osf.io,monikagrabowska/osf.io,monikagrabowska/osf.io,mluo613/osf.io,felliott/osf.io,ticklemepierce/osf.io,brianjgeiger/osf.io,KAsante95/osf.io,acshi/osf.io,RomanZWang/osf.io,bdyetton/prettychart,cosenal/osf.io,arpitar/osf.io,adlius/osf.io,aaxelb/osf.io,lyndsysimon/osf.io,MerlinZhang/osf.io,Johnetordoff/osf.io,jolene-esposito/osf.io,mfraezz/osf.io,caseyrollins/osf.io | from os.path import basename
from website import settings
def serialize_addon_config(config, user):
lookup = config.template_lookup
return {
'addon_short_name': config.short_name,
'addon_full_name': config.full_name,
'node_settings_template': lookup.get_template(basename(config.node_settings_template)),
'user_settings_template': lookup.get_template(basename(config.user_settings_template)),
'is_enabled': user.get_addon(config.short_name) is not None,
}
def get_addons_by_config_type(config_type, user):
addons = [addon for addon in settings.ADDONS_AVAILABLE if config_type in addon.configs]
addon_settings = []
for addon_config in sorted(addons, key=lambda cfg: cfg.full_name.lower()):
# short_name = addon_config.short_name
config = serialize_addon_config(addon_config, user)
'''
user_settings = user.get_addon(short_name)
if user_settings:
user_settings = user_settings.to_json(user)
config.update({
'user_settings': user_settings or {}
})
'''
addon_settings.append(config)
return addon_settings
Add user_settings to serialized addon settings | from os.path import basename
from website import settings
def serialize_addon_config(config, user):
lookup = config.template_lookup
user_addon = user.get_addon(config.short_name)
ret = {
'addon_short_name': config.short_name,
'addon_full_name': config.full_name,
'node_settings_template': lookup.get_template(basename(config.node_settings_template)),
'user_settings_template': lookup.get_template(basename(config.user_settings_template)),
'is_enabled': user_addon is not None,
}
ret.update(user_addon.to_json(user) if user_addon else {})
return ret
def get_addons_by_config_type(config_type, user):
addons = [addon for addon in settings.ADDONS_AVAILABLE if config_type in addon.configs]
return [serialize_addon_config(addon_config, user) for addon_config in sorted(addons, key=lambda cfg: cfg.full_name.lower())]
| <commit_before>from os.path import basename
from website import settings
def serialize_addon_config(config, user):
lookup = config.template_lookup
return {
'addon_short_name': config.short_name,
'addon_full_name': config.full_name,
'node_settings_template': lookup.get_template(basename(config.node_settings_template)),
'user_settings_template': lookup.get_template(basename(config.user_settings_template)),
'is_enabled': user.get_addon(config.short_name) is not None,
}
def get_addons_by_config_type(config_type, user):
addons = [addon for addon in settings.ADDONS_AVAILABLE if config_type in addon.configs]
addon_settings = []
for addon_config in sorted(addons, key=lambda cfg: cfg.full_name.lower()):
# short_name = addon_config.short_name
config = serialize_addon_config(addon_config, user)
'''
user_settings = user.get_addon(short_name)
if user_settings:
user_settings = user_settings.to_json(user)
config.update({
'user_settings': user_settings or {}
})
'''
addon_settings.append(config)
return addon_settings
<commit_msg>Add user_settings to serialized addon settings<commit_after> | from os.path import basename
from website import settings
def serialize_addon_config(config, user):
lookup = config.template_lookup
user_addon = user.get_addon(config.short_name)
ret = {
'addon_short_name': config.short_name,
'addon_full_name': config.full_name,
'node_settings_template': lookup.get_template(basename(config.node_settings_template)),
'user_settings_template': lookup.get_template(basename(config.user_settings_template)),
'is_enabled': user_addon is not None,
}
ret.update(user_addon.to_json(user) if user_addon else {})
return ret
def get_addons_by_config_type(config_type, user):
addons = [addon for addon in settings.ADDONS_AVAILABLE if config_type in addon.configs]
return [serialize_addon_config(addon_config, user) for addon_config in sorted(addons, key=lambda cfg: cfg.full_name.lower())]
| from os.path import basename
from website import settings
def serialize_addon_config(config, user):
lookup = config.template_lookup
return {
'addon_short_name': config.short_name,
'addon_full_name': config.full_name,
'node_settings_template': lookup.get_template(basename(config.node_settings_template)),
'user_settings_template': lookup.get_template(basename(config.user_settings_template)),
'is_enabled': user.get_addon(config.short_name) is not None,
}
def get_addons_by_config_type(config_type, user):
addons = [addon for addon in settings.ADDONS_AVAILABLE if config_type in addon.configs]
addon_settings = []
for addon_config in sorted(addons, key=lambda cfg: cfg.full_name.lower()):
# short_name = addon_config.short_name
config = serialize_addon_config(addon_config, user)
'''
user_settings = user.get_addon(short_name)
if user_settings:
user_settings = user_settings.to_json(user)
config.update({
'user_settings': user_settings or {}
})
'''
addon_settings.append(config)
return addon_settings
Add user_settings to serialized addon settingsfrom os.path import basename
from website import settings
def serialize_addon_config(config, user):
lookup = config.template_lookup
user_addon = user.get_addon(config.short_name)
ret = {
'addon_short_name': config.short_name,
'addon_full_name': config.full_name,
'node_settings_template': lookup.get_template(basename(config.node_settings_template)),
'user_settings_template': lookup.get_template(basename(config.user_settings_template)),
'is_enabled': user_addon is not None,
}
ret.update(user_addon.to_json(user) if user_addon else {})
return ret
def get_addons_by_config_type(config_type, user):
addons = [addon for addon in settings.ADDONS_AVAILABLE if config_type in addon.configs]
return [serialize_addon_config(addon_config, user) for addon_config in sorted(addons, key=lambda cfg: cfg.full_name.lower())]
| <commit_before>from os.path import basename
from website import settings
def serialize_addon_config(config, user):
lookup = config.template_lookup
return {
'addon_short_name': config.short_name,
'addon_full_name': config.full_name,
'node_settings_template': lookup.get_template(basename(config.node_settings_template)),
'user_settings_template': lookup.get_template(basename(config.user_settings_template)),
'is_enabled': user.get_addon(config.short_name) is not None,
}
def get_addons_by_config_type(config_type, user):
addons = [addon for addon in settings.ADDONS_AVAILABLE if config_type in addon.configs]
addon_settings = []
for addon_config in sorted(addons, key=lambda cfg: cfg.full_name.lower()):
# short_name = addon_config.short_name
config = serialize_addon_config(addon_config, user)
'''
user_settings = user.get_addon(short_name)
if user_settings:
user_settings = user_settings.to_json(user)
config.update({
'user_settings': user_settings or {}
})
'''
addon_settings.append(config)
return addon_settings
<commit_msg>Add user_settings to serialized addon settings<commit_after>from os.path import basename
from website import settings
def serialize_addon_config(config, user):
lookup = config.template_lookup
user_addon = user.get_addon(config.short_name)
ret = {
'addon_short_name': config.short_name,
'addon_full_name': config.full_name,
'node_settings_template': lookup.get_template(basename(config.node_settings_template)),
'user_settings_template': lookup.get_template(basename(config.user_settings_template)),
'is_enabled': user_addon is not None,
}
ret.update(user_addon.to_json(user) if user_addon else {})
return ret
def get_addons_by_config_type(config_type, user):
addons = [addon for addon in settings.ADDONS_AVAILABLE if config_type in addon.configs]
return [serialize_addon_config(addon_config, user) for addon_config in sorted(addons, key=lambda cfg: cfg.full_name.lower())]
|
13774b20f18d23dfb69c65dd151e3aed9734a88f | website/core/settings/loc.py | website/core/settings/loc.py | """Local settings and globals."""
import sys
from os.path import normpath, join
from .base import *
# Import secrets
sys.path.append(
abspath(join(PROJECT_ROOT, '../secrets/buzz/stg'))
)
from secrets import *
# Set static URL
STATIC_URL = '/static' | """Local settings and globals."""
import sys
from os.path import normpath, join
from .base import *
# Import secrets -- not needed
#sys.path.append(
# abspath(join(PROJECT_ROOT, '../secrets/TimelineJS/stg'))
#)
#from secrets import *
# Set static URL
STATIC_URL = '/static' | Comment out secrets import (not needed for this project) | Comment out secrets import (not needed for this project)
| Python | mpl-2.0 | stea4lth/TimelineJS,noikiy/TimelineJS,azeemmufti/TimelineJS,ryekee/TimelineJS,djaney/TimelineJS,1modm/TimelineJS,zstao/TimelineJS,wangjun/TimelineJS,1modm/TimelineJS,stea4lth/TimelineJS,matt-edgedesign/Timelinejs,LauraHilliger/TimelineJS,djaney/TimelineJS,ycaihua/TimelineJS,deenjohn/TimelineJS,ryekee/TimelineJS,deenjohn/TimelineJS,anxintiancai/TimelineJS,CrossLead/TimelineJS,JoaquinSiabra/TimelineJS,cweems/api-timeline-js,deenjohn/TimelineJS,LauraHilliger/TimelineJS,NUKnightLab/TimelineJS,NUKnightLab/TimelineJS,angeliaz/TimelineJS,ryekee/TimelineJS,zstao/TimelineJS,1modm/TimelineJS,landsurveyorsunited/TimelineJS,pom95/timeline,JoaquinSiabra/TimelineJS,wangjun/TimelineJS,JoaquinSiabra/TimelineJS,angeliaz/TimelineJS,noikiy/TimelineJS,james-logan/TimelineJS,stea4lth/TimelineJS,noikiy/TimelineJS,ycaihua/TimelineJS,anxintiancai/TimelineJS,landsurveyorsunited/TimelineJS,pom95/timeline,ycaihua/TimelineJS,CrossLead/TimelineJS,azeemmufti/TimelineJS,LauraHilliger/TimelineJS,wangjun/TimelineJS,cweems/api-timeline-js,matt-edgedesign/Timelinejs,james-logan/TimelineJS,zstao/TimelineJS,pom95/timeline,matt-edgedesign/Timelinejs,djaney/TimelineJS,anxintiancai/TimelineJS,NUKnightLab/TimelineJS,james-logan/TimelineJS,landsurveyorsunited/TimelineJS | """Local settings and globals."""
import sys
from os.path import normpath, join
from .base import *
# Import secrets
sys.path.append(
abspath(join(PROJECT_ROOT, '../secrets/buzz/stg'))
)
from secrets import *
# Set static URL
STATIC_URL = '/static'Comment out secrets import (not needed for this project) | """Local settings and globals."""
import sys
from os.path import normpath, join
from .base import *
# Import secrets -- not needed
#sys.path.append(
# abspath(join(PROJECT_ROOT, '../secrets/TimelineJS/stg'))
#)
#from secrets import *
# Set static URL
STATIC_URL = '/static' | <commit_before>"""Local settings and globals."""
import sys
from os.path import normpath, join
from .base import *
# Import secrets
sys.path.append(
abspath(join(PROJECT_ROOT, '../secrets/buzz/stg'))
)
from secrets import *
# Set static URL
STATIC_URL = '/static'<commit_msg>Comment out secrets import (not needed for this project)<commit_after> | """Local settings and globals."""
import sys
from os.path import normpath, join
from .base import *
# Import secrets -- not needed
#sys.path.append(
# abspath(join(PROJECT_ROOT, '../secrets/TimelineJS/stg'))
#)
#from secrets import *
# Set static URL
STATIC_URL = '/static' | """Local settings and globals."""
import sys
from os.path import normpath, join
from .base import *
# Import secrets
sys.path.append(
abspath(join(PROJECT_ROOT, '../secrets/buzz/stg'))
)
from secrets import *
# Set static URL
STATIC_URL = '/static'Comment out secrets import (not needed for this project)"""Local settings and globals."""
import sys
from os.path import normpath, join
from .base import *
# Import secrets -- not needed
#sys.path.append(
# abspath(join(PROJECT_ROOT, '../secrets/TimelineJS/stg'))
#)
#from secrets import *
# Set static URL
STATIC_URL = '/static' | <commit_before>"""Local settings and globals."""
import sys
from os.path import normpath, join
from .base import *
# Import secrets
sys.path.append(
abspath(join(PROJECT_ROOT, '../secrets/buzz/stg'))
)
from secrets import *
# Set static URL
STATIC_URL = '/static'<commit_msg>Comment out secrets import (not needed for this project)<commit_after>"""Local settings and globals."""
import sys
from os.path import normpath, join
from .base import *
# Import secrets -- not needed
#sys.path.append(
# abspath(join(PROJECT_ROOT, '../secrets/TimelineJS/stg'))
#)
#from secrets import *
# Set static URL
STATIC_URL = '/static' |
1cb7581f63d0d9d4e6eca69316930912c41a4fb5 | Instanssi/admin_upload/models.py | Instanssi/admin_upload/models.py | # -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
class UploadedFile(models.Model):
user = models.ForeignKey(User, verbose_name=u'Käyttäjä')
description = models.TextField(u'Kuvaus', help_text=u'Lyhyt kuvaus siitä, mihin/missä tiedostoa käytetään.', blank=True)
file = models.FileField(u'Tiedosto', upload_to='admin_upload/')
date = models.DateTimeField(u'Aika')
def __unicode__(self):
return self.file.name + ' by' + self.user.username + ')'
class Meta:
verbose_name=u"tiedosto"
verbose_name_plural=u"tiedostot" | # -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
import os.path
class UploadedFile(models.Model):
user = models.ForeignKey(User, verbose_name=u'Käyttäjä')
description = models.TextField(u'Kuvaus', help_text=u'Lyhyt kuvaus siitä, mihin/missä tiedostoa käytetään.', blank=True)
file = models.FileField(u'Tiedosto', upload_to='admin_upload/')
date = models.DateTimeField(u'Aika')
def __unicode__(self):
return self.file.name + ' by' + self.user.username + ')'
class Meta:
verbose_name=u"tiedosto"
verbose_name_plural=u"tiedostot"
def name(self):
return os.path.basename(self.file.name)
try:
admin.site.register(UploadedFile)
except:
pass | Add helper function for getting name from UploadedFile, add model to admin. | admin_upload: Add helper function for getting name from UploadedFile, add model to admin.
| Python | mit | Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org | # -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
class UploadedFile(models.Model):
user = models.ForeignKey(User, verbose_name=u'Käyttäjä')
description = models.TextField(u'Kuvaus', help_text=u'Lyhyt kuvaus siitä, mihin/missä tiedostoa käytetään.', blank=True)
file = models.FileField(u'Tiedosto', upload_to='admin_upload/')
date = models.DateTimeField(u'Aika')
def __unicode__(self):
return self.file.name + ' by' + self.user.username + ')'
class Meta:
verbose_name=u"tiedosto"
verbose_name_plural=u"tiedostot"admin_upload: Add helper function for getting name from UploadedFile, add model to admin. | # -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
import os.path
class UploadedFile(models.Model):
user = models.ForeignKey(User, verbose_name=u'Käyttäjä')
description = models.TextField(u'Kuvaus', help_text=u'Lyhyt kuvaus siitä, mihin/missä tiedostoa käytetään.', blank=True)
file = models.FileField(u'Tiedosto', upload_to='admin_upload/')
date = models.DateTimeField(u'Aika')
def __unicode__(self):
return self.file.name + ' by' + self.user.username + ')'
class Meta:
verbose_name=u"tiedosto"
verbose_name_plural=u"tiedostot"
def name(self):
return os.path.basename(self.file.name)
try:
admin.site.register(UploadedFile)
except:
pass | <commit_before># -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
class UploadedFile(models.Model):
user = models.ForeignKey(User, verbose_name=u'Käyttäjä')
description = models.TextField(u'Kuvaus', help_text=u'Lyhyt kuvaus siitä, mihin/missä tiedostoa käytetään.', blank=True)
file = models.FileField(u'Tiedosto', upload_to='admin_upload/')
date = models.DateTimeField(u'Aika')
def __unicode__(self):
return self.file.name + ' by' + self.user.username + ')'
class Meta:
verbose_name=u"tiedosto"
verbose_name_plural=u"tiedostot"<commit_msg>admin_upload: Add helper function for getting name from UploadedFile, add model to admin.<commit_after> | # -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
import os.path
class UploadedFile(models.Model):
user = models.ForeignKey(User, verbose_name=u'Käyttäjä')
description = models.TextField(u'Kuvaus', help_text=u'Lyhyt kuvaus siitä, mihin/missä tiedostoa käytetään.', blank=True)
file = models.FileField(u'Tiedosto', upload_to='admin_upload/')
date = models.DateTimeField(u'Aika')
def __unicode__(self):
return self.file.name + ' by' + self.user.username + ')'
class Meta:
verbose_name=u"tiedosto"
verbose_name_plural=u"tiedostot"
def name(self):
return os.path.basename(self.file.name)
try:
admin.site.register(UploadedFile)
except:
pass | # -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
class UploadedFile(models.Model):
user = models.ForeignKey(User, verbose_name=u'Käyttäjä')
description = models.TextField(u'Kuvaus', help_text=u'Lyhyt kuvaus siitä, mihin/missä tiedostoa käytetään.', blank=True)
file = models.FileField(u'Tiedosto', upload_to='admin_upload/')
date = models.DateTimeField(u'Aika')
def __unicode__(self):
return self.file.name + ' by' + self.user.username + ')'
class Meta:
verbose_name=u"tiedosto"
verbose_name_plural=u"tiedostot"admin_upload: Add helper function for getting name from UploadedFile, add model to admin.# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
import os.path
class UploadedFile(models.Model):
user = models.ForeignKey(User, verbose_name=u'Käyttäjä')
description = models.TextField(u'Kuvaus', help_text=u'Lyhyt kuvaus siitä, mihin/missä tiedostoa käytetään.', blank=True)
file = models.FileField(u'Tiedosto', upload_to='admin_upload/')
date = models.DateTimeField(u'Aika')
def __unicode__(self):
return self.file.name + ' by' + self.user.username + ')'
class Meta:
verbose_name=u"tiedosto"
verbose_name_plural=u"tiedostot"
def name(self):
return os.path.basename(self.file.name)
try:
admin.site.register(UploadedFile)
except:
pass | <commit_before># -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
class UploadedFile(models.Model):
user = models.ForeignKey(User, verbose_name=u'Käyttäjä')
description = models.TextField(u'Kuvaus', help_text=u'Lyhyt kuvaus siitä, mihin/missä tiedostoa käytetään.', blank=True)
file = models.FileField(u'Tiedosto', upload_to='admin_upload/')
date = models.DateTimeField(u'Aika')
def __unicode__(self):
return self.file.name + ' by' + self.user.username + ')'
class Meta:
verbose_name=u"tiedosto"
verbose_name_plural=u"tiedostot"<commit_msg>admin_upload: Add helper function for getting name from UploadedFile, add model to admin.<commit_after># -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
import os.path
class UploadedFile(models.Model):
user = models.ForeignKey(User, verbose_name=u'Käyttäjä')
description = models.TextField(u'Kuvaus', help_text=u'Lyhyt kuvaus siitä, mihin/missä tiedostoa käytetään.', blank=True)
file = models.FileField(u'Tiedosto', upload_to='admin_upload/')
date = models.DateTimeField(u'Aika')
def __unicode__(self):
return self.file.name + ' by' + self.user.username + ')'
class Meta:
verbose_name=u"tiedosto"
verbose_name_plural=u"tiedostot"
def name(self):
return os.path.basename(self.file.name)
try:
admin.site.register(UploadedFile)
except:
pass |
140ff37058eefe4ab79932d96cff4a90aa7b113e | contrib/tests/test_bind_provider.py | contrib/tests/test_bind_provider.py | import unittest
from mock import patch, Mock, MagicMock
import os
import sys
from bind.provider import Provider
class TestBindProvider(unittest.TestCase):
@patch('subprocess.check_output')
@patch('bind.provider.unit_get')
def test_first_setup(self, ugm, spcom):
spcom.return_value = '10.0.0.1'
bp = Provider('example.com')
parser = MagicMock()
bp.first_setup(parser)
ugm.assert_called_once_with('public-address')
parser.dict_to_zone.assert_called_with({'rr': 'A', 'alias': 'ns',
'addr': '10.0.0.1',
'ttl': 300})
@patch('bind.provider.ZoneParser.dict_to_zone')
@patch('bind.provider.ZoneParser.save')
def test_add_record(self, zps, zpm):
bp = Provider('example.com')
bp.reload_config = Mock()
bp.add_record({'rr': 'A', 'alias': 'foo', 'addr': '127.0.0.1'})
zps.assert_called_once_with()
zpm.assert_called_once_with({'alias': 'foo', 'addr': '127.0.0.1', 'rr': 'A'})
bp.reload_config.assert_called_once_with()
| import unittest
from mock import patch, Mock, MagicMock
import os
import sys
from bind.provider import Provider
class TestBindProvider(unittest.TestCase):
@patch('subprocess.check_output')
@patch('bind.provider.unit_get')
def test_first_setup(self, ugm, spcom):
ugm.return_value = '10.0.0.1'
bp = Provider('example.com')
parser = MagicMock()
bp.first_setup(parser)
ugm.assert_called_once_with('public-address')
parser.dict_to_zone.assert_called_with({'rr': 'A', 'alias': 'ns',
'addr': '10.0.0.1',
'ttl': 300})
@patch('bind.provider.ZoneParser.dict_to_zone')
@patch('bind.provider.ZoneParser.save')
def test_add_record(self, zps, zpm):
bp = Provider('example.com')
bp.reload_config = Mock()
bp.add_record({'rr': 'A', 'alias': 'foo', 'addr': '127.0.0.1'})
zps.assert_called_once_with()
zpm.assert_called_once_with({'alias': 'foo', 'addr': '127.0.0.1', 'rr': 'A'})
bp.reload_config.assert_called_once_with()
| Correct bind provider mock in tests | Correct bind provider mock in tests
| Python | mit | chuckbutler/DNS-Charm,chuckbutler/DNS-Charm | import unittest
from mock import patch, Mock, MagicMock
import os
import sys
from bind.provider import Provider
class TestBindProvider(unittest.TestCase):
@patch('subprocess.check_output')
@patch('bind.provider.unit_get')
def test_first_setup(self, ugm, spcom):
spcom.return_value = '10.0.0.1'
bp = Provider('example.com')
parser = MagicMock()
bp.first_setup(parser)
ugm.assert_called_once_with('public-address')
parser.dict_to_zone.assert_called_with({'rr': 'A', 'alias': 'ns',
'addr': '10.0.0.1',
'ttl': 300})
@patch('bind.provider.ZoneParser.dict_to_zone')
@patch('bind.provider.ZoneParser.save')
def test_add_record(self, zps, zpm):
bp = Provider('example.com')
bp.reload_config = Mock()
bp.add_record({'rr': 'A', 'alias': 'foo', 'addr': '127.0.0.1'})
zps.assert_called_once_with()
zpm.assert_called_once_with({'alias': 'foo', 'addr': '127.0.0.1', 'rr': 'A'})
bp.reload_config.assert_called_once_with()
Correct bind provider mock in tests | import unittest
from mock import patch, Mock, MagicMock
import os
import sys
from bind.provider import Provider
class TestBindProvider(unittest.TestCase):
@patch('subprocess.check_output')
@patch('bind.provider.unit_get')
def test_first_setup(self, ugm, spcom):
ugm.return_value = '10.0.0.1'
bp = Provider('example.com')
parser = MagicMock()
bp.first_setup(parser)
ugm.assert_called_once_with('public-address')
parser.dict_to_zone.assert_called_with({'rr': 'A', 'alias': 'ns',
'addr': '10.0.0.1',
'ttl': 300})
@patch('bind.provider.ZoneParser.dict_to_zone')
@patch('bind.provider.ZoneParser.save')
def test_add_record(self, zps, zpm):
bp = Provider('example.com')
bp.reload_config = Mock()
bp.add_record({'rr': 'A', 'alias': 'foo', 'addr': '127.0.0.1'})
zps.assert_called_once_with()
zpm.assert_called_once_with({'alias': 'foo', 'addr': '127.0.0.1', 'rr': 'A'})
bp.reload_config.assert_called_once_with()
| <commit_before>import unittest
from mock import patch, Mock, MagicMock
import os
import sys
from bind.provider import Provider
class TestBindProvider(unittest.TestCase):
@patch('subprocess.check_output')
@patch('bind.provider.unit_get')
def test_first_setup(self, ugm, spcom):
spcom.return_value = '10.0.0.1'
bp = Provider('example.com')
parser = MagicMock()
bp.first_setup(parser)
ugm.assert_called_once_with('public-address')
parser.dict_to_zone.assert_called_with({'rr': 'A', 'alias': 'ns',
'addr': '10.0.0.1',
'ttl': 300})
@patch('bind.provider.ZoneParser.dict_to_zone')
@patch('bind.provider.ZoneParser.save')
def test_add_record(self, zps, zpm):
bp = Provider('example.com')
bp.reload_config = Mock()
bp.add_record({'rr': 'A', 'alias': 'foo', 'addr': '127.0.0.1'})
zps.assert_called_once_with()
zpm.assert_called_once_with({'alias': 'foo', 'addr': '127.0.0.1', 'rr': 'A'})
bp.reload_config.assert_called_once_with()
<commit_msg>Correct bind provider mock in tests<commit_after> | import unittest
from mock import patch, Mock, MagicMock
import os
import sys
from bind.provider import Provider
class TestBindProvider(unittest.TestCase):
@patch('subprocess.check_output')
@patch('bind.provider.unit_get')
def test_first_setup(self, ugm, spcom):
ugm.return_value = '10.0.0.1'
bp = Provider('example.com')
parser = MagicMock()
bp.first_setup(parser)
ugm.assert_called_once_with('public-address')
parser.dict_to_zone.assert_called_with({'rr': 'A', 'alias': 'ns',
'addr': '10.0.0.1',
'ttl': 300})
@patch('bind.provider.ZoneParser.dict_to_zone')
@patch('bind.provider.ZoneParser.save')
def test_add_record(self, zps, zpm):
bp = Provider('example.com')
bp.reload_config = Mock()
bp.add_record({'rr': 'A', 'alias': 'foo', 'addr': '127.0.0.1'})
zps.assert_called_once_with()
zpm.assert_called_once_with({'alias': 'foo', 'addr': '127.0.0.1', 'rr': 'A'})
bp.reload_config.assert_called_once_with()
| import unittest
from mock import patch, Mock, MagicMock
import os
import sys
from bind.provider import Provider
class TestBindProvider(unittest.TestCase):
@patch('subprocess.check_output')
@patch('bind.provider.unit_get')
def test_first_setup(self, ugm, spcom):
spcom.return_value = '10.0.0.1'
bp = Provider('example.com')
parser = MagicMock()
bp.first_setup(parser)
ugm.assert_called_once_with('public-address')
parser.dict_to_zone.assert_called_with({'rr': 'A', 'alias': 'ns',
'addr': '10.0.0.1',
'ttl': 300})
@patch('bind.provider.ZoneParser.dict_to_zone')
@patch('bind.provider.ZoneParser.save')
def test_add_record(self, zps, zpm):
bp = Provider('example.com')
bp.reload_config = Mock()
bp.add_record({'rr': 'A', 'alias': 'foo', 'addr': '127.0.0.1'})
zps.assert_called_once_with()
zpm.assert_called_once_with({'alias': 'foo', 'addr': '127.0.0.1', 'rr': 'A'})
bp.reload_config.assert_called_once_with()
Correct bind provider mock in testsimport unittest
from mock import patch, Mock, MagicMock
import os
import sys
from bind.provider import Provider
class TestBindProvider(unittest.TestCase):
@patch('subprocess.check_output')
@patch('bind.provider.unit_get')
def test_first_setup(self, ugm, spcom):
ugm.return_value = '10.0.0.1'
bp = Provider('example.com')
parser = MagicMock()
bp.first_setup(parser)
ugm.assert_called_once_with('public-address')
parser.dict_to_zone.assert_called_with({'rr': 'A', 'alias': 'ns',
'addr': '10.0.0.1',
'ttl': 300})
@patch('bind.provider.ZoneParser.dict_to_zone')
@patch('bind.provider.ZoneParser.save')
def test_add_record(self, zps, zpm):
bp = Provider('example.com')
bp.reload_config = Mock()
bp.add_record({'rr': 'A', 'alias': 'foo', 'addr': '127.0.0.1'})
zps.assert_called_once_with()
zpm.assert_called_once_with({'alias': 'foo', 'addr': '127.0.0.1', 'rr': 'A'})
bp.reload_config.assert_called_once_with()
| <commit_before>import unittest
from mock import patch, Mock, MagicMock
import os
import sys
from bind.provider import Provider
class TestBindProvider(unittest.TestCase):
@patch('subprocess.check_output')
@patch('bind.provider.unit_get')
def test_first_setup(self, ugm, spcom):
spcom.return_value = '10.0.0.1'
bp = Provider('example.com')
parser = MagicMock()
bp.first_setup(parser)
ugm.assert_called_once_with('public-address')
parser.dict_to_zone.assert_called_with({'rr': 'A', 'alias': 'ns',
'addr': '10.0.0.1',
'ttl': 300})
@patch('bind.provider.ZoneParser.dict_to_zone')
@patch('bind.provider.ZoneParser.save')
def test_add_record(self, zps, zpm):
bp = Provider('example.com')
bp.reload_config = Mock()
bp.add_record({'rr': 'A', 'alias': 'foo', 'addr': '127.0.0.1'})
zps.assert_called_once_with()
zpm.assert_called_once_with({'alias': 'foo', 'addr': '127.0.0.1', 'rr': 'A'})
bp.reload_config.assert_called_once_with()
<commit_msg>Correct bind provider mock in tests<commit_after>import unittest
from mock import patch, Mock, MagicMock
import os
import sys
from bind.provider import Provider
class TestBindProvider(unittest.TestCase):
@patch('subprocess.check_output')
@patch('bind.provider.unit_get')
def test_first_setup(self, ugm, spcom):
ugm.return_value = '10.0.0.1'
bp = Provider('example.com')
parser = MagicMock()
bp.first_setup(parser)
ugm.assert_called_once_with('public-address')
parser.dict_to_zone.assert_called_with({'rr': 'A', 'alias': 'ns',
'addr': '10.0.0.1',
'ttl': 300})
@patch('bind.provider.ZoneParser.dict_to_zone')
@patch('bind.provider.ZoneParser.save')
def test_add_record(self, zps, zpm):
bp = Provider('example.com')
bp.reload_config = Mock()
bp.add_record({'rr': 'A', 'alias': 'foo', 'addr': '127.0.0.1'})
zps.assert_called_once_with()
zpm.assert_called_once_with({'alias': 'foo', 'addr': '127.0.0.1', 'rr': 'A'})
bp.reload_config.assert_called_once_with()
|
d213aa242b6293a67ba13859a81af4354d81f522 | h2o-py/tests/testdir_algos/gam/pyunit_PUBDEV_7798_overlapped_knots.py | h2o-py/tests/testdir_algos/gam/pyunit_PUBDEV_7798_overlapped_knots.py | import h2o
import numpy as np
from h2o.estimators.gam import H2OGeneralizedAdditiveEstimator
from tests import pyunit_utils
def knots_error():
# load and prepare California housing dataset
np.random.seed(1234)
data = h2o.H2OFrame(
python_obj={'C1': list(np.random.randint(0, 9, size=1000)),
'target': list(np.random.randint(0, 2, size=1000))
})
# use only 3 features and transform into classification problem
feature_names = ['C1']
data['target'] = data['target'].asfactor()
# split into train and validation sets
train, test = data.split_frame([0.8], seed=1234)
# build the GAM model
h2o_model = H2OGeneralizedAdditiveEstimator(family='binomial',
gam_columns=feature_names,
scale=[1],
num_knots=[10],
)
try:
h2o_model.train(x=feature_names, y='target', training_frame=train)
except:
print("Error correctly raised when cardinality < num_knots")
else:
raise Exception("Error not raised despited cardinality < num_knots")
print("done")
if __name__ == "__main__":
pyunit_utils.standalone_test(knots_error())
else:
knots_error()
| import h2o
import numpy as np
from h2o.estimators.gam import H2OGeneralizedAdditiveEstimator
from tests import pyunit_utils
def knots_error():
# load and prepare California housing dataset
np.random.seed(1234)
data = h2o.H2OFrame(
python_obj={'C1': list(np.random.randint(0, 9, size=1000)),
'target': list(np.random.randint(0, 2, size=1000))
})
# use only 3 features and transform into classification problem
feature_names = ['C1']
data['target'] = data['target'].asfactor()
# split into train and validation sets
train, test = data.split_frame([0.8], seed=1234)
# build the GAM model
h2o_model = H2OGeneralizedAdditiveEstimator(family='binomial',
gam_columns=feature_names,
scale=[1],
num_knots=[10],
)
try:
h2o_model.train(x=feature_names, y='target', training_frame=train)
assert False, "Number of knots validation should have failed"
except:
print("Error correctly raised when cardinality < num_knots")
else:
raise Exception("Error not raised despited cardinality < num_knots")
print("done")
if __name__ == "__main__":
pyunit_utils.standalone_test(knots_error())
else:
knots_error()
| Add assert to num knots validation unit test | Add assert to num knots validation unit test
| Python | apache-2.0 | h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-3 | import h2o
import numpy as np
from h2o.estimators.gam import H2OGeneralizedAdditiveEstimator
from tests import pyunit_utils
def knots_error():
# load and prepare California housing dataset
np.random.seed(1234)
data = h2o.H2OFrame(
python_obj={'C1': list(np.random.randint(0, 9, size=1000)),
'target': list(np.random.randint(0, 2, size=1000))
})
# use only 3 features and transform into classification problem
feature_names = ['C1']
data['target'] = data['target'].asfactor()
# split into train and validation sets
train, test = data.split_frame([0.8], seed=1234)
# build the GAM model
h2o_model = H2OGeneralizedAdditiveEstimator(family='binomial',
gam_columns=feature_names,
scale=[1],
num_knots=[10],
)
try:
h2o_model.train(x=feature_names, y='target', training_frame=train)
except:
print("Error correctly raised when cardinality < num_knots")
else:
raise Exception("Error not raised despited cardinality < num_knots")
print("done")
if __name__ == "__main__":
pyunit_utils.standalone_test(knots_error())
else:
knots_error()
Add assert to num knots validation unit test | import h2o
import numpy as np
from h2o.estimators.gam import H2OGeneralizedAdditiveEstimator
from tests import pyunit_utils
def knots_error():
# load and prepare California housing dataset
np.random.seed(1234)
data = h2o.H2OFrame(
python_obj={'C1': list(np.random.randint(0, 9, size=1000)),
'target': list(np.random.randint(0, 2, size=1000))
})
# use only 3 features and transform into classification problem
feature_names = ['C1']
data['target'] = data['target'].asfactor()
# split into train and validation sets
train, test = data.split_frame([0.8], seed=1234)
# build the GAM model
h2o_model = H2OGeneralizedAdditiveEstimator(family='binomial',
gam_columns=feature_names,
scale=[1],
num_knots=[10],
)
try:
h2o_model.train(x=feature_names, y='target', training_frame=train)
assert False, "Number of knots validation should have failed"
except:
print("Error correctly raised when cardinality < num_knots")
else:
raise Exception("Error not raised despited cardinality < num_knots")
print("done")
if __name__ == "__main__":
pyunit_utils.standalone_test(knots_error())
else:
knots_error()
| <commit_before>import h2o
import numpy as np
from h2o.estimators.gam import H2OGeneralizedAdditiveEstimator
from tests import pyunit_utils
def knots_error():
# load and prepare California housing dataset
np.random.seed(1234)
data = h2o.H2OFrame(
python_obj={'C1': list(np.random.randint(0, 9, size=1000)),
'target': list(np.random.randint(0, 2, size=1000))
})
# use only 3 features and transform into classification problem
feature_names = ['C1']
data['target'] = data['target'].asfactor()
# split into train and validation sets
train, test = data.split_frame([0.8], seed=1234)
# build the GAM model
h2o_model = H2OGeneralizedAdditiveEstimator(family='binomial',
gam_columns=feature_names,
scale=[1],
num_knots=[10],
)
try:
h2o_model.train(x=feature_names, y='target', training_frame=train)
except:
print("Error correctly raised when cardinality < num_knots")
else:
raise Exception("Error not raised despited cardinality < num_knots")
print("done")
if __name__ == "__main__":
pyunit_utils.standalone_test(knots_error())
else:
knots_error()
<commit_msg>Add assert to num knots validation unit test<commit_after> | import h2o
import numpy as np
from h2o.estimators.gam import H2OGeneralizedAdditiveEstimator
from tests import pyunit_utils
def knots_error():
# load and prepare California housing dataset
np.random.seed(1234)
data = h2o.H2OFrame(
python_obj={'C1': list(np.random.randint(0, 9, size=1000)),
'target': list(np.random.randint(0, 2, size=1000))
})
# use only 3 features and transform into classification problem
feature_names = ['C1']
data['target'] = data['target'].asfactor()
# split into train and validation sets
train, test = data.split_frame([0.8], seed=1234)
# build the GAM model
h2o_model = H2OGeneralizedAdditiveEstimator(family='binomial',
gam_columns=feature_names,
scale=[1],
num_knots=[10],
)
try:
h2o_model.train(x=feature_names, y='target', training_frame=train)
assert False, "Number of knots validation should have failed"
except:
print("Error correctly raised when cardinality < num_knots")
else:
raise Exception("Error not raised despited cardinality < num_knots")
print("done")
if __name__ == "__main__":
pyunit_utils.standalone_test(knots_error())
else:
knots_error()
| import h2o
import numpy as np
from h2o.estimators.gam import H2OGeneralizedAdditiveEstimator
from tests import pyunit_utils
def knots_error():
# load and prepare California housing dataset
np.random.seed(1234)
data = h2o.H2OFrame(
python_obj={'C1': list(np.random.randint(0, 9, size=1000)),
'target': list(np.random.randint(0, 2, size=1000))
})
# use only 3 features and transform into classification problem
feature_names = ['C1']
data['target'] = data['target'].asfactor()
# split into train and validation sets
train, test = data.split_frame([0.8], seed=1234)
# build the GAM model
h2o_model = H2OGeneralizedAdditiveEstimator(family='binomial',
gam_columns=feature_names,
scale=[1],
num_knots=[10],
)
try:
h2o_model.train(x=feature_names, y='target', training_frame=train)
except:
print("Error correctly raised when cardinality < num_knots")
else:
raise Exception("Error not raised despited cardinality < num_knots")
print("done")
if __name__ == "__main__":
pyunit_utils.standalone_test(knots_error())
else:
knots_error()
Add assert to num knots validation unit testimport h2o
import numpy as np
from h2o.estimators.gam import H2OGeneralizedAdditiveEstimator
from tests import pyunit_utils
def knots_error():
# load and prepare California housing dataset
np.random.seed(1234)
data = h2o.H2OFrame(
python_obj={'C1': list(np.random.randint(0, 9, size=1000)),
'target': list(np.random.randint(0, 2, size=1000))
})
# use only 3 features and transform into classification problem
feature_names = ['C1']
data['target'] = data['target'].asfactor()
# split into train and validation sets
train, test = data.split_frame([0.8], seed=1234)
# build the GAM model
h2o_model = H2OGeneralizedAdditiveEstimator(family='binomial',
gam_columns=feature_names,
scale=[1],
num_knots=[10],
)
try:
h2o_model.train(x=feature_names, y='target', training_frame=train)
assert False, "Number of knots validation should have failed"
except:
print("Error correctly raised when cardinality < num_knots")
else:
raise Exception("Error not raised despited cardinality < num_knots")
print("done")
if __name__ == "__main__":
pyunit_utils.standalone_test(knots_error())
else:
knots_error()
| <commit_before>import h2o
import numpy as np
from h2o.estimators.gam import H2OGeneralizedAdditiveEstimator
from tests import pyunit_utils
def knots_error():
# load and prepare California housing dataset
np.random.seed(1234)
data = h2o.H2OFrame(
python_obj={'C1': list(np.random.randint(0, 9, size=1000)),
'target': list(np.random.randint(0, 2, size=1000))
})
# use only 3 features and transform into classification problem
feature_names = ['C1']
data['target'] = data['target'].asfactor()
# split into train and validation sets
train, test = data.split_frame([0.8], seed=1234)
# build the GAM model
h2o_model = H2OGeneralizedAdditiveEstimator(family='binomial',
gam_columns=feature_names,
scale=[1],
num_knots=[10],
)
try:
h2o_model.train(x=feature_names, y='target', training_frame=train)
except:
print("Error correctly raised when cardinality < num_knots")
else:
raise Exception("Error not raised despited cardinality < num_knots")
print("done")
if __name__ == "__main__":
pyunit_utils.standalone_test(knots_error())
else:
knots_error()
<commit_msg>Add assert to num knots validation unit test<commit_after>import h2o
import numpy as np
from h2o.estimators.gam import H2OGeneralizedAdditiveEstimator
from tests import pyunit_utils
def knots_error():
# load and prepare California housing dataset
np.random.seed(1234)
data = h2o.H2OFrame(
python_obj={'C1': list(np.random.randint(0, 9, size=1000)),
'target': list(np.random.randint(0, 2, size=1000))
})
# use only 3 features and transform into classification problem
feature_names = ['C1']
data['target'] = data['target'].asfactor()
# split into train and validation sets
train, test = data.split_frame([0.8], seed=1234)
# build the GAM model
h2o_model = H2OGeneralizedAdditiveEstimator(family='binomial',
gam_columns=feature_names,
scale=[1],
num_knots=[10],
)
try:
h2o_model.train(x=feature_names, y='target', training_frame=train)
assert False, "Number of knots validation should have failed"
except:
print("Error correctly raised when cardinality < num_knots")
else:
raise Exception("Error not raised despited cardinality < num_knots")
print("done")
if __name__ == "__main__":
pyunit_utils.standalone_test(knots_error())
else:
knots_error()
|
380baa34af7e8a704780f0ec535b626f4a286e23 | deflect/admin.py | deflect/admin.py | from django.contrib import admin
from .models import RedirectURL
class RedirectURLAdmin(admin.ModelAdmin):
list_display = ('url', 'short_url', 'hits', 'last_used', 'creator', 'campaign', 'medium',)
list_filter = ('creator__username', 'campaign', 'medium',)
ordering = ('-last_used',)
readonly_fields = ('created', 'short_url', 'qr_code', 'hits', 'last_used',)
search_fields = ['url', 'campaign']
fieldsets = ((None, {'fields': ('url', 'short_url',)}),
('Google', {'fields': ('campaign', 'medium', 'content',)}),
('Additional info', {'fields': ('description', 'qr_code',)}),
('Short URL Usage', {'fields': ('hits', 'created', 'last_used',)}),)
def save_model(self, request, obj, form, change):
obj.user = request.user
obj.save()
admin.site.register(RedirectURL, RedirectURLAdmin)
| from django.contrib import admin
from .models import RedirectURL
class RedirectURLAdmin(admin.ModelAdmin):
list_display = ('url', 'short_url', 'hits', 'last_used', 'creator', 'campaign', 'medium',)
list_filter = ('creator__username', 'campaign', 'medium',)
ordering = ('-last_used',)
readonly_fields = ('created', 'short_url', 'qr_code', 'hits', 'last_used',)
search_fields = ['url', 'campaign']
fieldsets = ((None, {'fields': ('url', 'short_url',)}),
('Google', {'fields': ('campaign', 'medium', 'content',)}),
('Additional info', {'fields': ('description', 'qr_code',)}),
('Short URL Usage', {'fields': ('hits', 'created', 'last_used',)}),)
def save_model(self, request, obj, form, change):
if not change:
obj.creator = request.user
obj.save()
admin.site.register(RedirectURL, RedirectURLAdmin)
| Fix model creator updating on change event | Fix model creator updating on change event
| Python | bsd-3-clause | jbittel/django-deflect | from django.contrib import admin
from .models import RedirectURL
class RedirectURLAdmin(admin.ModelAdmin):
list_display = ('url', 'short_url', 'hits', 'last_used', 'creator', 'campaign', 'medium',)
list_filter = ('creator__username', 'campaign', 'medium',)
ordering = ('-last_used',)
readonly_fields = ('created', 'short_url', 'qr_code', 'hits', 'last_used',)
search_fields = ['url', 'campaign']
fieldsets = ((None, {'fields': ('url', 'short_url',)}),
('Google', {'fields': ('campaign', 'medium', 'content',)}),
('Additional info', {'fields': ('description', 'qr_code',)}),
('Short URL Usage', {'fields': ('hits', 'created', 'last_used',)}),)
def save_model(self, request, obj, form, change):
obj.user = request.user
obj.save()
admin.site.register(RedirectURL, RedirectURLAdmin)
Fix model creator updating on change event | from django.contrib import admin
from .models import RedirectURL
class RedirectURLAdmin(admin.ModelAdmin):
list_display = ('url', 'short_url', 'hits', 'last_used', 'creator', 'campaign', 'medium',)
list_filter = ('creator__username', 'campaign', 'medium',)
ordering = ('-last_used',)
readonly_fields = ('created', 'short_url', 'qr_code', 'hits', 'last_used',)
search_fields = ['url', 'campaign']
fieldsets = ((None, {'fields': ('url', 'short_url',)}),
('Google', {'fields': ('campaign', 'medium', 'content',)}),
('Additional info', {'fields': ('description', 'qr_code',)}),
('Short URL Usage', {'fields': ('hits', 'created', 'last_used',)}),)
def save_model(self, request, obj, form, change):
if not change:
obj.creator = request.user
obj.save()
admin.site.register(RedirectURL, RedirectURLAdmin)
| <commit_before>from django.contrib import admin
from .models import RedirectURL
class RedirectURLAdmin(admin.ModelAdmin):
list_display = ('url', 'short_url', 'hits', 'last_used', 'creator', 'campaign', 'medium',)
list_filter = ('creator__username', 'campaign', 'medium',)
ordering = ('-last_used',)
readonly_fields = ('created', 'short_url', 'qr_code', 'hits', 'last_used',)
search_fields = ['url', 'campaign']
fieldsets = ((None, {'fields': ('url', 'short_url',)}),
('Google', {'fields': ('campaign', 'medium', 'content',)}),
('Additional info', {'fields': ('description', 'qr_code',)}),
('Short URL Usage', {'fields': ('hits', 'created', 'last_used',)}),)
def save_model(self, request, obj, form, change):
obj.user = request.user
obj.save()
admin.site.register(RedirectURL, RedirectURLAdmin)
<commit_msg>Fix model creator updating on change event<commit_after> | from django.contrib import admin
from .models import RedirectURL
class RedirectURLAdmin(admin.ModelAdmin):
list_display = ('url', 'short_url', 'hits', 'last_used', 'creator', 'campaign', 'medium',)
list_filter = ('creator__username', 'campaign', 'medium',)
ordering = ('-last_used',)
readonly_fields = ('created', 'short_url', 'qr_code', 'hits', 'last_used',)
search_fields = ['url', 'campaign']
fieldsets = ((None, {'fields': ('url', 'short_url',)}),
('Google', {'fields': ('campaign', 'medium', 'content',)}),
('Additional info', {'fields': ('description', 'qr_code',)}),
('Short URL Usage', {'fields': ('hits', 'created', 'last_used',)}),)
def save_model(self, request, obj, form, change):
if not change:
obj.creator = request.user
obj.save()
admin.site.register(RedirectURL, RedirectURLAdmin)
| from django.contrib import admin
from .models import RedirectURL
class RedirectURLAdmin(admin.ModelAdmin):
list_display = ('url', 'short_url', 'hits', 'last_used', 'creator', 'campaign', 'medium',)
list_filter = ('creator__username', 'campaign', 'medium',)
ordering = ('-last_used',)
readonly_fields = ('created', 'short_url', 'qr_code', 'hits', 'last_used',)
search_fields = ['url', 'campaign']
fieldsets = ((None, {'fields': ('url', 'short_url',)}),
('Google', {'fields': ('campaign', 'medium', 'content',)}),
('Additional info', {'fields': ('description', 'qr_code',)}),
('Short URL Usage', {'fields': ('hits', 'created', 'last_used',)}),)
def save_model(self, request, obj, form, change):
obj.user = request.user
obj.save()
admin.site.register(RedirectURL, RedirectURLAdmin)
Fix model creator updating on change eventfrom django.contrib import admin
from .models import RedirectURL
class RedirectURLAdmin(admin.ModelAdmin):
list_display = ('url', 'short_url', 'hits', 'last_used', 'creator', 'campaign', 'medium',)
list_filter = ('creator__username', 'campaign', 'medium',)
ordering = ('-last_used',)
readonly_fields = ('created', 'short_url', 'qr_code', 'hits', 'last_used',)
search_fields = ['url', 'campaign']
fieldsets = ((None, {'fields': ('url', 'short_url',)}),
('Google', {'fields': ('campaign', 'medium', 'content',)}),
('Additional info', {'fields': ('description', 'qr_code',)}),
('Short URL Usage', {'fields': ('hits', 'created', 'last_used',)}),)
def save_model(self, request, obj, form, change):
if not change:
obj.creator = request.user
obj.save()
admin.site.register(RedirectURL, RedirectURLAdmin)
| <commit_before>from django.contrib import admin
from .models import RedirectURL
class RedirectURLAdmin(admin.ModelAdmin):
list_display = ('url', 'short_url', 'hits', 'last_used', 'creator', 'campaign', 'medium',)
list_filter = ('creator__username', 'campaign', 'medium',)
ordering = ('-last_used',)
readonly_fields = ('created', 'short_url', 'qr_code', 'hits', 'last_used',)
search_fields = ['url', 'campaign']
fieldsets = ((None, {'fields': ('url', 'short_url',)}),
('Google', {'fields': ('campaign', 'medium', 'content',)}),
('Additional info', {'fields': ('description', 'qr_code',)}),
('Short URL Usage', {'fields': ('hits', 'created', 'last_used',)}),)
def save_model(self, request, obj, form, change):
obj.user = request.user
obj.save()
admin.site.register(RedirectURL, RedirectURLAdmin)
<commit_msg>Fix model creator updating on change event<commit_after>from django.contrib import admin
from .models import RedirectURL
class RedirectURLAdmin(admin.ModelAdmin):
list_display = ('url', 'short_url', 'hits', 'last_used', 'creator', 'campaign', 'medium',)
list_filter = ('creator__username', 'campaign', 'medium',)
ordering = ('-last_used',)
readonly_fields = ('created', 'short_url', 'qr_code', 'hits', 'last_used',)
search_fields = ['url', 'campaign']
fieldsets = ((None, {'fields': ('url', 'short_url',)}),
('Google', {'fields': ('campaign', 'medium', 'content',)}),
('Additional info', {'fields': ('description', 'qr_code',)}),
('Short URL Usage', {'fields': ('hits', 'created', 'last_used',)}),)
def save_model(self, request, obj, form, change):
if not change:
obj.creator = request.user
obj.save()
admin.site.register(RedirectURL, RedirectURLAdmin)
|
cc48ad87026b57b02530322b3c27f2d60e94f2e4 | packages/mono_crypto.py | packages/mono_crypto.py | from mono_master import MonoMasterPackage
from bockbuild.util.util import *
class MonoMasterEncryptedPackage (MonoMasterPackage):
def __init__(self):
MonoMasterPackage.__init__ (self)
self.configure_flags.extend(['--enable-extension-module=crypto --enable-native-types'])
def prep(self):
MonoMasterPackage.prep(self)
retry (self.checkout_mono_extensions)
def checkout_mono_extensions(self):
ext = 'git@github.com:xamarin/mono-extensions.git'
dirname = os.path.join(self.profile.build_root, "mono-extensions")
if not os.path.exists(dirname):
self.sh('%' + '{git} clone --local --shared "%s" "%s"' % (ext, dirname))
self.pushd(dirname)
try:
self.sh('%{git} clean -xffd')
self.sh('%{git} fetch --all --prune')
if "pr/" not in self.git_branch:
self.sh('%' + '{git} checkout origin/%s' % self.git_branch)
else:
self.sh('%{git} checkout origin/master')
except Exception as e:
self.rm_if_exists (dirname)
raise
finally:
info ('Mono crypto extensions (rev. %s)' % git_get_revision (self))
self.popd ()
MonoMasterEncryptedPackage() | from mono_master import MonoMasterPackage
from bockbuild.util.util import *
class MonoMasterEncryptedPackage (MonoMasterPackage):
def __init__(self):
MonoMasterPackage.__init__ (self)
self.configure_flags.extend(['--enable-extension-module=crypto --enable-native-types'])
def prep(self):
MonoMasterPackage.prep(self)
retry (self.checkout_mono_extensions)
def checkout_mono_extensions(self):
ext = 'git@github.com:xamarin/mono-extensions.git'
dirname = os.path.join(self.profile.build_root, "mono-extensions")
if not os.path.exists(dirname):
self.sh('%' + '{git} clone --local --shared "%s" "%s"' % (ext, dirname))
self.pushd(dirname)
try:
self.sh('%{git} clean -xffd')
self.sh('%{git} fetch --all --prune')
if "pr/" not in self.git_branch:
self.sh('%' + '{git} checkout origin/%s' % self.git_branch)
else:
self.sh('%{git} checkout origin/master')
self.sh ('%{git} reset --hard')
except Exception as e:
self.rm_if_exists (dirname)
raise
finally:
info ('Mono crypto extensions (rev. %s)' % git_get_revision (self))
self.popd ()
MonoMasterEncryptedPackage() | Add a git reset to trigger a possible 'error: unable to read sha1 file...' error and cause a fresh checkout to resolve | Add a git reset to trigger a possible 'error: unable to read sha1 file...' error and cause a fresh checkout to resolve
| Python | mit | mono/bockbuild,mono/bockbuild | from mono_master import MonoMasterPackage
from bockbuild.util.util import *
class MonoMasterEncryptedPackage (MonoMasterPackage):
def __init__(self):
MonoMasterPackage.__init__ (self)
self.configure_flags.extend(['--enable-extension-module=crypto --enable-native-types'])
def prep(self):
MonoMasterPackage.prep(self)
retry (self.checkout_mono_extensions)
def checkout_mono_extensions(self):
ext = 'git@github.com:xamarin/mono-extensions.git'
dirname = os.path.join(self.profile.build_root, "mono-extensions")
if not os.path.exists(dirname):
self.sh('%' + '{git} clone --local --shared "%s" "%s"' % (ext, dirname))
self.pushd(dirname)
try:
self.sh('%{git} clean -xffd')
self.sh('%{git} fetch --all --prune')
if "pr/" not in self.git_branch:
self.sh('%' + '{git} checkout origin/%s' % self.git_branch)
else:
self.sh('%{git} checkout origin/master')
except Exception as e:
self.rm_if_exists (dirname)
raise
finally:
info ('Mono crypto extensions (rev. %s)' % git_get_revision (self))
self.popd ()
MonoMasterEncryptedPackage()Add a git reset to trigger a possible 'error: unable to read sha1 file...' error and cause a fresh checkout to resolve | from mono_master import MonoMasterPackage
from bockbuild.util.util import *
class MonoMasterEncryptedPackage (MonoMasterPackage):
def __init__(self):
MonoMasterPackage.__init__ (self)
self.configure_flags.extend(['--enable-extension-module=crypto --enable-native-types'])
def prep(self):
MonoMasterPackage.prep(self)
retry (self.checkout_mono_extensions)
def checkout_mono_extensions(self):
ext = 'git@github.com:xamarin/mono-extensions.git'
dirname = os.path.join(self.profile.build_root, "mono-extensions")
if not os.path.exists(dirname):
self.sh('%' + '{git} clone --local --shared "%s" "%s"' % (ext, dirname))
self.pushd(dirname)
try:
self.sh('%{git} clean -xffd')
self.sh('%{git} fetch --all --prune')
if "pr/" not in self.git_branch:
self.sh('%' + '{git} checkout origin/%s' % self.git_branch)
else:
self.sh('%{git} checkout origin/master')
self.sh ('%{git} reset --hard')
except Exception as e:
self.rm_if_exists (dirname)
raise
finally:
info ('Mono crypto extensions (rev. %s)' % git_get_revision (self))
self.popd ()
MonoMasterEncryptedPackage() | <commit_before>from mono_master import MonoMasterPackage
from bockbuild.util.util import *
class MonoMasterEncryptedPackage (MonoMasterPackage):
def __init__(self):
MonoMasterPackage.__init__ (self)
self.configure_flags.extend(['--enable-extension-module=crypto --enable-native-types'])
def prep(self):
MonoMasterPackage.prep(self)
retry (self.checkout_mono_extensions)
def checkout_mono_extensions(self):
ext = 'git@github.com:xamarin/mono-extensions.git'
dirname = os.path.join(self.profile.build_root, "mono-extensions")
if not os.path.exists(dirname):
self.sh('%' + '{git} clone --local --shared "%s" "%s"' % (ext, dirname))
self.pushd(dirname)
try:
self.sh('%{git} clean -xffd')
self.sh('%{git} fetch --all --prune')
if "pr/" not in self.git_branch:
self.sh('%' + '{git} checkout origin/%s' % self.git_branch)
else:
self.sh('%{git} checkout origin/master')
except Exception as e:
self.rm_if_exists (dirname)
raise
finally:
info ('Mono crypto extensions (rev. %s)' % git_get_revision (self))
self.popd ()
MonoMasterEncryptedPackage()<commit_msg>Add a git reset to trigger a possible 'error: unable to read sha1 file...' error and cause a fresh checkout to resolve<commit_after> | from mono_master import MonoMasterPackage
from bockbuild.util.util import *
class MonoMasterEncryptedPackage (MonoMasterPackage):
def __init__(self):
MonoMasterPackage.__init__ (self)
self.configure_flags.extend(['--enable-extension-module=crypto --enable-native-types'])
def prep(self):
MonoMasterPackage.prep(self)
retry (self.checkout_mono_extensions)
def checkout_mono_extensions(self):
ext = 'git@github.com:xamarin/mono-extensions.git'
dirname = os.path.join(self.profile.build_root, "mono-extensions")
if not os.path.exists(dirname):
self.sh('%' + '{git} clone --local --shared "%s" "%s"' % (ext, dirname))
self.pushd(dirname)
try:
self.sh('%{git} clean -xffd')
self.sh('%{git} fetch --all --prune')
if "pr/" not in self.git_branch:
self.sh('%' + '{git} checkout origin/%s' % self.git_branch)
else:
self.sh('%{git} checkout origin/master')
self.sh ('%{git} reset --hard')
except Exception as e:
self.rm_if_exists (dirname)
raise
finally:
info ('Mono crypto extensions (rev. %s)' % git_get_revision (self))
self.popd ()
MonoMasterEncryptedPackage() | from mono_master import MonoMasterPackage
from bockbuild.util.util import *
class MonoMasterEncryptedPackage (MonoMasterPackage):
def __init__(self):
MonoMasterPackage.__init__ (self)
self.configure_flags.extend(['--enable-extension-module=crypto --enable-native-types'])
def prep(self):
MonoMasterPackage.prep(self)
retry (self.checkout_mono_extensions)
def checkout_mono_extensions(self):
ext = 'git@github.com:xamarin/mono-extensions.git'
dirname = os.path.join(self.profile.build_root, "mono-extensions")
if not os.path.exists(dirname):
self.sh('%' + '{git} clone --local --shared "%s" "%s"' % (ext, dirname))
self.pushd(dirname)
try:
self.sh('%{git} clean -xffd')
self.sh('%{git} fetch --all --prune')
if "pr/" not in self.git_branch:
self.sh('%' + '{git} checkout origin/%s' % self.git_branch)
else:
self.sh('%{git} checkout origin/master')
except Exception as e:
self.rm_if_exists (dirname)
raise
finally:
info ('Mono crypto extensions (rev. %s)' % git_get_revision (self))
self.popd ()
MonoMasterEncryptedPackage()Add a git reset to trigger a possible 'error: unable to read sha1 file...' error and cause a fresh checkout to resolvefrom mono_master import MonoMasterPackage
from bockbuild.util.util import *
class MonoMasterEncryptedPackage (MonoMasterPackage):
def __init__(self):
MonoMasterPackage.__init__ (self)
self.configure_flags.extend(['--enable-extension-module=crypto --enable-native-types'])
def prep(self):
MonoMasterPackage.prep(self)
retry (self.checkout_mono_extensions)
def checkout_mono_extensions(self):
ext = 'git@github.com:xamarin/mono-extensions.git'
dirname = os.path.join(self.profile.build_root, "mono-extensions")
if not os.path.exists(dirname):
self.sh('%' + '{git} clone --local --shared "%s" "%s"' % (ext, dirname))
self.pushd(dirname)
try:
self.sh('%{git} clean -xffd')
self.sh('%{git} fetch --all --prune')
if "pr/" not in self.git_branch:
self.sh('%' + '{git} checkout origin/%s' % self.git_branch)
else:
self.sh('%{git} checkout origin/master')
self.sh ('%{git} reset --hard')
except Exception as e:
self.rm_if_exists (dirname)
raise
finally:
info ('Mono crypto extensions (rev. %s)' % git_get_revision (self))
self.popd ()
MonoMasterEncryptedPackage() | <commit_before>from mono_master import MonoMasterPackage
from bockbuild.util.util import *
class MonoMasterEncryptedPackage (MonoMasterPackage):
def __init__(self):
MonoMasterPackage.__init__ (self)
self.configure_flags.extend(['--enable-extension-module=crypto --enable-native-types'])
def prep(self):
MonoMasterPackage.prep(self)
retry (self.checkout_mono_extensions)
def checkout_mono_extensions(self):
ext = 'git@github.com:xamarin/mono-extensions.git'
dirname = os.path.join(self.profile.build_root, "mono-extensions")
if not os.path.exists(dirname):
self.sh('%' + '{git} clone --local --shared "%s" "%s"' % (ext, dirname))
self.pushd(dirname)
try:
self.sh('%{git} clean -xffd')
self.sh('%{git} fetch --all --prune')
if "pr/" not in self.git_branch:
self.sh('%' + '{git} checkout origin/%s' % self.git_branch)
else:
self.sh('%{git} checkout origin/master')
except Exception as e:
self.rm_if_exists (dirname)
raise
finally:
info ('Mono crypto extensions (rev. %s)' % git_get_revision (self))
self.popd ()
MonoMasterEncryptedPackage()<commit_msg>Add a git reset to trigger a possible 'error: unable to read sha1 file...' error and cause a fresh checkout to resolve<commit_after>from mono_master import MonoMasterPackage
from bockbuild.util.util import *
class MonoMasterEncryptedPackage (MonoMasterPackage):
def __init__(self):
MonoMasterPackage.__init__ (self)
self.configure_flags.extend(['--enable-extension-module=crypto --enable-native-types'])
def prep(self):
MonoMasterPackage.prep(self)
retry (self.checkout_mono_extensions)
def checkout_mono_extensions(self):
ext = 'git@github.com:xamarin/mono-extensions.git'
dirname = os.path.join(self.profile.build_root, "mono-extensions")
if not os.path.exists(dirname):
self.sh('%' + '{git} clone --local --shared "%s" "%s"' % (ext, dirname))
self.pushd(dirname)
try:
self.sh('%{git} clean -xffd')
self.sh('%{git} fetch --all --prune')
if "pr/" not in self.git_branch:
self.sh('%' + '{git} checkout origin/%s' % self.git_branch)
else:
self.sh('%{git} checkout origin/master')
self.sh ('%{git} reset --hard')
except Exception as e:
self.rm_if_exists (dirname)
raise
finally:
info ('Mono crypto extensions (rev. %s)' % git_get_revision (self))
self.popd ()
MonoMasterEncryptedPackage() |
1cda84c7f23c6a5e89c9f871dba5d12c00789d1a | extract_contamination.py | extract_contamination.py | import sys
import os
header = ['Mouse_single', 'Mouse_multiple', 'Human', 'Other', 'Unmapped']
print '\t'.join(header)
for fi in sys.argv[1:]:
sample = os.path.basename(fi).split('.')[0]
with open(fi) as screen_results:
results = {}
for line in screen_results:
fields = line.strip().split()
if len(fields) and fields[0][0] != '#' and fields[0] != 'Library':
if fields[0] == '%Hit_no_libraries:':
results['unmapped'] = int(float(fields[1]) / 100.0 * results['no_reads'])
continue
results[fields[0] + '_single'] = int(fields[4])
results[fields[0] + '_multiple'] = int(fields[6])
results['no_reads'] = int(fields[1])
try:
data = [results['Mouse_single'],
results['Mouse_multiple'],
results['Human_single'] + results['Human_multiple']]
except:
sys.exit('Malformed file: {0}'.format(fi))
data.append(results['no_reads'] - sum(data) - results['unmapped'])
data.append(results['unmapped'])
data = map(lambda i:str(i / float(sum(data))),data)
data = [sample] + data
print '\t'.join(data)
| import sys
import os
header = ['Mouse_single', 'Mouse_multiple', 'Human', 'Other', 'Unmapped']
print '\t'.join(header)
for fi in sys.argv[1:]:
sample = os.path.basename(fi).split('.')[0]
with open(fi) as screen_results:
results = {}
for line in screen_results:
fields = line.strip().split()
if len(fields) and fields[0][0] != '#' and fields[0] != 'Library':
if fields[0] == '%Hit_no_libraries:':
results['unmapped'] = int(float(fields[1]) / 100.0 * results['no_reads'])
continue
results[fields[0] + '_single'] = int(fields[4])
results[fields[0] + '_multiple'] = int(fields[6])
results['no_reads'] = int(fields[1])
if not len(results):
data = ['0'] * 5
else:
try:
data = [results['Mouse_single'],
results['Mouse_multiple'],
results['Human_single'] + results['Human_multiple']]
except:
sys.exit('Malformed file: {0}'.format(fi))
data.append(results['no_reads'] - sum(data) - results['unmapped'])
data.append(results['unmapped'])
data = map(lambda i:str(i / float(sum(data))),data)
data = [sample] + data
print '\t'.join(data)
| Handle empty fastq_screen files properly. | Handle empty fastq_screen files properly.
| Python | apache-2.0 | pombo-lab/gamtools,pombo-lab/gamtools | import sys
import os
header = ['Mouse_single', 'Mouse_multiple', 'Human', 'Other', 'Unmapped']
print '\t'.join(header)
for fi in sys.argv[1:]:
sample = os.path.basename(fi).split('.')[0]
with open(fi) as screen_results:
results = {}
for line in screen_results:
fields = line.strip().split()
if len(fields) and fields[0][0] != '#' and fields[0] != 'Library':
if fields[0] == '%Hit_no_libraries:':
results['unmapped'] = int(float(fields[1]) / 100.0 * results['no_reads'])
continue
results[fields[0] + '_single'] = int(fields[4])
results[fields[0] + '_multiple'] = int(fields[6])
results['no_reads'] = int(fields[1])
try:
data = [results['Mouse_single'],
results['Mouse_multiple'],
results['Human_single'] + results['Human_multiple']]
except:
sys.exit('Malformed file: {0}'.format(fi))
data.append(results['no_reads'] - sum(data) - results['unmapped'])
data.append(results['unmapped'])
data = map(lambda i:str(i / float(sum(data))),data)
data = [sample] + data
print '\t'.join(data)
Handle empty fastq_screen files properly. | import sys
import os
header = ['Mouse_single', 'Mouse_multiple', 'Human', 'Other', 'Unmapped']
print '\t'.join(header)
for fi in sys.argv[1:]:
sample = os.path.basename(fi).split('.')[0]
with open(fi) as screen_results:
results = {}
for line in screen_results:
fields = line.strip().split()
if len(fields) and fields[0][0] != '#' and fields[0] != 'Library':
if fields[0] == '%Hit_no_libraries:':
results['unmapped'] = int(float(fields[1]) / 100.0 * results['no_reads'])
continue
results[fields[0] + '_single'] = int(fields[4])
results[fields[0] + '_multiple'] = int(fields[6])
results['no_reads'] = int(fields[1])
if not len(results):
data = ['0'] * 5
else:
try:
data = [results['Mouse_single'],
results['Mouse_multiple'],
results['Human_single'] + results['Human_multiple']]
except:
sys.exit('Malformed file: {0}'.format(fi))
data.append(results['no_reads'] - sum(data) - results['unmapped'])
data.append(results['unmapped'])
data = map(lambda i:str(i / float(sum(data))),data)
data = [sample] + data
print '\t'.join(data)
| <commit_before>import sys
import os
header = ['Mouse_single', 'Mouse_multiple', 'Human', 'Other', 'Unmapped']
print '\t'.join(header)
for fi in sys.argv[1:]:
sample = os.path.basename(fi).split('.')[0]
with open(fi) as screen_results:
results = {}
for line in screen_results:
fields = line.strip().split()
if len(fields) and fields[0][0] != '#' and fields[0] != 'Library':
if fields[0] == '%Hit_no_libraries:':
results['unmapped'] = int(float(fields[1]) / 100.0 * results['no_reads'])
continue
results[fields[0] + '_single'] = int(fields[4])
results[fields[0] + '_multiple'] = int(fields[6])
results['no_reads'] = int(fields[1])
try:
data = [results['Mouse_single'],
results['Mouse_multiple'],
results['Human_single'] + results['Human_multiple']]
except:
sys.exit('Malformed file: {0}'.format(fi))
data.append(results['no_reads'] - sum(data) - results['unmapped'])
data.append(results['unmapped'])
data = map(lambda i:str(i / float(sum(data))),data)
data = [sample] + data
print '\t'.join(data)
<commit_msg>Handle empty fastq_screen files properly.<commit_after> | import sys
import os
header = ['Mouse_single', 'Mouse_multiple', 'Human', 'Other', 'Unmapped']
print '\t'.join(header)
for fi in sys.argv[1:]:
sample = os.path.basename(fi).split('.')[0]
with open(fi) as screen_results:
results = {}
for line in screen_results:
fields = line.strip().split()
if len(fields) and fields[0][0] != '#' and fields[0] != 'Library':
if fields[0] == '%Hit_no_libraries:':
results['unmapped'] = int(float(fields[1]) / 100.0 * results['no_reads'])
continue
results[fields[0] + '_single'] = int(fields[4])
results[fields[0] + '_multiple'] = int(fields[6])
results['no_reads'] = int(fields[1])
if not len(results):
data = ['0'] * 5
else:
try:
data = [results['Mouse_single'],
results['Mouse_multiple'],
results['Human_single'] + results['Human_multiple']]
except:
sys.exit('Malformed file: {0}'.format(fi))
data.append(results['no_reads'] - sum(data) - results['unmapped'])
data.append(results['unmapped'])
data = map(lambda i:str(i / float(sum(data))),data)
data = [sample] + data
print '\t'.join(data)
| import sys
import os
header = ['Mouse_single', 'Mouse_multiple', 'Human', 'Other', 'Unmapped']
print '\t'.join(header)
for fi in sys.argv[1:]:
sample = os.path.basename(fi).split('.')[0]
with open(fi) as screen_results:
results = {}
for line in screen_results:
fields = line.strip().split()
if len(fields) and fields[0][0] != '#' and fields[0] != 'Library':
if fields[0] == '%Hit_no_libraries:':
results['unmapped'] = int(float(fields[1]) / 100.0 * results['no_reads'])
continue
results[fields[0] + '_single'] = int(fields[4])
results[fields[0] + '_multiple'] = int(fields[6])
results['no_reads'] = int(fields[1])
try:
data = [results['Mouse_single'],
results['Mouse_multiple'],
results['Human_single'] + results['Human_multiple']]
except:
sys.exit('Malformed file: {0}'.format(fi))
data.append(results['no_reads'] - sum(data) - results['unmapped'])
data.append(results['unmapped'])
data = map(lambda i:str(i / float(sum(data))),data)
data = [sample] + data
print '\t'.join(data)
Handle empty fastq_screen files properly.import sys
import os
header = ['Mouse_single', 'Mouse_multiple', 'Human', 'Other', 'Unmapped']
print '\t'.join(header)
for fi in sys.argv[1:]:
sample = os.path.basename(fi).split('.')[0]
with open(fi) as screen_results:
results = {}
for line in screen_results:
fields = line.strip().split()
if len(fields) and fields[0][0] != '#' and fields[0] != 'Library':
if fields[0] == '%Hit_no_libraries:':
results['unmapped'] = int(float(fields[1]) / 100.0 * results['no_reads'])
continue
results[fields[0] + '_single'] = int(fields[4])
results[fields[0] + '_multiple'] = int(fields[6])
results['no_reads'] = int(fields[1])
if not len(results):
data = ['0'] * 5
else:
try:
data = [results['Mouse_single'],
results['Mouse_multiple'],
results['Human_single'] + results['Human_multiple']]
except:
sys.exit('Malformed file: {0}'.format(fi))
data.append(results['no_reads'] - sum(data) - results['unmapped'])
data.append(results['unmapped'])
data = map(lambda i:str(i / float(sum(data))),data)
data = [sample] + data
print '\t'.join(data)
| <commit_before>import sys
import os
header = ['Mouse_single', 'Mouse_multiple', 'Human', 'Other', 'Unmapped']
print '\t'.join(header)
for fi in sys.argv[1:]:
sample = os.path.basename(fi).split('.')[0]
with open(fi) as screen_results:
results = {}
for line in screen_results:
fields = line.strip().split()
if len(fields) and fields[0][0] != '#' and fields[0] != 'Library':
if fields[0] == '%Hit_no_libraries:':
results['unmapped'] = int(float(fields[1]) / 100.0 * results['no_reads'])
continue
results[fields[0] + '_single'] = int(fields[4])
results[fields[0] + '_multiple'] = int(fields[6])
results['no_reads'] = int(fields[1])
try:
data = [results['Mouse_single'],
results['Mouse_multiple'],
results['Human_single'] + results['Human_multiple']]
except:
sys.exit('Malformed file: {0}'.format(fi))
data.append(results['no_reads'] - sum(data) - results['unmapped'])
data.append(results['unmapped'])
data = map(lambda i:str(i / float(sum(data))),data)
data = [sample] + data
print '\t'.join(data)
<commit_msg>Handle empty fastq_screen files properly.<commit_after>import sys
import os
header = ['Mouse_single', 'Mouse_multiple', 'Human', 'Other', 'Unmapped']
print '\t'.join(header)
for fi in sys.argv[1:]:
sample = os.path.basename(fi).split('.')[0]
with open(fi) as screen_results:
results = {}
for line in screen_results:
fields = line.strip().split()
if len(fields) and fields[0][0] != '#' and fields[0] != 'Library':
if fields[0] == '%Hit_no_libraries:':
results['unmapped'] = int(float(fields[1]) / 100.0 * results['no_reads'])
continue
results[fields[0] + '_single'] = int(fields[4])
results[fields[0] + '_multiple'] = int(fields[6])
results['no_reads'] = int(fields[1])
if not len(results):
data = ['0'] * 5
else:
try:
data = [results['Mouse_single'],
results['Mouse_multiple'],
results['Human_single'] + results['Human_multiple']]
except:
sys.exit('Malformed file: {0}'.format(fi))
data.append(results['no_reads'] - sum(data) - results['unmapped'])
data.append(results['unmapped'])
data = map(lambda i:str(i / float(sum(data))),data)
data = [sample] + data
print '\t'.join(data)
|
d9ab07c9c984d50ff93040d0220e4a3997e29f79 | fluent_comments/email.py | fluent_comments/email.py | from django.conf import settings
from django.core.mail import send_mail
from django.template.loader import render_to_string
try:
from django.contrib.sites.shortcuts import get_current_site # Django 1.9+
except ImportError:
from django.contrib.sites.models import get_current_site
def send_comment_posted(comment, request):
"""
Send the email to staff that an comment was posted.
While the django_comments module has email support,
it doesn't pass the 'request' to the context.
This also changes the subject to show the page title.
"""
recipient_list = [manager_tuple[1] for manager_tuple in settings.MANAGERS]
site = get_current_site(request)
content_object = comment.content_object
content_title = str(content_object)
if comment.is_removed:
subject = u'[{0}] Spam comment on "{1}"'.format(site.name, content_title)
elif not comment.is_public:
subject = u'[{0}] Moderated comment on "{1}"'.format(site.name, content_title)
else:
subject = u'[{0}] New comment posted on "{1}"'.format(site.name, content_title)
context = {
'site': site,
'comment': comment,
'content_object': content_object
}
message = render_to_string("comments/comment_notification_email.txt", context, request=request)
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list, fail_silently=True)
| from django.conf import settings
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.encoding import force_text
try:
from django.contrib.sites.shortcuts import get_current_site # Django 1.9+
except ImportError:
from django.contrib.sites.models import get_current_site
def send_comment_posted(comment, request):
"""
Send the email to staff that an comment was posted.
While the django_comments module has email support,
it doesn't pass the 'request' to the context.
This also changes the subject to show the page title.
"""
recipient_list = [manager_tuple[1] for manager_tuple in settings.MANAGERS]
site = get_current_site(request)
content_object = comment.content_object
content_title = force_text(content_object)
if comment.is_removed:
subject = u'[{0}] Spam comment on "{1}"'.format(site.name, content_title)
elif not comment.is_public:
subject = u'[{0}] Moderated comment on "{1}"'.format(site.name, content_title)
else:
subject = u'[{0}] New comment posted on "{1}"'.format(site.name, content_title)
context = {
'site': site,
'comment': comment,
'content_object': content_object
}
message = render_to_string("comments/comment_notification_email.txt", context, request=request)
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list, fail_silently=True)
| Use force_text() to get page title | Use force_text() to get page title
Some models might handle __unicode__/__str__ badly
| Python | apache-2.0 | edoburu/django-fluent-comments,django-fluent/django-fluent-comments,edoburu/django-fluent-comments,django-fluent/django-fluent-comments,django-fluent/django-fluent-comments,django-fluent/django-fluent-comments,edoburu/django-fluent-comments | from django.conf import settings
from django.core.mail import send_mail
from django.template.loader import render_to_string
try:
from django.contrib.sites.shortcuts import get_current_site # Django 1.9+
except ImportError:
from django.contrib.sites.models import get_current_site
def send_comment_posted(comment, request):
"""
Send the email to staff that an comment was posted.
While the django_comments module has email support,
it doesn't pass the 'request' to the context.
This also changes the subject to show the page title.
"""
recipient_list = [manager_tuple[1] for manager_tuple in settings.MANAGERS]
site = get_current_site(request)
content_object = comment.content_object
content_title = str(content_object)
if comment.is_removed:
subject = u'[{0}] Spam comment on "{1}"'.format(site.name, content_title)
elif not comment.is_public:
subject = u'[{0}] Moderated comment on "{1}"'.format(site.name, content_title)
else:
subject = u'[{0}] New comment posted on "{1}"'.format(site.name, content_title)
context = {
'site': site,
'comment': comment,
'content_object': content_object
}
message = render_to_string("comments/comment_notification_email.txt", context, request=request)
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list, fail_silently=True)
Use force_text() to get page title
Some models might handle __unicode__/__str__ badly | from django.conf import settings
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.encoding import force_text
try:
from django.contrib.sites.shortcuts import get_current_site # Django 1.9+
except ImportError:
from django.contrib.sites.models import get_current_site
def send_comment_posted(comment, request):
"""
Send the email to staff that an comment was posted.
While the django_comments module has email support,
it doesn't pass the 'request' to the context.
This also changes the subject to show the page title.
"""
recipient_list = [manager_tuple[1] for manager_tuple in settings.MANAGERS]
site = get_current_site(request)
content_object = comment.content_object
content_title = force_text(content_object)
if comment.is_removed:
subject = u'[{0}] Spam comment on "{1}"'.format(site.name, content_title)
elif not comment.is_public:
subject = u'[{0}] Moderated comment on "{1}"'.format(site.name, content_title)
else:
subject = u'[{0}] New comment posted on "{1}"'.format(site.name, content_title)
context = {
'site': site,
'comment': comment,
'content_object': content_object
}
message = render_to_string("comments/comment_notification_email.txt", context, request=request)
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list, fail_silently=True)
| <commit_before>from django.conf import settings
from django.core.mail import send_mail
from django.template.loader import render_to_string
try:
from django.contrib.sites.shortcuts import get_current_site # Django 1.9+
except ImportError:
from django.contrib.sites.models import get_current_site
def send_comment_posted(comment, request):
"""
Send the email to staff that an comment was posted.
While the django_comments module has email support,
it doesn't pass the 'request' to the context.
This also changes the subject to show the page title.
"""
recipient_list = [manager_tuple[1] for manager_tuple in settings.MANAGERS]
site = get_current_site(request)
content_object = comment.content_object
content_title = str(content_object)
if comment.is_removed:
subject = u'[{0}] Spam comment on "{1}"'.format(site.name, content_title)
elif not comment.is_public:
subject = u'[{0}] Moderated comment on "{1}"'.format(site.name, content_title)
else:
subject = u'[{0}] New comment posted on "{1}"'.format(site.name, content_title)
context = {
'site': site,
'comment': comment,
'content_object': content_object
}
message = render_to_string("comments/comment_notification_email.txt", context, request=request)
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list, fail_silently=True)
<commit_msg>Use force_text() to get page title
Some models might handle __unicode__/__str__ badly<commit_after> | from django.conf import settings
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.encoding import force_text
try:
from django.contrib.sites.shortcuts import get_current_site # Django 1.9+
except ImportError:
from django.contrib.sites.models import get_current_site
def send_comment_posted(comment, request):
"""
Send the email to staff that an comment was posted.
While the django_comments module has email support,
it doesn't pass the 'request' to the context.
This also changes the subject to show the page title.
"""
recipient_list = [manager_tuple[1] for manager_tuple in settings.MANAGERS]
site = get_current_site(request)
content_object = comment.content_object
content_title = force_text(content_object)
if comment.is_removed:
subject = u'[{0}] Spam comment on "{1}"'.format(site.name, content_title)
elif not comment.is_public:
subject = u'[{0}] Moderated comment on "{1}"'.format(site.name, content_title)
else:
subject = u'[{0}] New comment posted on "{1}"'.format(site.name, content_title)
context = {
'site': site,
'comment': comment,
'content_object': content_object
}
message = render_to_string("comments/comment_notification_email.txt", context, request=request)
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list, fail_silently=True)
| from django.conf import settings
from django.core.mail import send_mail
from django.template.loader import render_to_string
try:
from django.contrib.sites.shortcuts import get_current_site # Django 1.9+
except ImportError:
from django.contrib.sites.models import get_current_site
def send_comment_posted(comment, request):
"""
Send the email to staff that an comment was posted.
While the django_comments module has email support,
it doesn't pass the 'request' to the context.
This also changes the subject to show the page title.
"""
recipient_list = [manager_tuple[1] for manager_tuple in settings.MANAGERS]
site = get_current_site(request)
content_object = comment.content_object
content_title = str(content_object)
if comment.is_removed:
subject = u'[{0}] Spam comment on "{1}"'.format(site.name, content_title)
elif not comment.is_public:
subject = u'[{0}] Moderated comment on "{1}"'.format(site.name, content_title)
else:
subject = u'[{0}] New comment posted on "{1}"'.format(site.name, content_title)
context = {
'site': site,
'comment': comment,
'content_object': content_object
}
message = render_to_string("comments/comment_notification_email.txt", context, request=request)
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list, fail_silently=True)
Use force_text() to get page title
Some models might handle __unicode__/__str__ badlyfrom django.conf import settings
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.encoding import force_text
try:
from django.contrib.sites.shortcuts import get_current_site # Django 1.9+
except ImportError:
from django.contrib.sites.models import get_current_site
def send_comment_posted(comment, request):
"""
Send the email to staff that an comment was posted.
While the django_comments module has email support,
it doesn't pass the 'request' to the context.
This also changes the subject to show the page title.
"""
recipient_list = [manager_tuple[1] for manager_tuple in settings.MANAGERS]
site = get_current_site(request)
content_object = comment.content_object
content_title = force_text(content_object)
if comment.is_removed:
subject = u'[{0}] Spam comment on "{1}"'.format(site.name, content_title)
elif not comment.is_public:
subject = u'[{0}] Moderated comment on "{1}"'.format(site.name, content_title)
else:
subject = u'[{0}] New comment posted on "{1}"'.format(site.name, content_title)
context = {
'site': site,
'comment': comment,
'content_object': content_object
}
message = render_to_string("comments/comment_notification_email.txt", context, request=request)
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list, fail_silently=True)
| <commit_before>from django.conf import settings
from django.core.mail import send_mail
from django.template.loader import render_to_string
try:
from django.contrib.sites.shortcuts import get_current_site # Django 1.9+
except ImportError:
from django.contrib.sites.models import get_current_site
def send_comment_posted(comment, request):
"""
Send the email to staff that an comment was posted.
While the django_comments module has email support,
it doesn't pass the 'request' to the context.
This also changes the subject to show the page title.
"""
recipient_list = [manager_tuple[1] for manager_tuple in settings.MANAGERS]
site = get_current_site(request)
content_object = comment.content_object
content_title = str(content_object)
if comment.is_removed:
subject = u'[{0}] Spam comment on "{1}"'.format(site.name, content_title)
elif not comment.is_public:
subject = u'[{0}] Moderated comment on "{1}"'.format(site.name, content_title)
else:
subject = u'[{0}] New comment posted on "{1}"'.format(site.name, content_title)
context = {
'site': site,
'comment': comment,
'content_object': content_object
}
message = render_to_string("comments/comment_notification_email.txt", context, request=request)
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list, fail_silently=True)
<commit_msg>Use force_text() to get page title
Some models might handle __unicode__/__str__ badly<commit_after>from django.conf import settings
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.encoding import force_text
try:
from django.contrib.sites.shortcuts import get_current_site # Django 1.9+
except ImportError:
from django.contrib.sites.models import get_current_site
def send_comment_posted(comment, request):
"""
Send the email to staff that an comment was posted.
While the django_comments module has email support,
it doesn't pass the 'request' to the context.
This also changes the subject to show the page title.
"""
recipient_list = [manager_tuple[1] for manager_tuple in settings.MANAGERS]
site = get_current_site(request)
content_object = comment.content_object
content_title = force_text(content_object)
if comment.is_removed:
subject = u'[{0}] Spam comment on "{1}"'.format(site.name, content_title)
elif not comment.is_public:
subject = u'[{0}] Moderated comment on "{1}"'.format(site.name, content_title)
else:
subject = u'[{0}] New comment posted on "{1}"'.format(site.name, content_title)
context = {
'site': site,
'comment': comment,
'content_object': content_object
}
message = render_to_string("comments/comment_notification_email.txt", context, request=request)
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list, fail_silently=True)
|
815c246f1ef185e24991efc4075b2358c7955c6c | onadata/libs/utils/storage.py | onadata/libs/utils/storage.py | # coding: utf-8
import os
import shutil
from django.core.files.storage import get_storage_class
def delete_user_storage(username):
storage = get_storage_class()()
def _recursive_delete(path):
directories, files = storage.listdir(path)
for file_ in files:
storage.delete(os.path.join(path, file_))
for directory in directories:
_recursive_delete(os.path.join(path, directory))
if storage.__class__.__name__ == 'FileSystemStorage':
if storage.exists(username):
shutil.rmtree(storage.path(username))
else:
_recursive_delete(username)
def user_storage_exists(username):
storage = get_storage_class()()
return storage.exists(username)
| # coding: utf-8
import os
import shutil
from django.core.files.storage import FileSystemStorage, get_storage_class
def delete_user_storage(username):
storage = get_storage_class()()
def _recursive_delete(path):
directories, files = storage.listdir(path)
for file_ in files:
storage.delete(os.path.join(path, file_))
for directory in directories:
_recursive_delete(os.path.join(path, directory))
if isinstance(storage, FileSystemStorage):
if storage.exists(username):
shutil.rmtree(storage.path(username))
else:
_recursive_delete(username)
def user_storage_exists(username):
storage = get_storage_class()()
return storage.exists(username)
| Use `isinstance()` at the cost of an extra import | Use `isinstance()` at the cost of an extra import
| Python | bsd-2-clause | kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat | # coding: utf-8
import os
import shutil
from django.core.files.storage import get_storage_class
def delete_user_storage(username):
storage = get_storage_class()()
def _recursive_delete(path):
directories, files = storage.listdir(path)
for file_ in files:
storage.delete(os.path.join(path, file_))
for directory in directories:
_recursive_delete(os.path.join(path, directory))
if storage.__class__.__name__ == 'FileSystemStorage':
if storage.exists(username):
shutil.rmtree(storage.path(username))
else:
_recursive_delete(username)
def user_storage_exists(username):
storage = get_storage_class()()
return storage.exists(username)
Use `isinstance()` at the cost of an extra import | # coding: utf-8
import os
import shutil
from django.core.files.storage import FileSystemStorage, get_storage_class
def delete_user_storage(username):
storage = get_storage_class()()
def _recursive_delete(path):
directories, files = storage.listdir(path)
for file_ in files:
storage.delete(os.path.join(path, file_))
for directory in directories:
_recursive_delete(os.path.join(path, directory))
if isinstance(storage, FileSystemStorage):
if storage.exists(username):
shutil.rmtree(storage.path(username))
else:
_recursive_delete(username)
def user_storage_exists(username):
storage = get_storage_class()()
return storage.exists(username)
| <commit_before># coding: utf-8
import os
import shutil
from django.core.files.storage import get_storage_class
def delete_user_storage(username):
storage = get_storage_class()()
def _recursive_delete(path):
directories, files = storage.listdir(path)
for file_ in files:
storage.delete(os.path.join(path, file_))
for directory in directories:
_recursive_delete(os.path.join(path, directory))
if storage.__class__.__name__ == 'FileSystemStorage':
if storage.exists(username):
shutil.rmtree(storage.path(username))
else:
_recursive_delete(username)
def user_storage_exists(username):
storage = get_storage_class()()
return storage.exists(username)
<commit_msg>Use `isinstance()` at the cost of an extra import<commit_after> | # coding: utf-8
import os
import shutil
from django.core.files.storage import FileSystemStorage, get_storage_class
def delete_user_storage(username):
storage = get_storage_class()()
def _recursive_delete(path):
directories, files = storage.listdir(path)
for file_ in files:
storage.delete(os.path.join(path, file_))
for directory in directories:
_recursive_delete(os.path.join(path, directory))
if isinstance(storage, FileSystemStorage):
if storage.exists(username):
shutil.rmtree(storage.path(username))
else:
_recursive_delete(username)
def user_storage_exists(username):
storage = get_storage_class()()
return storage.exists(username)
| # coding: utf-8
import os
import shutil
from django.core.files.storage import get_storage_class
def delete_user_storage(username):
storage = get_storage_class()()
def _recursive_delete(path):
directories, files = storage.listdir(path)
for file_ in files:
storage.delete(os.path.join(path, file_))
for directory in directories:
_recursive_delete(os.path.join(path, directory))
if storage.__class__.__name__ == 'FileSystemStorage':
if storage.exists(username):
shutil.rmtree(storage.path(username))
else:
_recursive_delete(username)
def user_storage_exists(username):
storage = get_storage_class()()
return storage.exists(username)
Use `isinstance()` at the cost of an extra import# coding: utf-8
import os
import shutil
from django.core.files.storage import FileSystemStorage, get_storage_class
def delete_user_storage(username):
storage = get_storage_class()()
def _recursive_delete(path):
directories, files = storage.listdir(path)
for file_ in files:
storage.delete(os.path.join(path, file_))
for directory in directories:
_recursive_delete(os.path.join(path, directory))
if isinstance(storage, FileSystemStorage):
if storage.exists(username):
shutil.rmtree(storage.path(username))
else:
_recursive_delete(username)
def user_storage_exists(username):
storage = get_storage_class()()
return storage.exists(username)
| <commit_before># coding: utf-8
import os
import shutil
from django.core.files.storage import get_storage_class
def delete_user_storage(username):
storage = get_storage_class()()
def _recursive_delete(path):
directories, files = storage.listdir(path)
for file_ in files:
storage.delete(os.path.join(path, file_))
for directory in directories:
_recursive_delete(os.path.join(path, directory))
if storage.__class__.__name__ == 'FileSystemStorage':
if storage.exists(username):
shutil.rmtree(storage.path(username))
else:
_recursive_delete(username)
def user_storage_exists(username):
storage = get_storage_class()()
return storage.exists(username)
<commit_msg>Use `isinstance()` at the cost of an extra import<commit_after># coding: utf-8
import os
import shutil
from django.core.files.storage import FileSystemStorage, get_storage_class
def delete_user_storage(username):
storage = get_storage_class()()
def _recursive_delete(path):
directories, files = storage.listdir(path)
for file_ in files:
storage.delete(os.path.join(path, file_))
for directory in directories:
_recursive_delete(os.path.join(path, directory))
if isinstance(storage, FileSystemStorage):
if storage.exists(username):
shutil.rmtree(storage.path(username))
else:
_recursive_delete(username)
def user_storage_exists(username):
storage = get_storage_class()()
return storage.exists(username)
|
736388eaf2b408ec28c2948aa412411067f8346d | tests/helper.py | tests/helper.py | import logging
import shutil
import os
opsutils_logger = logging.getLogger('opsutils')
opsutils_logger.setLevel(logging.DEBUG)
opsutils_logger.addHandler(logging.StreamHandler())
PATH = os.path.join(os.path.realpath(os.path.dirname(__file__)), '.tmp')
class Workspace(object):
def __init__(self, name='default', path=PATH, create=True):
self._path = os.path.join(path, name)
if create:
self.create()
@property
def path(self):
return self._path
def join(self, *args):
return os.path.join(self.path, *args)
def create(self):
self.destroy()
os.makedirs(self.path)
def destroy(self):
if not os.path.exists(self.path):
return
if os.path.isdir(self.path):
shutil.rmtree(self.path)
elif os.path.isfile(self.path):
os.remote(self.path)
else:
raise Exception('Test only deletes files and directories: %s' % self.path)
try:
os.rmdir(PATH)
except OSError:
pass
| import logging
import shutil
import os
if os.environ.get('OPSUTILS_TEST_LOGGING'):
opsutils_logger = logging.getLogger('opsutils')
opsutils_logger.setLevel(logging.DEBUG)
opsutils_logger.addHandler(logging.StreamHandler())
PATH = os.path.join(os.path.realpath(os.path.dirname(__file__)), '.tmp')
class Workspace(object):
def __init__(self, name='default', path=PATH, create=True):
self._path = os.path.join(path, name)
if create:
self.create()
@property
def path(self):
return self._path
def join(self, *args):
return os.path.join(self.path, *args)
def create(self):
self.destroy()
os.makedirs(self.path)
def destroy(self):
if not os.path.exists(self.path):
return
if os.path.isdir(self.path):
shutil.rmtree(self.path)
elif os.path.isfile(self.path):
os.remote(self.path)
else:
raise Exception('Test only deletes files and directories: %s' % self.path)
try:
os.rmdir(PATH)
except OSError:
pass
| Make test logging a configurable setting | Make test logging a configurable setting
| Python | mit | silas/ops | import logging
import shutil
import os
opsutils_logger = logging.getLogger('opsutils')
opsutils_logger.setLevel(logging.DEBUG)
opsutils_logger.addHandler(logging.StreamHandler())
PATH = os.path.join(os.path.realpath(os.path.dirname(__file__)), '.tmp')
class Workspace(object):
def __init__(self, name='default', path=PATH, create=True):
self._path = os.path.join(path, name)
if create:
self.create()
@property
def path(self):
return self._path
def join(self, *args):
return os.path.join(self.path, *args)
def create(self):
self.destroy()
os.makedirs(self.path)
def destroy(self):
if not os.path.exists(self.path):
return
if os.path.isdir(self.path):
shutil.rmtree(self.path)
elif os.path.isfile(self.path):
os.remote(self.path)
else:
raise Exception('Test only deletes files and directories: %s' % self.path)
try:
os.rmdir(PATH)
except OSError:
pass
Make test logging a configurable setting | import logging
import shutil
import os
if os.environ.get('OPSUTILS_TEST_LOGGING'):
opsutils_logger = logging.getLogger('opsutils')
opsutils_logger.setLevel(logging.DEBUG)
opsutils_logger.addHandler(logging.StreamHandler())
PATH = os.path.join(os.path.realpath(os.path.dirname(__file__)), '.tmp')
class Workspace(object):
def __init__(self, name='default', path=PATH, create=True):
self._path = os.path.join(path, name)
if create:
self.create()
@property
def path(self):
return self._path
def join(self, *args):
return os.path.join(self.path, *args)
def create(self):
self.destroy()
os.makedirs(self.path)
def destroy(self):
if not os.path.exists(self.path):
return
if os.path.isdir(self.path):
shutil.rmtree(self.path)
elif os.path.isfile(self.path):
os.remote(self.path)
else:
raise Exception('Test only deletes files and directories: %s' % self.path)
try:
os.rmdir(PATH)
except OSError:
pass
| <commit_before>import logging
import shutil
import os
opsutils_logger = logging.getLogger('opsutils')
opsutils_logger.setLevel(logging.DEBUG)
opsutils_logger.addHandler(logging.StreamHandler())
PATH = os.path.join(os.path.realpath(os.path.dirname(__file__)), '.tmp')
class Workspace(object):
def __init__(self, name='default', path=PATH, create=True):
self._path = os.path.join(path, name)
if create:
self.create()
@property
def path(self):
return self._path
def join(self, *args):
return os.path.join(self.path, *args)
def create(self):
self.destroy()
os.makedirs(self.path)
def destroy(self):
if not os.path.exists(self.path):
return
if os.path.isdir(self.path):
shutil.rmtree(self.path)
elif os.path.isfile(self.path):
os.remote(self.path)
else:
raise Exception('Test only deletes files and directories: %s' % self.path)
try:
os.rmdir(PATH)
except OSError:
pass
<commit_msg>Make test logging a configurable setting<commit_after> | import logging
import shutil
import os
if os.environ.get('OPSUTILS_TEST_LOGGING'):
opsutils_logger = logging.getLogger('opsutils')
opsutils_logger.setLevel(logging.DEBUG)
opsutils_logger.addHandler(logging.StreamHandler())
PATH = os.path.join(os.path.realpath(os.path.dirname(__file__)), '.tmp')
class Workspace(object):
def __init__(self, name='default', path=PATH, create=True):
self._path = os.path.join(path, name)
if create:
self.create()
@property
def path(self):
return self._path
def join(self, *args):
return os.path.join(self.path, *args)
def create(self):
self.destroy()
os.makedirs(self.path)
def destroy(self):
if not os.path.exists(self.path):
return
if os.path.isdir(self.path):
shutil.rmtree(self.path)
elif os.path.isfile(self.path):
os.remote(self.path)
else:
raise Exception('Test only deletes files and directories: %s' % self.path)
try:
os.rmdir(PATH)
except OSError:
pass
| import logging
import shutil
import os
opsutils_logger = logging.getLogger('opsutils')
opsutils_logger.setLevel(logging.DEBUG)
opsutils_logger.addHandler(logging.StreamHandler())
PATH = os.path.join(os.path.realpath(os.path.dirname(__file__)), '.tmp')
class Workspace(object):
def __init__(self, name='default', path=PATH, create=True):
self._path = os.path.join(path, name)
if create:
self.create()
@property
def path(self):
return self._path
def join(self, *args):
return os.path.join(self.path, *args)
def create(self):
self.destroy()
os.makedirs(self.path)
def destroy(self):
if not os.path.exists(self.path):
return
if os.path.isdir(self.path):
shutil.rmtree(self.path)
elif os.path.isfile(self.path):
os.remote(self.path)
else:
raise Exception('Test only deletes files and directories: %s' % self.path)
try:
os.rmdir(PATH)
except OSError:
pass
Make test logging a configurable settingimport logging
import shutil
import os
if os.environ.get('OPSUTILS_TEST_LOGGING'):
opsutils_logger = logging.getLogger('opsutils')
opsutils_logger.setLevel(logging.DEBUG)
opsutils_logger.addHandler(logging.StreamHandler())
PATH = os.path.join(os.path.realpath(os.path.dirname(__file__)), '.tmp')
class Workspace(object):
def __init__(self, name='default', path=PATH, create=True):
self._path = os.path.join(path, name)
if create:
self.create()
@property
def path(self):
return self._path
def join(self, *args):
return os.path.join(self.path, *args)
def create(self):
self.destroy()
os.makedirs(self.path)
def destroy(self):
if not os.path.exists(self.path):
return
if os.path.isdir(self.path):
shutil.rmtree(self.path)
elif os.path.isfile(self.path):
os.remote(self.path)
else:
raise Exception('Test only deletes files and directories: %s' % self.path)
try:
os.rmdir(PATH)
except OSError:
pass
| <commit_before>import logging
import shutil
import os
opsutils_logger = logging.getLogger('opsutils')
opsutils_logger.setLevel(logging.DEBUG)
opsutils_logger.addHandler(logging.StreamHandler())
PATH = os.path.join(os.path.realpath(os.path.dirname(__file__)), '.tmp')
class Workspace(object):
def __init__(self, name='default', path=PATH, create=True):
self._path = os.path.join(path, name)
if create:
self.create()
@property
def path(self):
return self._path
def join(self, *args):
return os.path.join(self.path, *args)
def create(self):
self.destroy()
os.makedirs(self.path)
def destroy(self):
if not os.path.exists(self.path):
return
if os.path.isdir(self.path):
shutil.rmtree(self.path)
elif os.path.isfile(self.path):
os.remote(self.path)
else:
raise Exception('Test only deletes files and directories: %s' % self.path)
try:
os.rmdir(PATH)
except OSError:
pass
<commit_msg>Make test logging a configurable setting<commit_after>import logging
import shutil
import os
if os.environ.get('OPSUTILS_TEST_LOGGING'):
opsutils_logger = logging.getLogger('opsutils')
opsutils_logger.setLevel(logging.DEBUG)
opsutils_logger.addHandler(logging.StreamHandler())
PATH = os.path.join(os.path.realpath(os.path.dirname(__file__)), '.tmp')
class Workspace(object):
def __init__(self, name='default', path=PATH, create=True):
self._path = os.path.join(path, name)
if create:
self.create()
@property
def path(self):
return self._path
def join(self, *args):
return os.path.join(self.path, *args)
def create(self):
self.destroy()
os.makedirs(self.path)
def destroy(self):
if not os.path.exists(self.path):
return
if os.path.isdir(self.path):
shutil.rmtree(self.path)
elif os.path.isfile(self.path):
os.remote(self.path)
else:
raise Exception('Test only deletes files and directories: %s' % self.path)
try:
os.rmdir(PATH)
except OSError:
pass
|
b242de3217ad9cf6a98ca2513ed1e4f66d2537ad | tests/NongeneratingSymbolsRemove/SimpleTest.py | tests/NongeneratingSymbolsRemove/SimpleTest.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy-transforms
"""
from unittest import TestCase, main
from grammpy import *
from grammpy_transforms import ContextFree
class SimpleTest(TestCase):
pass
if __name__ == '__main__':
main()
| #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy-transforms
"""
from unittest import TestCase, main
from grammpy import *
from grammpy_transforms import ContextFree
class A(Nonterminal):
pass
class B(Nonterminal):
pass
class C(Nonterminal):
pass
class RuleAto0B(Rule):
fromSymbol = A
right = [0, B]
class RuleBto1(Rule):
fromSymbol = B
toSymbol = 1
class SimpleTest(TestCase):
def test_simpleTest(self):
g = Grammar(terminals=[0, 1],
nonterminals=[A, B, C],
rules=[RuleAto0B, RuleBto1])
changed = ContextFree.remove_nongenerastingSymbols(g)
self.assertTrue(changed.have_term([0, 1]))
self.assertTrue(changed.have_nonterm([A, B]))
self.assertFalse(changed.have_nonterm(C))
if __name__ == '__main__':
main()
| Add simple test of removing nongenerating symbols | Add simple test of removing nongenerating symbols
| Python | mit | PatrikValkovic/grammpy | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy-transforms
"""
from unittest import TestCase, main
from grammpy import *
from grammpy_transforms import ContextFree
class SimpleTest(TestCase):
pass
if __name__ == '__main__':
main()
Add simple test of removing nongenerating symbols | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy-transforms
"""
from unittest import TestCase, main
from grammpy import *
from grammpy_transforms import ContextFree
class A(Nonterminal):
pass
class B(Nonterminal):
pass
class C(Nonterminal):
pass
class RuleAto0B(Rule):
fromSymbol = A
right = [0, B]
class RuleBto1(Rule):
fromSymbol = B
toSymbol = 1
class SimpleTest(TestCase):
def test_simpleTest(self):
g = Grammar(terminals=[0, 1],
nonterminals=[A, B, C],
rules=[RuleAto0B, RuleBto1])
changed = ContextFree.remove_nongenerastingSymbols(g)
self.assertTrue(changed.have_term([0, 1]))
self.assertTrue(changed.have_nonterm([A, B]))
self.assertFalse(changed.have_nonterm(C))
if __name__ == '__main__':
main()
| <commit_before>#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy-transforms
"""
from unittest import TestCase, main
from grammpy import *
from grammpy_transforms import ContextFree
class SimpleTest(TestCase):
pass
if __name__ == '__main__':
main()
<commit_msg>Add simple test of removing nongenerating symbols<commit_after> | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy-transforms
"""
from unittest import TestCase, main
from grammpy import *
from grammpy_transforms import ContextFree
class A(Nonterminal):
pass
class B(Nonterminal):
pass
class C(Nonterminal):
pass
class RuleAto0B(Rule):
fromSymbol = A
right = [0, B]
class RuleBto1(Rule):
fromSymbol = B
toSymbol = 1
class SimpleTest(TestCase):
def test_simpleTest(self):
g = Grammar(terminals=[0, 1],
nonterminals=[A, B, C],
rules=[RuleAto0B, RuleBto1])
changed = ContextFree.remove_nongenerastingSymbols(g)
self.assertTrue(changed.have_term([0, 1]))
self.assertTrue(changed.have_nonterm([A, B]))
self.assertFalse(changed.have_nonterm(C))
if __name__ == '__main__':
main()
| #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy-transforms
"""
from unittest import TestCase, main
from grammpy import *
from grammpy_transforms import ContextFree
class SimpleTest(TestCase):
pass
if __name__ == '__main__':
main()
Add simple test of removing nongenerating symbols#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy-transforms
"""
from unittest import TestCase, main
from grammpy import *
from grammpy_transforms import ContextFree
class A(Nonterminal):
pass
class B(Nonterminal):
pass
class C(Nonterminal):
pass
class RuleAto0B(Rule):
fromSymbol = A
right = [0, B]
class RuleBto1(Rule):
fromSymbol = B
toSymbol = 1
class SimpleTest(TestCase):
def test_simpleTest(self):
g = Grammar(terminals=[0, 1],
nonterminals=[A, B, C],
rules=[RuleAto0B, RuleBto1])
changed = ContextFree.remove_nongenerastingSymbols(g)
self.assertTrue(changed.have_term([0, 1]))
self.assertTrue(changed.have_nonterm([A, B]))
self.assertFalse(changed.have_nonterm(C))
if __name__ == '__main__':
main()
| <commit_before>#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy-transforms
"""
from unittest import TestCase, main
from grammpy import *
from grammpy_transforms import ContextFree
class SimpleTest(TestCase):
pass
if __name__ == '__main__':
main()
<commit_msg>Add simple test of removing nongenerating symbols<commit_after>#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy-transforms
"""
from unittest import TestCase, main
from grammpy import *
from grammpy_transforms import ContextFree
class A(Nonterminal):
pass
class B(Nonterminal):
pass
class C(Nonterminal):
pass
class RuleAto0B(Rule):
fromSymbol = A
right = [0, B]
class RuleBto1(Rule):
fromSymbol = B
toSymbol = 1
class SimpleTest(TestCase):
def test_simpleTest(self):
g = Grammar(terminals=[0, 1],
nonterminals=[A, B, C],
rules=[RuleAto0B, RuleBto1])
changed = ContextFree.remove_nongenerastingSymbols(g)
self.assertTrue(changed.have_term([0, 1]))
self.assertTrue(changed.have_nonterm([A, B]))
self.assertFalse(changed.have_nonterm(C))
if __name__ == '__main__':
main()
|
dd8c4843b7872023e276247a4d8de052b42fa9a6 | token_stream.py | token_stream.py | # '2+3' -> {type:num, value: 2}, {type:op, value:'+'}, {type:num, value: 3}
class TokenStream:
def __init__(self, input_stream):
self.input_stream = input_stream
def is_whitespace(self, char):
return char in ' \t'
def is_digit(self, char):
return char.isdigit()
def is_operator(self, char):
return char in '+*'
def read_while(self, predicate_func):
_str = ""
while not self.input_stream.is_eof() and predicate_func(self.input_stream.peek()):
_str += self.input_stream.next()
return _str
def read_number(self):
number = self.read_while(self.is_digit)
return {'type': 'num', 'value': int(number)}
def read_operator(self):
operator = self.read_while(self.is_operator)
return {'type': 'op', 'value': operator}
def read_next(self):
_ = self.read_while(self.is_whitespace)
if self.input_stream.is_eof():
return None
char = self.input_stream.peek()
if self.is_digit(char):
return self.read_number()
if self.is_operator(char):
return self.read_operator()
self.input_stream.croak("Can't handle character: " + char)
self.input_stream.next()
return None | # '2+3' -> {type:num, value: 2}, {type:op, value:'+'}, {type:num, value: 3}
operators = {
'+': {'prec': 10, 'assoc': 'left'},
'*': {'prec': 20, 'assoc': 'left'}
}
class TokenStream:
def __init__(self, input_stream):
self.input_stream = input_stream
def is_whitespace(self, char):
return char in ' \t'
def is_digit(self, char):
return char.isdigit()
def is_operator(self, char):
return char in operators
def read_while(self, predicate_func):
_str = ""
while not self.input_stream.is_eof() and predicate_func(self.input_stream.peek()):
_str += self.input_stream.next()
return _str
def read_number(self):
number = self.read_while(self.is_digit)
return {'type': 'num', 'value': int(number)}
def read_operator(self):
operator = self.read_while(self.is_operator)
return {'type': 'op', 'value': operator}
def read_next(self):
_ = self.read_while(self.is_whitespace)
if self.input_stream.is_eof():
return None
char = self.input_stream.peek()
if self.is_digit(char):
return self.read_number()
if self.is_operator(char):
return self.read_operator()
self.input_stream.croak("Can't handle character: " + char)
self.input_stream.next()
return None | Define precedence and associativity for operators | Define precedence and associativity for operators
| Python | mit | babu-thomas/calculator-parser | # '2+3' -> {type:num, value: 2}, {type:op, value:'+'}, {type:num, value: 3}
class TokenStream:
def __init__(self, input_stream):
self.input_stream = input_stream
def is_whitespace(self, char):
return char in ' \t'
def is_digit(self, char):
return char.isdigit()
def is_operator(self, char):
return char in '+*'
def read_while(self, predicate_func):
_str = ""
while not self.input_stream.is_eof() and predicate_func(self.input_stream.peek()):
_str += self.input_stream.next()
return _str
def read_number(self):
number = self.read_while(self.is_digit)
return {'type': 'num', 'value': int(number)}
def read_operator(self):
operator = self.read_while(self.is_operator)
return {'type': 'op', 'value': operator}
def read_next(self):
_ = self.read_while(self.is_whitespace)
if self.input_stream.is_eof():
return None
char = self.input_stream.peek()
if self.is_digit(char):
return self.read_number()
if self.is_operator(char):
return self.read_operator()
self.input_stream.croak("Can't handle character: " + char)
self.input_stream.next()
return NoneDefine precedence and associativity for operators | # '2+3' -> {type:num, value: 2}, {type:op, value:'+'}, {type:num, value: 3}
operators = {
'+': {'prec': 10, 'assoc': 'left'},
'*': {'prec': 20, 'assoc': 'left'}
}
class TokenStream:
def __init__(self, input_stream):
self.input_stream = input_stream
def is_whitespace(self, char):
return char in ' \t'
def is_digit(self, char):
return char.isdigit()
def is_operator(self, char):
return char in operators
def read_while(self, predicate_func):
_str = ""
while not self.input_stream.is_eof() and predicate_func(self.input_stream.peek()):
_str += self.input_stream.next()
return _str
def read_number(self):
number = self.read_while(self.is_digit)
return {'type': 'num', 'value': int(number)}
def read_operator(self):
operator = self.read_while(self.is_operator)
return {'type': 'op', 'value': operator}
def read_next(self):
_ = self.read_while(self.is_whitespace)
if self.input_stream.is_eof():
return None
char = self.input_stream.peek()
if self.is_digit(char):
return self.read_number()
if self.is_operator(char):
return self.read_operator()
self.input_stream.croak("Can't handle character: " + char)
self.input_stream.next()
return None | <commit_before># '2+3' -> {type:num, value: 2}, {type:op, value:'+'}, {type:num, value: 3}
class TokenStream:
def __init__(self, input_stream):
self.input_stream = input_stream
def is_whitespace(self, char):
return char in ' \t'
def is_digit(self, char):
return char.isdigit()
def is_operator(self, char):
return char in '+*'
def read_while(self, predicate_func):
_str = ""
while not self.input_stream.is_eof() and predicate_func(self.input_stream.peek()):
_str += self.input_stream.next()
return _str
def read_number(self):
number = self.read_while(self.is_digit)
return {'type': 'num', 'value': int(number)}
def read_operator(self):
operator = self.read_while(self.is_operator)
return {'type': 'op', 'value': operator}
def read_next(self):
_ = self.read_while(self.is_whitespace)
if self.input_stream.is_eof():
return None
char = self.input_stream.peek()
if self.is_digit(char):
return self.read_number()
if self.is_operator(char):
return self.read_operator()
self.input_stream.croak("Can't handle character: " + char)
self.input_stream.next()
return None<commit_msg>Define precedence and associativity for operators<commit_after> | # '2+3' -> {type:num, value: 2}, {type:op, value:'+'}, {type:num, value: 3}
operators = {
'+': {'prec': 10, 'assoc': 'left'},
'*': {'prec': 20, 'assoc': 'left'}
}
class TokenStream:
def __init__(self, input_stream):
self.input_stream = input_stream
def is_whitespace(self, char):
return char in ' \t'
def is_digit(self, char):
return char.isdigit()
def is_operator(self, char):
return char in operators
def read_while(self, predicate_func):
_str = ""
while not self.input_stream.is_eof() and predicate_func(self.input_stream.peek()):
_str += self.input_stream.next()
return _str
def read_number(self):
number = self.read_while(self.is_digit)
return {'type': 'num', 'value': int(number)}
def read_operator(self):
operator = self.read_while(self.is_operator)
return {'type': 'op', 'value': operator}
def read_next(self):
_ = self.read_while(self.is_whitespace)
if self.input_stream.is_eof():
return None
char = self.input_stream.peek()
if self.is_digit(char):
return self.read_number()
if self.is_operator(char):
return self.read_operator()
self.input_stream.croak("Can't handle character: " + char)
self.input_stream.next()
return None | # '2+3' -> {type:num, value: 2}, {type:op, value:'+'}, {type:num, value: 3}
class TokenStream:
def __init__(self, input_stream):
self.input_stream = input_stream
def is_whitespace(self, char):
return char in ' \t'
def is_digit(self, char):
return char.isdigit()
def is_operator(self, char):
return char in '+*'
def read_while(self, predicate_func):
_str = ""
while not self.input_stream.is_eof() and predicate_func(self.input_stream.peek()):
_str += self.input_stream.next()
return _str
def read_number(self):
number = self.read_while(self.is_digit)
return {'type': 'num', 'value': int(number)}
def read_operator(self):
operator = self.read_while(self.is_operator)
return {'type': 'op', 'value': operator}
def read_next(self):
_ = self.read_while(self.is_whitespace)
if self.input_stream.is_eof():
return None
char = self.input_stream.peek()
if self.is_digit(char):
return self.read_number()
if self.is_operator(char):
return self.read_operator()
self.input_stream.croak("Can't handle character: " + char)
self.input_stream.next()
return NoneDefine precedence and associativity for operators# '2+3' -> {type:num, value: 2}, {type:op, value:'+'}, {type:num, value: 3}
operators = {
'+': {'prec': 10, 'assoc': 'left'},
'*': {'prec': 20, 'assoc': 'left'}
}
class TokenStream:
def __init__(self, input_stream):
self.input_stream = input_stream
def is_whitespace(self, char):
return char in ' \t'
def is_digit(self, char):
return char.isdigit()
def is_operator(self, char):
return char in operators
def read_while(self, predicate_func):
_str = ""
while not self.input_stream.is_eof() and predicate_func(self.input_stream.peek()):
_str += self.input_stream.next()
return _str
def read_number(self):
number = self.read_while(self.is_digit)
return {'type': 'num', 'value': int(number)}
def read_operator(self):
operator = self.read_while(self.is_operator)
return {'type': 'op', 'value': operator}
def read_next(self):
_ = self.read_while(self.is_whitespace)
if self.input_stream.is_eof():
return None
char = self.input_stream.peek()
if self.is_digit(char):
return self.read_number()
if self.is_operator(char):
return self.read_operator()
self.input_stream.croak("Can't handle character: " + char)
self.input_stream.next()
return None | <commit_before># '2+3' -> {type:num, value: 2}, {type:op, value:'+'}, {type:num, value: 3}
class TokenStream:
def __init__(self, input_stream):
self.input_stream = input_stream
def is_whitespace(self, char):
return char in ' \t'
def is_digit(self, char):
return char.isdigit()
def is_operator(self, char):
return char in '+*'
def read_while(self, predicate_func):
_str = ""
while not self.input_stream.is_eof() and predicate_func(self.input_stream.peek()):
_str += self.input_stream.next()
return _str
def read_number(self):
number = self.read_while(self.is_digit)
return {'type': 'num', 'value': int(number)}
def read_operator(self):
operator = self.read_while(self.is_operator)
return {'type': 'op', 'value': operator}
def read_next(self):
_ = self.read_while(self.is_whitespace)
if self.input_stream.is_eof():
return None
char = self.input_stream.peek()
if self.is_digit(char):
return self.read_number()
if self.is_operator(char):
return self.read_operator()
self.input_stream.croak("Can't handle character: " + char)
self.input_stream.next()
return None<commit_msg>Define precedence and associativity for operators<commit_after># '2+3' -> {type:num, value: 2}, {type:op, value:'+'}, {type:num, value: 3}
operators = {
'+': {'prec': 10, 'assoc': 'left'},
'*': {'prec': 20, 'assoc': 'left'}
}
class TokenStream:
def __init__(self, input_stream):
self.input_stream = input_stream
def is_whitespace(self, char):
return char in ' \t'
def is_digit(self, char):
return char.isdigit()
def is_operator(self, char):
return char in operators
def read_while(self, predicate_func):
_str = ""
while not self.input_stream.is_eof() and predicate_func(self.input_stream.peek()):
_str += self.input_stream.next()
return _str
def read_number(self):
number = self.read_while(self.is_digit)
return {'type': 'num', 'value': int(number)}
def read_operator(self):
operator = self.read_while(self.is_operator)
return {'type': 'op', 'value': operator}
def read_next(self):
_ = self.read_while(self.is_whitespace)
if self.input_stream.is_eof():
return None
char = self.input_stream.peek()
if self.is_digit(char):
return self.read_number()
if self.is_operator(char):
return self.read_operator()
self.input_stream.croak("Can't handle character: " + char)
self.input_stream.next()
return None |
b834f553501d4c9ba47bcad6497555aacc06249c | gavel/controllers/api.py | gavel/controllers/api.py | from gavel import app
from gavel.models import *
import gavel.utils as utils
from flask import Response
@app.route('/api/items.csv')
@utils.requires_auth
def item_dump():
items = Item.query.order_by(desc(Item.mu)).all()
data = [['Mu', 'Sigma Squared', 'Name', 'Location', 'Description', 'Active']]
data += [[
str(item.mu),
str(item.sigma_sq),
item.name,
item.location,
item.description,
item.active
] for item in items]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
@app.route('/api/annotators.csv')
@utils.requires_auth
def annotator_dump():
annotators = Annotator.query.all()
data = [['Name', 'Email', 'Description', 'Secret']]
data += [[str(a.name), a.email, a.description, a.secret] for a in annotators]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
| from gavel import app
from gavel.models import *
import gavel.utils as utils
from flask import Response
@app.route('/api/items.csv')
@utils.requires_auth
def item_dump():
items = Item.query.order_by(desc(Item.mu)).all()
data = [['Mu', 'Sigma Squared', 'Name', 'Location', 'Description', 'Active']]
data += [[
str(item.mu),
str(item.sigma_sq),
item.name,
item.location,
item.description,
item.active
] for item in items]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
@app.route('/api/annotators.csv')
@utils.requires_auth
def annotator_dump():
annotators = Annotator.query.all()
data = [['Name', 'Email', 'Description', 'Secret']]
data += [[
str(a.name),
a.email,
a.description,
a.secret
] for a in annotators]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
@app.route('/api/decisions.csv')
@utils.requires_auth
def decisions_dump():
decisions = Decision.query.all()
data = [['Annotator ID', 'Winner ID', 'Loser ID', 'Time']]
data += [[
str(d.annotator.id),
str(d.winner.id),
str(d.loser.id),
str(d.time)
] for d in decisions]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
| Add API endpoint for getting decisions | Add API endpoint for getting decisions
| Python | agpl-3.0 | atagh/gavel-clone,anishathalye/gavel,atagh/gavel-clone,anishathalye/gavel,anishathalye/gavel | from gavel import app
from gavel.models import *
import gavel.utils as utils
from flask import Response
@app.route('/api/items.csv')
@utils.requires_auth
def item_dump():
items = Item.query.order_by(desc(Item.mu)).all()
data = [['Mu', 'Sigma Squared', 'Name', 'Location', 'Description', 'Active']]
data += [[
str(item.mu),
str(item.sigma_sq),
item.name,
item.location,
item.description,
item.active
] for item in items]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
@app.route('/api/annotators.csv')
@utils.requires_auth
def annotator_dump():
annotators = Annotator.query.all()
data = [['Name', 'Email', 'Description', 'Secret']]
data += [[str(a.name), a.email, a.description, a.secret] for a in annotators]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
Add API endpoint for getting decisions | from gavel import app
from gavel.models import *
import gavel.utils as utils
from flask import Response
@app.route('/api/items.csv')
@utils.requires_auth
def item_dump():
items = Item.query.order_by(desc(Item.mu)).all()
data = [['Mu', 'Sigma Squared', 'Name', 'Location', 'Description', 'Active']]
data += [[
str(item.mu),
str(item.sigma_sq),
item.name,
item.location,
item.description,
item.active
] for item in items]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
@app.route('/api/annotators.csv')
@utils.requires_auth
def annotator_dump():
annotators = Annotator.query.all()
data = [['Name', 'Email', 'Description', 'Secret']]
data += [[
str(a.name),
a.email,
a.description,
a.secret
] for a in annotators]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
@app.route('/api/decisions.csv')
@utils.requires_auth
def decisions_dump():
decisions = Decision.query.all()
data = [['Annotator ID', 'Winner ID', 'Loser ID', 'Time']]
data += [[
str(d.annotator.id),
str(d.winner.id),
str(d.loser.id),
str(d.time)
] for d in decisions]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
| <commit_before>from gavel import app
from gavel.models import *
import gavel.utils as utils
from flask import Response
@app.route('/api/items.csv')
@utils.requires_auth
def item_dump():
items = Item.query.order_by(desc(Item.mu)).all()
data = [['Mu', 'Sigma Squared', 'Name', 'Location', 'Description', 'Active']]
data += [[
str(item.mu),
str(item.sigma_sq),
item.name,
item.location,
item.description,
item.active
] for item in items]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
@app.route('/api/annotators.csv')
@utils.requires_auth
def annotator_dump():
annotators = Annotator.query.all()
data = [['Name', 'Email', 'Description', 'Secret']]
data += [[str(a.name), a.email, a.description, a.secret] for a in annotators]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
<commit_msg>Add API endpoint for getting decisions<commit_after> | from gavel import app
from gavel.models import *
import gavel.utils as utils
from flask import Response
@app.route('/api/items.csv')
@utils.requires_auth
def item_dump():
items = Item.query.order_by(desc(Item.mu)).all()
data = [['Mu', 'Sigma Squared', 'Name', 'Location', 'Description', 'Active']]
data += [[
str(item.mu),
str(item.sigma_sq),
item.name,
item.location,
item.description,
item.active
] for item in items]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
@app.route('/api/annotators.csv')
@utils.requires_auth
def annotator_dump():
annotators = Annotator.query.all()
data = [['Name', 'Email', 'Description', 'Secret']]
data += [[
str(a.name),
a.email,
a.description,
a.secret
] for a in annotators]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
@app.route('/api/decisions.csv')
@utils.requires_auth
def decisions_dump():
decisions = Decision.query.all()
data = [['Annotator ID', 'Winner ID', 'Loser ID', 'Time']]
data += [[
str(d.annotator.id),
str(d.winner.id),
str(d.loser.id),
str(d.time)
] for d in decisions]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
| from gavel import app
from gavel.models import *
import gavel.utils as utils
from flask import Response
@app.route('/api/items.csv')
@utils.requires_auth
def item_dump():
items = Item.query.order_by(desc(Item.mu)).all()
data = [['Mu', 'Sigma Squared', 'Name', 'Location', 'Description', 'Active']]
data += [[
str(item.mu),
str(item.sigma_sq),
item.name,
item.location,
item.description,
item.active
] for item in items]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
@app.route('/api/annotators.csv')
@utils.requires_auth
def annotator_dump():
annotators = Annotator.query.all()
data = [['Name', 'Email', 'Description', 'Secret']]
data += [[str(a.name), a.email, a.description, a.secret] for a in annotators]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
Add API endpoint for getting decisionsfrom gavel import app
from gavel.models import *
import gavel.utils as utils
from flask import Response
@app.route('/api/items.csv')
@utils.requires_auth
def item_dump():
items = Item.query.order_by(desc(Item.mu)).all()
data = [['Mu', 'Sigma Squared', 'Name', 'Location', 'Description', 'Active']]
data += [[
str(item.mu),
str(item.sigma_sq),
item.name,
item.location,
item.description,
item.active
] for item in items]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
@app.route('/api/annotators.csv')
@utils.requires_auth
def annotator_dump():
annotators = Annotator.query.all()
data = [['Name', 'Email', 'Description', 'Secret']]
data += [[
str(a.name),
a.email,
a.description,
a.secret
] for a in annotators]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
@app.route('/api/decisions.csv')
@utils.requires_auth
def decisions_dump():
decisions = Decision.query.all()
data = [['Annotator ID', 'Winner ID', 'Loser ID', 'Time']]
data += [[
str(d.annotator.id),
str(d.winner.id),
str(d.loser.id),
str(d.time)
] for d in decisions]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
| <commit_before>from gavel import app
from gavel.models import *
import gavel.utils as utils
from flask import Response
@app.route('/api/items.csv')
@utils.requires_auth
def item_dump():
items = Item.query.order_by(desc(Item.mu)).all()
data = [['Mu', 'Sigma Squared', 'Name', 'Location', 'Description', 'Active']]
data += [[
str(item.mu),
str(item.sigma_sq),
item.name,
item.location,
item.description,
item.active
] for item in items]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
@app.route('/api/annotators.csv')
@utils.requires_auth
def annotator_dump():
annotators = Annotator.query.all()
data = [['Name', 'Email', 'Description', 'Secret']]
data += [[str(a.name), a.email, a.description, a.secret] for a in annotators]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
<commit_msg>Add API endpoint for getting decisions<commit_after>from gavel import app
from gavel.models import *
import gavel.utils as utils
from flask import Response
@app.route('/api/items.csv')
@utils.requires_auth
def item_dump():
items = Item.query.order_by(desc(Item.mu)).all()
data = [['Mu', 'Sigma Squared', 'Name', 'Location', 'Description', 'Active']]
data += [[
str(item.mu),
str(item.sigma_sq),
item.name,
item.location,
item.description,
item.active
] for item in items]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
@app.route('/api/annotators.csv')
@utils.requires_auth
def annotator_dump():
annotators = Annotator.query.all()
data = [['Name', 'Email', 'Description', 'Secret']]
data += [[
str(a.name),
a.email,
a.description,
a.secret
] for a in annotators]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
@app.route('/api/decisions.csv')
@utils.requires_auth
def decisions_dump():
decisions = Decision.query.all()
data = [['Annotator ID', 'Winner ID', 'Loser ID', 'Time']]
data += [[
str(d.annotator.id),
str(d.winner.id),
str(d.loser.id),
str(d.time)
] for d in decisions]
return Response(utils.data_to_csv_string(data), mimetype='text/csv')
|
31d0af7d5f3a984d4f6c7be62d599553a3bc7c08 | opps/articles/utils.py | opps/articles/utils.py | # -*- coding: utf-8 -*-
from django.utils import timezone
from opps.articles.models import ArticleBox, Article
def set_context_data(self, SUPER, **kwargs):
context = super(SUPER, self).get_context_data(**kwargs)
article = Article.objects.filter(
site=self.site,
channel_long_slug__in=self.channel_long_slug,
date_available__lte=timezone.now(),
published=True)
context['posts'] = article.filter(child_class='Post')[:self.limit]
context['albums'] = article.filter(child_class='Album')[:self.limit]
context['channel'] = {}
context['channel']['long_slug'] = self.long_slug
if self.channel:
context['channel']['level'] = self.channel.get_level()
context['articleboxes'] = ArticleBox.objects.filter(
channel__long_slug=self.long_slug)
if self.slug:
context['articleboxes'] = context['articleboxes'].filter(
article__slug=self.slug)
return context
| # -*- coding: utf-8 -*-
from django.utils import timezone
from opps.articles.models import ArticleBox, Article
def set_context_data(self, SUPER, **kwargs):
context = super(SUPER, self).get_context_data(**kwargs)
article = Article.objects.filter(
site=self.site,
channel_long_slug__in=self.channel_long_slug,
date_available__lte=timezone.now(),
published=True)
context['posts'] = article.filter(child_class='Post')[:self.limit]
context['albums'] = article.filter(child_class='Album')[:self.limit]
context['channel'] = {}
context['channel']['long_slug'] = self.long_slug
if self.channel:
context['channel']['level'] = self.channel.get_level()
context['channel']['root'] = self.channel.get_root()
context['articleboxes'] = ArticleBox.objects.filter(
channel__long_slug=self.long_slug)
if self.slug:
context['articleboxes'] = context['articleboxes'].filter(
article__slug=self.slug)
return context
| Add channel root on set context data, sent to template | Add channel root on set context data, sent to template
| Python | mit | YACOWS/opps,opps/opps,YACOWS/opps,williamroot/opps,opps/opps,jeanmask/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,williamroot/opps,williamroot/opps,opps/opps,YACOWS/opps,YACOWS/opps,jeanmask/opps,opps/opps | # -*- coding: utf-8 -*-
from django.utils import timezone
from opps.articles.models import ArticleBox, Article
def set_context_data(self, SUPER, **kwargs):
context = super(SUPER, self).get_context_data(**kwargs)
article = Article.objects.filter(
site=self.site,
channel_long_slug__in=self.channel_long_slug,
date_available__lte=timezone.now(),
published=True)
context['posts'] = article.filter(child_class='Post')[:self.limit]
context['albums'] = article.filter(child_class='Album')[:self.limit]
context['channel'] = {}
context['channel']['long_slug'] = self.long_slug
if self.channel:
context['channel']['level'] = self.channel.get_level()
context['articleboxes'] = ArticleBox.objects.filter(
channel__long_slug=self.long_slug)
if self.slug:
context['articleboxes'] = context['articleboxes'].filter(
article__slug=self.slug)
return context
Add channel root on set context data, sent to template | # -*- coding: utf-8 -*-
from django.utils import timezone
from opps.articles.models import ArticleBox, Article
def set_context_data(self, SUPER, **kwargs):
context = super(SUPER, self).get_context_data(**kwargs)
article = Article.objects.filter(
site=self.site,
channel_long_slug__in=self.channel_long_slug,
date_available__lte=timezone.now(),
published=True)
context['posts'] = article.filter(child_class='Post')[:self.limit]
context['albums'] = article.filter(child_class='Album')[:self.limit]
context['channel'] = {}
context['channel']['long_slug'] = self.long_slug
if self.channel:
context['channel']['level'] = self.channel.get_level()
context['channel']['root'] = self.channel.get_root()
context['articleboxes'] = ArticleBox.objects.filter(
channel__long_slug=self.long_slug)
if self.slug:
context['articleboxes'] = context['articleboxes'].filter(
article__slug=self.slug)
return context
| <commit_before># -*- coding: utf-8 -*-
from django.utils import timezone
from opps.articles.models import ArticleBox, Article
def set_context_data(self, SUPER, **kwargs):
context = super(SUPER, self).get_context_data(**kwargs)
article = Article.objects.filter(
site=self.site,
channel_long_slug__in=self.channel_long_slug,
date_available__lte=timezone.now(),
published=True)
context['posts'] = article.filter(child_class='Post')[:self.limit]
context['albums'] = article.filter(child_class='Album')[:self.limit]
context['channel'] = {}
context['channel']['long_slug'] = self.long_slug
if self.channel:
context['channel']['level'] = self.channel.get_level()
context['articleboxes'] = ArticleBox.objects.filter(
channel__long_slug=self.long_slug)
if self.slug:
context['articleboxes'] = context['articleboxes'].filter(
article__slug=self.slug)
return context
<commit_msg>Add channel root on set context data, sent to template<commit_after> | # -*- coding: utf-8 -*-
from django.utils import timezone
from opps.articles.models import ArticleBox, Article
def set_context_data(self, SUPER, **kwargs):
context = super(SUPER, self).get_context_data(**kwargs)
article = Article.objects.filter(
site=self.site,
channel_long_slug__in=self.channel_long_slug,
date_available__lte=timezone.now(),
published=True)
context['posts'] = article.filter(child_class='Post')[:self.limit]
context['albums'] = article.filter(child_class='Album')[:self.limit]
context['channel'] = {}
context['channel']['long_slug'] = self.long_slug
if self.channel:
context['channel']['level'] = self.channel.get_level()
context['channel']['root'] = self.channel.get_root()
context['articleboxes'] = ArticleBox.objects.filter(
channel__long_slug=self.long_slug)
if self.slug:
context['articleboxes'] = context['articleboxes'].filter(
article__slug=self.slug)
return context
| # -*- coding: utf-8 -*-
from django.utils import timezone
from opps.articles.models import ArticleBox, Article
def set_context_data(self, SUPER, **kwargs):
context = super(SUPER, self).get_context_data(**kwargs)
article = Article.objects.filter(
site=self.site,
channel_long_slug__in=self.channel_long_slug,
date_available__lte=timezone.now(),
published=True)
context['posts'] = article.filter(child_class='Post')[:self.limit]
context['albums'] = article.filter(child_class='Album')[:self.limit]
context['channel'] = {}
context['channel']['long_slug'] = self.long_slug
if self.channel:
context['channel']['level'] = self.channel.get_level()
context['articleboxes'] = ArticleBox.objects.filter(
channel__long_slug=self.long_slug)
if self.slug:
context['articleboxes'] = context['articleboxes'].filter(
article__slug=self.slug)
return context
Add channel root on set context data, sent to template# -*- coding: utf-8 -*-
from django.utils import timezone
from opps.articles.models import ArticleBox, Article
def set_context_data(self, SUPER, **kwargs):
context = super(SUPER, self).get_context_data(**kwargs)
article = Article.objects.filter(
site=self.site,
channel_long_slug__in=self.channel_long_slug,
date_available__lte=timezone.now(),
published=True)
context['posts'] = article.filter(child_class='Post')[:self.limit]
context['albums'] = article.filter(child_class='Album')[:self.limit]
context['channel'] = {}
context['channel']['long_slug'] = self.long_slug
if self.channel:
context['channel']['level'] = self.channel.get_level()
context['channel']['root'] = self.channel.get_root()
context['articleboxes'] = ArticleBox.objects.filter(
channel__long_slug=self.long_slug)
if self.slug:
context['articleboxes'] = context['articleboxes'].filter(
article__slug=self.slug)
return context
| <commit_before># -*- coding: utf-8 -*-
from django.utils import timezone
from opps.articles.models import ArticleBox, Article
def set_context_data(self, SUPER, **kwargs):
context = super(SUPER, self).get_context_data(**kwargs)
article = Article.objects.filter(
site=self.site,
channel_long_slug__in=self.channel_long_slug,
date_available__lte=timezone.now(),
published=True)
context['posts'] = article.filter(child_class='Post')[:self.limit]
context['albums'] = article.filter(child_class='Album')[:self.limit]
context['channel'] = {}
context['channel']['long_slug'] = self.long_slug
if self.channel:
context['channel']['level'] = self.channel.get_level()
context['articleboxes'] = ArticleBox.objects.filter(
channel__long_slug=self.long_slug)
if self.slug:
context['articleboxes'] = context['articleboxes'].filter(
article__slug=self.slug)
return context
<commit_msg>Add channel root on set context data, sent to template<commit_after># -*- coding: utf-8 -*-
from django.utils import timezone
from opps.articles.models import ArticleBox, Article
def set_context_data(self, SUPER, **kwargs):
context = super(SUPER, self).get_context_data(**kwargs)
article = Article.objects.filter(
site=self.site,
channel_long_slug__in=self.channel_long_slug,
date_available__lte=timezone.now(),
published=True)
context['posts'] = article.filter(child_class='Post')[:self.limit]
context['albums'] = article.filter(child_class='Album')[:self.limit]
context['channel'] = {}
context['channel']['long_slug'] = self.long_slug
if self.channel:
context['channel']['level'] = self.channel.get_level()
context['channel']['root'] = self.channel.get_root()
context['articleboxes'] = ArticleBox.objects.filter(
channel__long_slug=self.long_slug)
if self.slug:
context['articleboxes'] = context['articleboxes'].filter(
article__slug=self.slug)
return context
|
eb8884ce0c7dec3433d76c49942f0531cc96d915 | plugin/main.py | plugin/main.py | #!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Required fields should raise an error
url, key, secret = vargs['url'], vargs['access_key'], vargs['secret_key']
# Optional fields
compose_file = vargs.get('compose_file', 'docker-compose.yml')
stack = vargs.get('stack', payload['repo']['name'])
services = vargs.get('services', '')
# Change directory
deploy_path = payload["workspace"]["path"]
os.chdir(deploy_path)
rc_args = [
"rancher-compose", "-f", compose_file, "-p", stack, "up", services,
]
subprocess.call(rc_args)
if __name__ == "__main__":
main()
| #!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Required fields should raise an error
os.environ["RANCHER_URL"] = vargs['url']
os.environ["RANCHER_ACCESS_KEY"] = vargs['access_key']
os.environ["RANCHER_SECRET_KEY"] = vargs['secret_key']
# Optional fields
compose_file = vargs.get('compose_file', 'docker-compose.yml')
stack = vargs.get('stack', payload['repo']['name'])
services = vargs.get('services', '')
# Change directory
deploy_path = payload["workspace"]["path"]
os.chdir(deploy_path)
rc_args = [
"rancher-compose", "-f", compose_file, "-p", stack, "up", services,
]
subprocess.call(rc_args)
if __name__ == "__main__":
main()
| Set environmental vars for rancher-compose to work | Set environmental vars for rancher-compose to work
| Python | apache-2.0 | dangerfarms/drone-rancher | #!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Required fields should raise an error
url, key, secret = vargs['url'], vargs['access_key'], vargs['secret_key']
# Optional fields
compose_file = vargs.get('compose_file', 'docker-compose.yml')
stack = vargs.get('stack', payload['repo']['name'])
services = vargs.get('services', '')
# Change directory
deploy_path = payload["workspace"]["path"]
os.chdir(deploy_path)
rc_args = [
"rancher-compose", "-f", compose_file, "-p", stack, "up", services,
]
subprocess.call(rc_args)
if __name__ == "__main__":
main()
Set environmental vars for rancher-compose to work | #!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Required fields should raise an error
os.environ["RANCHER_URL"] = vargs['url']
os.environ["RANCHER_ACCESS_KEY"] = vargs['access_key']
os.environ["RANCHER_SECRET_KEY"] = vargs['secret_key']
# Optional fields
compose_file = vargs.get('compose_file', 'docker-compose.yml')
stack = vargs.get('stack', payload['repo']['name'])
services = vargs.get('services', '')
# Change directory
deploy_path = payload["workspace"]["path"]
os.chdir(deploy_path)
rc_args = [
"rancher-compose", "-f", compose_file, "-p", stack, "up", services,
]
subprocess.call(rc_args)
if __name__ == "__main__":
main()
| <commit_before>#!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Required fields should raise an error
url, key, secret = vargs['url'], vargs['access_key'], vargs['secret_key']
# Optional fields
compose_file = vargs.get('compose_file', 'docker-compose.yml')
stack = vargs.get('stack', payload['repo']['name'])
services = vargs.get('services', '')
# Change directory
deploy_path = payload["workspace"]["path"]
os.chdir(deploy_path)
rc_args = [
"rancher-compose", "-f", compose_file, "-p", stack, "up", services,
]
subprocess.call(rc_args)
if __name__ == "__main__":
main()
<commit_msg>Set environmental vars for rancher-compose to work<commit_after> | #!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Required fields should raise an error
os.environ["RANCHER_URL"] = vargs['url']
os.environ["RANCHER_ACCESS_KEY"] = vargs['access_key']
os.environ["RANCHER_SECRET_KEY"] = vargs['secret_key']
# Optional fields
compose_file = vargs.get('compose_file', 'docker-compose.yml')
stack = vargs.get('stack', payload['repo']['name'])
services = vargs.get('services', '')
# Change directory
deploy_path = payload["workspace"]["path"]
os.chdir(deploy_path)
rc_args = [
"rancher-compose", "-f", compose_file, "-p", stack, "up", services,
]
subprocess.call(rc_args)
if __name__ == "__main__":
main()
| #!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Required fields should raise an error
url, key, secret = vargs['url'], vargs['access_key'], vargs['secret_key']
# Optional fields
compose_file = vargs.get('compose_file', 'docker-compose.yml')
stack = vargs.get('stack', payload['repo']['name'])
services = vargs.get('services', '')
# Change directory
deploy_path = payload["workspace"]["path"]
os.chdir(deploy_path)
rc_args = [
"rancher-compose", "-f", compose_file, "-p", stack, "up", services,
]
subprocess.call(rc_args)
if __name__ == "__main__":
main()
Set environmental vars for rancher-compose to work#!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Required fields should raise an error
os.environ["RANCHER_URL"] = vargs['url']
os.environ["RANCHER_ACCESS_KEY"] = vargs['access_key']
os.environ["RANCHER_SECRET_KEY"] = vargs['secret_key']
# Optional fields
compose_file = vargs.get('compose_file', 'docker-compose.yml')
stack = vargs.get('stack', payload['repo']['name'])
services = vargs.get('services', '')
# Change directory
deploy_path = payload["workspace"]["path"]
os.chdir(deploy_path)
rc_args = [
"rancher-compose", "-f", compose_file, "-p", stack, "up", services,
]
subprocess.call(rc_args)
if __name__ == "__main__":
main()
| <commit_before>#!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Required fields should raise an error
url, key, secret = vargs['url'], vargs['access_key'], vargs['secret_key']
# Optional fields
compose_file = vargs.get('compose_file', 'docker-compose.yml')
stack = vargs.get('stack', payload['repo']['name'])
services = vargs.get('services', '')
# Change directory
deploy_path = payload["workspace"]["path"]
os.chdir(deploy_path)
rc_args = [
"rancher-compose", "-f", compose_file, "-p", stack, "up", services,
]
subprocess.call(rc_args)
if __name__ == "__main__":
main()
<commit_msg>Set environmental vars for rancher-compose to work<commit_after>#!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Required fields should raise an error
os.environ["RANCHER_URL"] = vargs['url']
os.environ["RANCHER_ACCESS_KEY"] = vargs['access_key']
os.environ["RANCHER_SECRET_KEY"] = vargs['secret_key']
# Optional fields
compose_file = vargs.get('compose_file', 'docker-compose.yml')
stack = vargs.get('stack', payload['repo']['name'])
services = vargs.get('services', '')
# Change directory
deploy_path = payload["workspace"]["path"]
os.chdir(deploy_path)
rc_args = [
"rancher-compose", "-f", compose_file, "-p", stack, "up", services,
]
subprocess.call(rc_args)
if __name__ == "__main__":
main()
|
a7028ca3d3dea5a9f8891dfd2947b671bbe02b7e | pentai/gui/my_button.py | pentai/gui/my_button.py |
from kivy.uix.button import Button
import audio as a_m
class MyButton(Button):
def on_touch_up(self, touch, *args, **kwargs):
if self.collide_point(*touch.pos):
if not hasattr(self, "silent"):
a_m.instance.click()
super(MyButton, self).on_touch_up(touch, *args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self, ignored=None):
self.state = "normal"
if not hasattr(self, "silent"):
a_m.instance.click()
|
from kivy.uix.button import Button
import audio as a_m
from pentai.base.defines import *
class MyButton(Button):
def __init__(self, *args, **kwargs):
super(MyButton, self).__init__(*args, **kwargs)
self.silent = False
def on_touch_up(self, touch, *args, **kwargs):
if self.collide_point(*touch.pos):
if not self.silent:
a_m.instance.click()
super(MyButton, self).on_touch_up(touch, *args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self, ignored=None):
self.state = "normal"
if not self.silent:
a_m.instance.click()
| Make "silent" an attribute from __init__ | Make "silent" an attribute from __init__
| Python | mit | cropleyb/pentai,cropleyb/pentai,cropleyb/pentai |
from kivy.uix.button import Button
import audio as a_m
class MyButton(Button):
def on_touch_up(self, touch, *args, **kwargs):
if self.collide_point(*touch.pos):
if not hasattr(self, "silent"):
a_m.instance.click()
super(MyButton, self).on_touch_up(touch, *args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self, ignored=None):
self.state = "normal"
if not hasattr(self, "silent"):
a_m.instance.click()
Make "silent" an attribute from __init__ |
from kivy.uix.button import Button
import audio as a_m
from pentai.base.defines import *
class MyButton(Button):
def __init__(self, *args, **kwargs):
super(MyButton, self).__init__(*args, **kwargs)
self.silent = False
def on_touch_up(self, touch, *args, **kwargs):
if self.collide_point(*touch.pos):
if not self.silent:
a_m.instance.click()
super(MyButton, self).on_touch_up(touch, *args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self, ignored=None):
self.state = "normal"
if not self.silent:
a_m.instance.click()
| <commit_before>
from kivy.uix.button import Button
import audio as a_m
class MyButton(Button):
def on_touch_up(self, touch, *args, **kwargs):
if self.collide_point(*touch.pos):
if not hasattr(self, "silent"):
a_m.instance.click()
super(MyButton, self).on_touch_up(touch, *args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self, ignored=None):
self.state = "normal"
if not hasattr(self, "silent"):
a_m.instance.click()
<commit_msg>Make "silent" an attribute from __init__<commit_after> |
from kivy.uix.button import Button
import audio as a_m
from pentai.base.defines import *
class MyButton(Button):
def __init__(self, *args, **kwargs):
super(MyButton, self).__init__(*args, **kwargs)
self.silent = False
def on_touch_up(self, touch, *args, **kwargs):
if self.collide_point(*touch.pos):
if not self.silent:
a_m.instance.click()
super(MyButton, self).on_touch_up(touch, *args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self, ignored=None):
self.state = "normal"
if not self.silent:
a_m.instance.click()
|
from kivy.uix.button import Button
import audio as a_m
class MyButton(Button):
def on_touch_up(self, touch, *args, **kwargs):
if self.collide_point(*touch.pos):
if not hasattr(self, "silent"):
a_m.instance.click()
super(MyButton, self).on_touch_up(touch, *args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self, ignored=None):
self.state = "normal"
if not hasattr(self, "silent"):
a_m.instance.click()
Make "silent" an attribute from __init__
from kivy.uix.button import Button
import audio as a_m
from pentai.base.defines import *
class MyButton(Button):
def __init__(self, *args, **kwargs):
super(MyButton, self).__init__(*args, **kwargs)
self.silent = False
def on_touch_up(self, touch, *args, **kwargs):
if self.collide_point(*touch.pos):
if not self.silent:
a_m.instance.click()
super(MyButton, self).on_touch_up(touch, *args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self, ignored=None):
self.state = "normal"
if not self.silent:
a_m.instance.click()
| <commit_before>
from kivy.uix.button import Button
import audio as a_m
class MyButton(Button):
def on_touch_up(self, touch, *args, **kwargs):
if self.collide_point(*touch.pos):
if not hasattr(self, "silent"):
a_m.instance.click()
super(MyButton, self).on_touch_up(touch, *args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self, ignored=None):
self.state = "normal"
if not hasattr(self, "silent"):
a_m.instance.click()
<commit_msg>Make "silent" an attribute from __init__<commit_after>
from kivy.uix.button import Button
import audio as a_m
from pentai.base.defines import *
class MyButton(Button):
def __init__(self, *args, **kwargs):
super(MyButton, self).__init__(*args, **kwargs)
self.silent = False
def on_touch_up(self, touch, *args, **kwargs):
if self.collide_point(*touch.pos):
if not self.silent:
a_m.instance.click()
super(MyButton, self).on_touch_up(touch, *args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self, ignored=None):
self.state = "normal"
if not self.silent:
a_m.instance.click()
|
ad07405ca877d65f30c9acd19abb4e782d854eaa | workshops/views.py | workshops/views.py | from django.views.generic import ListView, DetailView
from config.utils import get_active_event
from workshops.models import Workshop
class WorkshopListView(ListView):
template_name = 'workshops/list_workshops.html'
model = Workshop
context_object_name = 'workshops'
def get_queryset(self):
event = get_active_event()
return (super().get_queryset()
.filter(event=event)
.prefetch_related('applicants__user', 'skill_level')
.order_by('title'))
class WorkshopDetailView(DetailView):
template_name = 'workshops/view_workshop.html'
model = Workshop
def get_queryset(self):
return super().get_queryset().prefetch_related('applicants__user', 'skill_level')
| from django.views.generic import ListView, DetailView
from config.utils import get_active_event
from workshops.models import Workshop
class WorkshopListView(ListView):
template_name = 'workshops/list_workshops.html'
model = Workshop
context_object_name = 'workshops'
def get_queryset(self):
event = get_active_event()
return (super().get_queryset()
.filter(event=event)
.prefetch_related('applicants__user', 'skill_level')
.order_by('starts_at', 'title'))
class WorkshopDetailView(DetailView):
template_name = 'workshops/view_workshop.html'
model = Workshop
def get_queryset(self):
return super().get_queryset().prefetch_related('applicants__user', 'skill_level')
| Order workshops by start date before title | Order workshops by start date before title
| Python | bsd-3-clause | WebCampZg/conference-web,WebCampZg/conference-web,WebCampZg/conference-web | from django.views.generic import ListView, DetailView
from config.utils import get_active_event
from workshops.models import Workshop
class WorkshopListView(ListView):
template_name = 'workshops/list_workshops.html'
model = Workshop
context_object_name = 'workshops'
def get_queryset(self):
event = get_active_event()
return (super().get_queryset()
.filter(event=event)
.prefetch_related('applicants__user', 'skill_level')
.order_by('title'))
class WorkshopDetailView(DetailView):
template_name = 'workshops/view_workshop.html'
model = Workshop
def get_queryset(self):
return super().get_queryset().prefetch_related('applicants__user', 'skill_level')
Order workshops by start date before title | from django.views.generic import ListView, DetailView
from config.utils import get_active_event
from workshops.models import Workshop
class WorkshopListView(ListView):
template_name = 'workshops/list_workshops.html'
model = Workshop
context_object_name = 'workshops'
def get_queryset(self):
event = get_active_event()
return (super().get_queryset()
.filter(event=event)
.prefetch_related('applicants__user', 'skill_level')
.order_by('starts_at', 'title'))
class WorkshopDetailView(DetailView):
template_name = 'workshops/view_workshop.html'
model = Workshop
def get_queryset(self):
return super().get_queryset().prefetch_related('applicants__user', 'skill_level')
| <commit_before>from django.views.generic import ListView, DetailView
from config.utils import get_active_event
from workshops.models import Workshop
class WorkshopListView(ListView):
template_name = 'workshops/list_workshops.html'
model = Workshop
context_object_name = 'workshops'
def get_queryset(self):
event = get_active_event()
return (super().get_queryset()
.filter(event=event)
.prefetch_related('applicants__user', 'skill_level')
.order_by('title'))
class WorkshopDetailView(DetailView):
template_name = 'workshops/view_workshop.html'
model = Workshop
def get_queryset(self):
return super().get_queryset().prefetch_related('applicants__user', 'skill_level')
<commit_msg>Order workshops by start date before title<commit_after> | from django.views.generic import ListView, DetailView
from config.utils import get_active_event
from workshops.models import Workshop
class WorkshopListView(ListView):
template_name = 'workshops/list_workshops.html'
model = Workshop
context_object_name = 'workshops'
def get_queryset(self):
event = get_active_event()
return (super().get_queryset()
.filter(event=event)
.prefetch_related('applicants__user', 'skill_level')
.order_by('starts_at', 'title'))
class WorkshopDetailView(DetailView):
template_name = 'workshops/view_workshop.html'
model = Workshop
def get_queryset(self):
return super().get_queryset().prefetch_related('applicants__user', 'skill_level')
| from django.views.generic import ListView, DetailView
from config.utils import get_active_event
from workshops.models import Workshop
class WorkshopListView(ListView):
template_name = 'workshops/list_workshops.html'
model = Workshop
context_object_name = 'workshops'
def get_queryset(self):
event = get_active_event()
return (super().get_queryset()
.filter(event=event)
.prefetch_related('applicants__user', 'skill_level')
.order_by('title'))
class WorkshopDetailView(DetailView):
template_name = 'workshops/view_workshop.html'
model = Workshop
def get_queryset(self):
return super().get_queryset().prefetch_related('applicants__user', 'skill_level')
Order workshops by start date before titlefrom django.views.generic import ListView, DetailView
from config.utils import get_active_event
from workshops.models import Workshop
class WorkshopListView(ListView):
template_name = 'workshops/list_workshops.html'
model = Workshop
context_object_name = 'workshops'
def get_queryset(self):
event = get_active_event()
return (super().get_queryset()
.filter(event=event)
.prefetch_related('applicants__user', 'skill_level')
.order_by('starts_at', 'title'))
class WorkshopDetailView(DetailView):
template_name = 'workshops/view_workshop.html'
model = Workshop
def get_queryset(self):
return super().get_queryset().prefetch_related('applicants__user', 'skill_level')
| <commit_before>from django.views.generic import ListView, DetailView
from config.utils import get_active_event
from workshops.models import Workshop
class WorkshopListView(ListView):
template_name = 'workshops/list_workshops.html'
model = Workshop
context_object_name = 'workshops'
def get_queryset(self):
event = get_active_event()
return (super().get_queryset()
.filter(event=event)
.prefetch_related('applicants__user', 'skill_level')
.order_by('title'))
class WorkshopDetailView(DetailView):
template_name = 'workshops/view_workshop.html'
model = Workshop
def get_queryset(self):
return super().get_queryset().prefetch_related('applicants__user', 'skill_level')
<commit_msg>Order workshops by start date before title<commit_after>from django.views.generic import ListView, DetailView
from config.utils import get_active_event
from workshops.models import Workshop
class WorkshopListView(ListView):
template_name = 'workshops/list_workshops.html'
model = Workshop
context_object_name = 'workshops'
def get_queryset(self):
event = get_active_event()
return (super().get_queryset()
.filter(event=event)
.prefetch_related('applicants__user', 'skill_level')
.order_by('starts_at', 'title'))
class WorkshopDetailView(DetailView):
template_name = 'workshops/view_workshop.html'
model = Workshop
def get_queryset(self):
return super().get_queryset().prefetch_related('applicants__user', 'skill_level')
|
a39a7eb7d43282337d3e3df10921a1b0d9f0e3e4 | odeintw/__init__.py | odeintw/__init__.py | # Copyright (c) 2014, Warren Weckesser
# All rights reserved.
# See the LICENSE file for license information.
from numpy.testing import Tester as _Tester
from ._odeintw import odeintw
__version__ = "0.1.2.dev3"
test = _Tester().test
| # Copyright (c) 2014, Warren Weckesser
# All rights reserved.
# See the LICENSE file for license information.
from ._odeintw import odeintw
__version__ = "0.1.2.dev3"
| Remove some unused test infrastructure | MAINT: Remove some unused test infrastructure
| Python | bsd-3-clause | WarrenWeckesser/odeintw | # Copyright (c) 2014, Warren Weckesser
# All rights reserved.
# See the LICENSE file for license information.
from numpy.testing import Tester as _Tester
from ._odeintw import odeintw
__version__ = "0.1.2.dev3"
test = _Tester().test
MAINT: Remove some unused test infrastructure | # Copyright (c) 2014, Warren Weckesser
# All rights reserved.
# See the LICENSE file for license information.
from ._odeintw import odeintw
__version__ = "0.1.2.dev3"
| <commit_before># Copyright (c) 2014, Warren Weckesser
# All rights reserved.
# See the LICENSE file for license information.
from numpy.testing import Tester as _Tester
from ._odeintw import odeintw
__version__ = "0.1.2.dev3"
test = _Tester().test
<commit_msg>MAINT: Remove some unused test infrastructure<commit_after> | # Copyright (c) 2014, Warren Weckesser
# All rights reserved.
# See the LICENSE file for license information.
from ._odeintw import odeintw
__version__ = "0.1.2.dev3"
| # Copyright (c) 2014, Warren Weckesser
# All rights reserved.
# See the LICENSE file for license information.
from numpy.testing import Tester as _Tester
from ._odeintw import odeintw
__version__ = "0.1.2.dev3"
test = _Tester().test
MAINT: Remove some unused test infrastructure# Copyright (c) 2014, Warren Weckesser
# All rights reserved.
# See the LICENSE file for license information.
from ._odeintw import odeintw
__version__ = "0.1.2.dev3"
| <commit_before># Copyright (c) 2014, Warren Weckesser
# All rights reserved.
# See the LICENSE file for license information.
from numpy.testing import Tester as _Tester
from ._odeintw import odeintw
__version__ = "0.1.2.dev3"
test = _Tester().test
<commit_msg>MAINT: Remove some unused test infrastructure<commit_after># Copyright (c) 2014, Warren Weckesser
# All rights reserved.
# See the LICENSE file for license information.
from ._odeintw import odeintw
__version__ = "0.1.2.dev3"
|
73df211afe212124a69f8585e30d03332b20767c | migrate/__init__.py | migrate/__init__.py | """
SQLAlchemy migrate provides two APIs :mod:`migrate.versioning` for
database schema version and repository management and
:mod:`migrate.changeset` that allows to define database schema changes
using Python.
"""
from migrate.versioning import *
from migrate.changeset import *
__version__ = '0.7.3.dev'
| """
SQLAlchemy migrate provides two APIs :mod:`migrate.versioning` for
database schema version and repository management and
:mod:`migrate.changeset` that allows to define database schema changes
using Python.
"""
from migrate.versioning import *
from migrate.changeset import *
__version__ = '0.8.1'
| Fix the version number to match the last release. | Fix the version number to match the last release.
** NOTE: our release process really should do this
ahead of time.
Change-Id: Ic0cce0d57b4f05092417c4cf1a4ca5a74812ec3c
| Python | mit | rcherrueau/sqlalchemy-migrate,rcherrueau/sqlalchemy-migrate,andras-tim/sqlalchemy-migrate,dannon/sqlalchemy-migrate,stackforge/sqlalchemy-migrate,openstack/sqlalchemy-migrate,openstack/sqlalchemy-migrate | """
SQLAlchemy migrate provides two APIs :mod:`migrate.versioning` for
database schema version and repository management and
:mod:`migrate.changeset` that allows to define database schema changes
using Python.
"""
from migrate.versioning import *
from migrate.changeset import *
__version__ = '0.7.3.dev'
Fix the version number to match the last release.
** NOTE: our release process really should do this
ahead of time.
Change-Id: Ic0cce0d57b4f05092417c4cf1a4ca5a74812ec3c | """
SQLAlchemy migrate provides two APIs :mod:`migrate.versioning` for
database schema version and repository management and
:mod:`migrate.changeset` that allows to define database schema changes
using Python.
"""
from migrate.versioning import *
from migrate.changeset import *
__version__ = '0.8.1'
| <commit_before>"""
SQLAlchemy migrate provides two APIs :mod:`migrate.versioning` for
database schema version and repository management and
:mod:`migrate.changeset` that allows to define database schema changes
using Python.
"""
from migrate.versioning import *
from migrate.changeset import *
__version__ = '0.7.3.dev'
<commit_msg>Fix the version number to match the last release.
** NOTE: our release process really should do this
ahead of time.
Change-Id: Ic0cce0d57b4f05092417c4cf1a4ca5a74812ec3c<commit_after> | """
SQLAlchemy migrate provides two APIs :mod:`migrate.versioning` for
database schema version and repository management and
:mod:`migrate.changeset` that allows to define database schema changes
using Python.
"""
from migrate.versioning import *
from migrate.changeset import *
__version__ = '0.8.1'
| """
SQLAlchemy migrate provides two APIs :mod:`migrate.versioning` for
database schema version and repository management and
:mod:`migrate.changeset` that allows to define database schema changes
using Python.
"""
from migrate.versioning import *
from migrate.changeset import *
__version__ = '0.7.3.dev'
Fix the version number to match the last release.
** NOTE: our release process really should do this
ahead of time.
Change-Id: Ic0cce0d57b4f05092417c4cf1a4ca5a74812ec3c"""
SQLAlchemy migrate provides two APIs :mod:`migrate.versioning` for
database schema version and repository management and
:mod:`migrate.changeset` that allows to define database schema changes
using Python.
"""
from migrate.versioning import *
from migrate.changeset import *
__version__ = '0.8.1'
| <commit_before>"""
SQLAlchemy migrate provides two APIs :mod:`migrate.versioning` for
database schema version and repository management and
:mod:`migrate.changeset` that allows to define database schema changes
using Python.
"""
from migrate.versioning import *
from migrate.changeset import *
__version__ = '0.7.3.dev'
<commit_msg>Fix the version number to match the last release.
** NOTE: our release process really should do this
ahead of time.
Change-Id: Ic0cce0d57b4f05092417c4cf1a4ca5a74812ec3c<commit_after>"""
SQLAlchemy migrate provides two APIs :mod:`migrate.versioning` for
database schema version and repository management and
:mod:`migrate.changeset` that allows to define database schema changes
using Python.
"""
from migrate.versioning import *
from migrate.changeset import *
__version__ = '0.8.1'
|
a116b22a76b0f833aa9f7f2e2ce4b36a95bc9ba0 | freight/tasks/send_pending_notifications.py | freight/tasks/send_pending_notifications.py | from __future__ import absolute_import
import logging
from freight import notifiers
from freight.config import celery, redis
from freight.models import Task
from freight.notifiers import queue
from freight.utils.redis import lock
@celery.task(name='freight.send_pending_notifications', max_retries=None)
def send_pending_notifications():
while True:
with lock(redis, 'notificationcheck', timeout=5):
data = queue.get()
if data is None:
return
task = Task.query.get(data['task'])
if task is None:
continue
notifier = notifiers.get(data['type'])
try:
notifier.send(
task=task,
config=data['config'],
event=data['event'],
)
except Exception:
logging.exception('%s notifier failed to send Task(id=%s)',
data['type'], task.id)
| from __future__ import absolute_import
import logging
from freight import notifiers
from freight.config import celery, redis
from freight.models import Task
from freight.notifiers import queue
from freight.utils.redis import lock
@celery.task(name='freight.send_pending_notifications', max_retries=None)
def send_pending_notifications():
while True:
with lock(redis, 'notificationcheck', timeout=5):
data = queue.get()
if data is None:
logging.info('No due notifications found')
return
task = Task.query.get(data['task'])
if task is None:
continue
notifier = notifiers.get(data['type'])
try:
notifier.send(
task=task,
config=data['config'],
event=data['event'],
)
except Exception:
logging.exception('%s notifier failed to send Task(id=%s)',
data['type'], task.id)
| Add logging when no notifications due | Add logging when no notifications due
| Python | apache-2.0 | getsentry/freight,klynton/freight,rshk/freight,rshk/freight,rshk/freight,klynton/freight,rshk/freight,getsentry/freight,klynton/freight,klynton/freight,getsentry/freight,getsentry/freight,getsentry/freight | from __future__ import absolute_import
import logging
from freight import notifiers
from freight.config import celery, redis
from freight.models import Task
from freight.notifiers import queue
from freight.utils.redis import lock
@celery.task(name='freight.send_pending_notifications', max_retries=None)
def send_pending_notifications():
while True:
with lock(redis, 'notificationcheck', timeout=5):
data = queue.get()
if data is None:
return
task = Task.query.get(data['task'])
if task is None:
continue
notifier = notifiers.get(data['type'])
try:
notifier.send(
task=task,
config=data['config'],
event=data['event'],
)
except Exception:
logging.exception('%s notifier failed to send Task(id=%s)',
data['type'], task.id)
Add logging when no notifications due | from __future__ import absolute_import
import logging
from freight import notifiers
from freight.config import celery, redis
from freight.models import Task
from freight.notifiers import queue
from freight.utils.redis import lock
@celery.task(name='freight.send_pending_notifications', max_retries=None)
def send_pending_notifications():
while True:
with lock(redis, 'notificationcheck', timeout=5):
data = queue.get()
if data is None:
logging.info('No due notifications found')
return
task = Task.query.get(data['task'])
if task is None:
continue
notifier = notifiers.get(data['type'])
try:
notifier.send(
task=task,
config=data['config'],
event=data['event'],
)
except Exception:
logging.exception('%s notifier failed to send Task(id=%s)',
data['type'], task.id)
| <commit_before>from __future__ import absolute_import
import logging
from freight import notifiers
from freight.config import celery, redis
from freight.models import Task
from freight.notifiers import queue
from freight.utils.redis import lock
@celery.task(name='freight.send_pending_notifications', max_retries=None)
def send_pending_notifications():
while True:
with lock(redis, 'notificationcheck', timeout=5):
data = queue.get()
if data is None:
return
task = Task.query.get(data['task'])
if task is None:
continue
notifier = notifiers.get(data['type'])
try:
notifier.send(
task=task,
config=data['config'],
event=data['event'],
)
except Exception:
logging.exception('%s notifier failed to send Task(id=%s)',
data['type'], task.id)
<commit_msg>Add logging when no notifications due<commit_after> | from __future__ import absolute_import
import logging
from freight import notifiers
from freight.config import celery, redis
from freight.models import Task
from freight.notifiers import queue
from freight.utils.redis import lock
@celery.task(name='freight.send_pending_notifications', max_retries=None)
def send_pending_notifications():
while True:
with lock(redis, 'notificationcheck', timeout=5):
data = queue.get()
if data is None:
logging.info('No due notifications found')
return
task = Task.query.get(data['task'])
if task is None:
continue
notifier = notifiers.get(data['type'])
try:
notifier.send(
task=task,
config=data['config'],
event=data['event'],
)
except Exception:
logging.exception('%s notifier failed to send Task(id=%s)',
data['type'], task.id)
| from __future__ import absolute_import
import logging
from freight import notifiers
from freight.config import celery, redis
from freight.models import Task
from freight.notifiers import queue
from freight.utils.redis import lock
@celery.task(name='freight.send_pending_notifications', max_retries=None)
def send_pending_notifications():
while True:
with lock(redis, 'notificationcheck', timeout=5):
data = queue.get()
if data is None:
return
task = Task.query.get(data['task'])
if task is None:
continue
notifier = notifiers.get(data['type'])
try:
notifier.send(
task=task,
config=data['config'],
event=data['event'],
)
except Exception:
logging.exception('%s notifier failed to send Task(id=%s)',
data['type'], task.id)
Add logging when no notifications duefrom __future__ import absolute_import
import logging
from freight import notifiers
from freight.config import celery, redis
from freight.models import Task
from freight.notifiers import queue
from freight.utils.redis import lock
@celery.task(name='freight.send_pending_notifications', max_retries=None)
def send_pending_notifications():
while True:
with lock(redis, 'notificationcheck', timeout=5):
data = queue.get()
if data is None:
logging.info('No due notifications found')
return
task = Task.query.get(data['task'])
if task is None:
continue
notifier = notifiers.get(data['type'])
try:
notifier.send(
task=task,
config=data['config'],
event=data['event'],
)
except Exception:
logging.exception('%s notifier failed to send Task(id=%s)',
data['type'], task.id)
| <commit_before>from __future__ import absolute_import
import logging
from freight import notifiers
from freight.config import celery, redis
from freight.models import Task
from freight.notifiers import queue
from freight.utils.redis import lock
@celery.task(name='freight.send_pending_notifications', max_retries=None)
def send_pending_notifications():
while True:
with lock(redis, 'notificationcheck', timeout=5):
data = queue.get()
if data is None:
return
task = Task.query.get(data['task'])
if task is None:
continue
notifier = notifiers.get(data['type'])
try:
notifier.send(
task=task,
config=data['config'],
event=data['event'],
)
except Exception:
logging.exception('%s notifier failed to send Task(id=%s)',
data['type'], task.id)
<commit_msg>Add logging when no notifications due<commit_after>from __future__ import absolute_import
import logging
from freight import notifiers
from freight.config import celery, redis
from freight.models import Task
from freight.notifiers import queue
from freight.utils.redis import lock
@celery.task(name='freight.send_pending_notifications', max_retries=None)
def send_pending_notifications():
while True:
with lock(redis, 'notificationcheck', timeout=5):
data = queue.get()
if data is None:
logging.info('No due notifications found')
return
task = Task.query.get(data['task'])
if task is None:
continue
notifier = notifiers.get(data['type'])
try:
notifier.send(
task=task,
config=data['config'],
event=data['event'],
)
except Exception:
logging.exception('%s notifier failed to send Task(id=%s)',
data['type'], task.id)
|
83a517ad963e08e0200e4eeb3a817acc069ba7a4 | jacquard/cli.py | jacquard/cli.py | import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='store_true',
)
parser.add_argument(
'-c',
'--config',
help="config file",
type=pathlib.Path,
default=pathlib.Path('config.cfg'),
)
parser.set_defaults(func=None)
subparsers = parser.add_subparsers(metavar='subcommand')
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
command_help = getattr(command, 'help', entry_point.name)
subparser = subparsers.add_parser(
entry_point.name,
help=command_help,
description=command_help,
)
subparser.set_defaults(func=command.handle)
command.add_arguments(subparser)
return parser
def main(args=sys.argv[1:]):
parser = argument_parser()
options = parser.parse_args(args)
if options.func is None:
parser.print_usage()
return
# Parse options
config = load_config(options.config)
# Run subcommand
options.func(config, options)
if '__name__' == '__main__':
main()
| import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='store_true',
)
parser.add_argument(
'-c',
'--config',
help="config file",
type=pathlib.Path,
default=pathlib.Path('config.cfg'),
)
parser.set_defaults(func=None)
subparsers = parser.add_subparsers(metavar='subcommand')
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
command_help = getattr(command, 'help', entry_point.name)
subparser = subparsers.add_parser(
entry_point.name,
help=command_help,
description=command_help,
)
subparser.set_defaults(func=command.handle)
command.add_arguments(subparser)
return parser
def main(args=sys.argv[1:]):
parser = argument_parser()
options = parser.parse_args(args)
if options.func is None:
parser.print_help()
return
# Parse options
config = load_config(options.config)
# Run subcommand
options.func(config, options)
if '__name__' == '__main__':
main()
| Print help when invoked with no arguments | Print help when invoked with no arguments
This is more useful.
| Python | mit | prophile/jacquard,prophile/jacquard | import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='store_true',
)
parser.add_argument(
'-c',
'--config',
help="config file",
type=pathlib.Path,
default=pathlib.Path('config.cfg'),
)
parser.set_defaults(func=None)
subparsers = parser.add_subparsers(metavar='subcommand')
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
command_help = getattr(command, 'help', entry_point.name)
subparser = subparsers.add_parser(
entry_point.name,
help=command_help,
description=command_help,
)
subparser.set_defaults(func=command.handle)
command.add_arguments(subparser)
return parser
def main(args=sys.argv[1:]):
parser = argument_parser()
options = parser.parse_args(args)
if options.func is None:
parser.print_usage()
return
# Parse options
config = load_config(options.config)
# Run subcommand
options.func(config, options)
if '__name__' == '__main__':
main()
Print help when invoked with no arguments
This is more useful. | import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='store_true',
)
parser.add_argument(
'-c',
'--config',
help="config file",
type=pathlib.Path,
default=pathlib.Path('config.cfg'),
)
parser.set_defaults(func=None)
subparsers = parser.add_subparsers(metavar='subcommand')
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
command_help = getattr(command, 'help', entry_point.name)
subparser = subparsers.add_parser(
entry_point.name,
help=command_help,
description=command_help,
)
subparser.set_defaults(func=command.handle)
command.add_arguments(subparser)
return parser
def main(args=sys.argv[1:]):
parser = argument_parser()
options = parser.parse_args(args)
if options.func is None:
parser.print_help()
return
# Parse options
config = load_config(options.config)
# Run subcommand
options.func(config, options)
if '__name__' == '__main__':
main()
| <commit_before>import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='store_true',
)
parser.add_argument(
'-c',
'--config',
help="config file",
type=pathlib.Path,
default=pathlib.Path('config.cfg'),
)
parser.set_defaults(func=None)
subparsers = parser.add_subparsers(metavar='subcommand')
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
command_help = getattr(command, 'help', entry_point.name)
subparser = subparsers.add_parser(
entry_point.name,
help=command_help,
description=command_help,
)
subparser.set_defaults(func=command.handle)
command.add_arguments(subparser)
return parser
def main(args=sys.argv[1:]):
parser = argument_parser()
options = parser.parse_args(args)
if options.func is None:
parser.print_usage()
return
# Parse options
config = load_config(options.config)
# Run subcommand
options.func(config, options)
if '__name__' == '__main__':
main()
<commit_msg>Print help when invoked with no arguments
This is more useful.<commit_after> | import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='store_true',
)
parser.add_argument(
'-c',
'--config',
help="config file",
type=pathlib.Path,
default=pathlib.Path('config.cfg'),
)
parser.set_defaults(func=None)
subparsers = parser.add_subparsers(metavar='subcommand')
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
command_help = getattr(command, 'help', entry_point.name)
subparser = subparsers.add_parser(
entry_point.name,
help=command_help,
description=command_help,
)
subparser.set_defaults(func=command.handle)
command.add_arguments(subparser)
return parser
def main(args=sys.argv[1:]):
parser = argument_parser()
options = parser.parse_args(args)
if options.func is None:
parser.print_help()
return
# Parse options
config = load_config(options.config)
# Run subcommand
options.func(config, options)
if '__name__' == '__main__':
main()
| import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='store_true',
)
parser.add_argument(
'-c',
'--config',
help="config file",
type=pathlib.Path,
default=pathlib.Path('config.cfg'),
)
parser.set_defaults(func=None)
subparsers = parser.add_subparsers(metavar='subcommand')
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
command_help = getattr(command, 'help', entry_point.name)
subparser = subparsers.add_parser(
entry_point.name,
help=command_help,
description=command_help,
)
subparser.set_defaults(func=command.handle)
command.add_arguments(subparser)
return parser
def main(args=sys.argv[1:]):
parser = argument_parser()
options = parser.parse_args(args)
if options.func is None:
parser.print_usage()
return
# Parse options
config = load_config(options.config)
# Run subcommand
options.func(config, options)
if '__name__' == '__main__':
main()
Print help when invoked with no arguments
This is more useful.import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='store_true',
)
parser.add_argument(
'-c',
'--config',
help="config file",
type=pathlib.Path,
default=pathlib.Path('config.cfg'),
)
parser.set_defaults(func=None)
subparsers = parser.add_subparsers(metavar='subcommand')
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
command_help = getattr(command, 'help', entry_point.name)
subparser = subparsers.add_parser(
entry_point.name,
help=command_help,
description=command_help,
)
subparser.set_defaults(func=command.handle)
command.add_arguments(subparser)
return parser
def main(args=sys.argv[1:]):
parser = argument_parser()
options = parser.parse_args(args)
if options.func is None:
parser.print_help()
return
# Parse options
config = load_config(options.config)
# Run subcommand
options.func(config, options)
if '__name__' == '__main__':
main()
| <commit_before>import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='store_true',
)
parser.add_argument(
'-c',
'--config',
help="config file",
type=pathlib.Path,
default=pathlib.Path('config.cfg'),
)
parser.set_defaults(func=None)
subparsers = parser.add_subparsers(metavar='subcommand')
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
command_help = getattr(command, 'help', entry_point.name)
subparser = subparsers.add_parser(
entry_point.name,
help=command_help,
description=command_help,
)
subparser.set_defaults(func=command.handle)
command.add_arguments(subparser)
return parser
def main(args=sys.argv[1:]):
parser = argument_parser()
options = parser.parse_args(args)
if options.func is None:
parser.print_usage()
return
# Parse options
config = load_config(options.config)
# Run subcommand
options.func(config, options)
if '__name__' == '__main__':
main()
<commit_msg>Print help when invoked with no arguments
This is more useful.<commit_after>import sys
import pathlib
import argparse
import pkg_resources
from jacquard.config import load_config
def argument_parser():
parser = argparse.ArgumentParser(description="Split testing server")
parser.add_argument(
'-v',
'--verbose',
help="enable verbose output",
action='store_true',
)
parser.add_argument(
'-c',
'--config',
help="config file",
type=pathlib.Path,
default=pathlib.Path('config.cfg'),
)
parser.set_defaults(func=None)
subparsers = parser.add_subparsers(metavar='subcommand')
for entry_point in pkg_resources.iter_entry_points('jacquard.commands'):
command = entry_point.load()()
command_help = getattr(command, 'help', entry_point.name)
subparser = subparsers.add_parser(
entry_point.name,
help=command_help,
description=command_help,
)
subparser.set_defaults(func=command.handle)
command.add_arguments(subparser)
return parser
def main(args=sys.argv[1:]):
parser = argument_parser()
options = parser.parse_args(args)
if options.func is None:
parser.print_help()
return
# Parse options
config = load_config(options.config)
# Run subcommand
options.func(config, options)
if '__name__' == '__main__':
main()
|
882fc867ab115f2b84f2f185bcebf3eb4a1d2fc8 | core/forms.py | core/forms.py | from django.forms import ModelForm
from django.forms.fields import CharField
from models import UserProfile
class UserProfileForm(ModelForm):
first_name = CharField(label='First name', required=False)
last_name = CharField(label='Last name', required=False)
class Meta:
model = UserProfile
# Don't allow users edit someone else's user page,
# or to whitelist themselves
exclude = ('user', 'whitelisted',)
def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
if self.instance:
self.fields['first_name'].initial = self.instance.user.first_name
self.fields['last_name'].initial = self.instance.user.last_name
def save(self):
first_name = self.cleaned_data.pop('first_name', None)
last_name = self.cleaned_data.pop('last_name', None)
profile = super(UserProfileForm, self).save()
user = profile.user
user.first_name = first_name
user.last_name = last_name
user.save()
return profile | from django.forms import ModelForm
from django.forms.fields import CharField
from models import UserProfile
class UserProfileForm(ModelForm):
first_name = CharField(label='First name', required=False)
last_name = CharField(label='Last name', required=False)
class Meta:
model = UserProfile
# Don't allow users edit someone else's user page,
# or to whitelist themselves
exclude = ('user', 'whitelisted',)
def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
if self.is_bound:
self.fields['first_name'].initial = self.instance.user.first_name
self.fields['last_name'].initial = self.instance.user.last_name
def save(self):
first_name = self.cleaned_data.pop('first_name', None)
last_name = self.cleaned_data.pop('last_name', None)
profile = super(UserProfileForm, self).save()
user = profile.user
user.first_name = first_name
user.last_name = last_name
user.save()
return profile
| Fix profile creation. (Need tests badly). | Fix profile creation. (Need tests badly). | Python | mit | kenwang76/readthedocs.org,soulshake/readthedocs.org,nyergler/pythonslides,gjtorikian/readthedocs.org,tddv/readthedocs.org,kenshinthebattosai/readthedocs.org,ojii/readthedocs.org,LukasBoersma/readthedocs.org,mhils/readthedocs.org,sid-kap/readthedocs.org,michaelmcandrew/readthedocs.org,michaelmcandrew/readthedocs.org,ojii/readthedocs.org,royalwang/readthedocs.org,asampat3090/readthedocs.org,SteveViss/readthedocs.org,ojii/readthedocs.org,safwanrahman/readthedocs.org,kdkeyser/readthedocs.org,wanghaven/readthedocs.org,KamranMackey/readthedocs.org,johncosta/private-readthedocs.org,fujita-shintaro/readthedocs.org,Tazer/readthedocs.org,titiushko/readthedocs.org,istresearch/readthedocs.org,pombredanne/readthedocs.org,CedarLogic/readthedocs.org,wanghaven/readthedocs.org,davidfischer/readthedocs.org,wijerasa/readthedocs.org,CedarLogic/readthedocs.org,stevepiercy/readthedocs.org,gjtorikian/readthedocs.org,nyergler/pythonslides,takluyver/readthedocs.org,emawind84/readthedocs.org,sils1297/readthedocs.org,attakei/readthedocs-oauth,KamranMackey/readthedocs.org,dirn/readthedocs.org,titiushko/readthedocs.org,wijerasa/readthedocs.org,davidfischer/readthedocs.org,GovReady/readthedocs.org,VishvajitP/readthedocs.org,davidfischer/readthedocs.org,wanghaven/readthedocs.org,raven47git/readthedocs.org,clarkperkins/readthedocs.org,sid-kap/readthedocs.org,LukasBoersma/readthedocs.org,kenshinthebattosai/readthedocs.org,espdev/readthedocs.org,Tazer/readthedocs.org,SteveViss/readthedocs.org,davidfischer/readthedocs.org,mrshoki/readthedocs.org,soulshake/readthedocs.org,johncosta/private-readthedocs.org,singingwolfboy/readthedocs.org,espdev/readthedocs.org,GovReady/readthedocs.org,takluyver/readthedocs.org,d0ugal/readthedocs.org,asampat3090/readthedocs.org,royalwang/readthedocs.org,michaelmcandrew/readthedocs.org,SteveViss/readthedocs.org,royalwang/readthedocs.org,nikolas/readthedocs.org,istresearch/readthedocs.org,wijerasa/readthedocs.org,CedarLogic/readthedocs.org,techtonik/readthedocs.org,agjohnson/readthedocs.org,istresearch/readthedocs.org,dirn/readthedocs.org,Carreau/readthedocs.org,raven47git/readthedocs.org,raven47git/readthedocs.org,alex/readthedocs.org,emawind84/readthedocs.org,sunnyzwh/readthedocs.org,cgourlay/readthedocs.org,hach-que/readthedocs.org,Tazer/readthedocs.org,kenwang76/readthedocs.org,sils1297/readthedocs.org,kdkeyser/readthedocs.org,alex/readthedocs.org,VishvajitP/readthedocs.org,attakei/readthedocs-oauth,espdev/readthedocs.org,agjohnson/readthedocs.org,soulshake/readthedocs.org,tddv/readthedocs.org,sils1297/readthedocs.org,techtonik/readthedocs.org,soulshake/readthedocs.org,sunnyzwh/readthedocs.org,Carreau/readthedocs.org,hach-que/readthedocs.org,d0ugal/readthedocs.org,attakei/readthedocs-oauth,hach-que/readthedocs.org,atsuyim/readthedocs.org,stevepiercy/readthedocs.org,ojii/readthedocs.org,singingwolfboy/readthedocs.org,tddv/readthedocs.org,rtfd/readthedocs.org,espdev/readthedocs.org,KamranMackey/readthedocs.org,nyergler/pythonslides,techtonik/readthedocs.org,mrshoki/readthedocs.org,attakei/readthedocs-oauth,mhils/readthedocs.org,atsuyim/readthedocs.org,nikolas/readthedocs.org,johncosta/private-readthedocs.org,dirn/readthedocs.org,kenshinthebattosai/readthedocs.org,pombredanne/readthedocs.org,Carreau/readthedocs.org,jerel/readthedocs.org,nikolas/readthedocs.org,takluyver/readthedocs.org,titiushko/readthedocs.org,takluyver/readthedocs.org,laplaceliu/readthedocs.org,fujita-shintaro/readthedocs.org,cgourlay/readthedocs.org,rtfd/readthedocs.org,hach-que/readthedocs.org,espdev/readthedocs.org,laplaceliu/readthedocs.org,rtfd/readthedocs.org,gjtorikian/readthedocs.org,LukasBoersma/readthedocs.org,Carreau/readthedocs.org,sid-kap/readthedocs.org,jerel/readthedocs.org,sils1297/readthedocs.org,safwanrahman/readthedocs.org,clarkperkins/readthedocs.org,gjtorikian/readthedocs.org,kenshinthebattosai/readthedocs.org,alex/readthedocs.org,jerel/readthedocs.org,Tazer/readthedocs.org,atsuyim/readthedocs.org,VishvajitP/readthedocs.org,d0ugal/readthedocs.org,sunnyzwh/readthedocs.org,clarkperkins/readthedocs.org,stevepiercy/readthedocs.org,istresearch/readthedocs.org,GovReady/readthedocs.org,SteveViss/readthedocs.org,titiushko/readthedocs.org,agjohnson/readthedocs.org,fujita-shintaro/readthedocs.org,mrshoki/readthedocs.org,KamranMackey/readthedocs.org,stevepiercy/readthedocs.org,mhils/readthedocs.org,mhils/readthedocs.org,singingwolfboy/readthedocs.org,royalwang/readthedocs.org,safwanrahman/readthedocs.org,sid-kap/readthedocs.org,LukasBoersma/readthedocs.org,dirn/readthedocs.org,kenwang76/readthedocs.org,sunnyzwh/readthedocs.org,GovReady/readthedocs.org,emawind84/readthedocs.org,asampat3090/readthedocs.org,jerel/readthedocs.org,cgourlay/readthedocs.org,asampat3090/readthedocs.org,singingwolfboy/readthedocs.org,cgourlay/readthedocs.org,CedarLogic/readthedocs.org,safwanrahman/readthedocs.org,kdkeyser/readthedocs.org,techtonik/readthedocs.org,clarkperkins/readthedocs.org,kdkeyser/readthedocs.org,rtfd/readthedocs.org,wanghaven/readthedocs.org,kenwang76/readthedocs.org,pombredanne/readthedocs.org,emawind84/readthedocs.org,fujita-shintaro/readthedocs.org,wijerasa/readthedocs.org,nikolas/readthedocs.org,michaelmcandrew/readthedocs.org,mrshoki/readthedocs.org,d0ugal/readthedocs.org,atsuyim/readthedocs.org,laplaceliu/readthedocs.org,agjohnson/readthedocs.org,raven47git/readthedocs.org,alex/readthedocs.org,laplaceliu/readthedocs.org,nyergler/pythonslides,VishvajitP/readthedocs.org | from django.forms import ModelForm
from django.forms.fields import CharField
from models import UserProfile
class UserProfileForm(ModelForm):
first_name = CharField(label='First name', required=False)
last_name = CharField(label='Last name', required=False)
class Meta:
model = UserProfile
# Don't allow users edit someone else's user page,
# or to whitelist themselves
exclude = ('user', 'whitelisted',)
def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
if self.instance:
self.fields['first_name'].initial = self.instance.user.first_name
self.fields['last_name'].initial = self.instance.user.last_name
def save(self):
first_name = self.cleaned_data.pop('first_name', None)
last_name = self.cleaned_data.pop('last_name', None)
profile = super(UserProfileForm, self).save()
user = profile.user
user.first_name = first_name
user.last_name = last_name
user.save()
return profileFix profile creation. (Need tests badly). | from django.forms import ModelForm
from django.forms.fields import CharField
from models import UserProfile
class UserProfileForm(ModelForm):
first_name = CharField(label='First name', required=False)
last_name = CharField(label='Last name', required=False)
class Meta:
model = UserProfile
# Don't allow users edit someone else's user page,
# or to whitelist themselves
exclude = ('user', 'whitelisted',)
def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
if self.is_bound:
self.fields['first_name'].initial = self.instance.user.first_name
self.fields['last_name'].initial = self.instance.user.last_name
def save(self):
first_name = self.cleaned_data.pop('first_name', None)
last_name = self.cleaned_data.pop('last_name', None)
profile = super(UserProfileForm, self).save()
user = profile.user
user.first_name = first_name
user.last_name = last_name
user.save()
return profile
| <commit_before>from django.forms import ModelForm
from django.forms.fields import CharField
from models import UserProfile
class UserProfileForm(ModelForm):
first_name = CharField(label='First name', required=False)
last_name = CharField(label='Last name', required=False)
class Meta:
model = UserProfile
# Don't allow users edit someone else's user page,
# or to whitelist themselves
exclude = ('user', 'whitelisted',)
def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
if self.instance:
self.fields['first_name'].initial = self.instance.user.first_name
self.fields['last_name'].initial = self.instance.user.last_name
def save(self):
first_name = self.cleaned_data.pop('first_name', None)
last_name = self.cleaned_data.pop('last_name', None)
profile = super(UserProfileForm, self).save()
user = profile.user
user.first_name = first_name
user.last_name = last_name
user.save()
return profile<commit_msg>Fix profile creation. (Need tests badly).<commit_after> | from django.forms import ModelForm
from django.forms.fields import CharField
from models import UserProfile
class UserProfileForm(ModelForm):
first_name = CharField(label='First name', required=False)
last_name = CharField(label='Last name', required=False)
class Meta:
model = UserProfile
# Don't allow users edit someone else's user page,
# or to whitelist themselves
exclude = ('user', 'whitelisted',)
def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
if self.is_bound:
self.fields['first_name'].initial = self.instance.user.first_name
self.fields['last_name'].initial = self.instance.user.last_name
def save(self):
first_name = self.cleaned_data.pop('first_name', None)
last_name = self.cleaned_data.pop('last_name', None)
profile = super(UserProfileForm, self).save()
user = profile.user
user.first_name = first_name
user.last_name = last_name
user.save()
return profile
| from django.forms import ModelForm
from django.forms.fields import CharField
from models import UserProfile
class UserProfileForm(ModelForm):
first_name = CharField(label='First name', required=False)
last_name = CharField(label='Last name', required=False)
class Meta:
model = UserProfile
# Don't allow users edit someone else's user page,
# or to whitelist themselves
exclude = ('user', 'whitelisted',)
def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
if self.instance:
self.fields['first_name'].initial = self.instance.user.first_name
self.fields['last_name'].initial = self.instance.user.last_name
def save(self):
first_name = self.cleaned_data.pop('first_name', None)
last_name = self.cleaned_data.pop('last_name', None)
profile = super(UserProfileForm, self).save()
user = profile.user
user.first_name = first_name
user.last_name = last_name
user.save()
return profileFix profile creation. (Need tests badly).from django.forms import ModelForm
from django.forms.fields import CharField
from models import UserProfile
class UserProfileForm(ModelForm):
first_name = CharField(label='First name', required=False)
last_name = CharField(label='Last name', required=False)
class Meta:
model = UserProfile
# Don't allow users edit someone else's user page,
# or to whitelist themselves
exclude = ('user', 'whitelisted',)
def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
if self.is_bound:
self.fields['first_name'].initial = self.instance.user.first_name
self.fields['last_name'].initial = self.instance.user.last_name
def save(self):
first_name = self.cleaned_data.pop('first_name', None)
last_name = self.cleaned_data.pop('last_name', None)
profile = super(UserProfileForm, self).save()
user = profile.user
user.first_name = first_name
user.last_name = last_name
user.save()
return profile
| <commit_before>from django.forms import ModelForm
from django.forms.fields import CharField
from models import UserProfile
class UserProfileForm(ModelForm):
first_name = CharField(label='First name', required=False)
last_name = CharField(label='Last name', required=False)
class Meta:
model = UserProfile
# Don't allow users edit someone else's user page,
# or to whitelist themselves
exclude = ('user', 'whitelisted',)
def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
if self.instance:
self.fields['first_name'].initial = self.instance.user.first_name
self.fields['last_name'].initial = self.instance.user.last_name
def save(self):
first_name = self.cleaned_data.pop('first_name', None)
last_name = self.cleaned_data.pop('last_name', None)
profile = super(UserProfileForm, self).save()
user = profile.user
user.first_name = first_name
user.last_name = last_name
user.save()
return profile<commit_msg>Fix profile creation. (Need tests badly).<commit_after>from django.forms import ModelForm
from django.forms.fields import CharField
from models import UserProfile
class UserProfileForm(ModelForm):
first_name = CharField(label='First name', required=False)
last_name = CharField(label='Last name', required=False)
class Meta:
model = UserProfile
# Don't allow users edit someone else's user page,
# or to whitelist themselves
exclude = ('user', 'whitelisted',)
def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
if self.is_bound:
self.fields['first_name'].initial = self.instance.user.first_name
self.fields['last_name'].initial = self.instance.user.last_name
def save(self):
first_name = self.cleaned_data.pop('first_name', None)
last_name = self.cleaned_data.pop('last_name', None)
profile = super(UserProfileForm, self).save()
user = profile.user
user.first_name = first_name
user.last_name = last_name
user.save()
return profile
|
0874b3e5d5316c53d1d941e4e337bec45469bf6d | core/hybra.py | core/hybra.py | import data_loader
import descriptives
import network as module_network
import timeline as module_timeline
import wordclouds as module_wordclouds
__sources = dir( data_loader )
__sources = filter( lambda x: x.startswith('load_') , __sources )
__sources = map( lambda x: x[5:], __sources )
def data_sources():
return __sources
def data( type, **kwargs ):
if type not in __sources:
raise NameError('Unknown media type')
load = getattr( data_loader, 'load_' + type )
return load( **kwargs )
def describe( data ):
descriptives.describe( data )
## igrap plotting utilities
def timeline( data ):
module_timeline.create_timeline( data )
def network( data ):
module_network.create_network( data )
def wordcloud( data ):
module_wordclouds.create_wordcloud( data )
| import data_loader
import re
import descriptives
import network as module_network
import timeline as module_timeline
import wordclouds as module_wordclouds
__sources = dir( data_loader )
__sources = filter( lambda x: x.startswith('load_') , __sources )
__sources = map( lambda x: x[5:], __sources )
def data_sources():
return __sources
def data( type, **kwargs ):
if type not in __sources:
raise NameError('Unknown media type')
load = getattr( data_loader, 'load_' + type )
return load( **kwargs )
def filter_from_text( data, text = [], substrings = True ):
filtered_data = []
for d in data:
if substrings:
if all( string in d['text_content'] for string in text ):
filtered_data.append( d )
else:
words = re.findall(r'\w+', d['text_content'], re.UNICODE)
if all( string in words for string in text ):
filtered_data.append( d )
return filtered_data
def describe( data ):
descriptives.describe( data )
## igrap plotting utilities
def timeline( data ):
module_timeline.create_timeline( data )
def network( data ):
module_network.create_network( data )
def wordcloud( data ):
module_wordclouds.create_wordcloud( data )
| Add method for filtering from text | Add method for filtering from text
| Python | mit | HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core | import data_loader
import descriptives
import network as module_network
import timeline as module_timeline
import wordclouds as module_wordclouds
__sources = dir( data_loader )
__sources = filter( lambda x: x.startswith('load_') , __sources )
__sources = map( lambda x: x[5:], __sources )
def data_sources():
return __sources
def data( type, **kwargs ):
if type not in __sources:
raise NameError('Unknown media type')
load = getattr( data_loader, 'load_' + type )
return load( **kwargs )
def describe( data ):
descriptives.describe( data )
## igrap plotting utilities
def timeline( data ):
module_timeline.create_timeline( data )
def network( data ):
module_network.create_network( data )
def wordcloud( data ):
module_wordclouds.create_wordcloud( data )
Add method for filtering from text | import data_loader
import re
import descriptives
import network as module_network
import timeline as module_timeline
import wordclouds as module_wordclouds
__sources = dir( data_loader )
__sources = filter( lambda x: x.startswith('load_') , __sources )
__sources = map( lambda x: x[5:], __sources )
def data_sources():
return __sources
def data( type, **kwargs ):
if type not in __sources:
raise NameError('Unknown media type')
load = getattr( data_loader, 'load_' + type )
return load( **kwargs )
def filter_from_text( data, text = [], substrings = True ):
filtered_data = []
for d in data:
if substrings:
if all( string in d['text_content'] for string in text ):
filtered_data.append( d )
else:
words = re.findall(r'\w+', d['text_content'], re.UNICODE)
if all( string in words for string in text ):
filtered_data.append( d )
return filtered_data
def describe( data ):
descriptives.describe( data )
## igrap plotting utilities
def timeline( data ):
module_timeline.create_timeline( data )
def network( data ):
module_network.create_network( data )
def wordcloud( data ):
module_wordclouds.create_wordcloud( data )
| <commit_before>import data_loader
import descriptives
import network as module_network
import timeline as module_timeline
import wordclouds as module_wordclouds
__sources = dir( data_loader )
__sources = filter( lambda x: x.startswith('load_') , __sources )
__sources = map( lambda x: x[5:], __sources )
def data_sources():
return __sources
def data( type, **kwargs ):
if type not in __sources:
raise NameError('Unknown media type')
load = getattr( data_loader, 'load_' + type )
return load( **kwargs )
def describe( data ):
descriptives.describe( data )
## igrap plotting utilities
def timeline( data ):
module_timeline.create_timeline( data )
def network( data ):
module_network.create_network( data )
def wordcloud( data ):
module_wordclouds.create_wordcloud( data )
<commit_msg>Add method for filtering from text<commit_after> | import data_loader
import re
import descriptives
import network as module_network
import timeline as module_timeline
import wordclouds as module_wordclouds
__sources = dir( data_loader )
__sources = filter( lambda x: x.startswith('load_') , __sources )
__sources = map( lambda x: x[5:], __sources )
def data_sources():
return __sources
def data( type, **kwargs ):
if type not in __sources:
raise NameError('Unknown media type')
load = getattr( data_loader, 'load_' + type )
return load( **kwargs )
def filter_from_text( data, text = [], substrings = True ):
filtered_data = []
for d in data:
if substrings:
if all( string in d['text_content'] for string in text ):
filtered_data.append( d )
else:
words = re.findall(r'\w+', d['text_content'], re.UNICODE)
if all( string in words for string in text ):
filtered_data.append( d )
return filtered_data
def describe( data ):
descriptives.describe( data )
## igrap plotting utilities
def timeline( data ):
module_timeline.create_timeline( data )
def network( data ):
module_network.create_network( data )
def wordcloud( data ):
module_wordclouds.create_wordcloud( data )
| import data_loader
import descriptives
import network as module_network
import timeline as module_timeline
import wordclouds as module_wordclouds
__sources = dir( data_loader )
__sources = filter( lambda x: x.startswith('load_') , __sources )
__sources = map( lambda x: x[5:], __sources )
def data_sources():
return __sources
def data( type, **kwargs ):
if type not in __sources:
raise NameError('Unknown media type')
load = getattr( data_loader, 'load_' + type )
return load( **kwargs )
def describe( data ):
descriptives.describe( data )
## igrap plotting utilities
def timeline( data ):
module_timeline.create_timeline( data )
def network( data ):
module_network.create_network( data )
def wordcloud( data ):
module_wordclouds.create_wordcloud( data )
Add method for filtering from textimport data_loader
import re
import descriptives
import network as module_network
import timeline as module_timeline
import wordclouds as module_wordclouds
__sources = dir( data_loader )
__sources = filter( lambda x: x.startswith('load_') , __sources )
__sources = map( lambda x: x[5:], __sources )
def data_sources():
return __sources
def data( type, **kwargs ):
if type not in __sources:
raise NameError('Unknown media type')
load = getattr( data_loader, 'load_' + type )
return load( **kwargs )
def filter_from_text( data, text = [], substrings = True ):
filtered_data = []
for d in data:
if substrings:
if all( string in d['text_content'] for string in text ):
filtered_data.append( d )
else:
words = re.findall(r'\w+', d['text_content'], re.UNICODE)
if all( string in words for string in text ):
filtered_data.append( d )
return filtered_data
def describe( data ):
descriptives.describe( data )
## igrap plotting utilities
def timeline( data ):
module_timeline.create_timeline( data )
def network( data ):
module_network.create_network( data )
def wordcloud( data ):
module_wordclouds.create_wordcloud( data )
| <commit_before>import data_loader
import descriptives
import network as module_network
import timeline as module_timeline
import wordclouds as module_wordclouds
__sources = dir( data_loader )
__sources = filter( lambda x: x.startswith('load_') , __sources )
__sources = map( lambda x: x[5:], __sources )
def data_sources():
return __sources
def data( type, **kwargs ):
if type not in __sources:
raise NameError('Unknown media type')
load = getattr( data_loader, 'load_' + type )
return load( **kwargs )
def describe( data ):
descriptives.describe( data )
## igrap plotting utilities
def timeline( data ):
module_timeline.create_timeline( data )
def network( data ):
module_network.create_network( data )
def wordcloud( data ):
module_wordclouds.create_wordcloud( data )
<commit_msg>Add method for filtering from text<commit_after>import data_loader
import re
import descriptives
import network as module_network
import timeline as module_timeline
import wordclouds as module_wordclouds
__sources = dir( data_loader )
__sources = filter( lambda x: x.startswith('load_') , __sources )
__sources = map( lambda x: x[5:], __sources )
def data_sources():
return __sources
def data( type, **kwargs ):
if type not in __sources:
raise NameError('Unknown media type')
load = getattr( data_loader, 'load_' + type )
return load( **kwargs )
def filter_from_text( data, text = [], substrings = True ):
filtered_data = []
for d in data:
if substrings:
if all( string in d['text_content'] for string in text ):
filtered_data.append( d )
else:
words = re.findall(r'\w+', d['text_content'], re.UNICODE)
if all( string in words for string in text ):
filtered_data.append( d )
return filtered_data
def describe( data ):
descriptives.describe( data )
## igrap plotting utilities
def timeline( data ):
module_timeline.create_timeline( data )
def network( data ):
module_network.create_network( data )
def wordcloud( data ):
module_wordclouds.create_wordcloud( data )
|
28ee229284459402d73f41e756dc95fe99f0227b | pybot/resources/urls.py | pybot/resources/urls.py | FACEBOOK_MESSAGES_POST_URL = "https://graph.facebook.com/v2.6/me/messages" | FACEBOOK_MESSAGES_POST_URL = "https://graph.facebook.com/v2.6/" | Update URL for generic graph api url | Update URL for generic graph api url
| Python | mit | ben-cunningham/python-messenger-bot,ben-cunningham/pybot | FACEBOOK_MESSAGES_POST_URL = "https://graph.facebook.com/v2.6/me/messages"Update URL for generic graph api url | FACEBOOK_MESSAGES_POST_URL = "https://graph.facebook.com/v2.6/" | <commit_before>FACEBOOK_MESSAGES_POST_URL = "https://graph.facebook.com/v2.6/me/messages"<commit_msg>Update URL for generic graph api url<commit_after> | FACEBOOK_MESSAGES_POST_URL = "https://graph.facebook.com/v2.6/" | FACEBOOK_MESSAGES_POST_URL = "https://graph.facebook.com/v2.6/me/messages"Update URL for generic graph api urlFACEBOOK_MESSAGES_POST_URL = "https://graph.facebook.com/v2.6/" | <commit_before>FACEBOOK_MESSAGES_POST_URL = "https://graph.facebook.com/v2.6/me/messages"<commit_msg>Update URL for generic graph api url<commit_after>FACEBOOK_MESSAGES_POST_URL = "https://graph.facebook.com/v2.6/" |
ed45016c7319d2df1f894ec17971d0d1c4d8abe1 | museum_site/base.py | museum_site/base.py | from django.db import models
class BaseModel(models.Model):
model_name = None
#title
#description
#preview
#table_fields = []
def admin_url(self):
name = self.model_name.replace("-", "_").lower()
return "/admin/museum_site/{}/{}/change/".format(name, self.id)
def url(self):
return "URL!"
def preview_url(self):
return "Preview url"
def as_block(self):
return "AB"
def as_detailed_block(self):
return "AB"
def as_list_block(self):
return "X"
def as_gallery_block(self):
return "X"
def table_header(self):
row = ""
for f in self.table_fields:
row += "<th>{}</th>".format(f)
return "<tr>" + row + "</tr>"
def scrub(self):
return "X"
class Meta:
abstract = True
| from django.db import models
from django.utils.safestring import mark_safe
class BaseModel(models.Model):
model_name = None
#title
#description
#preview
#table_fields = []
def admin_url(self):
name = self.model_name.replace("-", "_").lower()
return "/admin/museum_site/{}/{}/change/".format(name, self.id)
def url(self):
return "URL!"
def preview_url(self):
return "Preview url"
def as_block(self, view="detailed", *args, **kwargs):
return getattr(self, "as_{}_block".format(view))(*args, **kwargs)
def as_detailed_block(self, *args, **kwargs):
raise NotImplementedError('Subclasses must implement "as_detailed_block" method.')
def as_list_block(self, *args, **kwargs):
raise NotImplementedError('Subclasses must implement "as_list_block" this method.')
def as_gallery_block(self, *args, **kwargs):
raise NotImplementedError('Subclasses must implement "as_gallery_block" method.')
@mark_safe
def table_header(self, *args, **kwargs):
row = ""
for f in self.table_fields:
row += "<th>{}</th>".format(f)
return "<tr>" + row + "</tr>"
def scrub(self):
raise NotImplementedError('Subclasses must implement "scrub" method.')
class Meta:
abstract = True
| Add specific error messages for mandatory subclass methods | Add specific error messages for mandatory subclass methods
| Python | mit | DrDos0016/z2,DrDos0016/z2,DrDos0016/z2 | from django.db import models
class BaseModel(models.Model):
model_name = None
#title
#description
#preview
#table_fields = []
def admin_url(self):
name = self.model_name.replace("-", "_").lower()
return "/admin/museum_site/{}/{}/change/".format(name, self.id)
def url(self):
return "URL!"
def preview_url(self):
return "Preview url"
def as_block(self):
return "AB"
def as_detailed_block(self):
return "AB"
def as_list_block(self):
return "X"
def as_gallery_block(self):
return "X"
def table_header(self):
row = ""
for f in self.table_fields:
row += "<th>{}</th>".format(f)
return "<tr>" + row + "</tr>"
def scrub(self):
return "X"
class Meta:
abstract = True
Add specific error messages for mandatory subclass methods | from django.db import models
from django.utils.safestring import mark_safe
class BaseModel(models.Model):
model_name = None
#title
#description
#preview
#table_fields = []
def admin_url(self):
name = self.model_name.replace("-", "_").lower()
return "/admin/museum_site/{}/{}/change/".format(name, self.id)
def url(self):
return "URL!"
def preview_url(self):
return "Preview url"
def as_block(self, view="detailed", *args, **kwargs):
return getattr(self, "as_{}_block".format(view))(*args, **kwargs)
def as_detailed_block(self, *args, **kwargs):
raise NotImplementedError('Subclasses must implement "as_detailed_block" method.')
def as_list_block(self, *args, **kwargs):
raise NotImplementedError('Subclasses must implement "as_list_block" this method.')
def as_gallery_block(self, *args, **kwargs):
raise NotImplementedError('Subclasses must implement "as_gallery_block" method.')
@mark_safe
def table_header(self, *args, **kwargs):
row = ""
for f in self.table_fields:
row += "<th>{}</th>".format(f)
return "<tr>" + row + "</tr>"
def scrub(self):
raise NotImplementedError('Subclasses must implement "scrub" method.')
class Meta:
abstract = True
| <commit_before>from django.db import models
class BaseModel(models.Model):
model_name = None
#title
#description
#preview
#table_fields = []
def admin_url(self):
name = self.model_name.replace("-", "_").lower()
return "/admin/museum_site/{}/{}/change/".format(name, self.id)
def url(self):
return "URL!"
def preview_url(self):
return "Preview url"
def as_block(self):
return "AB"
def as_detailed_block(self):
return "AB"
def as_list_block(self):
return "X"
def as_gallery_block(self):
return "X"
def table_header(self):
row = ""
for f in self.table_fields:
row += "<th>{}</th>".format(f)
return "<tr>" + row + "</tr>"
def scrub(self):
return "X"
class Meta:
abstract = True
<commit_msg>Add specific error messages for mandatory subclass methods<commit_after> | from django.db import models
from django.utils.safestring import mark_safe
class BaseModel(models.Model):
model_name = None
#title
#description
#preview
#table_fields = []
def admin_url(self):
name = self.model_name.replace("-", "_").lower()
return "/admin/museum_site/{}/{}/change/".format(name, self.id)
def url(self):
return "URL!"
def preview_url(self):
return "Preview url"
def as_block(self, view="detailed", *args, **kwargs):
return getattr(self, "as_{}_block".format(view))(*args, **kwargs)
def as_detailed_block(self, *args, **kwargs):
raise NotImplementedError('Subclasses must implement "as_detailed_block" method.')
def as_list_block(self, *args, **kwargs):
raise NotImplementedError('Subclasses must implement "as_list_block" this method.')
def as_gallery_block(self, *args, **kwargs):
raise NotImplementedError('Subclasses must implement "as_gallery_block" method.')
@mark_safe
def table_header(self, *args, **kwargs):
row = ""
for f in self.table_fields:
row += "<th>{}</th>".format(f)
return "<tr>" + row + "</tr>"
def scrub(self):
raise NotImplementedError('Subclasses must implement "scrub" method.')
class Meta:
abstract = True
| from django.db import models
class BaseModel(models.Model):
model_name = None
#title
#description
#preview
#table_fields = []
def admin_url(self):
name = self.model_name.replace("-", "_").lower()
return "/admin/museum_site/{}/{}/change/".format(name, self.id)
def url(self):
return "URL!"
def preview_url(self):
return "Preview url"
def as_block(self):
return "AB"
def as_detailed_block(self):
return "AB"
def as_list_block(self):
return "X"
def as_gallery_block(self):
return "X"
def table_header(self):
row = ""
for f in self.table_fields:
row += "<th>{}</th>".format(f)
return "<tr>" + row + "</tr>"
def scrub(self):
return "X"
class Meta:
abstract = True
Add specific error messages for mandatory subclass methodsfrom django.db import models
from django.utils.safestring import mark_safe
class BaseModel(models.Model):
model_name = None
#title
#description
#preview
#table_fields = []
def admin_url(self):
name = self.model_name.replace("-", "_").lower()
return "/admin/museum_site/{}/{}/change/".format(name, self.id)
def url(self):
return "URL!"
def preview_url(self):
return "Preview url"
def as_block(self, view="detailed", *args, **kwargs):
return getattr(self, "as_{}_block".format(view))(*args, **kwargs)
def as_detailed_block(self, *args, **kwargs):
raise NotImplementedError('Subclasses must implement "as_detailed_block" method.')
def as_list_block(self, *args, **kwargs):
raise NotImplementedError('Subclasses must implement "as_list_block" this method.')
def as_gallery_block(self, *args, **kwargs):
raise NotImplementedError('Subclasses must implement "as_gallery_block" method.')
@mark_safe
def table_header(self, *args, **kwargs):
row = ""
for f in self.table_fields:
row += "<th>{}</th>".format(f)
return "<tr>" + row + "</tr>"
def scrub(self):
raise NotImplementedError('Subclasses must implement "scrub" method.')
class Meta:
abstract = True
| <commit_before>from django.db import models
class BaseModel(models.Model):
model_name = None
#title
#description
#preview
#table_fields = []
def admin_url(self):
name = self.model_name.replace("-", "_").lower()
return "/admin/museum_site/{}/{}/change/".format(name, self.id)
def url(self):
return "URL!"
def preview_url(self):
return "Preview url"
def as_block(self):
return "AB"
def as_detailed_block(self):
return "AB"
def as_list_block(self):
return "X"
def as_gallery_block(self):
return "X"
def table_header(self):
row = ""
for f in self.table_fields:
row += "<th>{}</th>".format(f)
return "<tr>" + row + "</tr>"
def scrub(self):
return "X"
class Meta:
abstract = True
<commit_msg>Add specific error messages for mandatory subclass methods<commit_after>from django.db import models
from django.utils.safestring import mark_safe
class BaseModel(models.Model):
model_name = None
#title
#description
#preview
#table_fields = []
def admin_url(self):
name = self.model_name.replace("-", "_").lower()
return "/admin/museum_site/{}/{}/change/".format(name, self.id)
def url(self):
return "URL!"
def preview_url(self):
return "Preview url"
def as_block(self, view="detailed", *args, **kwargs):
return getattr(self, "as_{}_block".format(view))(*args, **kwargs)
def as_detailed_block(self, *args, **kwargs):
raise NotImplementedError('Subclasses must implement "as_detailed_block" method.')
def as_list_block(self, *args, **kwargs):
raise NotImplementedError('Subclasses must implement "as_list_block" this method.')
def as_gallery_block(self, *args, **kwargs):
raise NotImplementedError('Subclasses must implement "as_gallery_block" method.')
@mark_safe
def table_header(self, *args, **kwargs):
row = ""
for f in self.table_fields:
row += "<th>{}</th>".format(f)
return "<tr>" + row + "</tr>"
def scrub(self):
raise NotImplementedError('Subclasses must implement "scrub" method.')
class Meta:
abstract = True
|
6c19a46f4ef146a67c43ca46c3e71dd2a05358fc | api/caching/tasks.py | api/caching/tasks.py | import urlparse
import celery
import requests
from celery.utils.log import get_task_logger
from django.conf import settings
from framework.tasks import app as celery_app
logger = get_task_logger(__name__)
class VarnishTask(celery.Task):
abstract = True
max_retries = 5
def get_varnish_servers():
# TODO: this should get the varnish servers from HAProxy or a setting
return settings.VARNISH_SERVERS
@celery_app.task(base=VarnishTask, name='caching_tasks.ban_url')
# @logged('ban_url')
def ban_url(url):
if settings.ENABLE_VARNISH:
parsed_url = urlparse.urlparse(url)
for host in get_varnish_servers():
varnish_parsed_url = urlparse.urlparse(host)
ban_url = '{scheme}://{netloc}{path}.*'.format(
scheme=varnish_parsed_url.scheme,
netloc=varnish_parsed_url.netloc,
path=parsed_url.path
)
response = requests.request('BAN', ban_url, headers=dict(
Host=parsed_url.hostname
))
if not response.ok:
logger.error('Banning {} failed with message {}'.format(
url,
response.text
))
| import urlparse
import celery
import requests
from celery.utils.log import get_task_logger
from django.conf import settings
from framework.tasks import app as celery_app
logger = get_task_logger(__name__)
class VarnishTask(celery.Task):
abstract = True
max_retries = 5
def get_varnish_servers():
# TODO: this should get the varnish servers from HAProxy or a setting
return settings.VARNISH_SERVERS
@celery_app.task(base=VarnishTask, name='caching_tasks.ban_url')
def ban_url(url):
if settings.ENABLE_VARNISH:
parsed_url = urlparse.urlparse(url)
for host in get_varnish_servers():
varnish_parsed_url = urlparse.urlparse(host)
ban_url = '{scheme}://{netloc}{path}.*'.format(
scheme=varnish_parsed_url.scheme,
netloc=varnish_parsed_url.netloc,
path=parsed_url.path
)
response = requests.request('BAN', ban_url, headers=dict(
Host=parsed_url.hostname
))
if not response.ok:
logger.error('Banning {} failed with message {}'.format(
url,
response.text
))
| Remove commented out logged decorator | Remove commented out logged decorator
| Python | apache-2.0 | adlius/osf.io,billyhunt/osf.io,baylee-d/osf.io,GageGaskins/osf.io,caneruguz/osf.io,doublebits/osf.io,mluke93/osf.io,felliott/osf.io,asanfilippo7/osf.io,icereval/osf.io,billyhunt/osf.io,emetsger/osf.io,saradbowman/osf.io,doublebits/osf.io,mluke93/osf.io,zamattiac/osf.io,chennan47/osf.io,doublebits/osf.io,acshi/osf.io,cslzchen/osf.io,TomHeatwole/osf.io,adlius/osf.io,kwierman/osf.io,caseyrollins/osf.io,wearpants/osf.io,caseyrollins/osf.io,alexschiller/osf.io,pattisdr/osf.io,acshi/osf.io,hmoco/osf.io,felliott/osf.io,rdhyee/osf.io,chennan47/osf.io,monikagrabowska/osf.io,kwierman/osf.io,amyshi188/osf.io,zachjanicki/osf.io,billyhunt/osf.io,zamattiac/osf.io,Nesiehr/osf.io,sloria/osf.io,HalcyonChimera/osf.io,asanfilippo7/osf.io,mattclark/osf.io,mluo613/osf.io,mluke93/osf.io,GageGaskins/osf.io,leb2dg/osf.io,mfraezz/osf.io,CenterForOpenScience/osf.io,abought/osf.io,crcresearch/osf.io,crcresearch/osf.io,CenterForOpenScience/osf.io,monikagrabowska/osf.io,hmoco/osf.io,samchrisinger/osf.io,TomHeatwole/osf.io,RomanZWang/osf.io,HalcyonChimera/osf.io,jnayak1/osf.io,TomBaxter/osf.io,saradbowman/osf.io,rdhyee/osf.io,icereval/osf.io,TomHeatwole/osf.io,cslzchen/osf.io,DanielSBrown/osf.io,monikagrabowska/osf.io,acshi/osf.io,emetsger/osf.io,HalcyonChimera/osf.io,aaxelb/osf.io,chennan47/osf.io,abought/osf.io,icereval/osf.io,kwierman/osf.io,adlius/osf.io,mattclark/osf.io,brandonPurvis/osf.io,doublebits/osf.io,leb2dg/osf.io,billyhunt/osf.io,GageGaskins/osf.io,acshi/osf.io,erinspace/osf.io,emetsger/osf.io,Johnetordoff/osf.io,zachjanicki/osf.io,caseyrollins/osf.io,alexschiller/osf.io,hmoco/osf.io,KAsante95/osf.io,GageGaskins/osf.io,alexschiller/osf.io,DanielSBrown/osf.io,sloria/osf.io,aaxelb/osf.io,wearpants/osf.io,chrisseto/osf.io,TomBaxter/osf.io,RomanZWang/osf.io,erinspace/osf.io,monikagrabowska/osf.io,brianjgeiger/osf.io,laurenrevere/osf.io,brianjgeiger/osf.io,caneruguz/osf.io,brianjgeiger/osf.io,aaxelb/osf.io,cslzchen/osf.io,amyshi188/osf.io,mluo613/osf.io,SSJohns/osf.io,cwisecarver/osf.io,SSJohns/osf.io,HalcyonChimera/osf.io,billyhunt/osf.io,cwisecarver/osf.io,amyshi188/osf.io,RomanZWang/osf.io,chrisseto/osf.io,caneruguz/osf.io,felliott/osf.io,brandonPurvis/osf.io,mluo613/osf.io,erinspace/osf.io,chrisseto/osf.io,Nesiehr/osf.io,pattisdr/osf.io,rdhyee/osf.io,pattisdr/osf.io,leb2dg/osf.io,kch8qx/osf.io,DanielSBrown/osf.io,samchrisinger/osf.io,acshi/osf.io,laurenrevere/osf.io,amyshi188/osf.io,kch8qx/osf.io,Johnetordoff/osf.io,mluo613/osf.io,kch8qx/osf.io,SSJohns/osf.io,TomHeatwole/osf.io,brianjgeiger/osf.io,mfraezz/osf.io,samchrisinger/osf.io,GageGaskins/osf.io,sloria/osf.io,samchrisinger/osf.io,doublebits/osf.io,abought/osf.io,jnayak1/osf.io,brandonPurvis/osf.io,SSJohns/osf.io,KAsante95/osf.io,baylee-d/osf.io,wearpants/osf.io,zamattiac/osf.io,KAsante95/osf.io,alexschiller/osf.io,cwisecarver/osf.io,aaxelb/osf.io,zachjanicki/osf.io,kch8qx/osf.io,emetsger/osf.io,caneruguz/osf.io,RomanZWang/osf.io,KAsante95/osf.io,adlius/osf.io,zachjanicki/osf.io,cslzchen/osf.io,cwisecarver/osf.io,CenterForOpenScience/osf.io,mfraezz/osf.io,mluke93/osf.io,Johnetordoff/osf.io,mattclark/osf.io,laurenrevere/osf.io,leb2dg/osf.io,KAsante95/osf.io,mfraezz/osf.io,rdhyee/osf.io,brandonPurvis/osf.io,brandonPurvis/osf.io,TomBaxter/osf.io,Nesiehr/osf.io,binoculars/osf.io,mluo613/osf.io,zamattiac/osf.io,binoculars/osf.io,wearpants/osf.io,hmoco/osf.io,asanfilippo7/osf.io,kch8qx/osf.io,RomanZWang/osf.io,felliott/osf.io,jnayak1/osf.io,CenterForOpenScience/osf.io,Nesiehr/osf.io,crcresearch/osf.io,alexschiller/osf.io,jnayak1/osf.io,binoculars/osf.io,kwierman/osf.io,monikagrabowska/osf.io,Johnetordoff/osf.io,asanfilippo7/osf.io,chrisseto/osf.io,DanielSBrown/osf.io,baylee-d/osf.io,abought/osf.io | import urlparse
import celery
import requests
from celery.utils.log import get_task_logger
from django.conf import settings
from framework.tasks import app as celery_app
logger = get_task_logger(__name__)
class VarnishTask(celery.Task):
abstract = True
max_retries = 5
def get_varnish_servers():
# TODO: this should get the varnish servers from HAProxy or a setting
return settings.VARNISH_SERVERS
@celery_app.task(base=VarnishTask, name='caching_tasks.ban_url')
# @logged('ban_url')
def ban_url(url):
if settings.ENABLE_VARNISH:
parsed_url = urlparse.urlparse(url)
for host in get_varnish_servers():
varnish_parsed_url = urlparse.urlparse(host)
ban_url = '{scheme}://{netloc}{path}.*'.format(
scheme=varnish_parsed_url.scheme,
netloc=varnish_parsed_url.netloc,
path=parsed_url.path
)
response = requests.request('BAN', ban_url, headers=dict(
Host=parsed_url.hostname
))
if not response.ok:
logger.error('Banning {} failed with message {}'.format(
url,
response.text
))
Remove commented out logged decorator | import urlparse
import celery
import requests
from celery.utils.log import get_task_logger
from django.conf import settings
from framework.tasks import app as celery_app
logger = get_task_logger(__name__)
class VarnishTask(celery.Task):
abstract = True
max_retries = 5
def get_varnish_servers():
# TODO: this should get the varnish servers from HAProxy or a setting
return settings.VARNISH_SERVERS
@celery_app.task(base=VarnishTask, name='caching_tasks.ban_url')
def ban_url(url):
if settings.ENABLE_VARNISH:
parsed_url = urlparse.urlparse(url)
for host in get_varnish_servers():
varnish_parsed_url = urlparse.urlparse(host)
ban_url = '{scheme}://{netloc}{path}.*'.format(
scheme=varnish_parsed_url.scheme,
netloc=varnish_parsed_url.netloc,
path=parsed_url.path
)
response = requests.request('BAN', ban_url, headers=dict(
Host=parsed_url.hostname
))
if not response.ok:
logger.error('Banning {} failed with message {}'.format(
url,
response.text
))
| <commit_before>import urlparse
import celery
import requests
from celery.utils.log import get_task_logger
from django.conf import settings
from framework.tasks import app as celery_app
logger = get_task_logger(__name__)
class VarnishTask(celery.Task):
abstract = True
max_retries = 5
def get_varnish_servers():
# TODO: this should get the varnish servers from HAProxy or a setting
return settings.VARNISH_SERVERS
@celery_app.task(base=VarnishTask, name='caching_tasks.ban_url')
# @logged('ban_url')
def ban_url(url):
if settings.ENABLE_VARNISH:
parsed_url = urlparse.urlparse(url)
for host in get_varnish_servers():
varnish_parsed_url = urlparse.urlparse(host)
ban_url = '{scheme}://{netloc}{path}.*'.format(
scheme=varnish_parsed_url.scheme,
netloc=varnish_parsed_url.netloc,
path=parsed_url.path
)
response = requests.request('BAN', ban_url, headers=dict(
Host=parsed_url.hostname
))
if not response.ok:
logger.error('Banning {} failed with message {}'.format(
url,
response.text
))
<commit_msg>Remove commented out logged decorator<commit_after> | import urlparse
import celery
import requests
from celery.utils.log import get_task_logger
from django.conf import settings
from framework.tasks import app as celery_app
logger = get_task_logger(__name__)
class VarnishTask(celery.Task):
abstract = True
max_retries = 5
def get_varnish_servers():
# TODO: this should get the varnish servers from HAProxy or a setting
return settings.VARNISH_SERVERS
@celery_app.task(base=VarnishTask, name='caching_tasks.ban_url')
def ban_url(url):
if settings.ENABLE_VARNISH:
parsed_url = urlparse.urlparse(url)
for host in get_varnish_servers():
varnish_parsed_url = urlparse.urlparse(host)
ban_url = '{scheme}://{netloc}{path}.*'.format(
scheme=varnish_parsed_url.scheme,
netloc=varnish_parsed_url.netloc,
path=parsed_url.path
)
response = requests.request('BAN', ban_url, headers=dict(
Host=parsed_url.hostname
))
if not response.ok:
logger.error('Banning {} failed with message {}'.format(
url,
response.text
))
| import urlparse
import celery
import requests
from celery.utils.log import get_task_logger
from django.conf import settings
from framework.tasks import app as celery_app
logger = get_task_logger(__name__)
class VarnishTask(celery.Task):
abstract = True
max_retries = 5
def get_varnish_servers():
# TODO: this should get the varnish servers from HAProxy or a setting
return settings.VARNISH_SERVERS
@celery_app.task(base=VarnishTask, name='caching_tasks.ban_url')
# @logged('ban_url')
def ban_url(url):
if settings.ENABLE_VARNISH:
parsed_url = urlparse.urlparse(url)
for host in get_varnish_servers():
varnish_parsed_url = urlparse.urlparse(host)
ban_url = '{scheme}://{netloc}{path}.*'.format(
scheme=varnish_parsed_url.scheme,
netloc=varnish_parsed_url.netloc,
path=parsed_url.path
)
response = requests.request('BAN', ban_url, headers=dict(
Host=parsed_url.hostname
))
if not response.ok:
logger.error('Banning {} failed with message {}'.format(
url,
response.text
))
Remove commented out logged decoratorimport urlparse
import celery
import requests
from celery.utils.log import get_task_logger
from django.conf import settings
from framework.tasks import app as celery_app
logger = get_task_logger(__name__)
class VarnishTask(celery.Task):
abstract = True
max_retries = 5
def get_varnish_servers():
# TODO: this should get the varnish servers from HAProxy or a setting
return settings.VARNISH_SERVERS
@celery_app.task(base=VarnishTask, name='caching_tasks.ban_url')
def ban_url(url):
if settings.ENABLE_VARNISH:
parsed_url = urlparse.urlparse(url)
for host in get_varnish_servers():
varnish_parsed_url = urlparse.urlparse(host)
ban_url = '{scheme}://{netloc}{path}.*'.format(
scheme=varnish_parsed_url.scheme,
netloc=varnish_parsed_url.netloc,
path=parsed_url.path
)
response = requests.request('BAN', ban_url, headers=dict(
Host=parsed_url.hostname
))
if not response.ok:
logger.error('Banning {} failed with message {}'.format(
url,
response.text
))
| <commit_before>import urlparse
import celery
import requests
from celery.utils.log import get_task_logger
from django.conf import settings
from framework.tasks import app as celery_app
logger = get_task_logger(__name__)
class VarnishTask(celery.Task):
abstract = True
max_retries = 5
def get_varnish_servers():
# TODO: this should get the varnish servers from HAProxy or a setting
return settings.VARNISH_SERVERS
@celery_app.task(base=VarnishTask, name='caching_tasks.ban_url')
# @logged('ban_url')
def ban_url(url):
if settings.ENABLE_VARNISH:
parsed_url = urlparse.urlparse(url)
for host in get_varnish_servers():
varnish_parsed_url = urlparse.urlparse(host)
ban_url = '{scheme}://{netloc}{path}.*'.format(
scheme=varnish_parsed_url.scheme,
netloc=varnish_parsed_url.netloc,
path=parsed_url.path
)
response = requests.request('BAN', ban_url, headers=dict(
Host=parsed_url.hostname
))
if not response.ok:
logger.error('Banning {} failed with message {}'.format(
url,
response.text
))
<commit_msg>Remove commented out logged decorator<commit_after>import urlparse
import celery
import requests
from celery.utils.log import get_task_logger
from django.conf import settings
from framework.tasks import app as celery_app
logger = get_task_logger(__name__)
class VarnishTask(celery.Task):
abstract = True
max_retries = 5
def get_varnish_servers():
# TODO: this should get the varnish servers from HAProxy or a setting
return settings.VARNISH_SERVERS
@celery_app.task(base=VarnishTask, name='caching_tasks.ban_url')
def ban_url(url):
if settings.ENABLE_VARNISH:
parsed_url = urlparse.urlparse(url)
for host in get_varnish_servers():
varnish_parsed_url = urlparse.urlparse(host)
ban_url = '{scheme}://{netloc}{path}.*'.format(
scheme=varnish_parsed_url.scheme,
netloc=varnish_parsed_url.netloc,
path=parsed_url.path
)
response = requests.request('BAN', ban_url, headers=dict(
Host=parsed_url.hostname
))
if not response.ok:
logger.error('Banning {} failed with message {}'.format(
url,
response.text
))
|
0ad53b5dc887ab4b81e3cf83bfb897340880c3a2 | launch_control/models/test_case.py | launch_control/models/test_case.py | """
Module with the TestCase model.
"""
from launch_control.utils.json.pod import PlainOldData
class TestCase(PlainOldData):
"""
TestCase model.
Currently contains just two fields:
- test_case_id (test-case specific ID)
- name (human readable)
"""
__slots__ = ('test_case_id', 'desc')
def __init__(self, test_case_id, desc):
self.test_case_id = test_case_id
self.name = name
| """
Module with the TestCase model.
"""
from launch_control.utils.json.pod import PlainOldData
class TestCase(PlainOldData):
"""
TestCase model.
Currently contains just two fields:
- test_case_id (test-case specific ID)
- name (human readable)
"""
__slots__ = ('test_case_id', 'name')
def __init__(self, test_case_id, desc):
self.test_case_id = test_case_id
self.name = name
| Fix TestCase definition to have a slot 'name' instead of 'desc' | Fix TestCase definition to have a slot 'name' instead of 'desc'
| Python | agpl-3.0 | Linaro/lava-server,Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server,OSSystems/lava-server,OSSystems/lava-server,Linaro/lava-server | """
Module with the TestCase model.
"""
from launch_control.utils.json.pod import PlainOldData
class TestCase(PlainOldData):
"""
TestCase model.
Currently contains just two fields:
- test_case_id (test-case specific ID)
- name (human readable)
"""
__slots__ = ('test_case_id', 'desc')
def __init__(self, test_case_id, desc):
self.test_case_id = test_case_id
self.name = name
Fix TestCase definition to have a slot 'name' instead of 'desc' | """
Module with the TestCase model.
"""
from launch_control.utils.json.pod import PlainOldData
class TestCase(PlainOldData):
"""
TestCase model.
Currently contains just two fields:
- test_case_id (test-case specific ID)
- name (human readable)
"""
__slots__ = ('test_case_id', 'name')
def __init__(self, test_case_id, desc):
self.test_case_id = test_case_id
self.name = name
| <commit_before>"""
Module with the TestCase model.
"""
from launch_control.utils.json.pod import PlainOldData
class TestCase(PlainOldData):
"""
TestCase model.
Currently contains just two fields:
- test_case_id (test-case specific ID)
- name (human readable)
"""
__slots__ = ('test_case_id', 'desc')
def __init__(self, test_case_id, desc):
self.test_case_id = test_case_id
self.name = name
<commit_msg>Fix TestCase definition to have a slot 'name' instead of 'desc'<commit_after> | """
Module with the TestCase model.
"""
from launch_control.utils.json.pod import PlainOldData
class TestCase(PlainOldData):
"""
TestCase model.
Currently contains just two fields:
- test_case_id (test-case specific ID)
- name (human readable)
"""
__slots__ = ('test_case_id', 'name')
def __init__(self, test_case_id, desc):
self.test_case_id = test_case_id
self.name = name
| """
Module with the TestCase model.
"""
from launch_control.utils.json.pod import PlainOldData
class TestCase(PlainOldData):
"""
TestCase model.
Currently contains just two fields:
- test_case_id (test-case specific ID)
- name (human readable)
"""
__slots__ = ('test_case_id', 'desc')
def __init__(self, test_case_id, desc):
self.test_case_id = test_case_id
self.name = name
Fix TestCase definition to have a slot 'name' instead of 'desc'"""
Module with the TestCase model.
"""
from launch_control.utils.json.pod import PlainOldData
class TestCase(PlainOldData):
"""
TestCase model.
Currently contains just two fields:
- test_case_id (test-case specific ID)
- name (human readable)
"""
__slots__ = ('test_case_id', 'name')
def __init__(self, test_case_id, desc):
self.test_case_id = test_case_id
self.name = name
| <commit_before>"""
Module with the TestCase model.
"""
from launch_control.utils.json.pod import PlainOldData
class TestCase(PlainOldData):
"""
TestCase model.
Currently contains just two fields:
- test_case_id (test-case specific ID)
- name (human readable)
"""
__slots__ = ('test_case_id', 'desc')
def __init__(self, test_case_id, desc):
self.test_case_id = test_case_id
self.name = name
<commit_msg>Fix TestCase definition to have a slot 'name' instead of 'desc'<commit_after>"""
Module with the TestCase model.
"""
from launch_control.utils.json.pod import PlainOldData
class TestCase(PlainOldData):
"""
TestCase model.
Currently contains just two fields:
- test_case_id (test-case specific ID)
- name (human readable)
"""
__slots__ = ('test_case_id', 'name')
def __init__(self, test_case_id, desc):
self.test_case_id = test_case_id
self.name = name
|
149c56ba2285d42d319b525c04fea6e4a8ea0ec5 | ldaptor/protocols/ldap/__init__.py | ldaptor/protocols/ldap/__init__.py | # Twisted, the Framework of Your Internet
# Copyright (C) 2001 Matthew W. Lefkowitz
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""LDAP protocol logic"""
__all__ = [
"ldapclient",
"ldaperrors",
"schema",
"ldapfilter",
"ldif",
"ldapsyntax",
"distinguishedname",
"ldapconnector",
]
| # Twisted, the Framework of Your Internet
# Copyright (C) 2001 Matthew W. Lefkowitz
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""LDAP protocol logic"""
| Remove ldaptor.protocols.ldap.__all__, it's unnecessary and had wrong content. | Remove ldaptor.protocols.ldap.__all__, it's unnecessary and had wrong content.
git-svn-id: 554337001ebd49d78cdf0a90d762fa547a80d337@203 373aa48d-36e5-0310-bb30-ae74d9883905
| Python | lgpl-2.1 | antong/ldaptor,antong/ldaptor | # Twisted, the Framework of Your Internet
# Copyright (C) 2001 Matthew W. Lefkowitz
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""LDAP protocol logic"""
__all__ = [
"ldapclient",
"ldaperrors",
"schema",
"ldapfilter",
"ldif",
"ldapsyntax",
"distinguishedname",
"ldapconnector",
]
Remove ldaptor.protocols.ldap.__all__, it's unnecessary and had wrong content.
git-svn-id: 554337001ebd49d78cdf0a90d762fa547a80d337@203 373aa48d-36e5-0310-bb30-ae74d9883905 | # Twisted, the Framework of Your Internet
# Copyright (C) 2001 Matthew W. Lefkowitz
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""LDAP protocol logic"""
| <commit_before># Twisted, the Framework of Your Internet
# Copyright (C) 2001 Matthew W. Lefkowitz
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""LDAP protocol logic"""
__all__ = [
"ldapclient",
"ldaperrors",
"schema",
"ldapfilter",
"ldif",
"ldapsyntax",
"distinguishedname",
"ldapconnector",
]
<commit_msg>Remove ldaptor.protocols.ldap.__all__, it's unnecessary and had wrong content.
git-svn-id: 554337001ebd49d78cdf0a90d762fa547a80d337@203 373aa48d-36e5-0310-bb30-ae74d9883905<commit_after> | # Twisted, the Framework of Your Internet
# Copyright (C) 2001 Matthew W. Lefkowitz
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""LDAP protocol logic"""
| # Twisted, the Framework of Your Internet
# Copyright (C) 2001 Matthew W. Lefkowitz
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""LDAP protocol logic"""
__all__ = [
"ldapclient",
"ldaperrors",
"schema",
"ldapfilter",
"ldif",
"ldapsyntax",
"distinguishedname",
"ldapconnector",
]
Remove ldaptor.protocols.ldap.__all__, it's unnecessary and had wrong content.
git-svn-id: 554337001ebd49d78cdf0a90d762fa547a80d337@203 373aa48d-36e5-0310-bb30-ae74d9883905# Twisted, the Framework of Your Internet
# Copyright (C) 2001 Matthew W. Lefkowitz
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""LDAP protocol logic"""
| <commit_before># Twisted, the Framework of Your Internet
# Copyright (C) 2001 Matthew W. Lefkowitz
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""LDAP protocol logic"""
__all__ = [
"ldapclient",
"ldaperrors",
"schema",
"ldapfilter",
"ldif",
"ldapsyntax",
"distinguishedname",
"ldapconnector",
]
<commit_msg>Remove ldaptor.protocols.ldap.__all__, it's unnecessary and had wrong content.
git-svn-id: 554337001ebd49d78cdf0a90d762fa547a80d337@203 373aa48d-36e5-0310-bb30-ae74d9883905<commit_after># Twisted, the Framework of Your Internet
# Copyright (C) 2001 Matthew W. Lefkowitz
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""LDAP protocol logic"""
|
996e862befb339165a801673754343fc643ffa86 | source/services/rotten_tomatoes_service.py | source/services/rotten_tomatoes_service.py | import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class RottenTomatoesService:
__URL = 'http://www.rottentomatoes.com/m/'
__SEPERATOR = '_'
def __init__(self, title):
self.title = title
def get_rt_rating(self):
search_url = self.__URL + self.format_title()
movie_page = requests.get(search_url)
contents = movie_page.text
soup = BeautifulSoup(contents, 'lxml')
ratings = self.get_ratings(soup)
ratings.link = search_url
return ratings
def format_title(self):
formatted_title = self.title
if formatted_title.startswith('The '):
formatted_title = formatted_title.replace('The ', '', 1)
if "'s" in formatted_title:
formatted_title = formatted_title.replace("'", 's')
formatted_title = formatted_title.replace(' ', self.__SEPERATOR)
formatted_title = formatted_title.replace('-', '')
return formatted_title
def get_ratings(self, soup):
items = []
for item in soup.findAll(attrs={'itemprop': 'ratingValue'}):
items.append(item.get_text().strip('%'))
return RTRating(items)
| import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class RottenTomatoesService:
__URL = 'http://www.rottentomatoes.com/m/'
__SEPERATOR = '_'
def __init__(self, title):
self.title = title
def get_rt_rating(self):
search_url = self.__URL + self.format_title()
movie_page = requests.get(search_url)
contents = movie_page.text
soup = BeautifulSoup(contents, 'lxml')
ratings = self.get_ratings(soup)
ratings.link = search_url
return ratings
def format_title(self):
formatted_title = self.title
if formatted_title.startswith('The '):
formatted_title = formatted_title.replace('The ', '', 1)
if "'s" in formatted_title:
formatted_title = formatted_title.replace("'s", 's')
formatted_title = formatted_title.replace(' ', self.__SEPERATOR)
formatted_title = formatted_title.replace('-', '')
return formatted_title
def get_ratings(self, soup):
items = []
for item in soup.findAll(attrs={'itemprop': 'ratingValue'}):
items.append(item.get_text().strip('%'))
return RTRating(items)
| Fix typo from previous commit | Fix typo from previous commit
| Python | mit | jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu | import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class RottenTomatoesService:
__URL = 'http://www.rottentomatoes.com/m/'
__SEPERATOR = '_'
def __init__(self, title):
self.title = title
def get_rt_rating(self):
search_url = self.__URL + self.format_title()
movie_page = requests.get(search_url)
contents = movie_page.text
soup = BeautifulSoup(contents, 'lxml')
ratings = self.get_ratings(soup)
ratings.link = search_url
return ratings
def format_title(self):
formatted_title = self.title
if formatted_title.startswith('The '):
formatted_title = formatted_title.replace('The ', '', 1)
if "'s" in formatted_title:
formatted_title = formatted_title.replace("'", 's')
formatted_title = formatted_title.replace(' ', self.__SEPERATOR)
formatted_title = formatted_title.replace('-', '')
return formatted_title
def get_ratings(self, soup):
items = []
for item in soup.findAll(attrs={'itemprop': 'ratingValue'}):
items.append(item.get_text().strip('%'))
return RTRating(items)
Fix typo from previous commit | import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class RottenTomatoesService:
__URL = 'http://www.rottentomatoes.com/m/'
__SEPERATOR = '_'
def __init__(self, title):
self.title = title
def get_rt_rating(self):
search_url = self.__URL + self.format_title()
movie_page = requests.get(search_url)
contents = movie_page.text
soup = BeautifulSoup(contents, 'lxml')
ratings = self.get_ratings(soup)
ratings.link = search_url
return ratings
def format_title(self):
formatted_title = self.title
if formatted_title.startswith('The '):
formatted_title = formatted_title.replace('The ', '', 1)
if "'s" in formatted_title:
formatted_title = formatted_title.replace("'s", 's')
formatted_title = formatted_title.replace(' ', self.__SEPERATOR)
formatted_title = formatted_title.replace('-', '')
return formatted_title
def get_ratings(self, soup):
items = []
for item in soup.findAll(attrs={'itemprop': 'ratingValue'}):
items.append(item.get_text().strip('%'))
return RTRating(items)
| <commit_before>import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class RottenTomatoesService:
__URL = 'http://www.rottentomatoes.com/m/'
__SEPERATOR = '_'
def __init__(self, title):
self.title = title
def get_rt_rating(self):
search_url = self.__URL + self.format_title()
movie_page = requests.get(search_url)
contents = movie_page.text
soup = BeautifulSoup(contents, 'lxml')
ratings = self.get_ratings(soup)
ratings.link = search_url
return ratings
def format_title(self):
formatted_title = self.title
if formatted_title.startswith('The '):
formatted_title = formatted_title.replace('The ', '', 1)
if "'s" in formatted_title:
formatted_title = formatted_title.replace("'", 's')
formatted_title = formatted_title.replace(' ', self.__SEPERATOR)
formatted_title = formatted_title.replace('-', '')
return formatted_title
def get_ratings(self, soup):
items = []
for item in soup.findAll(attrs={'itemprop': 'ratingValue'}):
items.append(item.get_text().strip('%'))
return RTRating(items)
<commit_msg>Fix typo from previous commit<commit_after> | import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class RottenTomatoesService:
__URL = 'http://www.rottentomatoes.com/m/'
__SEPERATOR = '_'
def __init__(self, title):
self.title = title
def get_rt_rating(self):
search_url = self.__URL + self.format_title()
movie_page = requests.get(search_url)
contents = movie_page.text
soup = BeautifulSoup(contents, 'lxml')
ratings = self.get_ratings(soup)
ratings.link = search_url
return ratings
def format_title(self):
formatted_title = self.title
if formatted_title.startswith('The '):
formatted_title = formatted_title.replace('The ', '', 1)
if "'s" in formatted_title:
formatted_title = formatted_title.replace("'s", 's')
formatted_title = formatted_title.replace(' ', self.__SEPERATOR)
formatted_title = formatted_title.replace('-', '')
return formatted_title
def get_ratings(self, soup):
items = []
for item in soup.findAll(attrs={'itemprop': 'ratingValue'}):
items.append(item.get_text().strip('%'))
return RTRating(items)
| import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class RottenTomatoesService:
__URL = 'http://www.rottentomatoes.com/m/'
__SEPERATOR = '_'
def __init__(self, title):
self.title = title
def get_rt_rating(self):
search_url = self.__URL + self.format_title()
movie_page = requests.get(search_url)
contents = movie_page.text
soup = BeautifulSoup(contents, 'lxml')
ratings = self.get_ratings(soup)
ratings.link = search_url
return ratings
def format_title(self):
formatted_title = self.title
if formatted_title.startswith('The '):
formatted_title = formatted_title.replace('The ', '', 1)
if "'s" in formatted_title:
formatted_title = formatted_title.replace("'", 's')
formatted_title = formatted_title.replace(' ', self.__SEPERATOR)
formatted_title = formatted_title.replace('-', '')
return formatted_title
def get_ratings(self, soup):
items = []
for item in soup.findAll(attrs={'itemprop': 'ratingValue'}):
items.append(item.get_text().strip('%'))
return RTRating(items)
Fix typo from previous commitimport requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class RottenTomatoesService:
__URL = 'http://www.rottentomatoes.com/m/'
__SEPERATOR = '_'
def __init__(self, title):
self.title = title
def get_rt_rating(self):
search_url = self.__URL + self.format_title()
movie_page = requests.get(search_url)
contents = movie_page.text
soup = BeautifulSoup(contents, 'lxml')
ratings = self.get_ratings(soup)
ratings.link = search_url
return ratings
def format_title(self):
formatted_title = self.title
if formatted_title.startswith('The '):
formatted_title = formatted_title.replace('The ', '', 1)
if "'s" in formatted_title:
formatted_title = formatted_title.replace("'s", 's')
formatted_title = formatted_title.replace(' ', self.__SEPERATOR)
formatted_title = formatted_title.replace('-', '')
return formatted_title
def get_ratings(self, soup):
items = []
for item in soup.findAll(attrs={'itemprop': 'ratingValue'}):
items.append(item.get_text().strip('%'))
return RTRating(items)
| <commit_before>import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class RottenTomatoesService:
__URL = 'http://www.rottentomatoes.com/m/'
__SEPERATOR = '_'
def __init__(self, title):
self.title = title
def get_rt_rating(self):
search_url = self.__URL + self.format_title()
movie_page = requests.get(search_url)
contents = movie_page.text
soup = BeautifulSoup(contents, 'lxml')
ratings = self.get_ratings(soup)
ratings.link = search_url
return ratings
def format_title(self):
formatted_title = self.title
if formatted_title.startswith('The '):
formatted_title = formatted_title.replace('The ', '', 1)
if "'s" in formatted_title:
formatted_title = formatted_title.replace("'", 's')
formatted_title = formatted_title.replace(' ', self.__SEPERATOR)
formatted_title = formatted_title.replace('-', '')
return formatted_title
def get_ratings(self, soup):
items = []
for item in soup.findAll(attrs={'itemprop': 'ratingValue'}):
items.append(item.get_text().strip('%'))
return RTRating(items)
<commit_msg>Fix typo from previous commit<commit_after>import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class RottenTomatoesService:
__URL = 'http://www.rottentomatoes.com/m/'
__SEPERATOR = '_'
def __init__(self, title):
self.title = title
def get_rt_rating(self):
search_url = self.__URL + self.format_title()
movie_page = requests.get(search_url)
contents = movie_page.text
soup = BeautifulSoup(contents, 'lxml')
ratings = self.get_ratings(soup)
ratings.link = search_url
return ratings
def format_title(self):
formatted_title = self.title
if formatted_title.startswith('The '):
formatted_title = formatted_title.replace('The ', '', 1)
if "'s" in formatted_title:
formatted_title = formatted_title.replace("'s", 's')
formatted_title = formatted_title.replace(' ', self.__SEPERATOR)
formatted_title = formatted_title.replace('-', '')
return formatted_title
def get_ratings(self, soup):
items = []
for item in soup.findAll(attrs={'itemprop': 'ratingValue'}):
items.append(item.get_text().strip('%'))
return RTRating(items)
|
5dcdfa510e62d754bce6270286e42a76b37c23c4 | inpassing/worker/util.py | inpassing/worker/util.py | # Copyright (c) 2017 Luke San Antonio Bialecki
# All rights reserved.
from datetime import datetime, timezone
DATE_FMT = '%Y-%m-%d'
def date_to_str(day):
return day.strftime(DATE_FMT)
def str_to_date(s):
return datetime.strptime(s, DATE_FMT).replace(tzinfo=timezone.utc)
| # Copyright (c) 2017 Luke San Antonio Bialecki
# All rights reserved.
from datetime import datetime, timezone
DATE_FMT = '%Y-%m-%d'
def date_to_str(day):
return day.strftime(DATE_FMT)
def str_to_date(s, tz=None):
ret = datetime.strptime(s, DATE_FMT)
if tz:
return tz.localize(ret)
else:
return ret
| Support use of local timezones when parsing date strings | Support use of local timezones when parsing date strings
| Python | mit | lukesanantonio/inpassing-backend,lukesanantonio/inpassing-backend | # Copyright (c) 2017 Luke San Antonio Bialecki
# All rights reserved.
from datetime import datetime, timezone
DATE_FMT = '%Y-%m-%d'
def date_to_str(day):
return day.strftime(DATE_FMT)
def str_to_date(s):
return datetime.strptime(s, DATE_FMT).replace(tzinfo=timezone.utc)
Support use of local timezones when parsing date strings | # Copyright (c) 2017 Luke San Antonio Bialecki
# All rights reserved.
from datetime import datetime, timezone
DATE_FMT = '%Y-%m-%d'
def date_to_str(day):
return day.strftime(DATE_FMT)
def str_to_date(s, tz=None):
ret = datetime.strptime(s, DATE_FMT)
if tz:
return tz.localize(ret)
else:
return ret
| <commit_before># Copyright (c) 2017 Luke San Antonio Bialecki
# All rights reserved.
from datetime import datetime, timezone
DATE_FMT = '%Y-%m-%d'
def date_to_str(day):
return day.strftime(DATE_FMT)
def str_to_date(s):
return datetime.strptime(s, DATE_FMT).replace(tzinfo=timezone.utc)
<commit_msg>Support use of local timezones when parsing date strings<commit_after> | # Copyright (c) 2017 Luke San Antonio Bialecki
# All rights reserved.
from datetime import datetime, timezone
DATE_FMT = '%Y-%m-%d'
def date_to_str(day):
return day.strftime(DATE_FMT)
def str_to_date(s, tz=None):
ret = datetime.strptime(s, DATE_FMT)
if tz:
return tz.localize(ret)
else:
return ret
| # Copyright (c) 2017 Luke San Antonio Bialecki
# All rights reserved.
from datetime import datetime, timezone
DATE_FMT = '%Y-%m-%d'
def date_to_str(day):
return day.strftime(DATE_FMT)
def str_to_date(s):
return datetime.strptime(s, DATE_FMT).replace(tzinfo=timezone.utc)
Support use of local timezones when parsing date strings# Copyright (c) 2017 Luke San Antonio Bialecki
# All rights reserved.
from datetime import datetime, timezone
DATE_FMT = '%Y-%m-%d'
def date_to_str(day):
return day.strftime(DATE_FMT)
def str_to_date(s, tz=None):
ret = datetime.strptime(s, DATE_FMT)
if tz:
return tz.localize(ret)
else:
return ret
| <commit_before># Copyright (c) 2017 Luke San Antonio Bialecki
# All rights reserved.
from datetime import datetime, timezone
DATE_FMT = '%Y-%m-%d'
def date_to_str(day):
return day.strftime(DATE_FMT)
def str_to_date(s):
return datetime.strptime(s, DATE_FMT).replace(tzinfo=timezone.utc)
<commit_msg>Support use of local timezones when parsing date strings<commit_after># Copyright (c) 2017 Luke San Antonio Bialecki
# All rights reserved.
from datetime import datetime, timezone
DATE_FMT = '%Y-%m-%d'
def date_to_str(day):
return day.strftime(DATE_FMT)
def str_to_date(s, tz=None):
ret = datetime.strptime(s, DATE_FMT)
if tz:
return tz.localize(ret)
else:
return ret
|
cd9048f64c6a2184e148daf0baa7bb3be51b3268 | vol/__init__.py | vol/__init__.py | # coding: utf-8
from __future__ import unicode_literals, print_function
from sys import platform
if platform == 'darwin':
from .osx import OSXVolumeController as VolumeController
else:
raise NotImplementedError(
'VolumeController for {} platform has not been implemented yet'.format(platform)
)
| # coding: utf-8
'''
A cross platform implementation of volume control
'''
from __future__ import unicode_literals, print_function
from sys import platform
if platform == 'darwin':
from .osx import OSXVolumeController as VolumeController
else:
raise NotImplementedError(
'VolumeController for {} platform has not been implemented yet'.format(platform)
)
| Update doc for vol pkg | Update doc for vol pkg
| Python | bsd-3-clause | Microcore/AGT,Microcore/YAS | # coding: utf-8
from __future__ import unicode_literals, print_function
from sys import platform
if platform == 'darwin':
from .osx import OSXVolumeController as VolumeController
else:
raise NotImplementedError(
'VolumeController for {} platform has not been implemented yet'.format(platform)
)
Update doc for vol pkg | # coding: utf-8
'''
A cross platform implementation of volume control
'''
from __future__ import unicode_literals, print_function
from sys import platform
if platform == 'darwin':
from .osx import OSXVolumeController as VolumeController
else:
raise NotImplementedError(
'VolumeController for {} platform has not been implemented yet'.format(platform)
)
| <commit_before># coding: utf-8
from __future__ import unicode_literals, print_function
from sys import platform
if platform == 'darwin':
from .osx import OSXVolumeController as VolumeController
else:
raise NotImplementedError(
'VolumeController for {} platform has not been implemented yet'.format(platform)
)
<commit_msg>Update doc for vol pkg<commit_after> | # coding: utf-8
'''
A cross platform implementation of volume control
'''
from __future__ import unicode_literals, print_function
from sys import platform
if platform == 'darwin':
from .osx import OSXVolumeController as VolumeController
else:
raise NotImplementedError(
'VolumeController for {} platform has not been implemented yet'.format(platform)
)
| # coding: utf-8
from __future__ import unicode_literals, print_function
from sys import platform
if platform == 'darwin':
from .osx import OSXVolumeController as VolumeController
else:
raise NotImplementedError(
'VolumeController for {} platform has not been implemented yet'.format(platform)
)
Update doc for vol pkg# coding: utf-8
'''
A cross platform implementation of volume control
'''
from __future__ import unicode_literals, print_function
from sys import platform
if platform == 'darwin':
from .osx import OSXVolumeController as VolumeController
else:
raise NotImplementedError(
'VolumeController for {} platform has not been implemented yet'.format(platform)
)
| <commit_before># coding: utf-8
from __future__ import unicode_literals, print_function
from sys import platform
if platform == 'darwin':
from .osx import OSXVolumeController as VolumeController
else:
raise NotImplementedError(
'VolumeController for {} platform has not been implemented yet'.format(platform)
)
<commit_msg>Update doc for vol pkg<commit_after># coding: utf-8
'''
A cross platform implementation of volume control
'''
from __future__ import unicode_literals, print_function
from sys import platform
if platform == 'darwin':
from .osx import OSXVolumeController as VolumeController
else:
raise NotImplementedError(
'VolumeController for {} platform has not been implemented yet'.format(platform)
)
|
6aea2f1c3a478be0c6926f442924e1f263955430 | pip_run/__init__.py | pip_run/__init__.py | import sys
from . import deps
from . import commands
from . import launch
from . import scripts
def run(args=None):
if args is None:
args = sys.argv[1:]
pip_args, params = commands.parse_script_args(args)
commands.intercept(pip_args)
pip_args.extend(scripts.DepsReader.search(params))
with deps.load(*deps.not_installed(pip_args)) as home:
raise SystemExit(launch.with_path(home, params))
| import sys
from . import deps
from . import commands
from . import launch
from . import scripts
def run(args=None):
"""
Main entry point for pip-run.
"""
if args is None:
args = sys.argv[1:]
pip_args, params = commands.parse_script_args(args)
commands.intercept(pip_args)
pip_args.extend(scripts.DepsReader.search(params))
with deps.load(*deps.not_installed(pip_args)) as home:
raise SystemExit(launch.with_path(home, params))
| Add docstring to run function. | Add docstring to run function.
| Python | mit | jaraco/rwt | import sys
from . import deps
from . import commands
from . import launch
from . import scripts
def run(args=None):
if args is None:
args = sys.argv[1:]
pip_args, params = commands.parse_script_args(args)
commands.intercept(pip_args)
pip_args.extend(scripts.DepsReader.search(params))
with deps.load(*deps.not_installed(pip_args)) as home:
raise SystemExit(launch.with_path(home, params))
Add docstring to run function. | import sys
from . import deps
from . import commands
from . import launch
from . import scripts
def run(args=None):
"""
Main entry point for pip-run.
"""
if args is None:
args = sys.argv[1:]
pip_args, params = commands.parse_script_args(args)
commands.intercept(pip_args)
pip_args.extend(scripts.DepsReader.search(params))
with deps.load(*deps.not_installed(pip_args)) as home:
raise SystemExit(launch.with_path(home, params))
| <commit_before>import sys
from . import deps
from . import commands
from . import launch
from . import scripts
def run(args=None):
if args is None:
args = sys.argv[1:]
pip_args, params = commands.parse_script_args(args)
commands.intercept(pip_args)
pip_args.extend(scripts.DepsReader.search(params))
with deps.load(*deps.not_installed(pip_args)) as home:
raise SystemExit(launch.with_path(home, params))
<commit_msg>Add docstring to run function.<commit_after> | import sys
from . import deps
from . import commands
from . import launch
from . import scripts
def run(args=None):
"""
Main entry point for pip-run.
"""
if args is None:
args = sys.argv[1:]
pip_args, params = commands.parse_script_args(args)
commands.intercept(pip_args)
pip_args.extend(scripts.DepsReader.search(params))
with deps.load(*deps.not_installed(pip_args)) as home:
raise SystemExit(launch.with_path(home, params))
| import sys
from . import deps
from . import commands
from . import launch
from . import scripts
def run(args=None):
if args is None:
args = sys.argv[1:]
pip_args, params = commands.parse_script_args(args)
commands.intercept(pip_args)
pip_args.extend(scripts.DepsReader.search(params))
with deps.load(*deps.not_installed(pip_args)) as home:
raise SystemExit(launch.with_path(home, params))
Add docstring to run function.import sys
from . import deps
from . import commands
from . import launch
from . import scripts
def run(args=None):
"""
Main entry point for pip-run.
"""
if args is None:
args = sys.argv[1:]
pip_args, params = commands.parse_script_args(args)
commands.intercept(pip_args)
pip_args.extend(scripts.DepsReader.search(params))
with deps.load(*deps.not_installed(pip_args)) as home:
raise SystemExit(launch.with_path(home, params))
| <commit_before>import sys
from . import deps
from . import commands
from . import launch
from . import scripts
def run(args=None):
if args is None:
args = sys.argv[1:]
pip_args, params = commands.parse_script_args(args)
commands.intercept(pip_args)
pip_args.extend(scripts.DepsReader.search(params))
with deps.load(*deps.not_installed(pip_args)) as home:
raise SystemExit(launch.with_path(home, params))
<commit_msg>Add docstring to run function.<commit_after>import sys
from . import deps
from . import commands
from . import launch
from . import scripts
def run(args=None):
"""
Main entry point for pip-run.
"""
if args is None:
args = sys.argv[1:]
pip_args, params = commands.parse_script_args(args)
commands.intercept(pip_args)
pip_args.extend(scripts.DepsReader.search(params))
with deps.load(*deps.not_installed(pip_args)) as home:
raise SystemExit(launch.with_path(home, params))
|
1e0ac4612937583dec22a81db833c7962e91edc8 | registries/views.py | registries/views.py | from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from registries.models import Organization
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
queryset = Organization.objects.all()
serializer_class = DrillerListSerializer
# Create your views here.
def index(request):
return HttpResponse("TEST: Driller Register app home index.") | from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from registries.models import Organization
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
queryset = Organization.objects.all().select_related('province_state')
serializer_class = DrillerListSerializer
# Create your views here.
def index(request):
return HttpResponse("TEST: Driller Register app home index.")
| Add prefetch to reduce queries on province_state | Add prefetch to reduce queries on province_state
| Python | apache-2.0 | rstens/gwells,bcgov/gwells,bcgov/gwells,rstens/gwells,rstens/gwells,bcgov/gwells,rstens/gwells,bcgov/gwells | from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from registries.models import Organization
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
queryset = Organization.objects.all()
serializer_class = DrillerListSerializer
# Create your views here.
def index(request):
return HttpResponse("TEST: Driller Register app home index.")Add prefetch to reduce queries on province_state | from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from registries.models import Organization
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
queryset = Organization.objects.all().select_related('province_state')
serializer_class = DrillerListSerializer
# Create your views here.
def index(request):
return HttpResponse("TEST: Driller Register app home index.")
| <commit_before>from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from registries.models import Organization
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
queryset = Organization.objects.all()
serializer_class = DrillerListSerializer
# Create your views here.
def index(request):
return HttpResponse("TEST: Driller Register app home index.")<commit_msg>Add prefetch to reduce queries on province_state<commit_after> | from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from registries.models import Organization
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
queryset = Organization.objects.all().select_related('province_state')
serializer_class = DrillerListSerializer
# Create your views here.
def index(request):
return HttpResponse("TEST: Driller Register app home index.")
| from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from registries.models import Organization
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
queryset = Organization.objects.all()
serializer_class = DrillerListSerializer
# Create your views here.
def index(request):
return HttpResponse("TEST: Driller Register app home index.")Add prefetch to reduce queries on province_statefrom django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from registries.models import Organization
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
queryset = Organization.objects.all().select_related('province_state')
serializer_class = DrillerListSerializer
# Create your views here.
def index(request):
return HttpResponse("TEST: Driller Register app home index.")
| <commit_before>from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from registries.models import Organization
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
queryset = Organization.objects.all()
serializer_class = DrillerListSerializer
# Create your views here.
def index(request):
return HttpResponse("TEST: Driller Register app home index.")<commit_msg>Add prefetch to reduce queries on province_state<commit_after>from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from registries.models import Organization
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
queryset = Organization.objects.all().select_related('province_state')
serializer_class = DrillerListSerializer
# Create your views here.
def index(request):
return HttpResponse("TEST: Driller Register app home index.")
|
d74908f5acb5c1a88965ed086d41435e0041d85b | pyluos/modules/l0_dc_motor.py | pyluos/modules/l0_dc_motor.py | from __future__ import division
from .module import Module
class DCMotor(object):
def __init__(self, name, delegate):
self._name = name
self._delegate = delegate
self._speed = None
@property
def name(self):
return self._name
@property
def speed(self):
self._speed
@speed.setter
def speed(self, s):
s = min(max(s, -1.0), 1.0)
if s != self._speed:
self._speed = s
self._delegate._push_value(self.name, self._speed)
class L0DCMotor(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0DCMotor', id, alias, robot)
self.m1 = DCMotor('m1', self)
self.m2 = DCMotor('m2', self)
| from __future__ import division
from .module import Module
class DCMotor(object):
def __init__(self, name, delegate):
self._name = name
self._delegate = delegate
self._speed = None
@property
def name(self):
return self._name
@property
def speed(self):
self._speed
@speed.setter
def speed(self, s):
s = min(max(s, -1.0), 1.0)
if s != self._speed:
self._speed = s
field = self.name.replace('m', 's')
self._delegate._push_value(field, self._speed)
class L0DCMotor(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0DCMotor', id, alias, robot)
self.m1 = DCMotor('m1', self)
self.m2 = DCMotor('m2', self)
| Fix l0 dc field name. | Fix l0 dc field name.
| Python | mit | pollen/pyrobus | from __future__ import division
from .module import Module
class DCMotor(object):
def __init__(self, name, delegate):
self._name = name
self._delegate = delegate
self._speed = None
@property
def name(self):
return self._name
@property
def speed(self):
self._speed
@speed.setter
def speed(self, s):
s = min(max(s, -1.0), 1.0)
if s != self._speed:
self._speed = s
self._delegate._push_value(self.name, self._speed)
class L0DCMotor(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0DCMotor', id, alias, robot)
self.m1 = DCMotor('m1', self)
self.m2 = DCMotor('m2', self)
Fix l0 dc field name. | from __future__ import division
from .module import Module
class DCMotor(object):
def __init__(self, name, delegate):
self._name = name
self._delegate = delegate
self._speed = None
@property
def name(self):
return self._name
@property
def speed(self):
self._speed
@speed.setter
def speed(self, s):
s = min(max(s, -1.0), 1.0)
if s != self._speed:
self._speed = s
field = self.name.replace('m', 's')
self._delegate._push_value(field, self._speed)
class L0DCMotor(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0DCMotor', id, alias, robot)
self.m1 = DCMotor('m1', self)
self.m2 = DCMotor('m2', self)
| <commit_before>from __future__ import division
from .module import Module
class DCMotor(object):
def __init__(self, name, delegate):
self._name = name
self._delegate = delegate
self._speed = None
@property
def name(self):
return self._name
@property
def speed(self):
self._speed
@speed.setter
def speed(self, s):
s = min(max(s, -1.0), 1.0)
if s != self._speed:
self._speed = s
self._delegate._push_value(self.name, self._speed)
class L0DCMotor(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0DCMotor', id, alias, robot)
self.m1 = DCMotor('m1', self)
self.m2 = DCMotor('m2', self)
<commit_msg>Fix l0 dc field name.<commit_after> | from __future__ import division
from .module import Module
class DCMotor(object):
def __init__(self, name, delegate):
self._name = name
self._delegate = delegate
self._speed = None
@property
def name(self):
return self._name
@property
def speed(self):
self._speed
@speed.setter
def speed(self, s):
s = min(max(s, -1.0), 1.0)
if s != self._speed:
self._speed = s
field = self.name.replace('m', 's')
self._delegate._push_value(field, self._speed)
class L0DCMotor(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0DCMotor', id, alias, robot)
self.m1 = DCMotor('m1', self)
self.m2 = DCMotor('m2', self)
| from __future__ import division
from .module import Module
class DCMotor(object):
def __init__(self, name, delegate):
self._name = name
self._delegate = delegate
self._speed = None
@property
def name(self):
return self._name
@property
def speed(self):
self._speed
@speed.setter
def speed(self, s):
s = min(max(s, -1.0), 1.0)
if s != self._speed:
self._speed = s
self._delegate._push_value(self.name, self._speed)
class L0DCMotor(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0DCMotor', id, alias, robot)
self.m1 = DCMotor('m1', self)
self.m2 = DCMotor('m2', self)
Fix l0 dc field name.from __future__ import division
from .module import Module
class DCMotor(object):
def __init__(self, name, delegate):
self._name = name
self._delegate = delegate
self._speed = None
@property
def name(self):
return self._name
@property
def speed(self):
self._speed
@speed.setter
def speed(self, s):
s = min(max(s, -1.0), 1.0)
if s != self._speed:
self._speed = s
field = self.name.replace('m', 's')
self._delegate._push_value(field, self._speed)
class L0DCMotor(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0DCMotor', id, alias, robot)
self.m1 = DCMotor('m1', self)
self.m2 = DCMotor('m2', self)
| <commit_before>from __future__ import division
from .module import Module
class DCMotor(object):
def __init__(self, name, delegate):
self._name = name
self._delegate = delegate
self._speed = None
@property
def name(self):
return self._name
@property
def speed(self):
self._speed
@speed.setter
def speed(self, s):
s = min(max(s, -1.0), 1.0)
if s != self._speed:
self._speed = s
self._delegate._push_value(self.name, self._speed)
class L0DCMotor(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0DCMotor', id, alias, robot)
self.m1 = DCMotor('m1', self)
self.m2 = DCMotor('m2', self)
<commit_msg>Fix l0 dc field name.<commit_after>from __future__ import division
from .module import Module
class DCMotor(object):
def __init__(self, name, delegate):
self._name = name
self._delegate = delegate
self._speed = None
@property
def name(self):
return self._name
@property
def speed(self):
self._speed
@speed.setter
def speed(self, s):
s = min(max(s, -1.0), 1.0)
if s != self._speed:
self._speed = s
field = self.name.replace('m', 's')
self._delegate._push_value(field, self._speed)
class L0DCMotor(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0DCMotor', id, alias, robot)
self.m1 = DCMotor('m1', self)
self.m2 = DCMotor('m2', self)
|
7f863c30f7e49da29530d141a76c1976e0a679ee | massa/domain.py | massa/domain.py | # -*- coding: utf-8 -*-
from sqlalchemy import (
Column,
Date,
Integer,
MetaData,
Numeric,
String,
Table,
create_engine,
)
metadata = MetaData()
measurement = Table('measurement', metadata,
Column('id', Integer, primary_key=True),
Column('weight', Numeric(4, 1), nullable=False),
Column('code', String(25), nullable=False),
Column('date_measured', Date(), nullable=False),
)
def setup(app):
engine = create_engine(
app.config['SQLALCHEMY_DATABASE_URI'],
echo=app.config['SQLALCHEMY_ECHO']
)
metadata.bind = engine
| # -*- coding: utf-8 -*-
from sqlalchemy import (
Column,
Date,
Integer,
MetaData,
Numeric,
String,
Table,
create_engine,
)
metadata = MetaData()
measurement = Table('measurement', metadata,
Column('id', Integer, primary_key=True),
Column('weight', Numeric(4, 1), nullable=False),
Column('code', String(25), nullable=False),
Column('date_measured', Date(), nullable=False),
)
def setup(app):
engine = create_engine(
app.config['SQLALCHEMY_DATABASE_URI'],
echo=app.config['SQLALCHEMY_ECHO']
)
metadata.bind = engine
def make_tables():
metadata.create_all()
| Add a function do make db tables. | Add a function do make db tables. | Python | mit | jaapverloop/massa | # -*- coding: utf-8 -*-
from sqlalchemy import (
Column,
Date,
Integer,
MetaData,
Numeric,
String,
Table,
create_engine,
)
metadata = MetaData()
measurement = Table('measurement', metadata,
Column('id', Integer, primary_key=True),
Column('weight', Numeric(4, 1), nullable=False),
Column('code', String(25), nullable=False),
Column('date_measured', Date(), nullable=False),
)
def setup(app):
engine = create_engine(
app.config['SQLALCHEMY_DATABASE_URI'],
echo=app.config['SQLALCHEMY_ECHO']
)
metadata.bind = engine
Add a function do make db tables. | # -*- coding: utf-8 -*-
from sqlalchemy import (
Column,
Date,
Integer,
MetaData,
Numeric,
String,
Table,
create_engine,
)
metadata = MetaData()
measurement = Table('measurement', metadata,
Column('id', Integer, primary_key=True),
Column('weight', Numeric(4, 1), nullable=False),
Column('code', String(25), nullable=False),
Column('date_measured', Date(), nullable=False),
)
def setup(app):
engine = create_engine(
app.config['SQLALCHEMY_DATABASE_URI'],
echo=app.config['SQLALCHEMY_ECHO']
)
metadata.bind = engine
def make_tables():
metadata.create_all()
| <commit_before># -*- coding: utf-8 -*-
from sqlalchemy import (
Column,
Date,
Integer,
MetaData,
Numeric,
String,
Table,
create_engine,
)
metadata = MetaData()
measurement = Table('measurement', metadata,
Column('id', Integer, primary_key=True),
Column('weight', Numeric(4, 1), nullable=False),
Column('code', String(25), nullable=False),
Column('date_measured', Date(), nullable=False),
)
def setup(app):
engine = create_engine(
app.config['SQLALCHEMY_DATABASE_URI'],
echo=app.config['SQLALCHEMY_ECHO']
)
metadata.bind = engine
<commit_msg>Add a function do make db tables.<commit_after> | # -*- coding: utf-8 -*-
from sqlalchemy import (
Column,
Date,
Integer,
MetaData,
Numeric,
String,
Table,
create_engine,
)
metadata = MetaData()
measurement = Table('measurement', metadata,
Column('id', Integer, primary_key=True),
Column('weight', Numeric(4, 1), nullable=False),
Column('code', String(25), nullable=False),
Column('date_measured', Date(), nullable=False),
)
def setup(app):
engine = create_engine(
app.config['SQLALCHEMY_DATABASE_URI'],
echo=app.config['SQLALCHEMY_ECHO']
)
metadata.bind = engine
def make_tables():
metadata.create_all()
| # -*- coding: utf-8 -*-
from sqlalchemy import (
Column,
Date,
Integer,
MetaData,
Numeric,
String,
Table,
create_engine,
)
metadata = MetaData()
measurement = Table('measurement', metadata,
Column('id', Integer, primary_key=True),
Column('weight', Numeric(4, 1), nullable=False),
Column('code', String(25), nullable=False),
Column('date_measured', Date(), nullable=False),
)
def setup(app):
engine = create_engine(
app.config['SQLALCHEMY_DATABASE_URI'],
echo=app.config['SQLALCHEMY_ECHO']
)
metadata.bind = engine
Add a function do make db tables.# -*- coding: utf-8 -*-
from sqlalchemy import (
Column,
Date,
Integer,
MetaData,
Numeric,
String,
Table,
create_engine,
)
metadata = MetaData()
measurement = Table('measurement', metadata,
Column('id', Integer, primary_key=True),
Column('weight', Numeric(4, 1), nullable=False),
Column('code', String(25), nullable=False),
Column('date_measured', Date(), nullable=False),
)
def setup(app):
engine = create_engine(
app.config['SQLALCHEMY_DATABASE_URI'],
echo=app.config['SQLALCHEMY_ECHO']
)
metadata.bind = engine
def make_tables():
metadata.create_all()
| <commit_before># -*- coding: utf-8 -*-
from sqlalchemy import (
Column,
Date,
Integer,
MetaData,
Numeric,
String,
Table,
create_engine,
)
metadata = MetaData()
measurement = Table('measurement', metadata,
Column('id', Integer, primary_key=True),
Column('weight', Numeric(4, 1), nullable=False),
Column('code', String(25), nullable=False),
Column('date_measured', Date(), nullable=False),
)
def setup(app):
engine = create_engine(
app.config['SQLALCHEMY_DATABASE_URI'],
echo=app.config['SQLALCHEMY_ECHO']
)
metadata.bind = engine
<commit_msg>Add a function do make db tables.<commit_after># -*- coding: utf-8 -*-
from sqlalchemy import (
Column,
Date,
Integer,
MetaData,
Numeric,
String,
Table,
create_engine,
)
metadata = MetaData()
measurement = Table('measurement', metadata,
Column('id', Integer, primary_key=True),
Column('weight', Numeric(4, 1), nullable=False),
Column('code', String(25), nullable=False),
Column('date_measured', Date(), nullable=False),
)
def setup(app):
engine = create_engine(
app.config['SQLALCHEMY_DATABASE_URI'],
echo=app.config['SQLALCHEMY_ECHO']
)
metadata.bind = engine
def make_tables():
metadata.create_all()
|
e58688d87ba1c4af718ea3e427d94f68c3df3b16 | qipipe/interfaces/__init__.py | qipipe/interfaces/__init__.py | from .compress import Compress
from .copy import Copy
from .fix_dicom import FixDicom
from .group_dicom import GroupDicom
from .map_ctp import MapCTP
from .move import Move
from .glue import Glue
from .uncompress import Uncompress
from .xnat_upload import XNATUpload
from .xnat_download import XNATDownload
| from .compress import Compress
from .copy import Copy
from .fix_dicom import FixDicom
from .group_dicom import GroupDicom
from .map_ctp import MapCTP
from .move import Move
from .unpack import Unpack
from .uncompress import Uncompress
from .xnat_upload import XNATUpload
from .xnat_download import XNATDownload
from .fastfit import Fastfit
from .mri_volcluster import MriVolCluster
| Replace Glue interface by more restrictive Unpack. | Replace Glue interface by more restrictive Unpack.
| Python | bsd-2-clause | ohsu-qin/qipipe | from .compress import Compress
from .copy import Copy
from .fix_dicom import FixDicom
from .group_dicom import GroupDicom
from .map_ctp import MapCTP
from .move import Move
from .glue import Glue
from .uncompress import Uncompress
from .xnat_upload import XNATUpload
from .xnat_download import XNATDownload
Replace Glue interface by more restrictive Unpack. | from .compress import Compress
from .copy import Copy
from .fix_dicom import FixDicom
from .group_dicom import GroupDicom
from .map_ctp import MapCTP
from .move import Move
from .unpack import Unpack
from .uncompress import Uncompress
from .xnat_upload import XNATUpload
from .xnat_download import XNATDownload
from .fastfit import Fastfit
from .mri_volcluster import MriVolCluster
| <commit_before>from .compress import Compress
from .copy import Copy
from .fix_dicom import FixDicom
from .group_dicom import GroupDicom
from .map_ctp import MapCTP
from .move import Move
from .glue import Glue
from .uncompress import Uncompress
from .xnat_upload import XNATUpload
from .xnat_download import XNATDownload
<commit_msg>Replace Glue interface by more restrictive Unpack.<commit_after> | from .compress import Compress
from .copy import Copy
from .fix_dicom import FixDicom
from .group_dicom import GroupDicom
from .map_ctp import MapCTP
from .move import Move
from .unpack import Unpack
from .uncompress import Uncompress
from .xnat_upload import XNATUpload
from .xnat_download import XNATDownload
from .fastfit import Fastfit
from .mri_volcluster import MriVolCluster
| from .compress import Compress
from .copy import Copy
from .fix_dicom import FixDicom
from .group_dicom import GroupDicom
from .map_ctp import MapCTP
from .move import Move
from .glue import Glue
from .uncompress import Uncompress
from .xnat_upload import XNATUpload
from .xnat_download import XNATDownload
Replace Glue interface by more restrictive Unpack.from .compress import Compress
from .copy import Copy
from .fix_dicom import FixDicom
from .group_dicom import GroupDicom
from .map_ctp import MapCTP
from .move import Move
from .unpack import Unpack
from .uncompress import Uncompress
from .xnat_upload import XNATUpload
from .xnat_download import XNATDownload
from .fastfit import Fastfit
from .mri_volcluster import MriVolCluster
| <commit_before>from .compress import Compress
from .copy import Copy
from .fix_dicom import FixDicom
from .group_dicom import GroupDicom
from .map_ctp import MapCTP
from .move import Move
from .glue import Glue
from .uncompress import Uncompress
from .xnat_upload import XNATUpload
from .xnat_download import XNATDownload
<commit_msg>Replace Glue interface by more restrictive Unpack.<commit_after>from .compress import Compress
from .copy import Copy
from .fix_dicom import FixDicom
from .group_dicom import GroupDicom
from .map_ctp import MapCTP
from .move import Move
from .unpack import Unpack
from .uncompress import Uncompress
from .xnat_upload import XNATUpload
from .xnat_download import XNATDownload
from .fastfit import Fastfit
from .mri_volcluster import MriVolCluster
|
b2e537c2d054854d0b36ccee7567c9ba9c2a5516 | modulation_test.py | modulation_test.py | import pygame
import random
from demodulate.cfg import *
from gen_tone import *
if __name__ == "__main__":
pygame.mixer.pre_init(frequency = int(SAMPLE_FREQ), channels = 1)
pygame.mixer.init()
WPM = random.uniform(2,20)
pattern = [1,0,1,1,1,0,0,0,0,0,0,0] # morse code 'A'
#gen_test_data()
data = gen_tone(pattern, WPM)
snd = pygame.sndarray.make_sound(data)
snd.play()
| import pygame
import random
import time
from demodulate.cfg import *
from modulate import *
from gen_tone import *
if __name__ == "__main__":
pygame.mixer.pre_init(frequency = int(SAMPLE_FREQ), channels = 1)
pygame.mixer.init()
WPM = random.uniform(2,20)
pattern = chars_to_elements.letters_to_sequence("NA NA NA NA NA NA NA BATMAN")
#gen_test_data()
data = gen_tone(pattern, WPM)
snd = pygame.sndarray.make_sound(data)
chn = snd.play()
while chn.get_busy():
time.sleep(1)
| Make modulation test wait for sound to stop playing before exiting | Make modulation test wait for sound to stop playing before exiting
| Python | mit | nickodell/morse-code | import pygame
import random
from demodulate.cfg import *
from gen_tone import *
if __name__ == "__main__":
pygame.mixer.pre_init(frequency = int(SAMPLE_FREQ), channels = 1)
pygame.mixer.init()
WPM = random.uniform(2,20)
pattern = [1,0,1,1,1,0,0,0,0,0,0,0] # morse code 'A'
#gen_test_data()
data = gen_tone(pattern, WPM)
snd = pygame.sndarray.make_sound(data)
snd.play()
Make modulation test wait for sound to stop playing before exiting | import pygame
import random
import time
from demodulate.cfg import *
from modulate import *
from gen_tone import *
if __name__ == "__main__":
pygame.mixer.pre_init(frequency = int(SAMPLE_FREQ), channels = 1)
pygame.mixer.init()
WPM = random.uniform(2,20)
pattern = chars_to_elements.letters_to_sequence("NA NA NA NA NA NA NA BATMAN")
#gen_test_data()
data = gen_tone(pattern, WPM)
snd = pygame.sndarray.make_sound(data)
chn = snd.play()
while chn.get_busy():
time.sleep(1)
| <commit_before>import pygame
import random
from demodulate.cfg import *
from gen_tone import *
if __name__ == "__main__":
pygame.mixer.pre_init(frequency = int(SAMPLE_FREQ), channels = 1)
pygame.mixer.init()
WPM = random.uniform(2,20)
pattern = [1,0,1,1,1,0,0,0,0,0,0,0] # morse code 'A'
#gen_test_data()
data = gen_tone(pattern, WPM)
snd = pygame.sndarray.make_sound(data)
snd.play()
<commit_msg>Make modulation test wait for sound to stop playing before exiting<commit_after> | import pygame
import random
import time
from demodulate.cfg import *
from modulate import *
from gen_tone import *
if __name__ == "__main__":
pygame.mixer.pre_init(frequency = int(SAMPLE_FREQ), channels = 1)
pygame.mixer.init()
WPM = random.uniform(2,20)
pattern = chars_to_elements.letters_to_sequence("NA NA NA NA NA NA NA BATMAN")
#gen_test_data()
data = gen_tone(pattern, WPM)
snd = pygame.sndarray.make_sound(data)
chn = snd.play()
while chn.get_busy():
time.sleep(1)
| import pygame
import random
from demodulate.cfg import *
from gen_tone import *
if __name__ == "__main__":
pygame.mixer.pre_init(frequency = int(SAMPLE_FREQ), channels = 1)
pygame.mixer.init()
WPM = random.uniform(2,20)
pattern = [1,0,1,1,1,0,0,0,0,0,0,0] # morse code 'A'
#gen_test_data()
data = gen_tone(pattern, WPM)
snd = pygame.sndarray.make_sound(data)
snd.play()
Make modulation test wait for sound to stop playing before exitingimport pygame
import random
import time
from demodulate.cfg import *
from modulate import *
from gen_tone import *
if __name__ == "__main__":
pygame.mixer.pre_init(frequency = int(SAMPLE_FREQ), channels = 1)
pygame.mixer.init()
WPM = random.uniform(2,20)
pattern = chars_to_elements.letters_to_sequence("NA NA NA NA NA NA NA BATMAN")
#gen_test_data()
data = gen_tone(pattern, WPM)
snd = pygame.sndarray.make_sound(data)
chn = snd.play()
while chn.get_busy():
time.sleep(1)
| <commit_before>import pygame
import random
from demodulate.cfg import *
from gen_tone import *
if __name__ == "__main__":
pygame.mixer.pre_init(frequency = int(SAMPLE_FREQ), channels = 1)
pygame.mixer.init()
WPM = random.uniform(2,20)
pattern = [1,0,1,1,1,0,0,0,0,0,0,0] # morse code 'A'
#gen_test_data()
data = gen_tone(pattern, WPM)
snd = pygame.sndarray.make_sound(data)
snd.play()
<commit_msg>Make modulation test wait for sound to stop playing before exiting<commit_after>import pygame
import random
import time
from demodulate.cfg import *
from modulate import *
from gen_tone import *
if __name__ == "__main__":
pygame.mixer.pre_init(frequency = int(SAMPLE_FREQ), channels = 1)
pygame.mixer.init()
WPM = random.uniform(2,20)
pattern = chars_to_elements.letters_to_sequence("NA NA NA NA NA NA NA BATMAN")
#gen_test_data()
data = gen_tone(pattern, WPM)
snd = pygame.sndarray.make_sound(data)
chn = snd.play()
while chn.get_busy():
time.sleep(1)
|
e0c07b4078caaa4220040d0e8c4ed86e3a2bf087 | lextoumbourou/fabfile.py | lextoumbourou/fabfile.py | import os
from fabric.api import run, env, settings, cd, put, sudo
from fabric.contrib import files
import private
def prod():
env.hosts = list(private.PROD_SERVERS)
def local():
env.hosts = ['localhost']
def deploy():
"""
Deploy code to production
"""
git_repo = 'git://github.com/lextoumbourou/lextoumbourou.com.git'
with settings(warn_only=True):
if run('test -d {0}'.format(private.APP_DIR)).failed:
run('git clone {0} {1}'.format(git_repo, private.APP_DIR))
# Make sure permissions are correct
sudo('chown -R {0} {1}'.format(private.USER_GROUP, private.APP_DIR))
sudo('chmod -R 775 {0}'.format(private.APP_DIR))
# Django app deployment tasks
with cd(private.APP_DIR):
run('git pull')
put('private.py', 'lextoumbourou/private.py')
run('python manage.py syncdb')
run('python manage.py collectstatic --noinput')
| import os
from fabric.api import run, env, settings, cd, put, sudo
from fabric.contrib import files
import private
GIT_REPO = 'git://github.com/lextoumbourou/lextoumbourou.com.git'
def prod():
env.hosts = list(private.PROD_SERVERS)
def local():
env.hosts = ['localhost']
def initial_build():
"""
Clone project and set permissions
"""
# Clone project if it doesn't exist
with settings(warn_only=True):
if run('test -d {0}'.format(private.APP_DIR)).failed:
run('git clone {0} {1}'.format(GIT_REPO, private.APP_DIR))
# Make sure permissions are correct
sudo('chown -R {0} {1}'.format(private.USER_GROUP, private.APP_DIR))
sudo('chmod -R 775 {0}'.format(private.APP_DIR))
def deploy():
"""
Deploy code to production
"""
initial_build()
# Perform Django app deployment tasks
with cd(private.APP_DIR):
run('git pull')
put('private.py', 'lextoumbourou/private.py')
run('python manage.py syncdb')
run('python manage.py collectstatic --noinput')
| Move inital_build task into own function | Move inital_build task into own function
| Python | mit | lextoumbourou/lextoumbourou.com-old,lextoumbourou/lextoumbourou.com-old | import os
from fabric.api import run, env, settings, cd, put, sudo
from fabric.contrib import files
import private
def prod():
env.hosts = list(private.PROD_SERVERS)
def local():
env.hosts = ['localhost']
def deploy():
"""
Deploy code to production
"""
git_repo = 'git://github.com/lextoumbourou/lextoumbourou.com.git'
with settings(warn_only=True):
if run('test -d {0}'.format(private.APP_DIR)).failed:
run('git clone {0} {1}'.format(git_repo, private.APP_DIR))
# Make sure permissions are correct
sudo('chown -R {0} {1}'.format(private.USER_GROUP, private.APP_DIR))
sudo('chmod -R 775 {0}'.format(private.APP_DIR))
# Django app deployment tasks
with cd(private.APP_DIR):
run('git pull')
put('private.py', 'lextoumbourou/private.py')
run('python manage.py syncdb')
run('python manage.py collectstatic --noinput')
Move inital_build task into own function | import os
from fabric.api import run, env, settings, cd, put, sudo
from fabric.contrib import files
import private
GIT_REPO = 'git://github.com/lextoumbourou/lextoumbourou.com.git'
def prod():
env.hosts = list(private.PROD_SERVERS)
def local():
env.hosts = ['localhost']
def initial_build():
"""
Clone project and set permissions
"""
# Clone project if it doesn't exist
with settings(warn_only=True):
if run('test -d {0}'.format(private.APP_DIR)).failed:
run('git clone {0} {1}'.format(GIT_REPO, private.APP_DIR))
# Make sure permissions are correct
sudo('chown -R {0} {1}'.format(private.USER_GROUP, private.APP_DIR))
sudo('chmod -R 775 {0}'.format(private.APP_DIR))
def deploy():
"""
Deploy code to production
"""
initial_build()
# Perform Django app deployment tasks
with cd(private.APP_DIR):
run('git pull')
put('private.py', 'lextoumbourou/private.py')
run('python manage.py syncdb')
run('python manage.py collectstatic --noinput')
| <commit_before>import os
from fabric.api import run, env, settings, cd, put, sudo
from fabric.contrib import files
import private
def prod():
env.hosts = list(private.PROD_SERVERS)
def local():
env.hosts = ['localhost']
def deploy():
"""
Deploy code to production
"""
git_repo = 'git://github.com/lextoumbourou/lextoumbourou.com.git'
with settings(warn_only=True):
if run('test -d {0}'.format(private.APP_DIR)).failed:
run('git clone {0} {1}'.format(git_repo, private.APP_DIR))
# Make sure permissions are correct
sudo('chown -R {0} {1}'.format(private.USER_GROUP, private.APP_DIR))
sudo('chmod -R 775 {0}'.format(private.APP_DIR))
# Django app deployment tasks
with cd(private.APP_DIR):
run('git pull')
put('private.py', 'lextoumbourou/private.py')
run('python manage.py syncdb')
run('python manage.py collectstatic --noinput')
<commit_msg>Move inital_build task into own function<commit_after> | import os
from fabric.api import run, env, settings, cd, put, sudo
from fabric.contrib import files
import private
GIT_REPO = 'git://github.com/lextoumbourou/lextoumbourou.com.git'
def prod():
env.hosts = list(private.PROD_SERVERS)
def local():
env.hosts = ['localhost']
def initial_build():
"""
Clone project and set permissions
"""
# Clone project if it doesn't exist
with settings(warn_only=True):
if run('test -d {0}'.format(private.APP_DIR)).failed:
run('git clone {0} {1}'.format(GIT_REPO, private.APP_DIR))
# Make sure permissions are correct
sudo('chown -R {0} {1}'.format(private.USER_GROUP, private.APP_DIR))
sudo('chmod -R 775 {0}'.format(private.APP_DIR))
def deploy():
"""
Deploy code to production
"""
initial_build()
# Perform Django app deployment tasks
with cd(private.APP_DIR):
run('git pull')
put('private.py', 'lextoumbourou/private.py')
run('python manage.py syncdb')
run('python manage.py collectstatic --noinput')
| import os
from fabric.api import run, env, settings, cd, put, sudo
from fabric.contrib import files
import private
def prod():
env.hosts = list(private.PROD_SERVERS)
def local():
env.hosts = ['localhost']
def deploy():
"""
Deploy code to production
"""
git_repo = 'git://github.com/lextoumbourou/lextoumbourou.com.git'
with settings(warn_only=True):
if run('test -d {0}'.format(private.APP_DIR)).failed:
run('git clone {0} {1}'.format(git_repo, private.APP_DIR))
# Make sure permissions are correct
sudo('chown -R {0} {1}'.format(private.USER_GROUP, private.APP_DIR))
sudo('chmod -R 775 {0}'.format(private.APP_DIR))
# Django app deployment tasks
with cd(private.APP_DIR):
run('git pull')
put('private.py', 'lextoumbourou/private.py')
run('python manage.py syncdb')
run('python manage.py collectstatic --noinput')
Move inital_build task into own functionimport os
from fabric.api import run, env, settings, cd, put, sudo
from fabric.contrib import files
import private
GIT_REPO = 'git://github.com/lextoumbourou/lextoumbourou.com.git'
def prod():
env.hosts = list(private.PROD_SERVERS)
def local():
env.hosts = ['localhost']
def initial_build():
"""
Clone project and set permissions
"""
# Clone project if it doesn't exist
with settings(warn_only=True):
if run('test -d {0}'.format(private.APP_DIR)).failed:
run('git clone {0} {1}'.format(GIT_REPO, private.APP_DIR))
# Make sure permissions are correct
sudo('chown -R {0} {1}'.format(private.USER_GROUP, private.APP_DIR))
sudo('chmod -R 775 {0}'.format(private.APP_DIR))
def deploy():
"""
Deploy code to production
"""
initial_build()
# Perform Django app deployment tasks
with cd(private.APP_DIR):
run('git pull')
put('private.py', 'lextoumbourou/private.py')
run('python manage.py syncdb')
run('python manage.py collectstatic --noinput')
| <commit_before>import os
from fabric.api import run, env, settings, cd, put, sudo
from fabric.contrib import files
import private
def prod():
env.hosts = list(private.PROD_SERVERS)
def local():
env.hosts = ['localhost']
def deploy():
"""
Deploy code to production
"""
git_repo = 'git://github.com/lextoumbourou/lextoumbourou.com.git'
with settings(warn_only=True):
if run('test -d {0}'.format(private.APP_DIR)).failed:
run('git clone {0} {1}'.format(git_repo, private.APP_DIR))
# Make sure permissions are correct
sudo('chown -R {0} {1}'.format(private.USER_GROUP, private.APP_DIR))
sudo('chmod -R 775 {0}'.format(private.APP_DIR))
# Django app deployment tasks
with cd(private.APP_DIR):
run('git pull')
put('private.py', 'lextoumbourou/private.py')
run('python manage.py syncdb')
run('python manage.py collectstatic --noinput')
<commit_msg>Move inital_build task into own function<commit_after>import os
from fabric.api import run, env, settings, cd, put, sudo
from fabric.contrib import files
import private
GIT_REPO = 'git://github.com/lextoumbourou/lextoumbourou.com.git'
def prod():
env.hosts = list(private.PROD_SERVERS)
def local():
env.hosts = ['localhost']
def initial_build():
"""
Clone project and set permissions
"""
# Clone project if it doesn't exist
with settings(warn_only=True):
if run('test -d {0}'.format(private.APP_DIR)).failed:
run('git clone {0} {1}'.format(GIT_REPO, private.APP_DIR))
# Make sure permissions are correct
sudo('chown -R {0} {1}'.format(private.USER_GROUP, private.APP_DIR))
sudo('chmod -R 775 {0}'.format(private.APP_DIR))
def deploy():
"""
Deploy code to production
"""
initial_build()
# Perform Django app deployment tasks
with cd(private.APP_DIR):
run('git pull')
put('private.py', 'lextoumbourou/private.py')
run('python manage.py syncdb')
run('python manage.py collectstatic --noinput')
|
70efbd90d9d5601d368ddb5ea20a3b9910539b78 | members/urls.py | members/urls.py | from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('',
url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'),
url(r'^search/(?P<name>.*)/$', 'members.views.search', name='search'),
url(r'^archive/$', 'members.views.archive_student_council', name='archive_student_council'),
url(r'^profile/$', 'members.views.user_projects', name='user-projects'),
)
| from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'),
url(r'^search/(?P<name>.*)/$', 'members.views.search', name='search'),
url(r'^archive/$', 'members.views.archive_student_council', name='archive_student_council'),
url(r'^profile/$', 'members.views.user_projects', name='user-projects'),
)
| Change url and views for login/logout to django Defaults | Change url and views for login/logout to django Defaults
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('',
url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'),
url(r'^search/(?P<name>.*)/$', 'members.views.search', name='search'),
url(r'^archive/$', 'members.views.archive_student_council', name='archive_student_council'),
url(r'^profile/$', 'members.views.user_projects', name='user-projects'),
)
Change url and views for login/logout to django Defaults | from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'),
url(r'^search/(?P<name>.*)/$', 'members.views.search', name='search'),
url(r'^archive/$', 'members.views.archive_student_council', name='archive_student_council'),
url(r'^profile/$', 'members.views.user_projects', name='user-projects'),
)
| <commit_before>from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('',
url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'),
url(r'^search/(?P<name>.*)/$', 'members.views.search', name='search'),
url(r'^archive/$', 'members.views.archive_student_council', name='archive_student_council'),
url(r'^profile/$', 'members.views.user_projects', name='user-projects'),
)
<commit_msg>Change url and views for login/logout to django Defaults<commit_after> | from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'),
url(r'^search/(?P<name>.*)/$', 'members.views.search', name='search'),
url(r'^archive/$', 'members.views.archive_student_council', name='archive_student_council'),
url(r'^profile/$', 'members.views.user_projects', name='user-projects'),
)
| from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('',
url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'),
url(r'^search/(?P<name>.*)/$', 'members.views.search', name='search'),
url(r'^archive/$', 'members.views.archive_student_council', name='archive_student_council'),
url(r'^profile/$', 'members.views.user_projects', name='user-projects'),
)
Change url and views for login/logout to django Defaultsfrom django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'),
url(r'^search/(?P<name>.*)/$', 'members.views.search', name='search'),
url(r'^archive/$', 'members.views.archive_student_council', name='archive_student_council'),
url(r'^profile/$', 'members.views.user_projects', name='user-projects'),
)
| <commit_before>from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('',
url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'),
url(r'^search/(?P<name>.*)/$', 'members.views.search', name='search'),
url(r'^archive/$', 'members.views.archive_student_council', name='archive_student_council'),
url(r'^profile/$', 'members.views.user_projects', name='user-projects'),
)
<commit_msg>Change url and views for login/logout to django Defaults<commit_after>from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'),
url(r'^search/(?P<name>.*)/$', 'members.views.search', name='search'),
url(r'^archive/$', 'members.views.archive_student_council', name='archive_student_council'),
url(r'^profile/$', 'members.views.user_projects', name='user-projects'),
)
|
1aa050f2d50fb206ffb1a7d06e75cc2ba27cc91b | 1.py | 1.py | i = input()
floor = 0
for x in range(0, len(i)):
if i[x] == '(':
floor +=1;
elif i[x] == ')':
floor -=1;
print(floor) | i = input()
floor = 0
instruction = 0
for x in range(0, len(i)):
if i[x] == '(':
floor +=1
elif i[x] == ')':
floor -=1
if (floor < 0 and instruction == 0):
instruction = x+1
print("floor: %s" % floor)
print("basement entry: %s" % instruction) | Add second part of puzzle | Add second part of puzzle
| Python | mit | Walther/adventofcode,Walther/adventofcode,Walther/adventofcode | i = input()
floor = 0
for x in range(0, len(i)):
if i[x] == '(':
floor +=1;
elif i[x] == ')':
floor -=1;
print(floor)Add second part of puzzle | i = input()
floor = 0
instruction = 0
for x in range(0, len(i)):
if i[x] == '(':
floor +=1
elif i[x] == ')':
floor -=1
if (floor < 0 and instruction == 0):
instruction = x+1
print("floor: %s" % floor)
print("basement entry: %s" % instruction) | <commit_before>i = input()
floor = 0
for x in range(0, len(i)):
if i[x] == '(':
floor +=1;
elif i[x] == ')':
floor -=1;
print(floor)<commit_msg>Add second part of puzzle<commit_after> | i = input()
floor = 0
instruction = 0
for x in range(0, len(i)):
if i[x] == '(':
floor +=1
elif i[x] == ')':
floor -=1
if (floor < 0 and instruction == 0):
instruction = x+1
print("floor: %s" % floor)
print("basement entry: %s" % instruction) | i = input()
floor = 0
for x in range(0, len(i)):
if i[x] == '(':
floor +=1;
elif i[x] == ')':
floor -=1;
print(floor)Add second part of puzzlei = input()
floor = 0
instruction = 0
for x in range(0, len(i)):
if i[x] == '(':
floor +=1
elif i[x] == ')':
floor -=1
if (floor < 0 and instruction == 0):
instruction = x+1
print("floor: %s" % floor)
print("basement entry: %s" % instruction) | <commit_before>i = input()
floor = 0
for x in range(0, len(i)):
if i[x] == '(':
floor +=1;
elif i[x] == ')':
floor -=1;
print(floor)<commit_msg>Add second part of puzzle<commit_after>i = input()
floor = 0
instruction = 0
for x in range(0, len(i)):
if i[x] == '(':
floor +=1
elif i[x] == ')':
floor -=1
if (floor < 0 and instruction == 0):
instruction = x+1
print("floor: %s" % floor)
print("basement entry: %s" % instruction) |
6bc6a07ee60f68e2003b5afcc752c3820a176541 | astropy/conftest.py | astropy/conftest.py | # this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the astropy tree.
from .tests.pytest_plugins import *
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('Agg')
enable_deprecations_as_exceptions(include_astropy_deprecations=False)
| # this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the astropy tree.
from .tests.pytest_plugins import *
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('Agg')
enable_deprecations_as_exceptions(include_astropy_deprecations=False)
PYTEST_HEADER_MODULES['Cython'] = 'cython'
| Add Cython to py.test header | Add Cython to py.test header | Python | bsd-3-clause | kelle/astropy,tbabej/astropy,lpsinger/astropy,joergdietrich/astropy,pllim/astropy,MSeifert04/astropy,AustereCuriosity/astropy,saimn/astropy,aleksandr-bakanov/astropy,StuartLittlefair/astropy,tbabej/astropy,mhvk/astropy,DougBurke/astropy,pllim/astropy,StuartLittlefair/astropy,astropy/astropy,kelle/astropy,AustereCuriosity/astropy,pllim/astropy,funbaker/astropy,mhvk/astropy,larrybradley/astropy,dhomeier/astropy,larrybradley/astropy,astropy/astropy,MSeifert04/astropy,DougBurke/astropy,astropy/astropy,kelle/astropy,saimn/astropy,bsipocz/astropy,kelle/astropy,stargaser/astropy,lpsinger/astropy,joergdietrich/astropy,aleksandr-bakanov/astropy,astropy/astropy,AustereCuriosity/astropy,bsipocz/astropy,stargaser/astropy,dhomeier/astropy,stargaser/astropy,DougBurke/astropy,larrybradley/astropy,mhvk/astropy,MSeifert04/astropy,tbabej/astropy,pllim/astropy,StuartLittlefair/astropy,lpsinger/astropy,StuartLittlefair/astropy,stargaser/astropy,funbaker/astropy,lpsinger/astropy,saimn/astropy,pllim/astropy,AustereCuriosity/astropy,aleksandr-bakanov/astropy,astropy/astropy,larrybradley/astropy,mhvk/astropy,lpsinger/astropy,dhomeier/astropy,funbaker/astropy,mhvk/astropy,larrybradley/astropy,MSeifert04/astropy,funbaker/astropy,aleksandr-bakanov/astropy,bsipocz/astropy,saimn/astropy,dhomeier/astropy,AustereCuriosity/astropy,saimn/astropy,joergdietrich/astropy,StuartLittlefair/astropy,dhomeier/astropy,DougBurke/astropy,tbabej/astropy,tbabej/astropy,joergdietrich/astropy,kelle/astropy,bsipocz/astropy,joergdietrich/astropy | # this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the astropy tree.
from .tests.pytest_plugins import *
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('Agg')
enable_deprecations_as_exceptions(include_astropy_deprecations=False)
Add Cython to py.test header | # this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the astropy tree.
from .tests.pytest_plugins import *
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('Agg')
enable_deprecations_as_exceptions(include_astropy_deprecations=False)
PYTEST_HEADER_MODULES['Cython'] = 'cython'
| <commit_before># this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the astropy tree.
from .tests.pytest_plugins import *
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('Agg')
enable_deprecations_as_exceptions(include_astropy_deprecations=False)
<commit_msg>Add Cython to py.test header<commit_after> | # this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the astropy tree.
from .tests.pytest_plugins import *
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('Agg')
enable_deprecations_as_exceptions(include_astropy_deprecations=False)
PYTEST_HEADER_MODULES['Cython'] = 'cython'
| # this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the astropy tree.
from .tests.pytest_plugins import *
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('Agg')
enable_deprecations_as_exceptions(include_astropy_deprecations=False)
Add Cython to py.test header# this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the astropy tree.
from .tests.pytest_plugins import *
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('Agg')
enable_deprecations_as_exceptions(include_astropy_deprecations=False)
PYTEST_HEADER_MODULES['Cython'] = 'cython'
| <commit_before># this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the astropy tree.
from .tests.pytest_plugins import *
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('Agg')
enable_deprecations_as_exceptions(include_astropy_deprecations=False)
<commit_msg>Add Cython to py.test header<commit_after># this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the astropy tree.
from .tests.pytest_plugins import *
try:
import matplotlib
except ImportError:
pass
else:
matplotlib.use('Agg')
enable_deprecations_as_exceptions(include_astropy_deprecations=False)
PYTEST_HEADER_MODULES['Cython'] = 'cython'
|
ad0f4e793ea010df243b87f42fff94037432e7b2 | mla_game/apps/transcript/management/commands/fake_game_one_gameplay.py | mla_game/apps/transcript/management/commands/fake_game_one_gameplay.py | import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
class Command(BaseCommand):
help = 'Creates random votes for all phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript()
for phrase in transcript.phrases.all():
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(phrase)
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
| import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
class Command(BaseCommand):
help = 'Creates random votes for all phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript().first()
for phrase in transcript.phrases.all():
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(phrase)
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
| Fix fake game one script again | Fix fake game one script again
| Python | mit | WGBH/FixIt,WGBH/FixIt,WGBH/FixIt | import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
class Command(BaseCommand):
help = 'Creates random votes for all phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript()
for phrase in transcript.phrases.all():
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(phrase)
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
Fix fake game one script again | import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
class Command(BaseCommand):
help = 'Creates random votes for all phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript().first()
for phrase in transcript.phrases.all():
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(phrase)
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
| <commit_before>import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
class Command(BaseCommand):
help = 'Creates random votes for all phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript()
for phrase in transcript.phrases.all():
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(phrase)
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
<commit_msg>Fix fake game one script again<commit_after> | import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
class Command(BaseCommand):
help = 'Creates random votes for all phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript().first()
for phrase in transcript.phrases.all():
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(phrase)
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
| import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
class Command(BaseCommand):
help = 'Creates random votes for all phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript()
for phrase in transcript.phrases.all():
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(phrase)
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
Fix fake game one script againimport random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
class Command(BaseCommand):
help = 'Creates random votes for all phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript().first()
for phrase in transcript.phrases.all():
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(phrase)
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
| <commit_before>import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
class Command(BaseCommand):
help = 'Creates random votes for all phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript()
for phrase in transcript.phrases.all():
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(phrase)
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
<commit_msg>Fix fake game one script again<commit_after>import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
class Command(BaseCommand):
help = 'Creates random votes for all phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript().first()
for phrase in transcript.phrases.all():
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(phrase)
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
|
1056bb70699f2c480f887b13dd28b412a7aeb6c5 | opps/core/admin.py | opps/core/admin.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'channel', 'date_available', 'published']
list_filter = ['date_available', 'published', 'channel']
search_fields = ['title', 'slug', 'headline', 'channel']
exclude = ('user',)
date_hierarchy = ('date_available')
def save_model(self, request, obj, form, change):
if getattr(obj, 'pk', None) is None:
obj.user = request.user
obj.save()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'date_available', 'published']
list_filter = ['date_available', 'published']
search_fields = ['title', 'slug', 'headline']
exclude = ('user',)
def save_model(self, request, obj, form, change):
if getattr(obj, 'pk', None) is None:
obj.user = request.user
obj.save()
| Remove channel (list_display, list_filter and search_fields) on PublishableAdmin core | Remove channel (list_display, list_filter and search_fields) on PublishableAdmin core
| Python | mit | YACOWS/opps,jeanmask/opps,williamroot/opps,williamroot/opps,opps/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,opps/opps,williamroot/opps,YACOWS/opps,opps/opps,YACOWS/opps,opps/opps | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'channel', 'date_available', 'published']
list_filter = ['date_available', 'published', 'channel']
search_fields = ['title', 'slug', 'headline', 'channel']
exclude = ('user',)
date_hierarchy = ('date_available')
def save_model(self, request, obj, form, change):
if getattr(obj, 'pk', None) is None:
obj.user = request.user
obj.save()
Remove channel (list_display, list_filter and search_fields) on PublishableAdmin core | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'date_available', 'published']
list_filter = ['date_available', 'published']
search_fields = ['title', 'slug', 'headline']
exclude = ('user',)
def save_model(self, request, obj, form, change):
if getattr(obj, 'pk', None) is None:
obj.user = request.user
obj.save()
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'channel', 'date_available', 'published']
list_filter = ['date_available', 'published', 'channel']
search_fields = ['title', 'slug', 'headline', 'channel']
exclude = ('user',)
date_hierarchy = ('date_available')
def save_model(self, request, obj, form, change):
if getattr(obj, 'pk', None) is None:
obj.user = request.user
obj.save()
<commit_msg>Remove channel (list_display, list_filter and search_fields) on PublishableAdmin core<commit_after> | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'date_available', 'published']
list_filter = ['date_available', 'published']
search_fields = ['title', 'slug', 'headline']
exclude = ('user',)
def save_model(self, request, obj, form, change):
if getattr(obj, 'pk', None) is None:
obj.user = request.user
obj.save()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'channel', 'date_available', 'published']
list_filter = ['date_available', 'published', 'channel']
search_fields = ['title', 'slug', 'headline', 'channel']
exclude = ('user',)
date_hierarchy = ('date_available')
def save_model(self, request, obj, form, change):
if getattr(obj, 'pk', None) is None:
obj.user = request.user
obj.save()
Remove channel (list_display, list_filter and search_fields) on PublishableAdmin core#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'date_available', 'published']
list_filter = ['date_available', 'published']
search_fields = ['title', 'slug', 'headline']
exclude = ('user',)
def save_model(self, request, obj, form, change):
if getattr(obj, 'pk', None) is None:
obj.user = request.user
obj.save()
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'channel', 'date_available', 'published']
list_filter = ['date_available', 'published', 'channel']
search_fields = ['title', 'slug', 'headline', 'channel']
exclude = ('user',)
date_hierarchy = ('date_available')
def save_model(self, request, obj, form, change):
if getattr(obj, 'pk', None) is None:
obj.user = request.user
obj.save()
<commit_msg>Remove channel (list_display, list_filter and search_fields) on PublishableAdmin core<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'date_available', 'published']
list_filter = ['date_available', 'published']
search_fields = ['title', 'slug', 'headline']
exclude = ('user',)
def save_model(self, request, obj, form, change):
if getattr(obj, 'pk', None) is None:
obj.user = request.user
obj.save()
|
84eb438c966d5c2794a0842dccaefea726c0dbb9 | organizer/views.py | organizer/views.py | from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
def tag_detail(request):
# slug = ?
tag = Tag.objects.get(slug__iexact=slug)
template = loader.get_template(
'organizer/tag_detail.html')
context = Context({'tag': tag})
return HttpResponse(template.render(context))
| from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
def tag_detail(request, slug):
tag = Tag.objects.get(slug__iexact=slug)
template = loader.get_template(
'organizer/tag_detail.html')
context = Context({'tag': tag})
return HttpResponse(template.render(context))
| Tag Detail: get slug from URL pattern. | Ch05: Tag Detail: get slug from URL pattern.
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 | from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
def tag_detail(request):
# slug = ?
tag = Tag.objects.get(slug__iexact=slug)
template = loader.get_template(
'organizer/tag_detail.html')
context = Context({'tag': tag})
return HttpResponse(template.render(context))
Ch05: Tag Detail: get slug from URL pattern. | from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
def tag_detail(request, slug):
tag = Tag.objects.get(slug__iexact=slug)
template = loader.get_template(
'organizer/tag_detail.html')
context = Context({'tag': tag})
return HttpResponse(template.render(context))
| <commit_before>from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
def tag_detail(request):
# slug = ?
tag = Tag.objects.get(slug__iexact=slug)
template = loader.get_template(
'organizer/tag_detail.html')
context = Context({'tag': tag})
return HttpResponse(template.render(context))
<commit_msg>Ch05: Tag Detail: get slug from URL pattern.<commit_after> | from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
def tag_detail(request, slug):
tag = Tag.objects.get(slug__iexact=slug)
template = loader.get_template(
'organizer/tag_detail.html')
context = Context({'tag': tag})
return HttpResponse(template.render(context))
| from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
def tag_detail(request):
# slug = ?
tag = Tag.objects.get(slug__iexact=slug)
template = loader.get_template(
'organizer/tag_detail.html')
context = Context({'tag': tag})
return HttpResponse(template.render(context))
Ch05: Tag Detail: get slug from URL pattern.from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
def tag_detail(request, slug):
tag = Tag.objects.get(slug__iexact=slug)
template = loader.get_template(
'organizer/tag_detail.html')
context = Context({'tag': tag})
return HttpResponse(template.render(context))
| <commit_before>from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
def tag_detail(request):
# slug = ?
tag = Tag.objects.get(slug__iexact=slug)
template = loader.get_template(
'organizer/tag_detail.html')
context = Context({'tag': tag})
return HttpResponse(template.render(context))
<commit_msg>Ch05: Tag Detail: get slug from URL pattern.<commit_after>from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
def tag_detail(request, slug):
tag = Tag.objects.get(slug__iexact=slug)
template = loader.get_template(
'organizer/tag_detail.html')
context = Context({'tag': tag})
return HttpResponse(template.render(context))
|
d9d0af04ea76c6c6bd346ce417e9feb61580c90e | nuitka/plugins/commercial/__init__.py | nuitka/plugins/commercial/__init__.py | # Copyright 2020, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# 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.
#
""" Dummy file to make this directory a package. """
| # Copyright 2020, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# 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.
#
""" Commercial plugins package.
This may load code from places indicated by a heuristics.
"""
# Auto extend to a Nuitka commercial installation, by adding it to the package
# path. That aims at making extending Nuitka with these plugins easier.
import os
if "NUITKA_COMMERCIAL" in os.environ:
path = os.environ["NUITKA_COMMERCIAL"]
for candidate in "nuitka/plugins/commercial", ".":
candidate = os.path.join(path, candidate)
if os.path.isdir(candidate) and os.path.isfile(
os.path.join(candidate, "__init__.py")
):
__path__.append(candidate)
| Make it easier to integrate commercial plugins. | Plugins: Make it easier to integrate commercial plugins.
| Python | apache-2.0 | kayhayen/Nuitka,kayhayen/Nuitka,kayhayen/Nuitka,kayhayen/Nuitka | # Copyright 2020, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# 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.
#
""" Dummy file to make this directory a package. """
Plugins: Make it easier to integrate commercial plugins. | # Copyright 2020, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# 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.
#
""" Commercial plugins package.
This may load code from places indicated by a heuristics.
"""
# Auto extend to a Nuitka commercial installation, by adding it to the package
# path. That aims at making extending Nuitka with these plugins easier.
import os
if "NUITKA_COMMERCIAL" in os.environ:
path = os.environ["NUITKA_COMMERCIAL"]
for candidate in "nuitka/plugins/commercial", ".":
candidate = os.path.join(path, candidate)
if os.path.isdir(candidate) and os.path.isfile(
os.path.join(candidate, "__init__.py")
):
__path__.append(candidate)
| <commit_before># Copyright 2020, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# 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.
#
""" Dummy file to make this directory a package. """
<commit_msg>Plugins: Make it easier to integrate commercial plugins.<commit_after> | # Copyright 2020, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# 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.
#
""" Commercial plugins package.
This may load code from places indicated by a heuristics.
"""
# Auto extend to a Nuitka commercial installation, by adding it to the package
# path. That aims at making extending Nuitka with these plugins easier.
import os
if "NUITKA_COMMERCIAL" in os.environ:
path = os.environ["NUITKA_COMMERCIAL"]
for candidate in "nuitka/plugins/commercial", ".":
candidate = os.path.join(path, candidate)
if os.path.isdir(candidate) and os.path.isfile(
os.path.join(candidate, "__init__.py")
):
__path__.append(candidate)
| # Copyright 2020, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# 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.
#
""" Dummy file to make this directory a package. """
Plugins: Make it easier to integrate commercial plugins.# Copyright 2020, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# 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.
#
""" Commercial plugins package.
This may load code from places indicated by a heuristics.
"""
# Auto extend to a Nuitka commercial installation, by adding it to the package
# path. That aims at making extending Nuitka with these plugins easier.
import os
if "NUITKA_COMMERCIAL" in os.environ:
path = os.environ["NUITKA_COMMERCIAL"]
for candidate in "nuitka/plugins/commercial", ".":
candidate = os.path.join(path, candidate)
if os.path.isdir(candidate) and os.path.isfile(
os.path.join(candidate, "__init__.py")
):
__path__.append(candidate)
| <commit_before># Copyright 2020, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# 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.
#
""" Dummy file to make this directory a package. """
<commit_msg>Plugins: Make it easier to integrate commercial plugins.<commit_after># Copyright 2020, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# 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.
#
""" Commercial plugins package.
This may load code from places indicated by a heuristics.
"""
# Auto extend to a Nuitka commercial installation, by adding it to the package
# path. That aims at making extending Nuitka with these plugins easier.
import os
if "NUITKA_COMMERCIAL" in os.environ:
path = os.environ["NUITKA_COMMERCIAL"]
for candidate in "nuitka/plugins/commercial", ".":
candidate = os.path.join(path, candidate)
if os.path.isdir(candidate) and os.path.isfile(
os.path.join(candidate, "__init__.py")
):
__path__.append(candidate)
|
badda02f6cc81a8c5670b6f53e67009a3cb8b66f | rmake/core/constants.py | rmake/core/constants.py | #
# Copyright (c) 2010 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# 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 Common Public License for
# full details.
#
# Status codes for a job
JOB_OK = 200
JOB_FAILED = 400
# Status codes for a task
TASK_OK = 200
TASK_FAILED = 400
TASK_NOT_ASSIGNABLE = 401
# "ok" code for WorkerInfo.getScore() -- when can this task be assigned?
A_NOW = 0
A_LATER = 1
A_NEVER = 2
A_WRONG_ZONE = 3
| #
# Copyright (c) 2010 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# 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 Common Public License for
# full details.
#
# Status codes for a job
# Generic success
JOB_OK = 200
# Generic failure. Core failure codes will be in the range 450-499 and 550-599.
# All others are reserved for plugins.
JOB_FAILED = 450
# Status codes for a task
TASK_OK = 200
# See above note about core failure codes.
TASK_FAILED = 450
TASK_NOT_ASSIGNABLE = 451
# "ok" code for WorkerInfo.getScore() -- when can this task be assigned?
A_NOW = 0
A_LATER = 1
A_NEVER = 2
A_WRONG_ZONE = 3
| Relocate core status codes to the 450-499 range | Relocate core status codes to the 450-499 range
| Python | apache-2.0 | sassoftware/rmake3,sassoftware/rmake3,sassoftware/rmake3 | #
# Copyright (c) 2010 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# 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 Common Public License for
# full details.
#
# Status codes for a job
JOB_OK = 200
JOB_FAILED = 400
# Status codes for a task
TASK_OK = 200
TASK_FAILED = 400
TASK_NOT_ASSIGNABLE = 401
# "ok" code for WorkerInfo.getScore() -- when can this task be assigned?
A_NOW = 0
A_LATER = 1
A_NEVER = 2
A_WRONG_ZONE = 3
Relocate core status codes to the 450-499 range | #
# Copyright (c) 2010 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# 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 Common Public License for
# full details.
#
# Status codes for a job
# Generic success
JOB_OK = 200
# Generic failure. Core failure codes will be in the range 450-499 and 550-599.
# All others are reserved for plugins.
JOB_FAILED = 450
# Status codes for a task
TASK_OK = 200
# See above note about core failure codes.
TASK_FAILED = 450
TASK_NOT_ASSIGNABLE = 451
# "ok" code for WorkerInfo.getScore() -- when can this task be assigned?
A_NOW = 0
A_LATER = 1
A_NEVER = 2
A_WRONG_ZONE = 3
| <commit_before>#
# Copyright (c) 2010 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# 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 Common Public License for
# full details.
#
# Status codes for a job
JOB_OK = 200
JOB_FAILED = 400
# Status codes for a task
TASK_OK = 200
TASK_FAILED = 400
TASK_NOT_ASSIGNABLE = 401
# "ok" code for WorkerInfo.getScore() -- when can this task be assigned?
A_NOW = 0
A_LATER = 1
A_NEVER = 2
A_WRONG_ZONE = 3
<commit_msg>Relocate core status codes to the 450-499 range<commit_after> | #
# Copyright (c) 2010 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# 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 Common Public License for
# full details.
#
# Status codes for a job
# Generic success
JOB_OK = 200
# Generic failure. Core failure codes will be in the range 450-499 and 550-599.
# All others are reserved for plugins.
JOB_FAILED = 450
# Status codes for a task
TASK_OK = 200
# See above note about core failure codes.
TASK_FAILED = 450
TASK_NOT_ASSIGNABLE = 451
# "ok" code for WorkerInfo.getScore() -- when can this task be assigned?
A_NOW = 0
A_LATER = 1
A_NEVER = 2
A_WRONG_ZONE = 3
| #
# Copyright (c) 2010 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# 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 Common Public License for
# full details.
#
# Status codes for a job
JOB_OK = 200
JOB_FAILED = 400
# Status codes for a task
TASK_OK = 200
TASK_FAILED = 400
TASK_NOT_ASSIGNABLE = 401
# "ok" code for WorkerInfo.getScore() -- when can this task be assigned?
A_NOW = 0
A_LATER = 1
A_NEVER = 2
A_WRONG_ZONE = 3
Relocate core status codes to the 450-499 range#
# Copyright (c) 2010 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# 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 Common Public License for
# full details.
#
# Status codes for a job
# Generic success
JOB_OK = 200
# Generic failure. Core failure codes will be in the range 450-499 and 550-599.
# All others are reserved for plugins.
JOB_FAILED = 450
# Status codes for a task
TASK_OK = 200
# See above note about core failure codes.
TASK_FAILED = 450
TASK_NOT_ASSIGNABLE = 451
# "ok" code for WorkerInfo.getScore() -- when can this task be assigned?
A_NOW = 0
A_LATER = 1
A_NEVER = 2
A_WRONG_ZONE = 3
| <commit_before>#
# Copyright (c) 2010 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# 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 Common Public License for
# full details.
#
# Status codes for a job
JOB_OK = 200
JOB_FAILED = 400
# Status codes for a task
TASK_OK = 200
TASK_FAILED = 400
TASK_NOT_ASSIGNABLE = 401
# "ok" code for WorkerInfo.getScore() -- when can this task be assigned?
A_NOW = 0
A_LATER = 1
A_NEVER = 2
A_WRONG_ZONE = 3
<commit_msg>Relocate core status codes to the 450-499 range<commit_after>#
# Copyright (c) 2010 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# 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 Common Public License for
# full details.
#
# Status codes for a job
# Generic success
JOB_OK = 200
# Generic failure. Core failure codes will be in the range 450-499 and 550-599.
# All others are reserved for plugins.
JOB_FAILED = 450
# Status codes for a task
TASK_OK = 200
# See above note about core failure codes.
TASK_FAILED = 450
TASK_NOT_ASSIGNABLE = 451
# "ok" code for WorkerInfo.getScore() -- when can this task be assigned?
A_NOW = 0
A_LATER = 1
A_NEVER = 2
A_WRONG_ZONE = 3
|
cb408af79e46f32eca7337545f87fa169b32cba5 | n6/run_tests.py | n6/run_tests.py | #!/usr/bin/env python3
#
# Affero GPL
#
import unittest
def alltests():
return unittest.TestSuite([
])
unittest.TextTestRunner(verbosity = 2).run(alltests())
| Set up run tests file. | Set up run tests file.
| Python | agpl-3.0 | JasonCozens/en | Set up run tests file. | #!/usr/bin/env python3
#
# Affero GPL
#
import unittest
def alltests():
return unittest.TestSuite([
])
unittest.TextTestRunner(verbosity = 2).run(alltests())
| <commit_before><commit_msg>Set up run tests file.<commit_after> | #!/usr/bin/env python3
#
# Affero GPL
#
import unittest
def alltests():
return unittest.TestSuite([
])
unittest.TextTestRunner(verbosity = 2).run(alltests())
| Set up run tests file.#!/usr/bin/env python3
#
# Affero GPL
#
import unittest
def alltests():
return unittest.TestSuite([
])
unittest.TextTestRunner(verbosity = 2).run(alltests())
| <commit_before><commit_msg>Set up run tests file.<commit_after>#!/usr/bin/env python3
#
# Affero GPL
#
import unittest
def alltests():
return unittest.TestSuite([
])
unittest.TextTestRunner(verbosity = 2).run(alltests())
| |
ce67500ec566784f6f8883e1ffcaef6ad768d810 | 2018/05/solve.py | 2018/05/solve.py | data = open("input.txt").read().strip()
import re
from collections import Counter
def solve1(data):
prevData = None
while data != prevData:
prevData = data
for a,b in zip(data, data[1:]):
if (a != b and a == b.lower()) or (a != b and a.lower() == b):
data = data.replace(a+b, "")
break
return len(data)
print(solve1("""dabAcCaCBAcCcaDA"""))
print(solve1(data))
def solve2(data):
min_len = len(data)
min_chr = None
for c in 'abcdefghijklmnopqrstubwxyz':
d = data.replace(c, "").replace(c.upper(), "")
l = solve1(d)
if l < min_len:
min_len = l
min_chr = c
return min_len
print(solve2("""dabAcCaCBAcCcaDA"""))
print(solve2(data))
| data = open("input.txt").read().strip()
import re
import string
from collections import Counter
def solve1(data):
prevData = None
while data != prevData:
prevData = data
for a,b in zip(data, data[1:]):
if (a != b and a == b.lower()) or (a != b and a.lower() == b):
data = data.replace(a+b, "")
break
return len(data)
print(solve1("""dabAcCaCBAcCcaDA"""))
print(solve1(data))
def solve2(data):
min_len = len(data)
for c in string.ascii_lowercase:
d = data.replace(c, "").replace(c.upper(), "")
l = solve1(d)
if l < min_len:
min_len = l
return min_len
print(solve2("""dabAcCaCBAcCcaDA"""))
print(solve2(data))
| Fix bug with omitting v | Fix bug with omitting v
| Python | mit | lamperi/aoc,lamperi/aoc,lamperi/aoc,lamperi/aoc,lamperi/aoc | data = open("input.txt").read().strip()
import re
from collections import Counter
def solve1(data):
prevData = None
while data != prevData:
prevData = data
for a,b in zip(data, data[1:]):
if (a != b and a == b.lower()) or (a != b and a.lower() == b):
data = data.replace(a+b, "")
break
return len(data)
print(solve1("""dabAcCaCBAcCcaDA"""))
print(solve1(data))
def solve2(data):
min_len = len(data)
min_chr = None
for c in 'abcdefghijklmnopqrstubwxyz':
d = data.replace(c, "").replace(c.upper(), "")
l = solve1(d)
if l < min_len:
min_len = l
min_chr = c
return min_len
print(solve2("""dabAcCaCBAcCcaDA"""))
print(solve2(data))
Fix bug with omitting v | data = open("input.txt").read().strip()
import re
import string
from collections import Counter
def solve1(data):
prevData = None
while data != prevData:
prevData = data
for a,b in zip(data, data[1:]):
if (a != b and a == b.lower()) or (a != b and a.lower() == b):
data = data.replace(a+b, "")
break
return len(data)
print(solve1("""dabAcCaCBAcCcaDA"""))
print(solve1(data))
def solve2(data):
min_len = len(data)
for c in string.ascii_lowercase:
d = data.replace(c, "").replace(c.upper(), "")
l = solve1(d)
if l < min_len:
min_len = l
return min_len
print(solve2("""dabAcCaCBAcCcaDA"""))
print(solve2(data))
| <commit_before>data = open("input.txt").read().strip()
import re
from collections import Counter
def solve1(data):
prevData = None
while data != prevData:
prevData = data
for a,b in zip(data, data[1:]):
if (a != b and a == b.lower()) or (a != b and a.lower() == b):
data = data.replace(a+b, "")
break
return len(data)
print(solve1("""dabAcCaCBAcCcaDA"""))
print(solve1(data))
def solve2(data):
min_len = len(data)
min_chr = None
for c in 'abcdefghijklmnopqrstubwxyz':
d = data.replace(c, "").replace(c.upper(), "")
l = solve1(d)
if l < min_len:
min_len = l
min_chr = c
return min_len
print(solve2("""dabAcCaCBAcCcaDA"""))
print(solve2(data))
<commit_msg>Fix bug with omitting v<commit_after> | data = open("input.txt").read().strip()
import re
import string
from collections import Counter
def solve1(data):
prevData = None
while data != prevData:
prevData = data
for a,b in zip(data, data[1:]):
if (a != b and a == b.lower()) or (a != b and a.lower() == b):
data = data.replace(a+b, "")
break
return len(data)
print(solve1("""dabAcCaCBAcCcaDA"""))
print(solve1(data))
def solve2(data):
min_len = len(data)
for c in string.ascii_lowercase:
d = data.replace(c, "").replace(c.upper(), "")
l = solve1(d)
if l < min_len:
min_len = l
return min_len
print(solve2("""dabAcCaCBAcCcaDA"""))
print(solve2(data))
| data = open("input.txt").read().strip()
import re
from collections import Counter
def solve1(data):
prevData = None
while data != prevData:
prevData = data
for a,b in zip(data, data[1:]):
if (a != b and a == b.lower()) or (a != b and a.lower() == b):
data = data.replace(a+b, "")
break
return len(data)
print(solve1("""dabAcCaCBAcCcaDA"""))
print(solve1(data))
def solve2(data):
min_len = len(data)
min_chr = None
for c in 'abcdefghijklmnopqrstubwxyz':
d = data.replace(c, "").replace(c.upper(), "")
l = solve1(d)
if l < min_len:
min_len = l
min_chr = c
return min_len
print(solve2("""dabAcCaCBAcCcaDA"""))
print(solve2(data))
Fix bug with omitting vdata = open("input.txt").read().strip()
import re
import string
from collections import Counter
def solve1(data):
prevData = None
while data != prevData:
prevData = data
for a,b in zip(data, data[1:]):
if (a != b and a == b.lower()) or (a != b and a.lower() == b):
data = data.replace(a+b, "")
break
return len(data)
print(solve1("""dabAcCaCBAcCcaDA"""))
print(solve1(data))
def solve2(data):
min_len = len(data)
for c in string.ascii_lowercase:
d = data.replace(c, "").replace(c.upper(), "")
l = solve1(d)
if l < min_len:
min_len = l
return min_len
print(solve2("""dabAcCaCBAcCcaDA"""))
print(solve2(data))
| <commit_before>data = open("input.txt").read().strip()
import re
from collections import Counter
def solve1(data):
prevData = None
while data != prevData:
prevData = data
for a,b in zip(data, data[1:]):
if (a != b and a == b.lower()) or (a != b and a.lower() == b):
data = data.replace(a+b, "")
break
return len(data)
print(solve1("""dabAcCaCBAcCcaDA"""))
print(solve1(data))
def solve2(data):
min_len = len(data)
min_chr = None
for c in 'abcdefghijklmnopqrstubwxyz':
d = data.replace(c, "").replace(c.upper(), "")
l = solve1(d)
if l < min_len:
min_len = l
min_chr = c
return min_len
print(solve2("""dabAcCaCBAcCcaDA"""))
print(solve2(data))
<commit_msg>Fix bug with omitting v<commit_after>data = open("input.txt").read().strip()
import re
import string
from collections import Counter
def solve1(data):
prevData = None
while data != prevData:
prevData = data
for a,b in zip(data, data[1:]):
if (a != b and a == b.lower()) or (a != b and a.lower() == b):
data = data.replace(a+b, "")
break
return len(data)
print(solve1("""dabAcCaCBAcCcaDA"""))
print(solve1(data))
def solve2(data):
min_len = len(data)
for c in string.ascii_lowercase:
d = data.replace(c, "").replace(c.upper(), "")
l = solve1(d)
if l < min_len:
min_len = l
return min_len
print(solve2("""dabAcCaCBAcCcaDA"""))
print(solve2(data))
|
640f54d769a01b3707591f76914c8e4cf5394eaa | micro/process_options.py | micro/process_options.py | import help_formatter
import argparse
def process_options():
parser = _make_options_parser()
return parser.parse_args()
def _make_options_parser():
parser = argparse.ArgumentParser(
prog='micro',
add_help=False,
formatter_class=help_formatter.HelpFormatter
)
parser.add_argument(
'-v',
'--version',
action='version',
help='- show the version message and exit',
version='Micro interpreter, v2.1\nCopyright (c) 2016 thewizardplusplus'
)
parser.add_argument(
'-h',
'--help',
action='help',
help='- show the help message and exit'
)
parser.add_argument(
'-t',
'--target',
choices=['tokens', 'preast', 'ast', 'evaluation'],
default='evaluation',
help='- set a target of a script processing'
)
parser.add_argument('script', nargs='?', default='-', help='- a script')
parser.add_argument(
'args',
nargs='*',
default=[],
help='- script arguments'
)
return parser
if __name__ == '__main__':
options = process_options()
print(options)
| import help_formatter
import argparse
def process_options():
parser = _make_options_parser()
return parser.parse_args()
def _make_options_parser():
parser = argparse.ArgumentParser(
prog='micro',
add_help=False,
formatter_class=help_formatter.HelpFormatter
)
parser.add_argument(
'-v',
'--version',
action='version',
help='- show the version message and exit',
version='Micro interpreter, v2.1\nCopyright (c) 2016, 2017 thewizardplusplus'
)
parser.add_argument(
'-h',
'--help',
action='help',
help='- show the help message and exit'
)
parser.add_argument(
'-t',
'--target',
choices=['tokens', 'preast', 'ast', 'evaluation'],
default='evaluation',
help='- set a target of a script processing'
)
parser.add_argument('script', nargs='?', default='-', help='- a script')
parser.add_argument(
'args',
nargs='*',
default=[],
help='- script arguments'
)
return parser
if __name__ == '__main__':
options = process_options()
print(options)
| Update copyright years of the interpreter | Update copyright years of the interpreter
| Python | mit | thewizardplusplus/micro,thewizardplusplus/micro,thewizardplusplus/micro | import help_formatter
import argparse
def process_options():
parser = _make_options_parser()
return parser.parse_args()
def _make_options_parser():
parser = argparse.ArgumentParser(
prog='micro',
add_help=False,
formatter_class=help_formatter.HelpFormatter
)
parser.add_argument(
'-v',
'--version',
action='version',
help='- show the version message and exit',
version='Micro interpreter, v2.1\nCopyright (c) 2016 thewizardplusplus'
)
parser.add_argument(
'-h',
'--help',
action='help',
help='- show the help message and exit'
)
parser.add_argument(
'-t',
'--target',
choices=['tokens', 'preast', 'ast', 'evaluation'],
default='evaluation',
help='- set a target of a script processing'
)
parser.add_argument('script', nargs='?', default='-', help='- a script')
parser.add_argument(
'args',
nargs='*',
default=[],
help='- script arguments'
)
return parser
if __name__ == '__main__':
options = process_options()
print(options)
Update copyright years of the interpreter | import help_formatter
import argparse
def process_options():
parser = _make_options_parser()
return parser.parse_args()
def _make_options_parser():
parser = argparse.ArgumentParser(
prog='micro',
add_help=False,
formatter_class=help_formatter.HelpFormatter
)
parser.add_argument(
'-v',
'--version',
action='version',
help='- show the version message and exit',
version='Micro interpreter, v2.1\nCopyright (c) 2016, 2017 thewizardplusplus'
)
parser.add_argument(
'-h',
'--help',
action='help',
help='- show the help message and exit'
)
parser.add_argument(
'-t',
'--target',
choices=['tokens', 'preast', 'ast', 'evaluation'],
default='evaluation',
help='- set a target of a script processing'
)
parser.add_argument('script', nargs='?', default='-', help='- a script')
parser.add_argument(
'args',
nargs='*',
default=[],
help='- script arguments'
)
return parser
if __name__ == '__main__':
options = process_options()
print(options)
| <commit_before>import help_formatter
import argparse
def process_options():
parser = _make_options_parser()
return parser.parse_args()
def _make_options_parser():
parser = argparse.ArgumentParser(
prog='micro',
add_help=False,
formatter_class=help_formatter.HelpFormatter
)
parser.add_argument(
'-v',
'--version',
action='version',
help='- show the version message and exit',
version='Micro interpreter, v2.1\nCopyright (c) 2016 thewizardplusplus'
)
parser.add_argument(
'-h',
'--help',
action='help',
help='- show the help message and exit'
)
parser.add_argument(
'-t',
'--target',
choices=['tokens', 'preast', 'ast', 'evaluation'],
default='evaluation',
help='- set a target of a script processing'
)
parser.add_argument('script', nargs='?', default='-', help='- a script')
parser.add_argument(
'args',
nargs='*',
default=[],
help='- script arguments'
)
return parser
if __name__ == '__main__':
options = process_options()
print(options)
<commit_msg>Update copyright years of the interpreter<commit_after> | import help_formatter
import argparse
def process_options():
parser = _make_options_parser()
return parser.parse_args()
def _make_options_parser():
parser = argparse.ArgumentParser(
prog='micro',
add_help=False,
formatter_class=help_formatter.HelpFormatter
)
parser.add_argument(
'-v',
'--version',
action='version',
help='- show the version message and exit',
version='Micro interpreter, v2.1\nCopyright (c) 2016, 2017 thewizardplusplus'
)
parser.add_argument(
'-h',
'--help',
action='help',
help='- show the help message and exit'
)
parser.add_argument(
'-t',
'--target',
choices=['tokens', 'preast', 'ast', 'evaluation'],
default='evaluation',
help='- set a target of a script processing'
)
parser.add_argument('script', nargs='?', default='-', help='- a script')
parser.add_argument(
'args',
nargs='*',
default=[],
help='- script arguments'
)
return parser
if __name__ == '__main__':
options = process_options()
print(options)
| import help_formatter
import argparse
def process_options():
parser = _make_options_parser()
return parser.parse_args()
def _make_options_parser():
parser = argparse.ArgumentParser(
prog='micro',
add_help=False,
formatter_class=help_formatter.HelpFormatter
)
parser.add_argument(
'-v',
'--version',
action='version',
help='- show the version message and exit',
version='Micro interpreter, v2.1\nCopyright (c) 2016 thewizardplusplus'
)
parser.add_argument(
'-h',
'--help',
action='help',
help='- show the help message and exit'
)
parser.add_argument(
'-t',
'--target',
choices=['tokens', 'preast', 'ast', 'evaluation'],
default='evaluation',
help='- set a target of a script processing'
)
parser.add_argument('script', nargs='?', default='-', help='- a script')
parser.add_argument(
'args',
nargs='*',
default=[],
help='- script arguments'
)
return parser
if __name__ == '__main__':
options = process_options()
print(options)
Update copyright years of the interpreterimport help_formatter
import argparse
def process_options():
parser = _make_options_parser()
return parser.parse_args()
def _make_options_parser():
parser = argparse.ArgumentParser(
prog='micro',
add_help=False,
formatter_class=help_formatter.HelpFormatter
)
parser.add_argument(
'-v',
'--version',
action='version',
help='- show the version message and exit',
version='Micro interpreter, v2.1\nCopyright (c) 2016, 2017 thewizardplusplus'
)
parser.add_argument(
'-h',
'--help',
action='help',
help='- show the help message and exit'
)
parser.add_argument(
'-t',
'--target',
choices=['tokens', 'preast', 'ast', 'evaluation'],
default='evaluation',
help='- set a target of a script processing'
)
parser.add_argument('script', nargs='?', default='-', help='- a script')
parser.add_argument(
'args',
nargs='*',
default=[],
help='- script arguments'
)
return parser
if __name__ == '__main__':
options = process_options()
print(options)
| <commit_before>import help_formatter
import argparse
def process_options():
parser = _make_options_parser()
return parser.parse_args()
def _make_options_parser():
parser = argparse.ArgumentParser(
prog='micro',
add_help=False,
formatter_class=help_formatter.HelpFormatter
)
parser.add_argument(
'-v',
'--version',
action='version',
help='- show the version message and exit',
version='Micro interpreter, v2.1\nCopyright (c) 2016 thewizardplusplus'
)
parser.add_argument(
'-h',
'--help',
action='help',
help='- show the help message and exit'
)
parser.add_argument(
'-t',
'--target',
choices=['tokens', 'preast', 'ast', 'evaluation'],
default='evaluation',
help='- set a target of a script processing'
)
parser.add_argument('script', nargs='?', default='-', help='- a script')
parser.add_argument(
'args',
nargs='*',
default=[],
help='- script arguments'
)
return parser
if __name__ == '__main__':
options = process_options()
print(options)
<commit_msg>Update copyright years of the interpreter<commit_after>import help_formatter
import argparse
def process_options():
parser = _make_options_parser()
return parser.parse_args()
def _make_options_parser():
parser = argparse.ArgumentParser(
prog='micro',
add_help=False,
formatter_class=help_formatter.HelpFormatter
)
parser.add_argument(
'-v',
'--version',
action='version',
help='- show the version message and exit',
version='Micro interpreter, v2.1\nCopyright (c) 2016, 2017 thewizardplusplus'
)
parser.add_argument(
'-h',
'--help',
action='help',
help='- show the help message and exit'
)
parser.add_argument(
'-t',
'--target',
choices=['tokens', 'preast', 'ast', 'evaluation'],
default='evaluation',
help='- set a target of a script processing'
)
parser.add_argument('script', nargs='?', default='-', help='- a script')
parser.add_argument(
'args',
nargs='*',
default=[],
help='- script arguments'
)
return parser
if __name__ == '__main__':
options = process_options()
print(options)
|
c43ddf1f36535604167e496508d242a15c813496 | roamer/main.py | roamer/main.py | #!/usr/bin/env python
"""
argh
"""
import os
from roamer.python_edit import file_editor
from roamer.directory import Directory
from roamer.edit_directory import EditDirectory
from roamer.engine import Engine
from roamer.record import Record
from roamer.constant import TRASH_DIR
def main():
"""
argh
"""
if not os.path.exists(TRASH_DIR):
os.makedirs(TRASH_DIR)
cwd = os.getcwd()
raw_entries = os.listdir(cwd)
directory = Directory(cwd, raw_entries)
output = file_editor(directory.text())
edit_directory = EditDirectory(cwd, output)
engine = Engine(directory, edit_directory)
print engine.print_commands()
engine.run_commands()
Record().add_dir(Directory(cwd, os.listdir(cwd)))
if __name__ == "__main__":
main()
| #!/usr/bin/env python
"""
argh
"""
import os
from roamer.python_edit import file_editor
from roamer.directory import Directory
from roamer.edit_directory import EditDirectory
from roamer.engine import Engine
from roamer.record import Record
from roamer.constant import TRASH_DIR
def main():
"""
argh
"""
if not os.path.exists(TRASH_DIR):
os.makedirs(TRASH_DIR)
cwd = os.getcwd()
raw_entries = os.listdir(cwd)
directory = Directory(cwd, raw_entries)
Record().add_dir(directory)
output = file_editor(directory.text())
edit_directory = EditDirectory(cwd, output)
engine = Engine(directory, edit_directory)
print engine.print_commands()
engine.run_commands()
Record().add_dir(Directory(cwd, os.listdir(cwd)))
if __name__ == "__main__":
main()
| Fix references not available after pulling up two instances of roamer | Fix references not available after pulling up two instances of roamer
| Python | mit | abaldwin88/roamer | #!/usr/bin/env python
"""
argh
"""
import os
from roamer.python_edit import file_editor
from roamer.directory import Directory
from roamer.edit_directory import EditDirectory
from roamer.engine import Engine
from roamer.record import Record
from roamer.constant import TRASH_DIR
def main():
"""
argh
"""
if not os.path.exists(TRASH_DIR):
os.makedirs(TRASH_DIR)
cwd = os.getcwd()
raw_entries = os.listdir(cwd)
directory = Directory(cwd, raw_entries)
output = file_editor(directory.text())
edit_directory = EditDirectory(cwd, output)
engine = Engine(directory, edit_directory)
print engine.print_commands()
engine.run_commands()
Record().add_dir(Directory(cwd, os.listdir(cwd)))
if __name__ == "__main__":
main()
Fix references not available after pulling up two instances of roamer | #!/usr/bin/env python
"""
argh
"""
import os
from roamer.python_edit import file_editor
from roamer.directory import Directory
from roamer.edit_directory import EditDirectory
from roamer.engine import Engine
from roamer.record import Record
from roamer.constant import TRASH_DIR
def main():
"""
argh
"""
if not os.path.exists(TRASH_DIR):
os.makedirs(TRASH_DIR)
cwd = os.getcwd()
raw_entries = os.listdir(cwd)
directory = Directory(cwd, raw_entries)
Record().add_dir(directory)
output = file_editor(directory.text())
edit_directory = EditDirectory(cwd, output)
engine = Engine(directory, edit_directory)
print engine.print_commands()
engine.run_commands()
Record().add_dir(Directory(cwd, os.listdir(cwd)))
if __name__ == "__main__":
main()
| <commit_before>#!/usr/bin/env python
"""
argh
"""
import os
from roamer.python_edit import file_editor
from roamer.directory import Directory
from roamer.edit_directory import EditDirectory
from roamer.engine import Engine
from roamer.record import Record
from roamer.constant import TRASH_DIR
def main():
"""
argh
"""
if not os.path.exists(TRASH_DIR):
os.makedirs(TRASH_DIR)
cwd = os.getcwd()
raw_entries = os.listdir(cwd)
directory = Directory(cwd, raw_entries)
output = file_editor(directory.text())
edit_directory = EditDirectory(cwd, output)
engine = Engine(directory, edit_directory)
print engine.print_commands()
engine.run_commands()
Record().add_dir(Directory(cwd, os.listdir(cwd)))
if __name__ == "__main__":
main()
<commit_msg>Fix references not available after pulling up two instances of roamer<commit_after> | #!/usr/bin/env python
"""
argh
"""
import os
from roamer.python_edit import file_editor
from roamer.directory import Directory
from roamer.edit_directory import EditDirectory
from roamer.engine import Engine
from roamer.record import Record
from roamer.constant import TRASH_DIR
def main():
"""
argh
"""
if not os.path.exists(TRASH_DIR):
os.makedirs(TRASH_DIR)
cwd = os.getcwd()
raw_entries = os.listdir(cwd)
directory = Directory(cwd, raw_entries)
Record().add_dir(directory)
output = file_editor(directory.text())
edit_directory = EditDirectory(cwd, output)
engine = Engine(directory, edit_directory)
print engine.print_commands()
engine.run_commands()
Record().add_dir(Directory(cwd, os.listdir(cwd)))
if __name__ == "__main__":
main()
| #!/usr/bin/env python
"""
argh
"""
import os
from roamer.python_edit import file_editor
from roamer.directory import Directory
from roamer.edit_directory import EditDirectory
from roamer.engine import Engine
from roamer.record import Record
from roamer.constant import TRASH_DIR
def main():
"""
argh
"""
if not os.path.exists(TRASH_DIR):
os.makedirs(TRASH_DIR)
cwd = os.getcwd()
raw_entries = os.listdir(cwd)
directory = Directory(cwd, raw_entries)
output = file_editor(directory.text())
edit_directory = EditDirectory(cwd, output)
engine = Engine(directory, edit_directory)
print engine.print_commands()
engine.run_commands()
Record().add_dir(Directory(cwd, os.listdir(cwd)))
if __name__ == "__main__":
main()
Fix references not available after pulling up two instances of roamer#!/usr/bin/env python
"""
argh
"""
import os
from roamer.python_edit import file_editor
from roamer.directory import Directory
from roamer.edit_directory import EditDirectory
from roamer.engine import Engine
from roamer.record import Record
from roamer.constant import TRASH_DIR
def main():
"""
argh
"""
if not os.path.exists(TRASH_DIR):
os.makedirs(TRASH_DIR)
cwd = os.getcwd()
raw_entries = os.listdir(cwd)
directory = Directory(cwd, raw_entries)
Record().add_dir(directory)
output = file_editor(directory.text())
edit_directory = EditDirectory(cwd, output)
engine = Engine(directory, edit_directory)
print engine.print_commands()
engine.run_commands()
Record().add_dir(Directory(cwd, os.listdir(cwd)))
if __name__ == "__main__":
main()
| <commit_before>#!/usr/bin/env python
"""
argh
"""
import os
from roamer.python_edit import file_editor
from roamer.directory import Directory
from roamer.edit_directory import EditDirectory
from roamer.engine import Engine
from roamer.record import Record
from roamer.constant import TRASH_DIR
def main():
"""
argh
"""
if not os.path.exists(TRASH_DIR):
os.makedirs(TRASH_DIR)
cwd = os.getcwd()
raw_entries = os.listdir(cwd)
directory = Directory(cwd, raw_entries)
output = file_editor(directory.text())
edit_directory = EditDirectory(cwd, output)
engine = Engine(directory, edit_directory)
print engine.print_commands()
engine.run_commands()
Record().add_dir(Directory(cwd, os.listdir(cwd)))
if __name__ == "__main__":
main()
<commit_msg>Fix references not available after pulling up two instances of roamer<commit_after>#!/usr/bin/env python
"""
argh
"""
import os
from roamer.python_edit import file_editor
from roamer.directory import Directory
from roamer.edit_directory import EditDirectory
from roamer.engine import Engine
from roamer.record import Record
from roamer.constant import TRASH_DIR
def main():
"""
argh
"""
if not os.path.exists(TRASH_DIR):
os.makedirs(TRASH_DIR)
cwd = os.getcwd()
raw_entries = os.listdir(cwd)
directory = Directory(cwd, raw_entries)
Record().add_dir(directory)
output = file_editor(directory.text())
edit_directory = EditDirectory(cwd, output)
engine = Engine(directory, edit_directory)
print engine.print_commands()
engine.run_commands()
Record().add_dir(Directory(cwd, os.listdir(cwd)))
if __name__ == "__main__":
main()
|
0fa565b79a2776cb2878d6a44299b25764150f15 | pywind/__init__.py | pywind/__init__.py | """ pywind module.
For more information visit https://github.com/zathras777/pywind
"""
__version__ = '1.1.0'
| """ pywind module.
For more information visit https://github.com/zathras777/pywind
"""
__version__ = '1.1.1'
| Update to next version number following release of 1.1.0 | Update to next version number following release of 1.1.0
| Python | unlicense | zathras777/pywind,zathras777/pywind | """ pywind module.
For more information visit https://github.com/zathras777/pywind
"""
__version__ = '1.1.0'
Update to next version number following release of 1.1.0 | """ pywind module.
For more information visit https://github.com/zathras777/pywind
"""
__version__ = '1.1.1'
| <commit_before>""" pywind module.
For more information visit https://github.com/zathras777/pywind
"""
__version__ = '1.1.0'
<commit_msg>Update to next version number following release of 1.1.0<commit_after> | """ pywind module.
For more information visit https://github.com/zathras777/pywind
"""
__version__ = '1.1.1'
| """ pywind module.
For more information visit https://github.com/zathras777/pywind
"""
__version__ = '1.1.0'
Update to next version number following release of 1.1.0""" pywind module.
For more information visit https://github.com/zathras777/pywind
"""
__version__ = '1.1.1'
| <commit_before>""" pywind module.
For more information visit https://github.com/zathras777/pywind
"""
__version__ = '1.1.0'
<commit_msg>Update to next version number following release of 1.1.0<commit_after>""" pywind module.
For more information visit https://github.com/zathras777/pywind
"""
__version__ = '1.1.1'
|
2aef43fcd44f075ff718475ea57ae23711de02aa | event/models.py | event/models.py | from django.db import models
class Artist(models.Model):
name = models.CharField(max_length=100)
image_url = models.URLField(blank=True)
thumb_url = models.URLField(blank=True)
events = models.ManyToManyField(
'event.Event',
related_name='artists',
blank=True,
)
def __str__(self):
return self.name
class Event(models.Model):
title = models.CharField(max_length=200)
datetime = models.DateTimeField()
venue = models.ForeignKey(
'event.Venue',
related_name='events',
on_delete=models.CASCADE,
)
def __str__(self):
return self.title
class Venue(models.Model):
name = models.CharField(max_length=100)
city = models.CharField(max_length=100)
country = models.CharField(max_length=100)
def __str__(self):
return self.name
| from django.db import models
class Artist(models.Model):
name = models.CharField(max_length=100)
image_url = models.URLField(blank=True)
thumb_url = models.URLField(blank=True)
events = models.ManyToManyField(
'event.Event',
related_name='artists',
blank=True,
)
class Meta:
ordering = ['name']
def __str__(self):
return self.name
class Event(models.Model):
title = models.CharField(max_length=200)
datetime = models.DateTimeField()
venue = models.ForeignKey(
'event.Venue',
related_name='events',
on_delete=models.CASCADE,
)
def __str__(self):
return self.title
class Venue(models.Model):
name = models.CharField(max_length=100)
city = models.CharField(max_length=100)
country = models.CharField(max_length=100)
def __str__(self):
return self.name
| Add Artist ordering by name | Add Artist ordering by name
| Python | mit | FedorSelitsky/eventrack,FedorSelitsky/eventrack,FedorSelitsky/eventrack,FedorSelitsky/eventrack | from django.db import models
class Artist(models.Model):
name = models.CharField(max_length=100)
image_url = models.URLField(blank=True)
thumb_url = models.URLField(blank=True)
events = models.ManyToManyField(
'event.Event',
related_name='artists',
blank=True,
)
def __str__(self):
return self.name
class Event(models.Model):
title = models.CharField(max_length=200)
datetime = models.DateTimeField()
venue = models.ForeignKey(
'event.Venue',
related_name='events',
on_delete=models.CASCADE,
)
def __str__(self):
return self.title
class Venue(models.Model):
name = models.CharField(max_length=100)
city = models.CharField(max_length=100)
country = models.CharField(max_length=100)
def __str__(self):
return self.name
Add Artist ordering by name | from django.db import models
class Artist(models.Model):
name = models.CharField(max_length=100)
image_url = models.URLField(blank=True)
thumb_url = models.URLField(blank=True)
events = models.ManyToManyField(
'event.Event',
related_name='artists',
blank=True,
)
class Meta:
ordering = ['name']
def __str__(self):
return self.name
class Event(models.Model):
title = models.CharField(max_length=200)
datetime = models.DateTimeField()
venue = models.ForeignKey(
'event.Venue',
related_name='events',
on_delete=models.CASCADE,
)
def __str__(self):
return self.title
class Venue(models.Model):
name = models.CharField(max_length=100)
city = models.CharField(max_length=100)
country = models.CharField(max_length=100)
def __str__(self):
return self.name
| <commit_before>from django.db import models
class Artist(models.Model):
name = models.CharField(max_length=100)
image_url = models.URLField(blank=True)
thumb_url = models.URLField(blank=True)
events = models.ManyToManyField(
'event.Event',
related_name='artists',
blank=True,
)
def __str__(self):
return self.name
class Event(models.Model):
title = models.CharField(max_length=200)
datetime = models.DateTimeField()
venue = models.ForeignKey(
'event.Venue',
related_name='events',
on_delete=models.CASCADE,
)
def __str__(self):
return self.title
class Venue(models.Model):
name = models.CharField(max_length=100)
city = models.CharField(max_length=100)
country = models.CharField(max_length=100)
def __str__(self):
return self.name
<commit_msg>Add Artist ordering by name<commit_after> | from django.db import models
class Artist(models.Model):
name = models.CharField(max_length=100)
image_url = models.URLField(blank=True)
thumb_url = models.URLField(blank=True)
events = models.ManyToManyField(
'event.Event',
related_name='artists',
blank=True,
)
class Meta:
ordering = ['name']
def __str__(self):
return self.name
class Event(models.Model):
title = models.CharField(max_length=200)
datetime = models.DateTimeField()
venue = models.ForeignKey(
'event.Venue',
related_name='events',
on_delete=models.CASCADE,
)
def __str__(self):
return self.title
class Venue(models.Model):
name = models.CharField(max_length=100)
city = models.CharField(max_length=100)
country = models.CharField(max_length=100)
def __str__(self):
return self.name
| from django.db import models
class Artist(models.Model):
name = models.CharField(max_length=100)
image_url = models.URLField(blank=True)
thumb_url = models.URLField(blank=True)
events = models.ManyToManyField(
'event.Event',
related_name='artists',
blank=True,
)
def __str__(self):
return self.name
class Event(models.Model):
title = models.CharField(max_length=200)
datetime = models.DateTimeField()
venue = models.ForeignKey(
'event.Venue',
related_name='events',
on_delete=models.CASCADE,
)
def __str__(self):
return self.title
class Venue(models.Model):
name = models.CharField(max_length=100)
city = models.CharField(max_length=100)
country = models.CharField(max_length=100)
def __str__(self):
return self.name
Add Artist ordering by namefrom django.db import models
class Artist(models.Model):
name = models.CharField(max_length=100)
image_url = models.URLField(blank=True)
thumb_url = models.URLField(blank=True)
events = models.ManyToManyField(
'event.Event',
related_name='artists',
blank=True,
)
class Meta:
ordering = ['name']
def __str__(self):
return self.name
class Event(models.Model):
title = models.CharField(max_length=200)
datetime = models.DateTimeField()
venue = models.ForeignKey(
'event.Venue',
related_name='events',
on_delete=models.CASCADE,
)
def __str__(self):
return self.title
class Venue(models.Model):
name = models.CharField(max_length=100)
city = models.CharField(max_length=100)
country = models.CharField(max_length=100)
def __str__(self):
return self.name
| <commit_before>from django.db import models
class Artist(models.Model):
name = models.CharField(max_length=100)
image_url = models.URLField(blank=True)
thumb_url = models.URLField(blank=True)
events = models.ManyToManyField(
'event.Event',
related_name='artists',
blank=True,
)
def __str__(self):
return self.name
class Event(models.Model):
title = models.CharField(max_length=200)
datetime = models.DateTimeField()
venue = models.ForeignKey(
'event.Venue',
related_name='events',
on_delete=models.CASCADE,
)
def __str__(self):
return self.title
class Venue(models.Model):
name = models.CharField(max_length=100)
city = models.CharField(max_length=100)
country = models.CharField(max_length=100)
def __str__(self):
return self.name
<commit_msg>Add Artist ordering by name<commit_after>from django.db import models
class Artist(models.Model):
name = models.CharField(max_length=100)
image_url = models.URLField(blank=True)
thumb_url = models.URLField(blank=True)
events = models.ManyToManyField(
'event.Event',
related_name='artists',
blank=True,
)
class Meta:
ordering = ['name']
def __str__(self):
return self.name
class Event(models.Model):
title = models.CharField(max_length=200)
datetime = models.DateTimeField()
venue = models.ForeignKey(
'event.Venue',
related_name='events',
on_delete=models.CASCADE,
)
def __str__(self):
return self.title
class Venue(models.Model):
name = models.CharField(max_length=100)
city = models.CharField(max_length=100)
country = models.CharField(max_length=100)
def __str__(self):
return self.name
|
aebc3440c98ee2b4cc5f880d648e106e1f9d6b9d | source/urls.py | source/urls.py | from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from task.views import *
from userprofile.views import *
router = routers.DefaultRouter()
router.register(r'tasks', TaskListViewSet)
router.register(r'tolausers', TolaUserViewset)
router.register(r'countries', CountryViewSet)
router.register(r'organizations', OrganizationViewset)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('', include('social.apps.django_app.urls', namespace='social')),
url(r'^api/auth/', include('userprofile.urls')),
#url(r'^api/', include('task.urls')),
#rest framework
url(r'^api/', include(router.urls)),
]
| from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from task.views import *
from userprofile.views import *
router = routers.DefaultRouter()
router.register(r'tasks', TaskListViewSet, base_name="my_task")
router.register(r'tolausers', TolaUserViewset)
router.register(r'countries', CountryViewSet)
router.register(r'organizations', OrganizationViewset)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('', include('social.apps.django_app.urls', namespace='social')),
url(r'^api/auth/', include('userprofile.urls')),
#url(r'^api/', include('task.urls')),
#rest framework
url(r'^api/', include(router.urls)),
]
| Add the base_name to the API routers for the custom query_set | Add the base_name to the API routers for the custom query_set
| Python | apache-2.0 | toladata/TolaProfile,toladata/TolaProfile,toladata/TolaProfile,toladata/TolaProfile | from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from task.views import *
from userprofile.views import *
router = routers.DefaultRouter()
router.register(r'tasks', TaskListViewSet)
router.register(r'tolausers', TolaUserViewset)
router.register(r'countries', CountryViewSet)
router.register(r'organizations', OrganizationViewset)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('', include('social.apps.django_app.urls', namespace='social')),
url(r'^api/auth/', include('userprofile.urls')),
#url(r'^api/', include('task.urls')),
#rest framework
url(r'^api/', include(router.urls)),
]
Add the base_name to the API routers for the custom query_set | from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from task.views import *
from userprofile.views import *
router = routers.DefaultRouter()
router.register(r'tasks', TaskListViewSet, base_name="my_task")
router.register(r'tolausers', TolaUserViewset)
router.register(r'countries', CountryViewSet)
router.register(r'organizations', OrganizationViewset)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('', include('social.apps.django_app.urls', namespace='social')),
url(r'^api/auth/', include('userprofile.urls')),
#url(r'^api/', include('task.urls')),
#rest framework
url(r'^api/', include(router.urls)),
]
| <commit_before>from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from task.views import *
from userprofile.views import *
router = routers.DefaultRouter()
router.register(r'tasks', TaskListViewSet)
router.register(r'tolausers', TolaUserViewset)
router.register(r'countries', CountryViewSet)
router.register(r'organizations', OrganizationViewset)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('', include('social.apps.django_app.urls', namespace='social')),
url(r'^api/auth/', include('userprofile.urls')),
#url(r'^api/', include('task.urls')),
#rest framework
url(r'^api/', include(router.urls)),
]
<commit_msg>Add the base_name to the API routers for the custom query_set<commit_after> | from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from task.views import *
from userprofile.views import *
router = routers.DefaultRouter()
router.register(r'tasks', TaskListViewSet, base_name="my_task")
router.register(r'tolausers', TolaUserViewset)
router.register(r'countries', CountryViewSet)
router.register(r'organizations', OrganizationViewset)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('', include('social.apps.django_app.urls', namespace='social')),
url(r'^api/auth/', include('userprofile.urls')),
#url(r'^api/', include('task.urls')),
#rest framework
url(r'^api/', include(router.urls)),
]
| from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from task.views import *
from userprofile.views import *
router = routers.DefaultRouter()
router.register(r'tasks', TaskListViewSet)
router.register(r'tolausers', TolaUserViewset)
router.register(r'countries', CountryViewSet)
router.register(r'organizations', OrganizationViewset)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('', include('social.apps.django_app.urls', namespace='social')),
url(r'^api/auth/', include('userprofile.urls')),
#url(r'^api/', include('task.urls')),
#rest framework
url(r'^api/', include(router.urls)),
]
Add the base_name to the API routers for the custom query_setfrom django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from task.views import *
from userprofile.views import *
router = routers.DefaultRouter()
router.register(r'tasks', TaskListViewSet, base_name="my_task")
router.register(r'tolausers', TolaUserViewset)
router.register(r'countries', CountryViewSet)
router.register(r'organizations', OrganizationViewset)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('', include('social.apps.django_app.urls', namespace='social')),
url(r'^api/auth/', include('userprofile.urls')),
#url(r'^api/', include('task.urls')),
#rest framework
url(r'^api/', include(router.urls)),
]
| <commit_before>from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from task.views import *
from userprofile.views import *
router = routers.DefaultRouter()
router.register(r'tasks', TaskListViewSet)
router.register(r'tolausers', TolaUserViewset)
router.register(r'countries', CountryViewSet)
router.register(r'organizations', OrganizationViewset)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('', include('social.apps.django_app.urls', namespace='social')),
url(r'^api/auth/', include('userprofile.urls')),
#url(r'^api/', include('task.urls')),
#rest framework
url(r'^api/', include(router.urls)),
]
<commit_msg>Add the base_name to the API routers for the custom query_set<commit_after>from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from task.views import *
from userprofile.views import *
router = routers.DefaultRouter()
router.register(r'tasks', TaskListViewSet, base_name="my_task")
router.register(r'tolausers', TolaUserViewset)
router.register(r'countries', CountryViewSet)
router.register(r'organizations', OrganizationViewset)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('', include('social.apps.django_app.urls', namespace='social')),
url(r'^api/auth/', include('userprofile.urls')),
#url(r'^api/', include('task.urls')),
#rest framework
url(r'^api/', include(router.urls)),
]
|
a099eab75245005527e03fb5278a49a6d565c8f9 | wagtailstartproject/project_template/tests/test_selenium/test_pages.py | wagtailstartproject/project_template/tests/test_selenium/test_pages.py | from wagtail.wagtailcore.models import Page
from .base import SeleniumTestCase
class PagesTest(SeleniumTestCase):
fixtures = ['basic_site.json']
def test_wagtail_pages(self):
"""Check if all Wagtail pages can be retrieved"""
pages = Page.objects.live()
for page in pages:
url = page.relative_url(page.get_site())
if url is not None:
self.get(url)
self.assert_status_code('200')
| from wagtail.wagtailcore.models import Page
from .base import SeleniumTestCase
class PagesTest(SeleniumTestCase):
def test_wagtail_pages(self):
"""Check if all Wagtail pages can be retrieved"""
pages = Page.objects.live()
for page in pages:
url = page.relative_url(page.get_site())
if url is not None:
self.get(url)
self.assert_status_code('200')
| Remove unnecessary fixtures attribute, already set by base class. | Remove unnecessary fixtures attribute, already set by base class.
| Python | mit | leukeleu/wagtail-startproject,leukeleu/wagtail-startproject | from wagtail.wagtailcore.models import Page
from .base import SeleniumTestCase
class PagesTest(SeleniumTestCase):
fixtures = ['basic_site.json']
def test_wagtail_pages(self):
"""Check if all Wagtail pages can be retrieved"""
pages = Page.objects.live()
for page in pages:
url = page.relative_url(page.get_site())
if url is not None:
self.get(url)
self.assert_status_code('200')
Remove unnecessary fixtures attribute, already set by base class. | from wagtail.wagtailcore.models import Page
from .base import SeleniumTestCase
class PagesTest(SeleniumTestCase):
def test_wagtail_pages(self):
"""Check if all Wagtail pages can be retrieved"""
pages = Page.objects.live()
for page in pages:
url = page.relative_url(page.get_site())
if url is not None:
self.get(url)
self.assert_status_code('200')
| <commit_before>from wagtail.wagtailcore.models import Page
from .base import SeleniumTestCase
class PagesTest(SeleniumTestCase):
fixtures = ['basic_site.json']
def test_wagtail_pages(self):
"""Check if all Wagtail pages can be retrieved"""
pages = Page.objects.live()
for page in pages:
url = page.relative_url(page.get_site())
if url is not None:
self.get(url)
self.assert_status_code('200')
<commit_msg>Remove unnecessary fixtures attribute, already set by base class.<commit_after> | from wagtail.wagtailcore.models import Page
from .base import SeleniumTestCase
class PagesTest(SeleniumTestCase):
def test_wagtail_pages(self):
"""Check if all Wagtail pages can be retrieved"""
pages = Page.objects.live()
for page in pages:
url = page.relative_url(page.get_site())
if url is not None:
self.get(url)
self.assert_status_code('200')
| from wagtail.wagtailcore.models import Page
from .base import SeleniumTestCase
class PagesTest(SeleniumTestCase):
fixtures = ['basic_site.json']
def test_wagtail_pages(self):
"""Check if all Wagtail pages can be retrieved"""
pages = Page.objects.live()
for page in pages:
url = page.relative_url(page.get_site())
if url is not None:
self.get(url)
self.assert_status_code('200')
Remove unnecessary fixtures attribute, already set by base class.from wagtail.wagtailcore.models import Page
from .base import SeleniumTestCase
class PagesTest(SeleniumTestCase):
def test_wagtail_pages(self):
"""Check if all Wagtail pages can be retrieved"""
pages = Page.objects.live()
for page in pages:
url = page.relative_url(page.get_site())
if url is not None:
self.get(url)
self.assert_status_code('200')
| <commit_before>from wagtail.wagtailcore.models import Page
from .base import SeleniumTestCase
class PagesTest(SeleniumTestCase):
fixtures = ['basic_site.json']
def test_wagtail_pages(self):
"""Check if all Wagtail pages can be retrieved"""
pages = Page.objects.live()
for page in pages:
url = page.relative_url(page.get_site())
if url is not None:
self.get(url)
self.assert_status_code('200')
<commit_msg>Remove unnecessary fixtures attribute, already set by base class.<commit_after>from wagtail.wagtailcore.models import Page
from .base import SeleniumTestCase
class PagesTest(SeleniumTestCase):
def test_wagtail_pages(self):
"""Check if all Wagtail pages can be retrieved"""
pages = Page.objects.live()
for page in pages:
url = page.relative_url(page.get_site())
if url is not None:
self.get(url)
self.assert_status_code('200')
|
104da4df7e0cd09d32457cf56fc00dc96fcdbdac | euler/p005.py | euler/p005.py | """Solution to Project Euler Problem 5
https://projecteuler.net/problem=5
"""
from fractions import gcd
from functools import reduce
MAXIMUM = 20
def compute(maximum=MAXIMUM):
"""Compute the LCM of all integers from 1 to `maximum`."""
return int(reduce(lambda x, y: (x*y)/gcd(x, y), range(1, maximum + 1)))
| """Solution to Project Euler Problem 5
https://projecteuler.net/problem=5
gcd, lcm, and lcmm functions by J.F. Sebastian.
http://stackoverflow.com/a/147539/6119465
"""
from functools import reduce
MAXIMUM = 20
def gcd(num1, num2):
"""Return greatest common divisor using Euclid's Algorithm."""
while num2:
num1, num2 = num2, num1 % num2
return num1
def lcm(num1, num2):
"""Return lowest common multiple."""
return num1 * num2 // gcd(num1, num2)
def lcmm(*args):
"""Return LCM of args."""
return reduce(lcm, args)
def compute(maximum=MAXIMUM):
"""Compute the LCM of all integers from 1 to `maximum`."""
return lcmm(*range(1, maximum + 1))
| Replace deprecated fractions.gcd with Euclid's Algorithm | Replace deprecated fractions.gcd with Euclid's Algorithm
| Python | mit | 2Cubed/ProjectEuler | """Solution to Project Euler Problem 5
https://projecteuler.net/problem=5
"""
from fractions import gcd
from functools import reduce
MAXIMUM = 20
def compute(maximum=MAXIMUM):
"""Compute the LCM of all integers from 1 to `maximum`."""
return int(reduce(lambda x, y: (x*y)/gcd(x, y), range(1, maximum + 1)))
Replace deprecated fractions.gcd with Euclid's Algorithm | """Solution to Project Euler Problem 5
https://projecteuler.net/problem=5
gcd, lcm, and lcmm functions by J.F. Sebastian.
http://stackoverflow.com/a/147539/6119465
"""
from functools import reduce
MAXIMUM = 20
def gcd(num1, num2):
"""Return greatest common divisor using Euclid's Algorithm."""
while num2:
num1, num2 = num2, num1 % num2
return num1
def lcm(num1, num2):
"""Return lowest common multiple."""
return num1 * num2 // gcd(num1, num2)
def lcmm(*args):
"""Return LCM of args."""
return reduce(lcm, args)
def compute(maximum=MAXIMUM):
"""Compute the LCM of all integers from 1 to `maximum`."""
return lcmm(*range(1, maximum + 1))
| <commit_before>"""Solution to Project Euler Problem 5
https://projecteuler.net/problem=5
"""
from fractions import gcd
from functools import reduce
MAXIMUM = 20
def compute(maximum=MAXIMUM):
"""Compute the LCM of all integers from 1 to `maximum`."""
return int(reduce(lambda x, y: (x*y)/gcd(x, y), range(1, maximum + 1)))
<commit_msg>Replace deprecated fractions.gcd with Euclid's Algorithm<commit_after> | """Solution to Project Euler Problem 5
https://projecteuler.net/problem=5
gcd, lcm, and lcmm functions by J.F. Sebastian.
http://stackoverflow.com/a/147539/6119465
"""
from functools import reduce
MAXIMUM = 20
def gcd(num1, num2):
"""Return greatest common divisor using Euclid's Algorithm."""
while num2:
num1, num2 = num2, num1 % num2
return num1
def lcm(num1, num2):
"""Return lowest common multiple."""
return num1 * num2 // gcd(num1, num2)
def lcmm(*args):
"""Return LCM of args."""
return reduce(lcm, args)
def compute(maximum=MAXIMUM):
"""Compute the LCM of all integers from 1 to `maximum`."""
return lcmm(*range(1, maximum + 1))
| """Solution to Project Euler Problem 5
https://projecteuler.net/problem=5
"""
from fractions import gcd
from functools import reduce
MAXIMUM = 20
def compute(maximum=MAXIMUM):
"""Compute the LCM of all integers from 1 to `maximum`."""
return int(reduce(lambda x, y: (x*y)/gcd(x, y), range(1, maximum + 1)))
Replace deprecated fractions.gcd with Euclid's Algorithm"""Solution to Project Euler Problem 5
https://projecteuler.net/problem=5
gcd, lcm, and lcmm functions by J.F. Sebastian.
http://stackoverflow.com/a/147539/6119465
"""
from functools import reduce
MAXIMUM = 20
def gcd(num1, num2):
"""Return greatest common divisor using Euclid's Algorithm."""
while num2:
num1, num2 = num2, num1 % num2
return num1
def lcm(num1, num2):
"""Return lowest common multiple."""
return num1 * num2 // gcd(num1, num2)
def lcmm(*args):
"""Return LCM of args."""
return reduce(lcm, args)
def compute(maximum=MAXIMUM):
"""Compute the LCM of all integers from 1 to `maximum`."""
return lcmm(*range(1, maximum + 1))
| <commit_before>"""Solution to Project Euler Problem 5
https://projecteuler.net/problem=5
"""
from fractions import gcd
from functools import reduce
MAXIMUM = 20
def compute(maximum=MAXIMUM):
"""Compute the LCM of all integers from 1 to `maximum`."""
return int(reduce(lambda x, y: (x*y)/gcd(x, y), range(1, maximum + 1)))
<commit_msg>Replace deprecated fractions.gcd with Euclid's Algorithm<commit_after>"""Solution to Project Euler Problem 5
https://projecteuler.net/problem=5
gcd, lcm, and lcmm functions by J.F. Sebastian.
http://stackoverflow.com/a/147539/6119465
"""
from functools import reduce
MAXIMUM = 20
def gcd(num1, num2):
"""Return greatest common divisor using Euclid's Algorithm."""
while num2:
num1, num2 = num2, num1 % num2
return num1
def lcm(num1, num2):
"""Return lowest common multiple."""
return num1 * num2 // gcd(num1, num2)
def lcmm(*args):
"""Return LCM of args."""
return reduce(lcm, args)
def compute(maximum=MAXIMUM):
"""Compute the LCM of all integers from 1 to `maximum`."""
return lcmm(*range(1, maximum + 1))
|
740762be1565690f78111861afe3152bdab4fadc | tests/test_soi.py | tests/test_soi.py | import os
import numpy as np
import pandas as pd
import unittest
from urllib2 import urlopen
from bom_data_parser import read_soi_html
class SOITest(unittest.TestCase):
def setUp(self):
self.test_soi_file = os.path.join(os.path.dirname(__file__), 'data', 'SOI', 'soiplaintext.html')
def test_soi(self):
with open(self.test_soi_file, 'r') as soi_file:
soi_data = read_soi_html(soi_file)
self.assertTrue('soi' in soi_data.columns)
self.assertEqual(soi_data.ix['1876-01'], 11.3)
self.assertEqual(soi_data.ix['1984-12'], -1.4)
self.assertEqual(soi_data.ix['2015-01'], 7.8)
| import os
import numpy as np
import pandas as pd
import unittest
from urllib2 import urlopen
from bom_data_parser import read_soi_html
class SOITest(unittest.TestCase):
def setUp(self):
self.test_soi_file = os.path.join(os.path.dirname(__file__), 'data', 'SOI', 'soiplaintext.html')
def test_soi(self):
with open(self.test_soi_file, 'r') as soi_file:
soi_data = read_soi_html(soi_file)
self.assertTrue('soi' in soi_data.columns)
self.assertEqual(soi_data.ix['1876-01'].values.item(), 11.3)
self.assertEqual(soi_data.ix['1984-12'].values.item(), -1.4)
self.assertEqual(soi_data.ix['2015-01'].values.item(), -7.8)
| Change unit test syntax for pandas > 0.12.0 compat | Change unit test syntax for pandas > 0.12.0 compat
| Python | bsd-3-clause | amacd31/bom_data_parser,amacd31/bom_data_parser | import os
import numpy as np
import pandas as pd
import unittest
from urllib2 import urlopen
from bom_data_parser import read_soi_html
class SOITest(unittest.TestCase):
def setUp(self):
self.test_soi_file = os.path.join(os.path.dirname(__file__), 'data', 'SOI', 'soiplaintext.html')
def test_soi(self):
with open(self.test_soi_file, 'r') as soi_file:
soi_data = read_soi_html(soi_file)
self.assertTrue('soi' in soi_data.columns)
self.assertEqual(soi_data.ix['1876-01'], 11.3)
self.assertEqual(soi_data.ix['1984-12'], -1.4)
self.assertEqual(soi_data.ix['2015-01'], 7.8)
Change unit test syntax for pandas > 0.12.0 compat | import os
import numpy as np
import pandas as pd
import unittest
from urllib2 import urlopen
from bom_data_parser import read_soi_html
class SOITest(unittest.TestCase):
def setUp(self):
self.test_soi_file = os.path.join(os.path.dirname(__file__), 'data', 'SOI', 'soiplaintext.html')
def test_soi(self):
with open(self.test_soi_file, 'r') as soi_file:
soi_data = read_soi_html(soi_file)
self.assertTrue('soi' in soi_data.columns)
self.assertEqual(soi_data.ix['1876-01'].values.item(), 11.3)
self.assertEqual(soi_data.ix['1984-12'].values.item(), -1.4)
self.assertEqual(soi_data.ix['2015-01'].values.item(), -7.8)
| <commit_before>import os
import numpy as np
import pandas as pd
import unittest
from urllib2 import urlopen
from bom_data_parser import read_soi_html
class SOITest(unittest.TestCase):
def setUp(self):
self.test_soi_file = os.path.join(os.path.dirname(__file__), 'data', 'SOI', 'soiplaintext.html')
def test_soi(self):
with open(self.test_soi_file, 'r') as soi_file:
soi_data = read_soi_html(soi_file)
self.assertTrue('soi' in soi_data.columns)
self.assertEqual(soi_data.ix['1876-01'], 11.3)
self.assertEqual(soi_data.ix['1984-12'], -1.4)
self.assertEqual(soi_data.ix['2015-01'], 7.8)
<commit_msg>Change unit test syntax for pandas > 0.12.0 compat<commit_after> | import os
import numpy as np
import pandas as pd
import unittest
from urllib2 import urlopen
from bom_data_parser import read_soi_html
class SOITest(unittest.TestCase):
def setUp(self):
self.test_soi_file = os.path.join(os.path.dirname(__file__), 'data', 'SOI', 'soiplaintext.html')
def test_soi(self):
with open(self.test_soi_file, 'r') as soi_file:
soi_data = read_soi_html(soi_file)
self.assertTrue('soi' in soi_data.columns)
self.assertEqual(soi_data.ix['1876-01'].values.item(), 11.3)
self.assertEqual(soi_data.ix['1984-12'].values.item(), -1.4)
self.assertEqual(soi_data.ix['2015-01'].values.item(), -7.8)
| import os
import numpy as np
import pandas as pd
import unittest
from urllib2 import urlopen
from bom_data_parser import read_soi_html
class SOITest(unittest.TestCase):
def setUp(self):
self.test_soi_file = os.path.join(os.path.dirname(__file__), 'data', 'SOI', 'soiplaintext.html')
def test_soi(self):
with open(self.test_soi_file, 'r') as soi_file:
soi_data = read_soi_html(soi_file)
self.assertTrue('soi' in soi_data.columns)
self.assertEqual(soi_data.ix['1876-01'], 11.3)
self.assertEqual(soi_data.ix['1984-12'], -1.4)
self.assertEqual(soi_data.ix['2015-01'], 7.8)
Change unit test syntax for pandas > 0.12.0 compatimport os
import numpy as np
import pandas as pd
import unittest
from urllib2 import urlopen
from bom_data_parser import read_soi_html
class SOITest(unittest.TestCase):
def setUp(self):
self.test_soi_file = os.path.join(os.path.dirname(__file__), 'data', 'SOI', 'soiplaintext.html')
def test_soi(self):
with open(self.test_soi_file, 'r') as soi_file:
soi_data = read_soi_html(soi_file)
self.assertTrue('soi' in soi_data.columns)
self.assertEqual(soi_data.ix['1876-01'].values.item(), 11.3)
self.assertEqual(soi_data.ix['1984-12'].values.item(), -1.4)
self.assertEqual(soi_data.ix['2015-01'].values.item(), -7.8)
| <commit_before>import os
import numpy as np
import pandas as pd
import unittest
from urllib2 import urlopen
from bom_data_parser import read_soi_html
class SOITest(unittest.TestCase):
def setUp(self):
self.test_soi_file = os.path.join(os.path.dirname(__file__), 'data', 'SOI', 'soiplaintext.html')
def test_soi(self):
with open(self.test_soi_file, 'r') as soi_file:
soi_data = read_soi_html(soi_file)
self.assertTrue('soi' in soi_data.columns)
self.assertEqual(soi_data.ix['1876-01'], 11.3)
self.assertEqual(soi_data.ix['1984-12'], -1.4)
self.assertEqual(soi_data.ix['2015-01'], 7.8)
<commit_msg>Change unit test syntax for pandas > 0.12.0 compat<commit_after>import os
import numpy as np
import pandas as pd
import unittest
from urllib2 import urlopen
from bom_data_parser import read_soi_html
class SOITest(unittest.TestCase):
def setUp(self):
self.test_soi_file = os.path.join(os.path.dirname(__file__), 'data', 'SOI', 'soiplaintext.html')
def test_soi(self):
with open(self.test_soi_file, 'r') as soi_file:
soi_data = read_soi_html(soi_file)
self.assertTrue('soi' in soi_data.columns)
self.assertEqual(soi_data.ix['1876-01'].values.item(), 11.3)
self.assertEqual(soi_data.ix['1984-12'].values.item(), -1.4)
self.assertEqual(soi_data.ix['2015-01'].values.item(), -7.8)
|
638e6a0f5b906e9cf63d95728da328b24f506173 | ananas/default/__init__.py | ananas/default/__init__.py | __all__ = ["roll", "tracery"]
from .roll import DiceBot
from .tracery import TraceryBot
| __all__ = ["roll", "tracery"]
from .roll import DiceBot
from .tracery import TraceryBot
from .announce import AnnounceBot
| Add announcebot to default module root for ease of import | Add announcebot to default module root for ease of import
| Python | mit | Chronister/ananas | __all__ = ["roll", "tracery"]
from .roll import DiceBot
from .tracery import TraceryBot
Add announcebot to default module root for ease of import | __all__ = ["roll", "tracery"]
from .roll import DiceBot
from .tracery import TraceryBot
from .announce import AnnounceBot
| <commit_before>__all__ = ["roll", "tracery"]
from .roll import DiceBot
from .tracery import TraceryBot
<commit_msg>Add announcebot to default module root for ease of import<commit_after> | __all__ = ["roll", "tracery"]
from .roll import DiceBot
from .tracery import TraceryBot
from .announce import AnnounceBot
| __all__ = ["roll", "tracery"]
from .roll import DiceBot
from .tracery import TraceryBot
Add announcebot to default module root for ease of import__all__ = ["roll", "tracery"]
from .roll import DiceBot
from .tracery import TraceryBot
from .announce import AnnounceBot
| <commit_before>__all__ = ["roll", "tracery"]
from .roll import DiceBot
from .tracery import TraceryBot
<commit_msg>Add announcebot to default module root for ease of import<commit_after>__all__ = ["roll", "tracery"]
from .roll import DiceBot
from .tracery import TraceryBot
from .announce import AnnounceBot
|
de96fab9b84c66b1d3bc3c200713bb595bce81b3 | examples/chart_maker/my_chart.py | examples/chart_maker/my_chart.py | from seleniumbase import BaseCase
class MyChartMakerClass(BaseCase):
def test_chart_maker(self):
self.create_pie_chart(title="Automated Tests")
self.add_data_point("Passed", 7, color="#95d96f")
self.add_data_point("Untested", 2, color="#eaeaea")
self.add_data_point("Failed", 1, color="#f1888f")
self.create_presentation()
self.add_slide(self.extract_chart())
self.begin_presentation()
| from seleniumbase import BaseCase
class MyChartMakerClass(BaseCase):
def test_chart_maker(self):
self.create_presentation()
self.create_pie_chart(title="Automated Tests")
self.add_data_point("Passed", 7, color="#95d96f")
self.add_data_point("Untested", 2, color="#eaeaea")
self.add_data_point("Failed", 1, color="#f1888f")
self.add_slide(self.extract_chart())
self.create_bar_chart(title="Code", libs=False)
self.add_data_point("Python", 33, color="Orange")
self.add_data_point("JavaScript", 27, color="Teal")
self.add_data_point("HTML + CSS", 21, color="Purple")
self.add_slide(self.extract_chart())
self.create_column_chart(title="Colors", libs=False)
self.add_data_point("Red", 10, color="Red")
self.add_data_point("Green", 25, color="Green")
self.add_data_point("Blue", 15, color="Blue")
self.add_slide(self.extract_chart())
self.begin_presentation()
| Expand on the Chart Maker example tests | Expand on the Chart Maker example tests
| Python | mit | mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase | from seleniumbase import BaseCase
class MyChartMakerClass(BaseCase):
def test_chart_maker(self):
self.create_pie_chart(title="Automated Tests")
self.add_data_point("Passed", 7, color="#95d96f")
self.add_data_point("Untested", 2, color="#eaeaea")
self.add_data_point("Failed", 1, color="#f1888f")
self.create_presentation()
self.add_slide(self.extract_chart())
self.begin_presentation()
Expand on the Chart Maker example tests | from seleniumbase import BaseCase
class MyChartMakerClass(BaseCase):
def test_chart_maker(self):
self.create_presentation()
self.create_pie_chart(title="Automated Tests")
self.add_data_point("Passed", 7, color="#95d96f")
self.add_data_point("Untested", 2, color="#eaeaea")
self.add_data_point("Failed", 1, color="#f1888f")
self.add_slide(self.extract_chart())
self.create_bar_chart(title="Code", libs=False)
self.add_data_point("Python", 33, color="Orange")
self.add_data_point("JavaScript", 27, color="Teal")
self.add_data_point("HTML + CSS", 21, color="Purple")
self.add_slide(self.extract_chart())
self.create_column_chart(title="Colors", libs=False)
self.add_data_point("Red", 10, color="Red")
self.add_data_point("Green", 25, color="Green")
self.add_data_point("Blue", 15, color="Blue")
self.add_slide(self.extract_chart())
self.begin_presentation()
| <commit_before>from seleniumbase import BaseCase
class MyChartMakerClass(BaseCase):
def test_chart_maker(self):
self.create_pie_chart(title="Automated Tests")
self.add_data_point("Passed", 7, color="#95d96f")
self.add_data_point("Untested", 2, color="#eaeaea")
self.add_data_point("Failed", 1, color="#f1888f")
self.create_presentation()
self.add_slide(self.extract_chart())
self.begin_presentation()
<commit_msg>Expand on the Chart Maker example tests<commit_after> | from seleniumbase import BaseCase
class MyChartMakerClass(BaseCase):
def test_chart_maker(self):
self.create_presentation()
self.create_pie_chart(title="Automated Tests")
self.add_data_point("Passed", 7, color="#95d96f")
self.add_data_point("Untested", 2, color="#eaeaea")
self.add_data_point("Failed", 1, color="#f1888f")
self.add_slide(self.extract_chart())
self.create_bar_chart(title="Code", libs=False)
self.add_data_point("Python", 33, color="Orange")
self.add_data_point("JavaScript", 27, color="Teal")
self.add_data_point("HTML + CSS", 21, color="Purple")
self.add_slide(self.extract_chart())
self.create_column_chart(title="Colors", libs=False)
self.add_data_point("Red", 10, color="Red")
self.add_data_point("Green", 25, color="Green")
self.add_data_point("Blue", 15, color="Blue")
self.add_slide(self.extract_chart())
self.begin_presentation()
| from seleniumbase import BaseCase
class MyChartMakerClass(BaseCase):
def test_chart_maker(self):
self.create_pie_chart(title="Automated Tests")
self.add_data_point("Passed", 7, color="#95d96f")
self.add_data_point("Untested", 2, color="#eaeaea")
self.add_data_point("Failed", 1, color="#f1888f")
self.create_presentation()
self.add_slide(self.extract_chart())
self.begin_presentation()
Expand on the Chart Maker example testsfrom seleniumbase import BaseCase
class MyChartMakerClass(BaseCase):
def test_chart_maker(self):
self.create_presentation()
self.create_pie_chart(title="Automated Tests")
self.add_data_point("Passed", 7, color="#95d96f")
self.add_data_point("Untested", 2, color="#eaeaea")
self.add_data_point("Failed", 1, color="#f1888f")
self.add_slide(self.extract_chart())
self.create_bar_chart(title="Code", libs=False)
self.add_data_point("Python", 33, color="Orange")
self.add_data_point("JavaScript", 27, color="Teal")
self.add_data_point("HTML + CSS", 21, color="Purple")
self.add_slide(self.extract_chart())
self.create_column_chart(title="Colors", libs=False)
self.add_data_point("Red", 10, color="Red")
self.add_data_point("Green", 25, color="Green")
self.add_data_point("Blue", 15, color="Blue")
self.add_slide(self.extract_chart())
self.begin_presentation()
| <commit_before>from seleniumbase import BaseCase
class MyChartMakerClass(BaseCase):
def test_chart_maker(self):
self.create_pie_chart(title="Automated Tests")
self.add_data_point("Passed", 7, color="#95d96f")
self.add_data_point("Untested", 2, color="#eaeaea")
self.add_data_point("Failed", 1, color="#f1888f")
self.create_presentation()
self.add_slide(self.extract_chart())
self.begin_presentation()
<commit_msg>Expand on the Chart Maker example tests<commit_after>from seleniumbase import BaseCase
class MyChartMakerClass(BaseCase):
def test_chart_maker(self):
self.create_presentation()
self.create_pie_chart(title="Automated Tests")
self.add_data_point("Passed", 7, color="#95d96f")
self.add_data_point("Untested", 2, color="#eaeaea")
self.add_data_point("Failed", 1, color="#f1888f")
self.add_slide(self.extract_chart())
self.create_bar_chart(title="Code", libs=False)
self.add_data_point("Python", 33, color="Orange")
self.add_data_point("JavaScript", 27, color="Teal")
self.add_data_point("HTML + CSS", 21, color="Purple")
self.add_slide(self.extract_chart())
self.create_column_chart(title="Colors", libs=False)
self.add_data_point("Red", 10, color="Red")
self.add_data_point("Green", 25, color="Green")
self.add_data_point("Blue", 15, color="Blue")
self.add_slide(self.extract_chart())
self.begin_presentation()
|
e4d271011ff352d4fa83c252739a71dc74a6c0d8 | packages/Python/lldbsuite/test/lang/swift/protocols/class_protocol/TestClassConstrainedProtocolArgument.py | packages/Python/lldbsuite/test/lang/swift/protocols/class_protocol/TestClassConstrainedProtocolArgument.py | """
Test that variables passed in as a class constrained protocol type
are correctly printed.
"""
import lldbsuite.test.lldbinline as lldbinline
lldbinline.MakeInlineTest(__file__, globals())
| """
Test that variables passed in as a class constrained protocol type
are correctly printed.
"""
import lldbsuite.test.lldbinline as lldbinline
import lldbsuite.test.decorators as decorators
lldbinline.MakeInlineTest(
__file__, globals(), decorators=[decorators.skipUnlessDarwin])
| Mark a test relying on foundation as darwin only. | [SwiftLanguageRuntime] Mark a test relying on foundation as darwin only.
| Python | apache-2.0 | apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb | """
Test that variables passed in as a class constrained protocol type
are correctly printed.
"""
import lldbsuite.test.lldbinline as lldbinline
lldbinline.MakeInlineTest(__file__, globals())
[SwiftLanguageRuntime] Mark a test relying on foundation as darwin only. | """
Test that variables passed in as a class constrained protocol type
are correctly printed.
"""
import lldbsuite.test.lldbinline as lldbinline
import lldbsuite.test.decorators as decorators
lldbinline.MakeInlineTest(
__file__, globals(), decorators=[decorators.skipUnlessDarwin])
| <commit_before>"""
Test that variables passed in as a class constrained protocol type
are correctly printed.
"""
import lldbsuite.test.lldbinline as lldbinline
lldbinline.MakeInlineTest(__file__, globals())
<commit_msg>[SwiftLanguageRuntime] Mark a test relying on foundation as darwin only.<commit_after> | """
Test that variables passed in as a class constrained protocol type
are correctly printed.
"""
import lldbsuite.test.lldbinline as lldbinline
import lldbsuite.test.decorators as decorators
lldbinline.MakeInlineTest(
__file__, globals(), decorators=[decorators.skipUnlessDarwin])
| """
Test that variables passed in as a class constrained protocol type
are correctly printed.
"""
import lldbsuite.test.lldbinline as lldbinline
lldbinline.MakeInlineTest(__file__, globals())
[SwiftLanguageRuntime] Mark a test relying on foundation as darwin only."""
Test that variables passed in as a class constrained protocol type
are correctly printed.
"""
import lldbsuite.test.lldbinline as lldbinline
import lldbsuite.test.decorators as decorators
lldbinline.MakeInlineTest(
__file__, globals(), decorators=[decorators.skipUnlessDarwin])
| <commit_before>"""
Test that variables passed in as a class constrained protocol type
are correctly printed.
"""
import lldbsuite.test.lldbinline as lldbinline
lldbinline.MakeInlineTest(__file__, globals())
<commit_msg>[SwiftLanguageRuntime] Mark a test relying on foundation as darwin only.<commit_after>"""
Test that variables passed in as a class constrained protocol type
are correctly printed.
"""
import lldbsuite.test.lldbinline as lldbinline
import lldbsuite.test.decorators as decorators
lldbinline.MakeInlineTest(
__file__, globals(), decorators=[decorators.skipUnlessDarwin])
|
01ed98138f9be1f55c5f46e5e073dde4271cc277 | useraudit/urls.py | useraudit/urls.py | from django.conf.urls import include, url
from .views import reactivate_user
app_name = "useraudit"
urlpatterns = [
url(r'/reactivate/(?P<user_id>\d+)[/]?$', reactivate_user, name="reactivate_user"),
]
| from django.conf.urls import include, url
from .views import reactivate_user
app_name = "useraudit"
urlpatterns = [
url(r'reactivate/(?P<user_id>\d+)[/]?$', reactivate_user, name="reactivate_user"),
]
| Remove / from the beginning of the '/reactivate' url | Remove / from the beginning of the '/reactivate' url
Fixes #10
| Python | bsd-3-clause | muccg/django-useraudit,muccg/django-useraudit,muccg/django-useraudit | from django.conf.urls import include, url
from .views import reactivate_user
app_name = "useraudit"
urlpatterns = [
url(r'/reactivate/(?P<user_id>\d+)[/]?$', reactivate_user, name="reactivate_user"),
]
Remove / from the beginning of the '/reactivate' url
Fixes #10 | from django.conf.urls import include, url
from .views import reactivate_user
app_name = "useraudit"
urlpatterns = [
url(r'reactivate/(?P<user_id>\d+)[/]?$', reactivate_user, name="reactivate_user"),
]
| <commit_before>from django.conf.urls import include, url
from .views import reactivate_user
app_name = "useraudit"
urlpatterns = [
url(r'/reactivate/(?P<user_id>\d+)[/]?$', reactivate_user, name="reactivate_user"),
]
<commit_msg>Remove / from the beginning of the '/reactivate' url
Fixes #10<commit_after> | from django.conf.urls import include, url
from .views import reactivate_user
app_name = "useraudit"
urlpatterns = [
url(r'reactivate/(?P<user_id>\d+)[/]?$', reactivate_user, name="reactivate_user"),
]
| from django.conf.urls import include, url
from .views import reactivate_user
app_name = "useraudit"
urlpatterns = [
url(r'/reactivate/(?P<user_id>\d+)[/]?$', reactivate_user, name="reactivate_user"),
]
Remove / from the beginning of the '/reactivate' url
Fixes #10from django.conf.urls import include, url
from .views import reactivate_user
app_name = "useraudit"
urlpatterns = [
url(r'reactivate/(?P<user_id>\d+)[/]?$', reactivate_user, name="reactivate_user"),
]
| <commit_before>from django.conf.urls import include, url
from .views import reactivate_user
app_name = "useraudit"
urlpatterns = [
url(r'/reactivate/(?P<user_id>\d+)[/]?$', reactivate_user, name="reactivate_user"),
]
<commit_msg>Remove / from the beginning of the '/reactivate' url
Fixes #10<commit_after>from django.conf.urls import include, url
from .views import reactivate_user
app_name = "useraudit"
urlpatterns = [
url(r'reactivate/(?P<user_id>\d+)[/]?$', reactivate_user, name="reactivate_user"),
]
|
2ba4e34af7a1078d4c19d5f964df42d291f9862a | slaveapi/clients/pdu.py | slaveapi/clients/pdu.py | class PDU(object):
def __init__(self, fqdn, port):
self.fqdn = fqdn
self.port = port
def off(self):
pass
def on(self):
pass
def powercycle(self, delay=None):
pass
| class PDU(object):
def __init__(self, fqdn, port):
self.fqdn = fqdn
self.port = port
def off(self):
pass
def on(self):
pass
def powercycle(self, delay=None):
raise NotImplementedError()
| Mark PDUs as not implemented to avoid false positives in reboots. | Mark PDUs as not implemented to avoid false positives in reboots.
| Python | mpl-2.0 | lundjordan/slaveapi | class PDU(object):
def __init__(self, fqdn, port):
self.fqdn = fqdn
self.port = port
def off(self):
pass
def on(self):
pass
def powercycle(self, delay=None):
pass
Mark PDUs as not implemented to avoid false positives in reboots. | class PDU(object):
def __init__(self, fqdn, port):
self.fqdn = fqdn
self.port = port
def off(self):
pass
def on(self):
pass
def powercycle(self, delay=None):
raise NotImplementedError()
| <commit_before>class PDU(object):
def __init__(self, fqdn, port):
self.fqdn = fqdn
self.port = port
def off(self):
pass
def on(self):
pass
def powercycle(self, delay=None):
pass
<commit_msg>Mark PDUs as not implemented to avoid false positives in reboots.<commit_after> | class PDU(object):
def __init__(self, fqdn, port):
self.fqdn = fqdn
self.port = port
def off(self):
pass
def on(self):
pass
def powercycle(self, delay=None):
raise NotImplementedError()
| class PDU(object):
def __init__(self, fqdn, port):
self.fqdn = fqdn
self.port = port
def off(self):
pass
def on(self):
pass
def powercycle(self, delay=None):
pass
Mark PDUs as not implemented to avoid false positives in reboots.class PDU(object):
def __init__(self, fqdn, port):
self.fqdn = fqdn
self.port = port
def off(self):
pass
def on(self):
pass
def powercycle(self, delay=None):
raise NotImplementedError()
| <commit_before>class PDU(object):
def __init__(self, fqdn, port):
self.fqdn = fqdn
self.port = port
def off(self):
pass
def on(self):
pass
def powercycle(self, delay=None):
pass
<commit_msg>Mark PDUs as not implemented to avoid false positives in reboots.<commit_after>class PDU(object):
def __init__(self, fqdn, port):
self.fqdn = fqdn
self.port = port
def off(self):
pass
def on(self):
pass
def powercycle(self, delay=None):
raise NotImplementedError()
|
4115cee1aa913346d5495230a98a5e723de9f5ab | bilgisayfam/utils/encoding.py | bilgisayfam/utils/encoding.py | # -*- coding: utf-8 -*-
"""
Provides a translation method that strips Turkish characters and replaces
them with ASCII equivalents.
"""
translate_table = {
ord(u"ğ"): u"g",
ord(u"ü"): u"u",
ord(u"ş"): u"s",
ord(u"ı"): u"i",
ord(u"ö"): u"o",
ord(u"ç"): u"c",
ord(u"Ğ"): u"G",
ord(u"Ü"): u"U",
ord(u"Ş"): u"S",
ord(u"İ"): u"I",
ord(u"Ö"): u"O",
ord(u"Ç"): u"C",
}
def normalize(s):
return s.translate(translate_table)
| # -*- coding: utf-8 -*-
"""
Provides a translation method that strips Turkish characters and replaces
them with ASCII equivalents.
"""
translate_table = {
ord(u"ğ"): u"g",
ord(u"ü"): u"u",
ord(u"ş"): u"s",
ord(u"ı"): u"i",
ord(u"ö"): u"o",
ord(u"ç"): u"c",
ord(u"Ğ"): u"G",
ord(u"Ü"): u"U",
ord(u"Ş"): u"S",
ord(u"İ"): u"I",
ord(u"Ö"): u"O",
ord(u"Ç"): u"C",
}
def normalize(s):
"""
Transforms a unicode string so that it can be searched and found even when
it is not exactly the same. So for example a user can search for "Oğlak"
and we can find "oğlak" by normalizing both to "oglak".
Lowercases all the letters and anglicanizes it.
Oğlak => oglak
başucu => basucu
Noel Baba => noel baba
"""
s = s.lower()
return s.translate(translate_table)
| Make normalize lower case as well. | Make normalize lower case as well.
| Python | mit | tayfun/bilgisayfam,tayfun/bilgisayfam,tayfun/bilgisayfam | # -*- coding: utf-8 -*-
"""
Provides a translation method that strips Turkish characters and replaces
them with ASCII equivalents.
"""
translate_table = {
ord(u"ğ"): u"g",
ord(u"ü"): u"u",
ord(u"ş"): u"s",
ord(u"ı"): u"i",
ord(u"ö"): u"o",
ord(u"ç"): u"c",
ord(u"Ğ"): u"G",
ord(u"Ü"): u"U",
ord(u"Ş"): u"S",
ord(u"İ"): u"I",
ord(u"Ö"): u"O",
ord(u"Ç"): u"C",
}
def normalize(s):
return s.translate(translate_table)
Make normalize lower case as well. | # -*- coding: utf-8 -*-
"""
Provides a translation method that strips Turkish characters and replaces
them with ASCII equivalents.
"""
translate_table = {
ord(u"ğ"): u"g",
ord(u"ü"): u"u",
ord(u"ş"): u"s",
ord(u"ı"): u"i",
ord(u"ö"): u"o",
ord(u"ç"): u"c",
ord(u"Ğ"): u"G",
ord(u"Ü"): u"U",
ord(u"Ş"): u"S",
ord(u"İ"): u"I",
ord(u"Ö"): u"O",
ord(u"Ç"): u"C",
}
def normalize(s):
"""
Transforms a unicode string so that it can be searched and found even when
it is not exactly the same. So for example a user can search for "Oğlak"
and we can find "oğlak" by normalizing both to "oglak".
Lowercases all the letters and anglicanizes it.
Oğlak => oglak
başucu => basucu
Noel Baba => noel baba
"""
s = s.lower()
return s.translate(translate_table)
| <commit_before># -*- coding: utf-8 -*-
"""
Provides a translation method that strips Turkish characters and replaces
them with ASCII equivalents.
"""
translate_table = {
ord(u"ğ"): u"g",
ord(u"ü"): u"u",
ord(u"ş"): u"s",
ord(u"ı"): u"i",
ord(u"ö"): u"o",
ord(u"ç"): u"c",
ord(u"Ğ"): u"G",
ord(u"Ü"): u"U",
ord(u"Ş"): u"S",
ord(u"İ"): u"I",
ord(u"Ö"): u"O",
ord(u"Ç"): u"C",
}
def normalize(s):
return s.translate(translate_table)
<commit_msg>Make normalize lower case as well.<commit_after> | # -*- coding: utf-8 -*-
"""
Provides a translation method that strips Turkish characters and replaces
them with ASCII equivalents.
"""
translate_table = {
ord(u"ğ"): u"g",
ord(u"ü"): u"u",
ord(u"ş"): u"s",
ord(u"ı"): u"i",
ord(u"ö"): u"o",
ord(u"ç"): u"c",
ord(u"Ğ"): u"G",
ord(u"Ü"): u"U",
ord(u"Ş"): u"S",
ord(u"İ"): u"I",
ord(u"Ö"): u"O",
ord(u"Ç"): u"C",
}
def normalize(s):
"""
Transforms a unicode string so that it can be searched and found even when
it is not exactly the same. So for example a user can search for "Oğlak"
and we can find "oğlak" by normalizing both to "oglak".
Lowercases all the letters and anglicanizes it.
Oğlak => oglak
başucu => basucu
Noel Baba => noel baba
"""
s = s.lower()
return s.translate(translate_table)
| # -*- coding: utf-8 -*-
"""
Provides a translation method that strips Turkish characters and replaces
them with ASCII equivalents.
"""
translate_table = {
ord(u"ğ"): u"g",
ord(u"ü"): u"u",
ord(u"ş"): u"s",
ord(u"ı"): u"i",
ord(u"ö"): u"o",
ord(u"ç"): u"c",
ord(u"Ğ"): u"G",
ord(u"Ü"): u"U",
ord(u"Ş"): u"S",
ord(u"İ"): u"I",
ord(u"Ö"): u"O",
ord(u"Ç"): u"C",
}
def normalize(s):
return s.translate(translate_table)
Make normalize lower case as well.# -*- coding: utf-8 -*-
"""
Provides a translation method that strips Turkish characters and replaces
them with ASCII equivalents.
"""
translate_table = {
ord(u"ğ"): u"g",
ord(u"ü"): u"u",
ord(u"ş"): u"s",
ord(u"ı"): u"i",
ord(u"ö"): u"o",
ord(u"ç"): u"c",
ord(u"Ğ"): u"G",
ord(u"Ü"): u"U",
ord(u"Ş"): u"S",
ord(u"İ"): u"I",
ord(u"Ö"): u"O",
ord(u"Ç"): u"C",
}
def normalize(s):
"""
Transforms a unicode string so that it can be searched and found even when
it is not exactly the same. So for example a user can search for "Oğlak"
and we can find "oğlak" by normalizing both to "oglak".
Lowercases all the letters and anglicanizes it.
Oğlak => oglak
başucu => basucu
Noel Baba => noel baba
"""
s = s.lower()
return s.translate(translate_table)
| <commit_before># -*- coding: utf-8 -*-
"""
Provides a translation method that strips Turkish characters and replaces
them with ASCII equivalents.
"""
translate_table = {
ord(u"ğ"): u"g",
ord(u"ü"): u"u",
ord(u"ş"): u"s",
ord(u"ı"): u"i",
ord(u"ö"): u"o",
ord(u"ç"): u"c",
ord(u"Ğ"): u"G",
ord(u"Ü"): u"U",
ord(u"Ş"): u"S",
ord(u"İ"): u"I",
ord(u"Ö"): u"O",
ord(u"Ç"): u"C",
}
def normalize(s):
return s.translate(translate_table)
<commit_msg>Make normalize lower case as well.<commit_after># -*- coding: utf-8 -*-
"""
Provides a translation method that strips Turkish characters and replaces
them with ASCII equivalents.
"""
translate_table = {
ord(u"ğ"): u"g",
ord(u"ü"): u"u",
ord(u"ş"): u"s",
ord(u"ı"): u"i",
ord(u"ö"): u"o",
ord(u"ç"): u"c",
ord(u"Ğ"): u"G",
ord(u"Ü"): u"U",
ord(u"Ş"): u"S",
ord(u"İ"): u"I",
ord(u"Ö"): u"O",
ord(u"Ç"): u"C",
}
def normalize(s):
"""
Transforms a unicode string so that it can be searched and found even when
it is not exactly the same. So for example a user can search for "Oğlak"
and we can find "oğlak" by normalizing both to "oglak".
Lowercases all the letters and anglicanizes it.
Oğlak => oglak
başucu => basucu
Noel Baba => noel baba
"""
s = s.lower()
return s.translate(translate_table)
|
18545c519c23e9463fa7558191552e69304dfef7 | blog/myblog/tests.py | blog/myblog/tests.py | import datetime
from django.test import TestCase
from django.utils import timezone
from myblog.models import Article, Author
class ArticleMethodTest(TestCase):
"""docstring for ArticleMethodTest - it shoult return False
if it was published in past or future"""
def setUp(self):
self.joe = Author(name="joe")
def test_was_published_with_future_date(self):
future_article = Article("21255", pub_date=timezone.now() + datetime.timedelta(days=30),
author=self.joe)
self.assertEqual(future_article.was_published_recently(), False)
def test_was_published_recently(self):
recent_article = Article("21255", pub_date=timezone.now() - datetime.timedelta(hours=1),
author=self.joe)
self.assertEqual(recent_article.was_published_recently(), True)
def test_was_published_not_recently(self):
old_article = Article("21255", pub_date=timezone.now() - datetime.timedelta(days=30),
author=self.joe)
self.assertEqual(old_article.was_published_recently(), False)
| import datetime
from django.test import TestCase
from django.utils import timezone
from django.core.urlresolvers import reverse
from myblog.models import Article, Author
class ArticleMethodTest(TestCase):
"""docstring for ArticleMethodTest - it shoult return False
if it was published in past or future"""
def setUp(self):
self.joe = Author(name="joe")
def test_was_published_with_future_date(self):
future_article = Article("21255", pub_date=timezone.now() + datetime.timedelta(days=30),
author=self.joe)
self.assertEqual(future_article.was_published_recently(), False)
def test_was_published_recently(self):
recent_article = Article("21255", pub_date=timezone.now() - datetime.timedelta(hours=1),
author=self.joe)
self.assertEqual(recent_article.was_published_recently(), True)
def test_was_published_not_recently(self):
old_article = Article("21255", pub_date=timezone.now() - datetime.timedelta(days=30),
author=self.joe)
self.assertEqual(old_article.was_published_recently(), False)
class ArticleViewTest(TestCase):
def create_article(title, text, days, author, rating, comment):
return Article.objects.create(title=title,
text=text,
pub_date=timezone.now() + datetime.timedelta(days=days),
author=author,
rating=rating,
comment=comment
)
def test_index_view_with_no_articles(self):
response = self.client.get(reverse("myblog:index"))
self.assertEqual(response.status_code, 200)
# is done if there are no articles
# self.assertContains(response, "No polls available")
self.assertQuerysetEqual(response.context["latest_articles"], [])
| Add test for article view | Add test for article view
| Python | mit | mileto94/Django-tutorial,mileto94/Django-tutorial | import datetime
from django.test import TestCase
from django.utils import timezone
from myblog.models import Article, Author
class ArticleMethodTest(TestCase):
"""docstring for ArticleMethodTest - it shoult return False
if it was published in past or future"""
def setUp(self):
self.joe = Author(name="joe")
def test_was_published_with_future_date(self):
future_article = Article("21255", pub_date=timezone.now() + datetime.timedelta(days=30),
author=self.joe)
self.assertEqual(future_article.was_published_recently(), False)
def test_was_published_recently(self):
recent_article = Article("21255", pub_date=timezone.now() - datetime.timedelta(hours=1),
author=self.joe)
self.assertEqual(recent_article.was_published_recently(), True)
def test_was_published_not_recently(self):
old_article = Article("21255", pub_date=timezone.now() - datetime.timedelta(days=30),
author=self.joe)
self.assertEqual(old_article.was_published_recently(), False)
Add test for article view | import datetime
from django.test import TestCase
from django.utils import timezone
from django.core.urlresolvers import reverse
from myblog.models import Article, Author
class ArticleMethodTest(TestCase):
"""docstring for ArticleMethodTest - it shoult return False
if it was published in past or future"""
def setUp(self):
self.joe = Author(name="joe")
def test_was_published_with_future_date(self):
future_article = Article("21255", pub_date=timezone.now() + datetime.timedelta(days=30),
author=self.joe)
self.assertEqual(future_article.was_published_recently(), False)
def test_was_published_recently(self):
recent_article = Article("21255", pub_date=timezone.now() - datetime.timedelta(hours=1),
author=self.joe)
self.assertEqual(recent_article.was_published_recently(), True)
def test_was_published_not_recently(self):
old_article = Article("21255", pub_date=timezone.now() - datetime.timedelta(days=30),
author=self.joe)
self.assertEqual(old_article.was_published_recently(), False)
class ArticleViewTest(TestCase):
def create_article(title, text, days, author, rating, comment):
return Article.objects.create(title=title,
text=text,
pub_date=timezone.now() + datetime.timedelta(days=days),
author=author,
rating=rating,
comment=comment
)
def test_index_view_with_no_articles(self):
response = self.client.get(reverse("myblog:index"))
self.assertEqual(response.status_code, 200)
# is done if there are no articles
# self.assertContains(response, "No polls available")
self.assertQuerysetEqual(response.context["latest_articles"], [])
| <commit_before>import datetime
from django.test import TestCase
from django.utils import timezone
from myblog.models import Article, Author
class ArticleMethodTest(TestCase):
"""docstring for ArticleMethodTest - it shoult return False
if it was published in past or future"""
def setUp(self):
self.joe = Author(name="joe")
def test_was_published_with_future_date(self):
future_article = Article("21255", pub_date=timezone.now() + datetime.timedelta(days=30),
author=self.joe)
self.assertEqual(future_article.was_published_recently(), False)
def test_was_published_recently(self):
recent_article = Article("21255", pub_date=timezone.now() - datetime.timedelta(hours=1),
author=self.joe)
self.assertEqual(recent_article.was_published_recently(), True)
def test_was_published_not_recently(self):
old_article = Article("21255", pub_date=timezone.now() - datetime.timedelta(days=30),
author=self.joe)
self.assertEqual(old_article.was_published_recently(), False)
<commit_msg>Add test for article view<commit_after> | import datetime
from django.test import TestCase
from django.utils import timezone
from django.core.urlresolvers import reverse
from myblog.models import Article, Author
class ArticleMethodTest(TestCase):
"""docstring for ArticleMethodTest - it shoult return False
if it was published in past or future"""
def setUp(self):
self.joe = Author(name="joe")
def test_was_published_with_future_date(self):
future_article = Article("21255", pub_date=timezone.now() + datetime.timedelta(days=30),
author=self.joe)
self.assertEqual(future_article.was_published_recently(), False)
def test_was_published_recently(self):
recent_article = Article("21255", pub_date=timezone.now() - datetime.timedelta(hours=1),
author=self.joe)
self.assertEqual(recent_article.was_published_recently(), True)
def test_was_published_not_recently(self):
old_article = Article("21255", pub_date=timezone.now() - datetime.timedelta(days=30),
author=self.joe)
self.assertEqual(old_article.was_published_recently(), False)
class ArticleViewTest(TestCase):
def create_article(title, text, days, author, rating, comment):
return Article.objects.create(title=title,
text=text,
pub_date=timezone.now() + datetime.timedelta(days=days),
author=author,
rating=rating,
comment=comment
)
def test_index_view_with_no_articles(self):
response = self.client.get(reverse("myblog:index"))
self.assertEqual(response.status_code, 200)
# is done if there are no articles
# self.assertContains(response, "No polls available")
self.assertQuerysetEqual(response.context["latest_articles"], [])
| import datetime
from django.test import TestCase
from django.utils import timezone
from myblog.models import Article, Author
class ArticleMethodTest(TestCase):
"""docstring for ArticleMethodTest - it shoult return False
if it was published in past or future"""
def setUp(self):
self.joe = Author(name="joe")
def test_was_published_with_future_date(self):
future_article = Article("21255", pub_date=timezone.now() + datetime.timedelta(days=30),
author=self.joe)
self.assertEqual(future_article.was_published_recently(), False)
def test_was_published_recently(self):
recent_article = Article("21255", pub_date=timezone.now() - datetime.timedelta(hours=1),
author=self.joe)
self.assertEqual(recent_article.was_published_recently(), True)
def test_was_published_not_recently(self):
old_article = Article("21255", pub_date=timezone.now() - datetime.timedelta(days=30),
author=self.joe)
self.assertEqual(old_article.was_published_recently(), False)
Add test for article viewimport datetime
from django.test import TestCase
from django.utils import timezone
from django.core.urlresolvers import reverse
from myblog.models import Article, Author
class ArticleMethodTest(TestCase):
"""docstring for ArticleMethodTest - it shoult return False
if it was published in past or future"""
def setUp(self):
self.joe = Author(name="joe")
def test_was_published_with_future_date(self):
future_article = Article("21255", pub_date=timezone.now() + datetime.timedelta(days=30),
author=self.joe)
self.assertEqual(future_article.was_published_recently(), False)
def test_was_published_recently(self):
recent_article = Article("21255", pub_date=timezone.now() - datetime.timedelta(hours=1),
author=self.joe)
self.assertEqual(recent_article.was_published_recently(), True)
def test_was_published_not_recently(self):
old_article = Article("21255", pub_date=timezone.now() - datetime.timedelta(days=30),
author=self.joe)
self.assertEqual(old_article.was_published_recently(), False)
class ArticleViewTest(TestCase):
def create_article(title, text, days, author, rating, comment):
return Article.objects.create(title=title,
text=text,
pub_date=timezone.now() + datetime.timedelta(days=days),
author=author,
rating=rating,
comment=comment
)
def test_index_view_with_no_articles(self):
response = self.client.get(reverse("myblog:index"))
self.assertEqual(response.status_code, 200)
# is done if there are no articles
# self.assertContains(response, "No polls available")
self.assertQuerysetEqual(response.context["latest_articles"], [])
| <commit_before>import datetime
from django.test import TestCase
from django.utils import timezone
from myblog.models import Article, Author
class ArticleMethodTest(TestCase):
"""docstring for ArticleMethodTest - it shoult return False
if it was published in past or future"""
def setUp(self):
self.joe = Author(name="joe")
def test_was_published_with_future_date(self):
future_article = Article("21255", pub_date=timezone.now() + datetime.timedelta(days=30),
author=self.joe)
self.assertEqual(future_article.was_published_recently(), False)
def test_was_published_recently(self):
recent_article = Article("21255", pub_date=timezone.now() - datetime.timedelta(hours=1),
author=self.joe)
self.assertEqual(recent_article.was_published_recently(), True)
def test_was_published_not_recently(self):
old_article = Article("21255", pub_date=timezone.now() - datetime.timedelta(days=30),
author=self.joe)
self.assertEqual(old_article.was_published_recently(), False)
<commit_msg>Add test for article view<commit_after>import datetime
from django.test import TestCase
from django.utils import timezone
from django.core.urlresolvers import reverse
from myblog.models import Article, Author
class ArticleMethodTest(TestCase):
"""docstring for ArticleMethodTest - it shoult return False
if it was published in past or future"""
def setUp(self):
self.joe = Author(name="joe")
def test_was_published_with_future_date(self):
future_article = Article("21255", pub_date=timezone.now() + datetime.timedelta(days=30),
author=self.joe)
self.assertEqual(future_article.was_published_recently(), False)
def test_was_published_recently(self):
recent_article = Article("21255", pub_date=timezone.now() - datetime.timedelta(hours=1),
author=self.joe)
self.assertEqual(recent_article.was_published_recently(), True)
def test_was_published_not_recently(self):
old_article = Article("21255", pub_date=timezone.now() - datetime.timedelta(days=30),
author=self.joe)
self.assertEqual(old_article.was_published_recently(), False)
class ArticleViewTest(TestCase):
def create_article(title, text, days, author, rating, comment):
return Article.objects.create(title=title,
text=text,
pub_date=timezone.now() + datetime.timedelta(days=days),
author=author,
rating=rating,
comment=comment
)
def test_index_view_with_no_articles(self):
response = self.client.get(reverse("myblog:index"))
self.assertEqual(response.status_code, 200)
# is done if there are no articles
# self.assertContains(response, "No polls available")
self.assertQuerysetEqual(response.context["latest_articles"], [])
|
897bbe8b4d70ca68fb0336774b8c549ed2fe4c3e | buildtools/cleanup-ghpages.py | buildtools/cleanup-ghpages.py | #! python
import sys
import requests
import urllib3
from os import listdir
from shutil import rmtree
from json import loads
urllib3.disable_warnings()
def main():
url = "https://api.github.com/repos/{}/ngeo/branches?per_page=100".format(sys.argv[1])
try:
json = requests.get(url).json()
expected = [
branch["name"] for branch in json
]
expected.append("index.html")
expected.append(".git")
for path in listdir(sys.argv[2]):
if path not in expected:
print("Remove: {}".format(path))
rmtree("{}/{}".format(sys.argv[2], path))
except Exception as e:
print("WARN {} seems unreachable ({}).".format(url, e))
if __name__ == "__main__":
main()
| #! python
import sys
import requests
import urllib3
from os import listdir
from shutil import rmtree
from json import loads
urllib3.disable_warnings()
def main():
url = "https://api.github.com/repos/{}/ngeo/branches?per_page=100".format(sys.argv[1])
try:
json = requests.get(url).json()
expected = [
branch["name"] for branch in json
]
expected.append("index.html")
expected.append(".git")
for path in listdir(sys.argv[2]):
if path not in expected or path.startswith("greenkeeper/"):
print("Remove: {}".format(path))
rmtree("{}/{}".format(sys.argv[2], path))
except Exception as e:
print("WARN {} seems unreachable ({}).".format(url, e))
if __name__ == "__main__":
main()
| Remove greenkeeper directories from gh-pages | Remove greenkeeper directories from gh-pages
| Python | mit | camptocamp/ngeo,camptocamp/ngeo,camptocamp/ngeo,camptocamp/ngeo,camptocamp/ngeo | #! python
import sys
import requests
import urllib3
from os import listdir
from shutil import rmtree
from json import loads
urllib3.disable_warnings()
def main():
url = "https://api.github.com/repos/{}/ngeo/branches?per_page=100".format(sys.argv[1])
try:
json = requests.get(url).json()
expected = [
branch["name"] for branch in json
]
expected.append("index.html")
expected.append(".git")
for path in listdir(sys.argv[2]):
if path not in expected:
print("Remove: {}".format(path))
rmtree("{}/{}".format(sys.argv[2], path))
except Exception as e:
print("WARN {} seems unreachable ({}).".format(url, e))
if __name__ == "__main__":
main()
Remove greenkeeper directories from gh-pages | #! python
import sys
import requests
import urllib3
from os import listdir
from shutil import rmtree
from json import loads
urllib3.disable_warnings()
def main():
url = "https://api.github.com/repos/{}/ngeo/branches?per_page=100".format(sys.argv[1])
try:
json = requests.get(url).json()
expected = [
branch["name"] for branch in json
]
expected.append("index.html")
expected.append(".git")
for path in listdir(sys.argv[2]):
if path not in expected or path.startswith("greenkeeper/"):
print("Remove: {}".format(path))
rmtree("{}/{}".format(sys.argv[2], path))
except Exception as e:
print("WARN {} seems unreachable ({}).".format(url, e))
if __name__ == "__main__":
main()
| <commit_before>#! python
import sys
import requests
import urllib3
from os import listdir
from shutil import rmtree
from json import loads
urllib3.disable_warnings()
def main():
url = "https://api.github.com/repos/{}/ngeo/branches?per_page=100".format(sys.argv[1])
try:
json = requests.get(url).json()
expected = [
branch["name"] for branch in json
]
expected.append("index.html")
expected.append(".git")
for path in listdir(sys.argv[2]):
if path not in expected:
print("Remove: {}".format(path))
rmtree("{}/{}".format(sys.argv[2], path))
except Exception as e:
print("WARN {} seems unreachable ({}).".format(url, e))
if __name__ == "__main__":
main()
<commit_msg>Remove greenkeeper directories from gh-pages<commit_after> | #! python
import sys
import requests
import urllib3
from os import listdir
from shutil import rmtree
from json import loads
urllib3.disable_warnings()
def main():
url = "https://api.github.com/repos/{}/ngeo/branches?per_page=100".format(sys.argv[1])
try:
json = requests.get(url).json()
expected = [
branch["name"] for branch in json
]
expected.append("index.html")
expected.append(".git")
for path in listdir(sys.argv[2]):
if path not in expected or path.startswith("greenkeeper/"):
print("Remove: {}".format(path))
rmtree("{}/{}".format(sys.argv[2], path))
except Exception as e:
print("WARN {} seems unreachable ({}).".format(url, e))
if __name__ == "__main__":
main()
| #! python
import sys
import requests
import urllib3
from os import listdir
from shutil import rmtree
from json import loads
urllib3.disable_warnings()
def main():
url = "https://api.github.com/repos/{}/ngeo/branches?per_page=100".format(sys.argv[1])
try:
json = requests.get(url).json()
expected = [
branch["name"] for branch in json
]
expected.append("index.html")
expected.append(".git")
for path in listdir(sys.argv[2]):
if path not in expected:
print("Remove: {}".format(path))
rmtree("{}/{}".format(sys.argv[2], path))
except Exception as e:
print("WARN {} seems unreachable ({}).".format(url, e))
if __name__ == "__main__":
main()
Remove greenkeeper directories from gh-pages#! python
import sys
import requests
import urllib3
from os import listdir
from shutil import rmtree
from json import loads
urllib3.disable_warnings()
def main():
url = "https://api.github.com/repos/{}/ngeo/branches?per_page=100".format(sys.argv[1])
try:
json = requests.get(url).json()
expected = [
branch["name"] for branch in json
]
expected.append("index.html")
expected.append(".git")
for path in listdir(sys.argv[2]):
if path not in expected or path.startswith("greenkeeper/"):
print("Remove: {}".format(path))
rmtree("{}/{}".format(sys.argv[2], path))
except Exception as e:
print("WARN {} seems unreachable ({}).".format(url, e))
if __name__ == "__main__":
main()
| <commit_before>#! python
import sys
import requests
import urllib3
from os import listdir
from shutil import rmtree
from json import loads
urllib3.disable_warnings()
def main():
url = "https://api.github.com/repos/{}/ngeo/branches?per_page=100".format(sys.argv[1])
try:
json = requests.get(url).json()
expected = [
branch["name"] for branch in json
]
expected.append("index.html")
expected.append(".git")
for path in listdir(sys.argv[2]):
if path not in expected:
print("Remove: {}".format(path))
rmtree("{}/{}".format(sys.argv[2], path))
except Exception as e:
print("WARN {} seems unreachable ({}).".format(url, e))
if __name__ == "__main__":
main()
<commit_msg>Remove greenkeeper directories from gh-pages<commit_after>#! python
import sys
import requests
import urllib3
from os import listdir
from shutil import rmtree
from json import loads
urllib3.disable_warnings()
def main():
url = "https://api.github.com/repos/{}/ngeo/branches?per_page=100".format(sys.argv[1])
try:
json = requests.get(url).json()
expected = [
branch["name"] for branch in json
]
expected.append("index.html")
expected.append(".git")
for path in listdir(sys.argv[2]):
if path not in expected or path.startswith("greenkeeper/"):
print("Remove: {}".format(path))
rmtree("{}/{}".format(sys.argv[2], path))
except Exception as e:
print("WARN {} seems unreachable ({}).".format(url, e))
if __name__ == "__main__":
main()
|
7c7aa833dd79c53dbd921f5ed59cf2620342dbe3 | python/ShortenUrl.py | python/ShortenUrl.py |
# This is fairly specific to using a Yourls server: see http://yourls.org/
import urllib
import urllib2
import Util
SHORTEN_PART = 'yourls-api.php'
def shorten(url, config):
def shortenerUrl(part):
return '%s/%s' % (config.shortenUrl, part)
index = Util.getAndIncrementIndexFile(config.indexFile)
shorturl = config.shortenPrefix +
data = urllib.urlencode(dict(signature=config.auth['yourls'],
action='shorturl',
keyword=shorturl,
url=url))
urllib2.urlopen(shortenerUrl(SHORTEN_PART), data)
return shortenerUrl(shorturl)
|
# This is fairly specific to using a Yourls server: see http://yourls.org/
import urllib
import urllib2
import Util
SHORTEN_PART = 'yourls-api.php'
def shorten(url, config):
def shortenerUrl(part):
return '%s/%s' % (config.shortenUrl, part)
index = Util.getAndIncrementIndexFile(config.indexFile)
shorturl = config.shortenPrefix + index
data = urllib.urlencode(dict(signature=config.auth['yourls'],
action='shorturl',
keyword=shorturl,
url=url))
urllib2.urlopen(shortenerUrl(SHORTEN_PART), data)
return shortenerUrl(shorturl)
| Fix tiny errors in Python code | Fix tiny errors in Python code
| Python | mit | rec/echomesh,rec/echomesh,rec/echomesh,rec/echomesh,rec/echomesh,rec/echomesh |
# This is fairly specific to using a Yourls server: see http://yourls.org/
import urllib
import urllib2
import Util
SHORTEN_PART = 'yourls-api.php'
def shorten(url, config):
def shortenerUrl(part):
return '%s/%s' % (config.shortenUrl, part)
index = Util.getAndIncrementIndexFile(config.indexFile)
shorturl = config.shortenPrefix +
data = urllib.urlencode(dict(signature=config.auth['yourls'],
action='shorturl',
keyword=shorturl,
url=url))
urllib2.urlopen(shortenerUrl(SHORTEN_PART), data)
return shortenerUrl(shorturl)
Fix tiny errors in Python code |
# This is fairly specific to using a Yourls server: see http://yourls.org/
import urllib
import urllib2
import Util
SHORTEN_PART = 'yourls-api.php'
def shorten(url, config):
def shortenerUrl(part):
return '%s/%s' % (config.shortenUrl, part)
index = Util.getAndIncrementIndexFile(config.indexFile)
shorturl = config.shortenPrefix + index
data = urllib.urlencode(dict(signature=config.auth['yourls'],
action='shorturl',
keyword=shorturl,
url=url))
urllib2.urlopen(shortenerUrl(SHORTEN_PART), data)
return shortenerUrl(shorturl)
| <commit_before>
# This is fairly specific to using a Yourls server: see http://yourls.org/
import urllib
import urllib2
import Util
SHORTEN_PART = 'yourls-api.php'
def shorten(url, config):
def shortenerUrl(part):
return '%s/%s' % (config.shortenUrl, part)
index = Util.getAndIncrementIndexFile(config.indexFile)
shorturl = config.shortenPrefix +
data = urllib.urlencode(dict(signature=config.auth['yourls'],
action='shorturl',
keyword=shorturl,
url=url))
urllib2.urlopen(shortenerUrl(SHORTEN_PART), data)
return shortenerUrl(shorturl)
<commit_msg>Fix tiny errors in Python code<commit_after> |
# This is fairly specific to using a Yourls server: see http://yourls.org/
import urllib
import urllib2
import Util
SHORTEN_PART = 'yourls-api.php'
def shorten(url, config):
def shortenerUrl(part):
return '%s/%s' % (config.shortenUrl, part)
index = Util.getAndIncrementIndexFile(config.indexFile)
shorturl = config.shortenPrefix + index
data = urllib.urlencode(dict(signature=config.auth['yourls'],
action='shorturl',
keyword=shorturl,
url=url))
urllib2.urlopen(shortenerUrl(SHORTEN_PART), data)
return shortenerUrl(shorturl)
|
# This is fairly specific to using a Yourls server: see http://yourls.org/
import urllib
import urllib2
import Util
SHORTEN_PART = 'yourls-api.php'
def shorten(url, config):
def shortenerUrl(part):
return '%s/%s' % (config.shortenUrl, part)
index = Util.getAndIncrementIndexFile(config.indexFile)
shorturl = config.shortenPrefix +
data = urllib.urlencode(dict(signature=config.auth['yourls'],
action='shorturl',
keyword=shorturl,
url=url))
urllib2.urlopen(shortenerUrl(SHORTEN_PART), data)
return shortenerUrl(shorturl)
Fix tiny errors in Python code
# This is fairly specific to using a Yourls server: see http://yourls.org/
import urllib
import urllib2
import Util
SHORTEN_PART = 'yourls-api.php'
def shorten(url, config):
def shortenerUrl(part):
return '%s/%s' % (config.shortenUrl, part)
index = Util.getAndIncrementIndexFile(config.indexFile)
shorturl = config.shortenPrefix + index
data = urllib.urlencode(dict(signature=config.auth['yourls'],
action='shorturl',
keyword=shorturl,
url=url))
urllib2.urlopen(shortenerUrl(SHORTEN_PART), data)
return shortenerUrl(shorturl)
| <commit_before>
# This is fairly specific to using a Yourls server: see http://yourls.org/
import urllib
import urllib2
import Util
SHORTEN_PART = 'yourls-api.php'
def shorten(url, config):
def shortenerUrl(part):
return '%s/%s' % (config.shortenUrl, part)
index = Util.getAndIncrementIndexFile(config.indexFile)
shorturl = config.shortenPrefix +
data = urllib.urlencode(dict(signature=config.auth['yourls'],
action='shorturl',
keyword=shorturl,
url=url))
urllib2.urlopen(shortenerUrl(SHORTEN_PART), data)
return shortenerUrl(shorturl)
<commit_msg>Fix tiny errors in Python code<commit_after>
# This is fairly specific to using a Yourls server: see http://yourls.org/
import urllib
import urllib2
import Util
SHORTEN_PART = 'yourls-api.php'
def shorten(url, config):
def shortenerUrl(part):
return '%s/%s' % (config.shortenUrl, part)
index = Util.getAndIncrementIndexFile(config.indexFile)
shorturl = config.shortenPrefix + index
data = urllib.urlencode(dict(signature=config.auth['yourls'],
action='shorturl',
keyword=shorturl,
url=url))
urllib2.urlopen(shortenerUrl(SHORTEN_PART), data)
return shortenerUrl(shorturl)
|
0e68fd50428ceaf53e00e22c11a45ec98185e738 | avocado/export/__init__.py | avocado/export/__init__.py | from avocado.core import loader
from avocado.conf import OPTIONAL_DEPS
from _base import BaseExporter # noqa
from _csv import CSVExporter
from _sas import SASExporter
from _r import RExporter
from _json import JSONExporter
from _html import HTMLExporter # noqa
registry = loader.Registry(register_instance=False)
registry.register(CSVExporter, 'csv')
registry.register(SASExporter, 'sas')
registry.register(RExporter, 'r')
registry.register(JSONExporter, 'json')
# registry.register(HTMLExporter, 'html')
if OPTIONAL_DEPS['openpyxl']:
from _excel import ExcelExporter
registry.register(ExcelExporter, 'excel')
loader.autodiscover('exporters')
| from avocado.core import loader
from avocado.conf import OPTIONAL_DEPS
from _base import BaseExporter # noqa
from _csv import CSVExporter
from _sas import SASExporter
from _r import RExporter
from _json import JSONExporter
from _html import HTMLExporter # noqa
registry = loader.Registry(register_instance=False)
registry.register(CSVExporter, CSVExporter.short_name.lower())
registry.register(SASExporter, SASExporter.short_name.lower())
registry.register(RExporter, RExporter.short_name.lower())
registry.register(JSONExporter, JSONExporter.short_name.lower())
# registry.register(HTMLExporter, HTMLExporter.short_name.lower())
if OPTIONAL_DEPS['openpyxl']:
from _excel import ExcelExporter
registry.register(ExcelExporter, ExcelExporter.short_name.lower())
loader.autodiscover('exporters')
| Replace exporter registry keys with short_name derivative | Replace exporter registry keys with short_name derivative
Fix #203
Signed-off-by: Byron Ruth <e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98@devel.io>
| Python | bsd-2-clause | murphyke/avocado,murphyke/avocado,murphyke/avocado,murphyke/avocado | from avocado.core import loader
from avocado.conf import OPTIONAL_DEPS
from _base import BaseExporter # noqa
from _csv import CSVExporter
from _sas import SASExporter
from _r import RExporter
from _json import JSONExporter
from _html import HTMLExporter # noqa
registry = loader.Registry(register_instance=False)
registry.register(CSVExporter, 'csv')
registry.register(SASExporter, 'sas')
registry.register(RExporter, 'r')
registry.register(JSONExporter, 'json')
# registry.register(HTMLExporter, 'html')
if OPTIONAL_DEPS['openpyxl']:
from _excel import ExcelExporter
registry.register(ExcelExporter, 'excel')
loader.autodiscover('exporters')
Replace exporter registry keys with short_name derivative
Fix #203
Signed-off-by: Byron Ruth <e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98@devel.io> | from avocado.core import loader
from avocado.conf import OPTIONAL_DEPS
from _base import BaseExporter # noqa
from _csv import CSVExporter
from _sas import SASExporter
from _r import RExporter
from _json import JSONExporter
from _html import HTMLExporter # noqa
registry = loader.Registry(register_instance=False)
registry.register(CSVExporter, CSVExporter.short_name.lower())
registry.register(SASExporter, SASExporter.short_name.lower())
registry.register(RExporter, RExporter.short_name.lower())
registry.register(JSONExporter, JSONExporter.short_name.lower())
# registry.register(HTMLExporter, HTMLExporter.short_name.lower())
if OPTIONAL_DEPS['openpyxl']:
from _excel import ExcelExporter
registry.register(ExcelExporter, ExcelExporter.short_name.lower())
loader.autodiscover('exporters')
| <commit_before>from avocado.core import loader
from avocado.conf import OPTIONAL_DEPS
from _base import BaseExporter # noqa
from _csv import CSVExporter
from _sas import SASExporter
from _r import RExporter
from _json import JSONExporter
from _html import HTMLExporter # noqa
registry = loader.Registry(register_instance=False)
registry.register(CSVExporter, 'csv')
registry.register(SASExporter, 'sas')
registry.register(RExporter, 'r')
registry.register(JSONExporter, 'json')
# registry.register(HTMLExporter, 'html')
if OPTIONAL_DEPS['openpyxl']:
from _excel import ExcelExporter
registry.register(ExcelExporter, 'excel')
loader.autodiscover('exporters')
<commit_msg>Replace exporter registry keys with short_name derivative
Fix #203
Signed-off-by: Byron Ruth <e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98@devel.io><commit_after> | from avocado.core import loader
from avocado.conf import OPTIONAL_DEPS
from _base import BaseExporter # noqa
from _csv import CSVExporter
from _sas import SASExporter
from _r import RExporter
from _json import JSONExporter
from _html import HTMLExporter # noqa
registry = loader.Registry(register_instance=False)
registry.register(CSVExporter, CSVExporter.short_name.lower())
registry.register(SASExporter, SASExporter.short_name.lower())
registry.register(RExporter, RExporter.short_name.lower())
registry.register(JSONExporter, JSONExporter.short_name.lower())
# registry.register(HTMLExporter, HTMLExporter.short_name.lower())
if OPTIONAL_DEPS['openpyxl']:
from _excel import ExcelExporter
registry.register(ExcelExporter, ExcelExporter.short_name.lower())
loader.autodiscover('exporters')
| from avocado.core import loader
from avocado.conf import OPTIONAL_DEPS
from _base import BaseExporter # noqa
from _csv import CSVExporter
from _sas import SASExporter
from _r import RExporter
from _json import JSONExporter
from _html import HTMLExporter # noqa
registry = loader.Registry(register_instance=False)
registry.register(CSVExporter, 'csv')
registry.register(SASExporter, 'sas')
registry.register(RExporter, 'r')
registry.register(JSONExporter, 'json')
# registry.register(HTMLExporter, 'html')
if OPTIONAL_DEPS['openpyxl']:
from _excel import ExcelExporter
registry.register(ExcelExporter, 'excel')
loader.autodiscover('exporters')
Replace exporter registry keys with short_name derivative
Fix #203
Signed-off-by: Byron Ruth <e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98@devel.io>from avocado.core import loader
from avocado.conf import OPTIONAL_DEPS
from _base import BaseExporter # noqa
from _csv import CSVExporter
from _sas import SASExporter
from _r import RExporter
from _json import JSONExporter
from _html import HTMLExporter # noqa
registry = loader.Registry(register_instance=False)
registry.register(CSVExporter, CSVExporter.short_name.lower())
registry.register(SASExporter, SASExporter.short_name.lower())
registry.register(RExporter, RExporter.short_name.lower())
registry.register(JSONExporter, JSONExporter.short_name.lower())
# registry.register(HTMLExporter, HTMLExporter.short_name.lower())
if OPTIONAL_DEPS['openpyxl']:
from _excel import ExcelExporter
registry.register(ExcelExporter, ExcelExporter.short_name.lower())
loader.autodiscover('exporters')
| <commit_before>from avocado.core import loader
from avocado.conf import OPTIONAL_DEPS
from _base import BaseExporter # noqa
from _csv import CSVExporter
from _sas import SASExporter
from _r import RExporter
from _json import JSONExporter
from _html import HTMLExporter # noqa
registry = loader.Registry(register_instance=False)
registry.register(CSVExporter, 'csv')
registry.register(SASExporter, 'sas')
registry.register(RExporter, 'r')
registry.register(JSONExporter, 'json')
# registry.register(HTMLExporter, 'html')
if OPTIONAL_DEPS['openpyxl']:
from _excel import ExcelExporter
registry.register(ExcelExporter, 'excel')
loader.autodiscover('exporters')
<commit_msg>Replace exporter registry keys with short_name derivative
Fix #203
Signed-off-by: Byron Ruth <e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98@devel.io><commit_after>from avocado.core import loader
from avocado.conf import OPTIONAL_DEPS
from _base import BaseExporter # noqa
from _csv import CSVExporter
from _sas import SASExporter
from _r import RExporter
from _json import JSONExporter
from _html import HTMLExporter # noqa
registry = loader.Registry(register_instance=False)
registry.register(CSVExporter, CSVExporter.short_name.lower())
registry.register(SASExporter, SASExporter.short_name.lower())
registry.register(RExporter, RExporter.short_name.lower())
registry.register(JSONExporter, JSONExporter.short_name.lower())
# registry.register(HTMLExporter, HTMLExporter.short_name.lower())
if OPTIONAL_DEPS['openpyxl']:
from _excel import ExcelExporter
registry.register(ExcelExporter, ExcelExporter.short_name.lower())
loader.autodiscover('exporters')
|
d55389580160c4585c131537c04c4045a38ea134 | fluxghost/http_server_base.py | fluxghost/http_server_base.py |
from select import select
import logging
import socket
logger = logging.getLogger("HTTPServer")
from fluxghost.http_handlers.websocket_handler import WebSocketHandler
from fluxghost.http_handlers.file_handler import FileHandler
class HttpServerBase(object):
def __init__(self, assets_path, address, backlog=10):
self.assets_handler = FileHandler(assets_path)
self.ws_handler = WebSocketHandler()
self.sock = s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(address)
s.listen(backlog)
logger.info("Listen HTTP on %s:%s" % address)
def serve_forever(self):
self.running = True
args = ((self.sock, ), (), (), 30.)
while self.running:
try:
rl = select(*args)[0]
if rl:
self.on_accept()
except InterruptedError:
pass
|
from select import select
import logging
import socket
logger = logging.getLogger("HTTPServer")
from fluxghost.http_handlers.websocket_handler import WebSocketHandler
from fluxghost.http_handlers.file_handler import FileHandler
class HttpServerBase(object):
def __init__(self, assets_path, address, backlog=10):
self.assets_handler = FileHandler(assets_path)
self.ws_handler = WebSocketHandler()
self.sock = s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(address)
s.listen(backlog)
if address[1] == 0:
from sys import stdout
address = s.getsockname()
stdout.write("LISTEN ON %i\n" % address[1])
stdout.flush()
logger.info("Listen HTTP on %s:%s" % address)
def serve_forever(self):
self.running = True
args = ((self.sock, ), (), (), 30.)
while self.running:
try:
rl = select(*args)[0]
if rl:
self.on_accept()
except InterruptedError:
pass
| Add auto select port function | Add auto select port function
| Python | agpl-3.0 | flux3dp/fluxghost,flux3dp/fluxghost,flux3dp/fluxghost,flux3dp/fluxghost |
from select import select
import logging
import socket
logger = logging.getLogger("HTTPServer")
from fluxghost.http_handlers.websocket_handler import WebSocketHandler
from fluxghost.http_handlers.file_handler import FileHandler
class HttpServerBase(object):
def __init__(self, assets_path, address, backlog=10):
self.assets_handler = FileHandler(assets_path)
self.ws_handler = WebSocketHandler()
self.sock = s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(address)
s.listen(backlog)
logger.info("Listen HTTP on %s:%s" % address)
def serve_forever(self):
self.running = True
args = ((self.sock, ), (), (), 30.)
while self.running:
try:
rl = select(*args)[0]
if rl:
self.on_accept()
except InterruptedError:
pass
Add auto select port function |
from select import select
import logging
import socket
logger = logging.getLogger("HTTPServer")
from fluxghost.http_handlers.websocket_handler import WebSocketHandler
from fluxghost.http_handlers.file_handler import FileHandler
class HttpServerBase(object):
def __init__(self, assets_path, address, backlog=10):
self.assets_handler = FileHandler(assets_path)
self.ws_handler = WebSocketHandler()
self.sock = s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(address)
s.listen(backlog)
if address[1] == 0:
from sys import stdout
address = s.getsockname()
stdout.write("LISTEN ON %i\n" % address[1])
stdout.flush()
logger.info("Listen HTTP on %s:%s" % address)
def serve_forever(self):
self.running = True
args = ((self.sock, ), (), (), 30.)
while self.running:
try:
rl = select(*args)[0]
if rl:
self.on_accept()
except InterruptedError:
pass
| <commit_before>
from select import select
import logging
import socket
logger = logging.getLogger("HTTPServer")
from fluxghost.http_handlers.websocket_handler import WebSocketHandler
from fluxghost.http_handlers.file_handler import FileHandler
class HttpServerBase(object):
def __init__(self, assets_path, address, backlog=10):
self.assets_handler = FileHandler(assets_path)
self.ws_handler = WebSocketHandler()
self.sock = s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(address)
s.listen(backlog)
logger.info("Listen HTTP on %s:%s" % address)
def serve_forever(self):
self.running = True
args = ((self.sock, ), (), (), 30.)
while self.running:
try:
rl = select(*args)[0]
if rl:
self.on_accept()
except InterruptedError:
pass
<commit_msg>Add auto select port function<commit_after> |
from select import select
import logging
import socket
logger = logging.getLogger("HTTPServer")
from fluxghost.http_handlers.websocket_handler import WebSocketHandler
from fluxghost.http_handlers.file_handler import FileHandler
class HttpServerBase(object):
def __init__(self, assets_path, address, backlog=10):
self.assets_handler = FileHandler(assets_path)
self.ws_handler = WebSocketHandler()
self.sock = s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(address)
s.listen(backlog)
if address[1] == 0:
from sys import stdout
address = s.getsockname()
stdout.write("LISTEN ON %i\n" % address[1])
stdout.flush()
logger.info("Listen HTTP on %s:%s" % address)
def serve_forever(self):
self.running = True
args = ((self.sock, ), (), (), 30.)
while self.running:
try:
rl = select(*args)[0]
if rl:
self.on_accept()
except InterruptedError:
pass
|
from select import select
import logging
import socket
logger = logging.getLogger("HTTPServer")
from fluxghost.http_handlers.websocket_handler import WebSocketHandler
from fluxghost.http_handlers.file_handler import FileHandler
class HttpServerBase(object):
def __init__(self, assets_path, address, backlog=10):
self.assets_handler = FileHandler(assets_path)
self.ws_handler = WebSocketHandler()
self.sock = s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(address)
s.listen(backlog)
logger.info("Listen HTTP on %s:%s" % address)
def serve_forever(self):
self.running = True
args = ((self.sock, ), (), (), 30.)
while self.running:
try:
rl = select(*args)[0]
if rl:
self.on_accept()
except InterruptedError:
pass
Add auto select port function
from select import select
import logging
import socket
logger = logging.getLogger("HTTPServer")
from fluxghost.http_handlers.websocket_handler import WebSocketHandler
from fluxghost.http_handlers.file_handler import FileHandler
class HttpServerBase(object):
def __init__(self, assets_path, address, backlog=10):
self.assets_handler = FileHandler(assets_path)
self.ws_handler = WebSocketHandler()
self.sock = s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(address)
s.listen(backlog)
if address[1] == 0:
from sys import stdout
address = s.getsockname()
stdout.write("LISTEN ON %i\n" % address[1])
stdout.flush()
logger.info("Listen HTTP on %s:%s" % address)
def serve_forever(self):
self.running = True
args = ((self.sock, ), (), (), 30.)
while self.running:
try:
rl = select(*args)[0]
if rl:
self.on_accept()
except InterruptedError:
pass
| <commit_before>
from select import select
import logging
import socket
logger = logging.getLogger("HTTPServer")
from fluxghost.http_handlers.websocket_handler import WebSocketHandler
from fluxghost.http_handlers.file_handler import FileHandler
class HttpServerBase(object):
def __init__(self, assets_path, address, backlog=10):
self.assets_handler = FileHandler(assets_path)
self.ws_handler = WebSocketHandler()
self.sock = s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(address)
s.listen(backlog)
logger.info("Listen HTTP on %s:%s" % address)
def serve_forever(self):
self.running = True
args = ((self.sock, ), (), (), 30.)
while self.running:
try:
rl = select(*args)[0]
if rl:
self.on_accept()
except InterruptedError:
pass
<commit_msg>Add auto select port function<commit_after>
from select import select
import logging
import socket
logger = logging.getLogger("HTTPServer")
from fluxghost.http_handlers.websocket_handler import WebSocketHandler
from fluxghost.http_handlers.file_handler import FileHandler
class HttpServerBase(object):
def __init__(self, assets_path, address, backlog=10):
self.assets_handler = FileHandler(assets_path)
self.ws_handler = WebSocketHandler()
self.sock = s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(address)
s.listen(backlog)
if address[1] == 0:
from sys import stdout
address = s.getsockname()
stdout.write("LISTEN ON %i\n" % address[1])
stdout.flush()
logger.info("Listen HTTP on %s:%s" % address)
def serve_forever(self):
self.running = True
args = ((self.sock, ), (), (), 30.)
while self.running:
try:
rl = select(*args)[0]
if rl:
self.on_accept()
except InterruptedError:
pass
|
ffdd11e7aeed179868618dd7b4666e5e149962b0 | solar/solar/core/handlers/__init__.py | solar/solar/core/handlers/__init__.py | # -*- coding: utf-8 -*-
from solar.core.handlers.ansible_template import AnsibleTemplate
from solar.core.handlers.ansible_playbook import AnsiblePlaybook
from solar.core.handlers.base import Empty
from solar.core.handlers.puppet import Puppet
from solar.core.handlers.shell import Shell
HANDLERS = {'ansible': AnsibleTemplate,
'ansible_playbook': AnsiblePlaybook,
'shell': Shell,
'none': Empty}
def get(handler_name):
handler = HANDLERS.get(handler_name, None)
if handler:
return handler
raise Exception('Handler {0} does not exist'.format(handler_name))
| # -*- coding: utf-8 -*-
from solar.core.handlers.ansible_template import AnsibleTemplate
from solar.core.handlers.ansible_playbook import AnsiblePlaybook
from solar.core.handlers.base import Empty
from solar.core.handlers.puppet import Puppet
from solar.core.handlers.shell import Shell
HANDLERS = {'ansible': AnsibleTemplate,
'ansible_playbook': AnsiblePlaybook,
'shell': Shell,
'puppet': Puppet,
'none': Empty}
def get(handler_name):
handler = HANDLERS.get(handler_name, None)
if handler:
return handler
raise Exception('Handler {0} does not exist'.format(handler_name))
| Add lost handler for puppet | Add lost handler for puppet
| Python | apache-2.0 | loles/solar,openstack/solar,zen/solar,dshulyak/solar,loles/solar,loles/solar,CGenie/solar,torgartor21/solar,pigmej/solar,Mirantis/solar,torgartor21/solar,zen/solar,Mirantis/solar,pigmej/solar,loles/solar,openstack/solar,pigmej/solar,zen/solar,Mirantis/solar,Mirantis/solar,zen/solar,openstack/solar,CGenie/solar,dshulyak/solar | # -*- coding: utf-8 -*-
from solar.core.handlers.ansible_template import AnsibleTemplate
from solar.core.handlers.ansible_playbook import AnsiblePlaybook
from solar.core.handlers.base import Empty
from solar.core.handlers.puppet import Puppet
from solar.core.handlers.shell import Shell
HANDLERS = {'ansible': AnsibleTemplate,
'ansible_playbook': AnsiblePlaybook,
'shell': Shell,
'none': Empty}
def get(handler_name):
handler = HANDLERS.get(handler_name, None)
if handler:
return handler
raise Exception('Handler {0} does not exist'.format(handler_name))
Add lost handler for puppet | # -*- coding: utf-8 -*-
from solar.core.handlers.ansible_template import AnsibleTemplate
from solar.core.handlers.ansible_playbook import AnsiblePlaybook
from solar.core.handlers.base import Empty
from solar.core.handlers.puppet import Puppet
from solar.core.handlers.shell import Shell
HANDLERS = {'ansible': AnsibleTemplate,
'ansible_playbook': AnsiblePlaybook,
'shell': Shell,
'puppet': Puppet,
'none': Empty}
def get(handler_name):
handler = HANDLERS.get(handler_name, None)
if handler:
return handler
raise Exception('Handler {0} does not exist'.format(handler_name))
| <commit_before># -*- coding: utf-8 -*-
from solar.core.handlers.ansible_template import AnsibleTemplate
from solar.core.handlers.ansible_playbook import AnsiblePlaybook
from solar.core.handlers.base import Empty
from solar.core.handlers.puppet import Puppet
from solar.core.handlers.shell import Shell
HANDLERS = {'ansible': AnsibleTemplate,
'ansible_playbook': AnsiblePlaybook,
'shell': Shell,
'none': Empty}
def get(handler_name):
handler = HANDLERS.get(handler_name, None)
if handler:
return handler
raise Exception('Handler {0} does not exist'.format(handler_name))
<commit_msg>Add lost handler for puppet<commit_after> | # -*- coding: utf-8 -*-
from solar.core.handlers.ansible_template import AnsibleTemplate
from solar.core.handlers.ansible_playbook import AnsiblePlaybook
from solar.core.handlers.base import Empty
from solar.core.handlers.puppet import Puppet
from solar.core.handlers.shell import Shell
HANDLERS = {'ansible': AnsibleTemplate,
'ansible_playbook': AnsiblePlaybook,
'shell': Shell,
'puppet': Puppet,
'none': Empty}
def get(handler_name):
handler = HANDLERS.get(handler_name, None)
if handler:
return handler
raise Exception('Handler {0} does not exist'.format(handler_name))
| # -*- coding: utf-8 -*-
from solar.core.handlers.ansible_template import AnsibleTemplate
from solar.core.handlers.ansible_playbook import AnsiblePlaybook
from solar.core.handlers.base import Empty
from solar.core.handlers.puppet import Puppet
from solar.core.handlers.shell import Shell
HANDLERS = {'ansible': AnsibleTemplate,
'ansible_playbook': AnsiblePlaybook,
'shell': Shell,
'none': Empty}
def get(handler_name):
handler = HANDLERS.get(handler_name, None)
if handler:
return handler
raise Exception('Handler {0} does not exist'.format(handler_name))
Add lost handler for puppet# -*- coding: utf-8 -*-
from solar.core.handlers.ansible_template import AnsibleTemplate
from solar.core.handlers.ansible_playbook import AnsiblePlaybook
from solar.core.handlers.base import Empty
from solar.core.handlers.puppet import Puppet
from solar.core.handlers.shell import Shell
HANDLERS = {'ansible': AnsibleTemplate,
'ansible_playbook': AnsiblePlaybook,
'shell': Shell,
'puppet': Puppet,
'none': Empty}
def get(handler_name):
handler = HANDLERS.get(handler_name, None)
if handler:
return handler
raise Exception('Handler {0} does not exist'.format(handler_name))
| <commit_before># -*- coding: utf-8 -*-
from solar.core.handlers.ansible_template import AnsibleTemplate
from solar.core.handlers.ansible_playbook import AnsiblePlaybook
from solar.core.handlers.base import Empty
from solar.core.handlers.puppet import Puppet
from solar.core.handlers.shell import Shell
HANDLERS = {'ansible': AnsibleTemplate,
'ansible_playbook': AnsiblePlaybook,
'shell': Shell,
'none': Empty}
def get(handler_name):
handler = HANDLERS.get(handler_name, None)
if handler:
return handler
raise Exception('Handler {0} does not exist'.format(handler_name))
<commit_msg>Add lost handler for puppet<commit_after># -*- coding: utf-8 -*-
from solar.core.handlers.ansible_template import AnsibleTemplate
from solar.core.handlers.ansible_playbook import AnsiblePlaybook
from solar.core.handlers.base import Empty
from solar.core.handlers.puppet import Puppet
from solar.core.handlers.shell import Shell
HANDLERS = {'ansible': AnsibleTemplate,
'ansible_playbook': AnsiblePlaybook,
'shell': Shell,
'puppet': Puppet,
'none': Empty}
def get(handler_name):
handler = HANDLERS.get(handler_name, None)
if handler:
return handler
raise Exception('Handler {0} does not exist'.format(handler_name))
|
d3beb067abca8a2c014ca8039556181881310392 | app/groups/utils.py | app/groups/utils.py | from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
def send_group_mail(request, to_email, subject, email_text_template, email_html_template):
"""Sends a email to a group of people using a standard layout"""
# Mail the admins to inform them of a new request
ctx = Context({'request': obj})
to_email = group.admins.values_list('email', flat=True)
msg = EmailMultiAlternatives(subject, get_template(email_text_template).render(ctx), getattr(settings, 'SERVER_EMAIL', 'auth@pleaseignore.com'), to_email)
msg.attach_alternative(get_template(email_html_template).render(ctx), 'text/html')
mag.send(fail_silently=True)
| from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
def send_group_mail(request, to_email, subject, email_text_template, email_html_template):
"""Sends a email to a group of people using a standard layout"""
# Mail the admins to inform them of a new request
ctx = Context({'request': obj})
to_email = group.admins.values_list('email', flat=True)
msg = EmailMultiAlternatives(subject, get_template(email_text_template).render(ctx), getattr(settings, 'DEFAULT_FROM_EMAIL', 'auth@pleaseignore.com'), to_email)
msg.attach_alternative(get_template(email_html_template).render(ctx), 'text/html')
mag.send(fail_silently=True)
| Switch to default mail from variable | Switch to default mail from variable
| Python | bsd-3-clause | nikdoof/test-auth | from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
def send_group_mail(request, to_email, subject, email_text_template, email_html_template):
"""Sends a email to a group of people using a standard layout"""
# Mail the admins to inform them of a new request
ctx = Context({'request': obj})
to_email = group.admins.values_list('email', flat=True)
msg = EmailMultiAlternatives(subject, get_template(email_text_template).render(ctx), getattr(settings, 'SERVER_EMAIL', 'auth@pleaseignore.com'), to_email)
msg.attach_alternative(get_template(email_html_template).render(ctx), 'text/html')
mag.send(fail_silently=True)
Switch to default mail from variable | from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
def send_group_mail(request, to_email, subject, email_text_template, email_html_template):
"""Sends a email to a group of people using a standard layout"""
# Mail the admins to inform them of a new request
ctx = Context({'request': obj})
to_email = group.admins.values_list('email', flat=True)
msg = EmailMultiAlternatives(subject, get_template(email_text_template).render(ctx), getattr(settings, 'DEFAULT_FROM_EMAIL', 'auth@pleaseignore.com'), to_email)
msg.attach_alternative(get_template(email_html_template).render(ctx), 'text/html')
mag.send(fail_silently=True)
| <commit_before>from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
def send_group_mail(request, to_email, subject, email_text_template, email_html_template):
"""Sends a email to a group of people using a standard layout"""
# Mail the admins to inform them of a new request
ctx = Context({'request': obj})
to_email = group.admins.values_list('email', flat=True)
msg = EmailMultiAlternatives(subject, get_template(email_text_template).render(ctx), getattr(settings, 'SERVER_EMAIL', 'auth@pleaseignore.com'), to_email)
msg.attach_alternative(get_template(email_html_template).render(ctx), 'text/html')
mag.send(fail_silently=True)
<commit_msg>Switch to default mail from variable<commit_after> | from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
def send_group_mail(request, to_email, subject, email_text_template, email_html_template):
"""Sends a email to a group of people using a standard layout"""
# Mail the admins to inform them of a new request
ctx = Context({'request': obj})
to_email = group.admins.values_list('email', flat=True)
msg = EmailMultiAlternatives(subject, get_template(email_text_template).render(ctx), getattr(settings, 'DEFAULT_FROM_EMAIL', 'auth@pleaseignore.com'), to_email)
msg.attach_alternative(get_template(email_html_template).render(ctx), 'text/html')
mag.send(fail_silently=True)
| from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
def send_group_mail(request, to_email, subject, email_text_template, email_html_template):
"""Sends a email to a group of people using a standard layout"""
# Mail the admins to inform them of a new request
ctx = Context({'request': obj})
to_email = group.admins.values_list('email', flat=True)
msg = EmailMultiAlternatives(subject, get_template(email_text_template).render(ctx), getattr(settings, 'SERVER_EMAIL', 'auth@pleaseignore.com'), to_email)
msg.attach_alternative(get_template(email_html_template).render(ctx), 'text/html')
mag.send(fail_silently=True)
Switch to default mail from variablefrom django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
def send_group_mail(request, to_email, subject, email_text_template, email_html_template):
"""Sends a email to a group of people using a standard layout"""
# Mail the admins to inform them of a new request
ctx = Context({'request': obj})
to_email = group.admins.values_list('email', flat=True)
msg = EmailMultiAlternatives(subject, get_template(email_text_template).render(ctx), getattr(settings, 'DEFAULT_FROM_EMAIL', 'auth@pleaseignore.com'), to_email)
msg.attach_alternative(get_template(email_html_template).render(ctx), 'text/html')
mag.send(fail_silently=True)
| <commit_before>from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
def send_group_mail(request, to_email, subject, email_text_template, email_html_template):
"""Sends a email to a group of people using a standard layout"""
# Mail the admins to inform them of a new request
ctx = Context({'request': obj})
to_email = group.admins.values_list('email', flat=True)
msg = EmailMultiAlternatives(subject, get_template(email_text_template).render(ctx), getattr(settings, 'SERVER_EMAIL', 'auth@pleaseignore.com'), to_email)
msg.attach_alternative(get_template(email_html_template).render(ctx), 'text/html')
mag.send(fail_silently=True)
<commit_msg>Switch to default mail from variable<commit_after>from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
def send_group_mail(request, to_email, subject, email_text_template, email_html_template):
"""Sends a email to a group of people using a standard layout"""
# Mail the admins to inform them of a new request
ctx = Context({'request': obj})
to_email = group.admins.values_list('email', flat=True)
msg = EmailMultiAlternatives(subject, get_template(email_text_template).render(ctx), getattr(settings, 'DEFAULT_FROM_EMAIL', 'auth@pleaseignore.com'), to_email)
msg.attach_alternative(get_template(email_html_template).render(ctx), 'text/html')
mag.send(fail_silently=True)
|
f3803452c669aa35ca71f00c18f613e276a70ca2 | scripts/add_users.py | scripts/add_users.py | #!/usr/bin/env python
"""
Add a series of users from a file of JSON objects, one per line.
The JSON user object lines can have the following fields:
{"name": "A. Non", "password": "pass12345", 'emailAddress': "email@email.com", "role": "supplier", "supplierId": 12345}
Usage:
add-users.py <data_api_endpoint> <data_api_token> <users_path>
"""
from docopt import docopt
from dmutils.apiclient import DataAPIClient
import json
def load_users(users_path):
with open(users_path) as f:
for line in f:
yield json.loads(line)
def update_suppliers(data_api_endpoint, data_api_token, users_path):
client = DataAPIClient(data_api_endpoint, data_api_token)
for user in load_users(users_path):
print("Adding {}".format(user))
client.create_user(user)
if __name__ == '__main__':
arguments = docopt(__doc__)
update_suppliers(
data_api_endpoint=arguments['<data_api_endpoint>'],
data_api_token=arguments['<data_api_token>'],
users_path=arguments['<users_path>'])
| #!/usr/bin/env python
"""
Add a series of users from a file of JSON objects, one per line.
The JSON user object lines can have the following fields:
{"name": "A. Non", "password": "pass12345", "emailAddress": "email@email.com", "role": "supplier", "supplierId": 12345}
Usage:
add-users.py <data_api_endpoint> <data_api_token> <users_path>
"""
from docopt import docopt
from dmutils.apiclient import DataAPIClient
import json
def load_users(users_path):
with open(users_path) as f:
for line in f:
yield json.loads(line)
def update_suppliers(data_api_endpoint, data_api_token, users_path):
client = DataAPIClient(data_api_endpoint, data_api_token)
for user in load_users(users_path):
print("Adding {}".format(user))
client.create_user(user)
if __name__ == '__main__':
arguments = docopt(__doc__)
update_suppliers(
data_api_endpoint=arguments['<data_api_endpoint>'],
data_api_token=arguments['<data_api_token>'],
users_path=arguments['<users_path>'])
| Fix example of how to run script, and make it executable | Fix example of how to run script, and make it executable
| Python | mit | alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api | #!/usr/bin/env python
"""
Add a series of users from a file of JSON objects, one per line.
The JSON user object lines can have the following fields:
{"name": "A. Non", "password": "pass12345", 'emailAddress': "email@email.com", "role": "supplier", "supplierId": 12345}
Usage:
add-users.py <data_api_endpoint> <data_api_token> <users_path>
"""
from docopt import docopt
from dmutils.apiclient import DataAPIClient
import json
def load_users(users_path):
with open(users_path) as f:
for line in f:
yield json.loads(line)
def update_suppliers(data_api_endpoint, data_api_token, users_path):
client = DataAPIClient(data_api_endpoint, data_api_token)
for user in load_users(users_path):
print("Adding {}".format(user))
client.create_user(user)
if __name__ == '__main__':
arguments = docopt(__doc__)
update_suppliers(
data_api_endpoint=arguments['<data_api_endpoint>'],
data_api_token=arguments['<data_api_token>'],
users_path=arguments['<users_path>'])
Fix example of how to run script, and make it executable | #!/usr/bin/env python
"""
Add a series of users from a file of JSON objects, one per line.
The JSON user object lines can have the following fields:
{"name": "A. Non", "password": "pass12345", "emailAddress": "email@email.com", "role": "supplier", "supplierId": 12345}
Usage:
add-users.py <data_api_endpoint> <data_api_token> <users_path>
"""
from docopt import docopt
from dmutils.apiclient import DataAPIClient
import json
def load_users(users_path):
with open(users_path) as f:
for line in f:
yield json.loads(line)
def update_suppliers(data_api_endpoint, data_api_token, users_path):
client = DataAPIClient(data_api_endpoint, data_api_token)
for user in load_users(users_path):
print("Adding {}".format(user))
client.create_user(user)
if __name__ == '__main__':
arguments = docopt(__doc__)
update_suppliers(
data_api_endpoint=arguments['<data_api_endpoint>'],
data_api_token=arguments['<data_api_token>'],
users_path=arguments['<users_path>'])
| <commit_before>#!/usr/bin/env python
"""
Add a series of users from a file of JSON objects, one per line.
The JSON user object lines can have the following fields:
{"name": "A. Non", "password": "pass12345", 'emailAddress': "email@email.com", "role": "supplier", "supplierId": 12345}
Usage:
add-users.py <data_api_endpoint> <data_api_token> <users_path>
"""
from docopt import docopt
from dmutils.apiclient import DataAPIClient
import json
def load_users(users_path):
with open(users_path) as f:
for line in f:
yield json.loads(line)
def update_suppliers(data_api_endpoint, data_api_token, users_path):
client = DataAPIClient(data_api_endpoint, data_api_token)
for user in load_users(users_path):
print("Adding {}".format(user))
client.create_user(user)
if __name__ == '__main__':
arguments = docopt(__doc__)
update_suppliers(
data_api_endpoint=arguments['<data_api_endpoint>'],
data_api_token=arguments['<data_api_token>'],
users_path=arguments['<users_path>'])
<commit_msg>Fix example of how to run script, and make it executable<commit_after> | #!/usr/bin/env python
"""
Add a series of users from a file of JSON objects, one per line.
The JSON user object lines can have the following fields:
{"name": "A. Non", "password": "pass12345", "emailAddress": "email@email.com", "role": "supplier", "supplierId": 12345}
Usage:
add-users.py <data_api_endpoint> <data_api_token> <users_path>
"""
from docopt import docopt
from dmutils.apiclient import DataAPIClient
import json
def load_users(users_path):
with open(users_path) as f:
for line in f:
yield json.loads(line)
def update_suppliers(data_api_endpoint, data_api_token, users_path):
client = DataAPIClient(data_api_endpoint, data_api_token)
for user in load_users(users_path):
print("Adding {}".format(user))
client.create_user(user)
if __name__ == '__main__':
arguments = docopt(__doc__)
update_suppliers(
data_api_endpoint=arguments['<data_api_endpoint>'],
data_api_token=arguments['<data_api_token>'],
users_path=arguments['<users_path>'])
| #!/usr/bin/env python
"""
Add a series of users from a file of JSON objects, one per line.
The JSON user object lines can have the following fields:
{"name": "A. Non", "password": "pass12345", 'emailAddress': "email@email.com", "role": "supplier", "supplierId": 12345}
Usage:
add-users.py <data_api_endpoint> <data_api_token> <users_path>
"""
from docopt import docopt
from dmutils.apiclient import DataAPIClient
import json
def load_users(users_path):
with open(users_path) as f:
for line in f:
yield json.loads(line)
def update_suppliers(data_api_endpoint, data_api_token, users_path):
client = DataAPIClient(data_api_endpoint, data_api_token)
for user in load_users(users_path):
print("Adding {}".format(user))
client.create_user(user)
if __name__ == '__main__':
arguments = docopt(__doc__)
update_suppliers(
data_api_endpoint=arguments['<data_api_endpoint>'],
data_api_token=arguments['<data_api_token>'],
users_path=arguments['<users_path>'])
Fix example of how to run script, and make it executable#!/usr/bin/env python
"""
Add a series of users from a file of JSON objects, one per line.
The JSON user object lines can have the following fields:
{"name": "A. Non", "password": "pass12345", "emailAddress": "email@email.com", "role": "supplier", "supplierId": 12345}
Usage:
add-users.py <data_api_endpoint> <data_api_token> <users_path>
"""
from docopt import docopt
from dmutils.apiclient import DataAPIClient
import json
def load_users(users_path):
with open(users_path) as f:
for line in f:
yield json.loads(line)
def update_suppliers(data_api_endpoint, data_api_token, users_path):
client = DataAPIClient(data_api_endpoint, data_api_token)
for user in load_users(users_path):
print("Adding {}".format(user))
client.create_user(user)
if __name__ == '__main__':
arguments = docopt(__doc__)
update_suppliers(
data_api_endpoint=arguments['<data_api_endpoint>'],
data_api_token=arguments['<data_api_token>'],
users_path=arguments['<users_path>'])
| <commit_before>#!/usr/bin/env python
"""
Add a series of users from a file of JSON objects, one per line.
The JSON user object lines can have the following fields:
{"name": "A. Non", "password": "pass12345", 'emailAddress': "email@email.com", "role": "supplier", "supplierId": 12345}
Usage:
add-users.py <data_api_endpoint> <data_api_token> <users_path>
"""
from docopt import docopt
from dmutils.apiclient import DataAPIClient
import json
def load_users(users_path):
with open(users_path) as f:
for line in f:
yield json.loads(line)
def update_suppliers(data_api_endpoint, data_api_token, users_path):
client = DataAPIClient(data_api_endpoint, data_api_token)
for user in load_users(users_path):
print("Adding {}".format(user))
client.create_user(user)
if __name__ == '__main__':
arguments = docopt(__doc__)
update_suppliers(
data_api_endpoint=arguments['<data_api_endpoint>'],
data_api_token=arguments['<data_api_token>'],
users_path=arguments['<users_path>'])
<commit_msg>Fix example of how to run script, and make it executable<commit_after>#!/usr/bin/env python
"""
Add a series of users from a file of JSON objects, one per line.
The JSON user object lines can have the following fields:
{"name": "A. Non", "password": "pass12345", "emailAddress": "email@email.com", "role": "supplier", "supplierId": 12345}
Usage:
add-users.py <data_api_endpoint> <data_api_token> <users_path>
"""
from docopt import docopt
from dmutils.apiclient import DataAPIClient
import json
def load_users(users_path):
with open(users_path) as f:
for line in f:
yield json.loads(line)
def update_suppliers(data_api_endpoint, data_api_token, users_path):
client = DataAPIClient(data_api_endpoint, data_api_token)
for user in load_users(users_path):
print("Adding {}".format(user))
client.create_user(user)
if __name__ == '__main__':
arguments = docopt(__doc__)
update_suppliers(
data_api_endpoint=arguments['<data_api_endpoint>'],
data_api_token=arguments['<data_api_token>'],
users_path=arguments['<users_path>'])
|
0ffd3699fc696bca7d7bd1b35870aa66fb0598ef | lms/djangoapps/instructor_task/admin.py | lms/djangoapps/instructor_task/admin.py | """
Basic admin screens to search and edit InstructorTasks.
This will mostly involve searching by course_id or task_id and manually failing
a task.
"""
from config_models.admin import ConfigurationModelAdmin
from django.contrib import admin
from .config.models import GradeReportSetting
from .models import InstructorTask
class InstructorTaskAdmin(admin.ModelAdmin):
list_display = [
'task_id',
'task_type',
'course_id',
'username',
'email',
'created',
'updated',
]
list_filter = ['task_type', 'task_state']
search_fields = [
'task_id', 'course_id', 'requester__email', 'requester__username'
]
raw_id_fields = ['requester'] # avoid trying to make a select dropdown
def email(self, task):
return task.requester.email
email.admin_order_field = 'requester__email'
def username(self, task):
return task.requester.username
email.admin_order_field = 'requester__username'
admin.site.register(InstructorTask, InstructorTaskAdmin)
admin.site.register(GradeReportSetting, ConfigurationModelAdmin)
| """
Basic admin screens to search and edit InstructorTasks.
This will mostly involve searching by course_id or task_id and manually failing
a task.
"""
from config_models.admin import ConfigurationModelAdmin
from django.contrib import admin
from .config.models import GradeReportSetting
from .models import InstructorTask
def mark_tasks_as_failed(modeladmin, request, queryset):
queryset.update(
task_state='FAILURE',
task_output='{}',
task_key='dummy_task_key',
)
mark_tasks_as_failed.short_description = "Mark Tasks as Failed"
class InstructorTaskAdmin(admin.ModelAdmin):
actions = [mark_tasks_as_failed]
list_display = [
'task_id',
'task_state',
'task_type',
'course_id',
'username',
'email',
'created',
'updated',
]
list_filter = ['task_type', 'task_state']
search_fields = [
'task_id', 'course_id', 'requester__email', 'requester__username'
]
raw_id_fields = ['requester'] # avoid trying to make a select dropdown
def email(self, task):
return task.requester.email
email.admin_order_field = 'requester__email'
def username(self, task):
return task.requester.username
email.admin_order_field = 'requester__username'
admin.site.register(InstructorTask, InstructorTaskAdmin)
admin.site.register(GradeReportSetting, ConfigurationModelAdmin)
| Add ability to manually fail instructor tasks in batches. | Add ability to manually fail instructor tasks in batches.
When an InstructorTask is stuck in QUEUING (say if there was a
problem with celery), the support team needs to manually intervene
and mark the task as "FAILED" so that new tasks of that type can
be created for that course. This is usually done one at a time,
but sometimes a bug or outage might cause many tasks to fail at
once, making recovery extremely cumbersome. This commit adds the
ability to do this process in batches.
| Python | agpl-3.0 | EDUlib/edx-platform,eduNEXT/edunext-platform,stvstnfrd/edx-platform,arbrandes/edx-platform,stvstnfrd/edx-platform,angelapper/edx-platform,arbrandes/edx-platform,eduNEXT/edx-platform,edx/edx-platform,eduNEXT/edx-platform,EDUlib/edx-platform,eduNEXT/edunext-platform,eduNEXT/edunext-platform,angelapper/edx-platform,edx/edx-platform,eduNEXT/edx-platform,angelapper/edx-platform,angelapper/edx-platform,edx/edx-platform,edx/edx-platform,eduNEXT/edx-platform,arbrandes/edx-platform,stvstnfrd/edx-platform,EDUlib/edx-platform,stvstnfrd/edx-platform,eduNEXT/edunext-platform,arbrandes/edx-platform,EDUlib/edx-platform | """
Basic admin screens to search and edit InstructorTasks.
This will mostly involve searching by course_id or task_id and manually failing
a task.
"""
from config_models.admin import ConfigurationModelAdmin
from django.contrib import admin
from .config.models import GradeReportSetting
from .models import InstructorTask
class InstructorTaskAdmin(admin.ModelAdmin):
list_display = [
'task_id',
'task_type',
'course_id',
'username',
'email',
'created',
'updated',
]
list_filter = ['task_type', 'task_state']
search_fields = [
'task_id', 'course_id', 'requester__email', 'requester__username'
]
raw_id_fields = ['requester'] # avoid trying to make a select dropdown
def email(self, task):
return task.requester.email
email.admin_order_field = 'requester__email'
def username(self, task):
return task.requester.username
email.admin_order_field = 'requester__username'
admin.site.register(InstructorTask, InstructorTaskAdmin)
admin.site.register(GradeReportSetting, ConfigurationModelAdmin)
Add ability to manually fail instructor tasks in batches.
When an InstructorTask is stuck in QUEUING (say if there was a
problem with celery), the support team needs to manually intervene
and mark the task as "FAILED" so that new tasks of that type can
be created for that course. This is usually done one at a time,
but sometimes a bug or outage might cause many tasks to fail at
once, making recovery extremely cumbersome. This commit adds the
ability to do this process in batches. | """
Basic admin screens to search and edit InstructorTasks.
This will mostly involve searching by course_id or task_id and manually failing
a task.
"""
from config_models.admin import ConfigurationModelAdmin
from django.contrib import admin
from .config.models import GradeReportSetting
from .models import InstructorTask
def mark_tasks_as_failed(modeladmin, request, queryset):
queryset.update(
task_state='FAILURE',
task_output='{}',
task_key='dummy_task_key',
)
mark_tasks_as_failed.short_description = "Mark Tasks as Failed"
class InstructorTaskAdmin(admin.ModelAdmin):
actions = [mark_tasks_as_failed]
list_display = [
'task_id',
'task_state',
'task_type',
'course_id',
'username',
'email',
'created',
'updated',
]
list_filter = ['task_type', 'task_state']
search_fields = [
'task_id', 'course_id', 'requester__email', 'requester__username'
]
raw_id_fields = ['requester'] # avoid trying to make a select dropdown
def email(self, task):
return task.requester.email
email.admin_order_field = 'requester__email'
def username(self, task):
return task.requester.username
email.admin_order_field = 'requester__username'
admin.site.register(InstructorTask, InstructorTaskAdmin)
admin.site.register(GradeReportSetting, ConfigurationModelAdmin)
| <commit_before>"""
Basic admin screens to search and edit InstructorTasks.
This will mostly involve searching by course_id or task_id and manually failing
a task.
"""
from config_models.admin import ConfigurationModelAdmin
from django.contrib import admin
from .config.models import GradeReportSetting
from .models import InstructorTask
class InstructorTaskAdmin(admin.ModelAdmin):
list_display = [
'task_id',
'task_type',
'course_id',
'username',
'email',
'created',
'updated',
]
list_filter = ['task_type', 'task_state']
search_fields = [
'task_id', 'course_id', 'requester__email', 'requester__username'
]
raw_id_fields = ['requester'] # avoid trying to make a select dropdown
def email(self, task):
return task.requester.email
email.admin_order_field = 'requester__email'
def username(self, task):
return task.requester.username
email.admin_order_field = 'requester__username'
admin.site.register(InstructorTask, InstructorTaskAdmin)
admin.site.register(GradeReportSetting, ConfigurationModelAdmin)
<commit_msg>Add ability to manually fail instructor tasks in batches.
When an InstructorTask is stuck in QUEUING (say if there was a
problem with celery), the support team needs to manually intervene
and mark the task as "FAILED" so that new tasks of that type can
be created for that course. This is usually done one at a time,
but sometimes a bug or outage might cause many tasks to fail at
once, making recovery extremely cumbersome. This commit adds the
ability to do this process in batches.<commit_after> | """
Basic admin screens to search and edit InstructorTasks.
This will mostly involve searching by course_id or task_id and manually failing
a task.
"""
from config_models.admin import ConfigurationModelAdmin
from django.contrib import admin
from .config.models import GradeReportSetting
from .models import InstructorTask
def mark_tasks_as_failed(modeladmin, request, queryset):
queryset.update(
task_state='FAILURE',
task_output='{}',
task_key='dummy_task_key',
)
mark_tasks_as_failed.short_description = "Mark Tasks as Failed"
class InstructorTaskAdmin(admin.ModelAdmin):
actions = [mark_tasks_as_failed]
list_display = [
'task_id',
'task_state',
'task_type',
'course_id',
'username',
'email',
'created',
'updated',
]
list_filter = ['task_type', 'task_state']
search_fields = [
'task_id', 'course_id', 'requester__email', 'requester__username'
]
raw_id_fields = ['requester'] # avoid trying to make a select dropdown
def email(self, task):
return task.requester.email
email.admin_order_field = 'requester__email'
def username(self, task):
return task.requester.username
email.admin_order_field = 'requester__username'
admin.site.register(InstructorTask, InstructorTaskAdmin)
admin.site.register(GradeReportSetting, ConfigurationModelAdmin)
| """
Basic admin screens to search and edit InstructorTasks.
This will mostly involve searching by course_id or task_id and manually failing
a task.
"""
from config_models.admin import ConfigurationModelAdmin
from django.contrib import admin
from .config.models import GradeReportSetting
from .models import InstructorTask
class InstructorTaskAdmin(admin.ModelAdmin):
list_display = [
'task_id',
'task_type',
'course_id',
'username',
'email',
'created',
'updated',
]
list_filter = ['task_type', 'task_state']
search_fields = [
'task_id', 'course_id', 'requester__email', 'requester__username'
]
raw_id_fields = ['requester'] # avoid trying to make a select dropdown
def email(self, task):
return task.requester.email
email.admin_order_field = 'requester__email'
def username(self, task):
return task.requester.username
email.admin_order_field = 'requester__username'
admin.site.register(InstructorTask, InstructorTaskAdmin)
admin.site.register(GradeReportSetting, ConfigurationModelAdmin)
Add ability to manually fail instructor tasks in batches.
When an InstructorTask is stuck in QUEUING (say if there was a
problem with celery), the support team needs to manually intervene
and mark the task as "FAILED" so that new tasks of that type can
be created for that course. This is usually done one at a time,
but sometimes a bug or outage might cause many tasks to fail at
once, making recovery extremely cumbersome. This commit adds the
ability to do this process in batches."""
Basic admin screens to search and edit InstructorTasks.
This will mostly involve searching by course_id or task_id and manually failing
a task.
"""
from config_models.admin import ConfigurationModelAdmin
from django.contrib import admin
from .config.models import GradeReportSetting
from .models import InstructorTask
def mark_tasks_as_failed(modeladmin, request, queryset):
queryset.update(
task_state='FAILURE',
task_output='{}',
task_key='dummy_task_key',
)
mark_tasks_as_failed.short_description = "Mark Tasks as Failed"
class InstructorTaskAdmin(admin.ModelAdmin):
actions = [mark_tasks_as_failed]
list_display = [
'task_id',
'task_state',
'task_type',
'course_id',
'username',
'email',
'created',
'updated',
]
list_filter = ['task_type', 'task_state']
search_fields = [
'task_id', 'course_id', 'requester__email', 'requester__username'
]
raw_id_fields = ['requester'] # avoid trying to make a select dropdown
def email(self, task):
return task.requester.email
email.admin_order_field = 'requester__email'
def username(self, task):
return task.requester.username
email.admin_order_field = 'requester__username'
admin.site.register(InstructorTask, InstructorTaskAdmin)
admin.site.register(GradeReportSetting, ConfigurationModelAdmin)
| <commit_before>"""
Basic admin screens to search and edit InstructorTasks.
This will mostly involve searching by course_id or task_id and manually failing
a task.
"""
from config_models.admin import ConfigurationModelAdmin
from django.contrib import admin
from .config.models import GradeReportSetting
from .models import InstructorTask
class InstructorTaskAdmin(admin.ModelAdmin):
list_display = [
'task_id',
'task_type',
'course_id',
'username',
'email',
'created',
'updated',
]
list_filter = ['task_type', 'task_state']
search_fields = [
'task_id', 'course_id', 'requester__email', 'requester__username'
]
raw_id_fields = ['requester'] # avoid trying to make a select dropdown
def email(self, task):
return task.requester.email
email.admin_order_field = 'requester__email'
def username(self, task):
return task.requester.username
email.admin_order_field = 'requester__username'
admin.site.register(InstructorTask, InstructorTaskAdmin)
admin.site.register(GradeReportSetting, ConfigurationModelAdmin)
<commit_msg>Add ability to manually fail instructor tasks in batches.
When an InstructorTask is stuck in QUEUING (say if there was a
problem with celery), the support team needs to manually intervene
and mark the task as "FAILED" so that new tasks of that type can
be created for that course. This is usually done one at a time,
but sometimes a bug or outage might cause many tasks to fail at
once, making recovery extremely cumbersome. This commit adds the
ability to do this process in batches.<commit_after>"""
Basic admin screens to search and edit InstructorTasks.
This will mostly involve searching by course_id or task_id and manually failing
a task.
"""
from config_models.admin import ConfigurationModelAdmin
from django.contrib import admin
from .config.models import GradeReportSetting
from .models import InstructorTask
def mark_tasks_as_failed(modeladmin, request, queryset):
queryset.update(
task_state='FAILURE',
task_output='{}',
task_key='dummy_task_key',
)
mark_tasks_as_failed.short_description = "Mark Tasks as Failed"
class InstructorTaskAdmin(admin.ModelAdmin):
actions = [mark_tasks_as_failed]
list_display = [
'task_id',
'task_state',
'task_type',
'course_id',
'username',
'email',
'created',
'updated',
]
list_filter = ['task_type', 'task_state']
search_fields = [
'task_id', 'course_id', 'requester__email', 'requester__username'
]
raw_id_fields = ['requester'] # avoid trying to make a select dropdown
def email(self, task):
return task.requester.email
email.admin_order_field = 'requester__email'
def username(self, task):
return task.requester.username
email.admin_order_field = 'requester__username'
admin.site.register(InstructorTask, InstructorTaskAdmin)
admin.site.register(GradeReportSetting, ConfigurationModelAdmin)
|
7e50594c47ff0f8fdaaa3c6fb3a7b6ec222fc9fa | hgallpaths.py | hgallpaths.py | # hgallpaths.py - pull and push too all paths
#
# Copyright 2012 Keegan Carruthers-Smith <keegan.csmith@gmail.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
'''push and pull too all paths'''
from mercurial import commands
cmdtable = {}
def do_command(command, path_kw, ui, *args, **opts):
cmd = getattr(commands, command)
paths = ui.configitems('paths')
exclude = set(ui.configlist('hgallpaths', 'exclude', []) +
ui.configlist('hgallpaths', 'exclude_%s' % command, []))
for name, path in paths:
if name not in exclude:
opts[path_kw] = path
cmd(ui, *args, **opts)
def create_command(command, path_kw):
def cmd(*args, **opts):
return do_command(command, path_kw, *args, **opts)
cmd.__doc__ = 'See help for %s' % command
global cmdtable
cmdtable[command + 'all'] = (cmd, [])
return cmd
pullall = create_command('pull', 'source')
pushall = create_command('push', 'dest')
| # hgallpaths.py - pull and push to all paths
#
# Copyright 2012 Keegan Carruthers-Smith <keegan.csmith@gmail.com>
#
# Released under the terms of the BSD License. See LICENSE.txt for details.
'''push and pull to all paths'''
from mercurial import commands
cmdtable = {}
def do_command(command, path_kw, ui, *args, **opts):
cmd = getattr(commands, command)
paths = ui.configitems('paths')
exclude = set(ui.configlist('hgallpaths', 'exclude', []) +
ui.configlist('hgallpaths', 'exclude_%s' % command, []))
for name, path in paths:
if name not in exclude:
opts[path_kw] = path
cmd(ui, *args, **opts)
def create_command(command, path_kw):
def cmd(*args, **opts):
return do_command(command, path_kw, *args, **opts)
cmd.__doc__ = 'See help for %s' % command
global cmdtable
cmdtable[command + 'all'] = (cmd, [])
return cmd
pullall = create_command('pull', 'source')
pushall = create_command('push', 'dest')
| Update license header to reference BSD. | Update license header to reference BSD.
| Python | bsd-2-clause | keegancsmith/hgallpaths | # hgallpaths.py - pull and push too all paths
#
# Copyright 2012 Keegan Carruthers-Smith <keegan.csmith@gmail.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
'''push and pull too all paths'''
from mercurial import commands
cmdtable = {}
def do_command(command, path_kw, ui, *args, **opts):
cmd = getattr(commands, command)
paths = ui.configitems('paths')
exclude = set(ui.configlist('hgallpaths', 'exclude', []) +
ui.configlist('hgallpaths', 'exclude_%s' % command, []))
for name, path in paths:
if name not in exclude:
opts[path_kw] = path
cmd(ui, *args, **opts)
def create_command(command, path_kw):
def cmd(*args, **opts):
return do_command(command, path_kw, *args, **opts)
cmd.__doc__ = 'See help for %s' % command
global cmdtable
cmdtable[command + 'all'] = (cmd, [])
return cmd
pullall = create_command('pull', 'source')
pushall = create_command('push', 'dest')
Update license header to reference BSD. | # hgallpaths.py - pull and push to all paths
#
# Copyright 2012 Keegan Carruthers-Smith <keegan.csmith@gmail.com>
#
# Released under the terms of the BSD License. See LICENSE.txt for details.
'''push and pull to all paths'''
from mercurial import commands
cmdtable = {}
def do_command(command, path_kw, ui, *args, **opts):
cmd = getattr(commands, command)
paths = ui.configitems('paths')
exclude = set(ui.configlist('hgallpaths', 'exclude', []) +
ui.configlist('hgallpaths', 'exclude_%s' % command, []))
for name, path in paths:
if name not in exclude:
opts[path_kw] = path
cmd(ui, *args, **opts)
def create_command(command, path_kw):
def cmd(*args, **opts):
return do_command(command, path_kw, *args, **opts)
cmd.__doc__ = 'See help for %s' % command
global cmdtable
cmdtable[command + 'all'] = (cmd, [])
return cmd
pullall = create_command('pull', 'source')
pushall = create_command('push', 'dest')
| <commit_before># hgallpaths.py - pull and push too all paths
#
# Copyright 2012 Keegan Carruthers-Smith <keegan.csmith@gmail.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
'''push and pull too all paths'''
from mercurial import commands
cmdtable = {}
def do_command(command, path_kw, ui, *args, **opts):
cmd = getattr(commands, command)
paths = ui.configitems('paths')
exclude = set(ui.configlist('hgallpaths', 'exclude', []) +
ui.configlist('hgallpaths', 'exclude_%s' % command, []))
for name, path in paths:
if name not in exclude:
opts[path_kw] = path
cmd(ui, *args, **opts)
def create_command(command, path_kw):
def cmd(*args, **opts):
return do_command(command, path_kw, *args, **opts)
cmd.__doc__ = 'See help for %s' % command
global cmdtable
cmdtable[command + 'all'] = (cmd, [])
return cmd
pullall = create_command('pull', 'source')
pushall = create_command('push', 'dest')
<commit_msg>Update license header to reference BSD.<commit_after> | # hgallpaths.py - pull and push to all paths
#
# Copyright 2012 Keegan Carruthers-Smith <keegan.csmith@gmail.com>
#
# Released under the terms of the BSD License. See LICENSE.txt for details.
'''push and pull to all paths'''
from mercurial import commands
cmdtable = {}
def do_command(command, path_kw, ui, *args, **opts):
cmd = getattr(commands, command)
paths = ui.configitems('paths')
exclude = set(ui.configlist('hgallpaths', 'exclude', []) +
ui.configlist('hgallpaths', 'exclude_%s' % command, []))
for name, path in paths:
if name not in exclude:
opts[path_kw] = path
cmd(ui, *args, **opts)
def create_command(command, path_kw):
def cmd(*args, **opts):
return do_command(command, path_kw, *args, **opts)
cmd.__doc__ = 'See help for %s' % command
global cmdtable
cmdtable[command + 'all'] = (cmd, [])
return cmd
pullall = create_command('pull', 'source')
pushall = create_command('push', 'dest')
| # hgallpaths.py - pull and push too all paths
#
# Copyright 2012 Keegan Carruthers-Smith <keegan.csmith@gmail.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
'''push and pull too all paths'''
from mercurial import commands
cmdtable = {}
def do_command(command, path_kw, ui, *args, **opts):
cmd = getattr(commands, command)
paths = ui.configitems('paths')
exclude = set(ui.configlist('hgallpaths', 'exclude', []) +
ui.configlist('hgallpaths', 'exclude_%s' % command, []))
for name, path in paths:
if name not in exclude:
opts[path_kw] = path
cmd(ui, *args, **opts)
def create_command(command, path_kw):
def cmd(*args, **opts):
return do_command(command, path_kw, *args, **opts)
cmd.__doc__ = 'See help for %s' % command
global cmdtable
cmdtable[command + 'all'] = (cmd, [])
return cmd
pullall = create_command('pull', 'source')
pushall = create_command('push', 'dest')
Update license header to reference BSD.# hgallpaths.py - pull and push to all paths
#
# Copyright 2012 Keegan Carruthers-Smith <keegan.csmith@gmail.com>
#
# Released under the terms of the BSD License. See LICENSE.txt for details.
'''push and pull to all paths'''
from mercurial import commands
cmdtable = {}
def do_command(command, path_kw, ui, *args, **opts):
cmd = getattr(commands, command)
paths = ui.configitems('paths')
exclude = set(ui.configlist('hgallpaths', 'exclude', []) +
ui.configlist('hgallpaths', 'exclude_%s' % command, []))
for name, path in paths:
if name not in exclude:
opts[path_kw] = path
cmd(ui, *args, **opts)
def create_command(command, path_kw):
def cmd(*args, **opts):
return do_command(command, path_kw, *args, **opts)
cmd.__doc__ = 'See help for %s' % command
global cmdtable
cmdtable[command + 'all'] = (cmd, [])
return cmd
pullall = create_command('pull', 'source')
pushall = create_command('push', 'dest')
| <commit_before># hgallpaths.py - pull and push too all paths
#
# Copyright 2012 Keegan Carruthers-Smith <keegan.csmith@gmail.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
'''push and pull too all paths'''
from mercurial import commands
cmdtable = {}
def do_command(command, path_kw, ui, *args, **opts):
cmd = getattr(commands, command)
paths = ui.configitems('paths')
exclude = set(ui.configlist('hgallpaths', 'exclude', []) +
ui.configlist('hgallpaths', 'exclude_%s' % command, []))
for name, path in paths:
if name not in exclude:
opts[path_kw] = path
cmd(ui, *args, **opts)
def create_command(command, path_kw):
def cmd(*args, **opts):
return do_command(command, path_kw, *args, **opts)
cmd.__doc__ = 'See help for %s' % command
global cmdtable
cmdtable[command + 'all'] = (cmd, [])
return cmd
pullall = create_command('pull', 'source')
pushall = create_command('push', 'dest')
<commit_msg>Update license header to reference BSD.<commit_after># hgallpaths.py - pull and push to all paths
#
# Copyright 2012 Keegan Carruthers-Smith <keegan.csmith@gmail.com>
#
# Released under the terms of the BSD License. See LICENSE.txt for details.
'''push and pull to all paths'''
from mercurial import commands
cmdtable = {}
def do_command(command, path_kw, ui, *args, **opts):
cmd = getattr(commands, command)
paths = ui.configitems('paths')
exclude = set(ui.configlist('hgallpaths', 'exclude', []) +
ui.configlist('hgallpaths', 'exclude_%s' % command, []))
for name, path in paths:
if name not in exclude:
opts[path_kw] = path
cmd(ui, *args, **opts)
def create_command(command, path_kw):
def cmd(*args, **opts):
return do_command(command, path_kw, *args, **opts)
cmd.__doc__ = 'See help for %s' % command
global cmdtable
cmdtable[command + 'all'] = (cmd, [])
return cmd
pullall = create_command('pull', 'source')
pushall = create_command('push', 'dest')
|
d7b5cd3c3ef51aef5264542fae03322955bd5ca8 | appengine_config.py | appengine_config.py | """Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Appstats URL.
# TODO: Drop this once it is the default.
appstats_stats_url = '/_ah/stats'
# Custom Appstats path normalization.
def appstats_normalize_path(path):
if path.startswith('/user/'):
return '/user/X'
if path.startswith('/user_popup/'):
return '/user_popup/X'
if path.startswith('/rss/'):
i = path.find('/', 5)
if i > 0:
return path[:i] + '/X'
return re.sub(r'\d+', 'X', path)
# Declare the Django version we need.
from google.appengine.dist import use_library
use_library('django', '1.0')
# Fail early if we can't import Django 1.x. Log identifying information.
import django
logging.info('django.__file__ = %r, django.VERSION = %r',
django.__file__, django.VERSION)
assert django.VERSION[0] >= 1, "This Django version is too old"
| """Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Appstats URL.
# TODO: Drop this once it is the default.
appstats_stats_url = '/_ah/stats'
# Custom Appstats path normalization.
def appstats_normalize_path(path):
if path.startswith('/user/'):
return '/user/X'
if path.startswith('/user_popup/'):
return '/user_popup/X'
if path.startswith('/rss/'):
i = path.find('/', 5)
if i > 0:
return path[:i] + '/X'
return re.sub(r'\d+', 'X', path)
# Declare the Django version we need.
from google.appengine.dist import use_library
use_library('django', '1.1')
# Fail early if we can't import Django 1.x. Log identifying information.
import django
logging.info('django.__file__ = %r, django.VERSION = %r',
django.__file__, django.VERSION)
assert django.VERSION[0] >= 1, "This Django version is too old"
| Switch Django version from 1.0 to 1.1 | Switch Django version from 1.0 to 1.1
| Python | apache-2.0 | ligthyear/quick-check,ligthyear/quick-check | """Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Appstats URL.
# TODO: Drop this once it is the default.
appstats_stats_url = '/_ah/stats'
# Custom Appstats path normalization.
def appstats_normalize_path(path):
if path.startswith('/user/'):
return '/user/X'
if path.startswith('/user_popup/'):
return '/user_popup/X'
if path.startswith('/rss/'):
i = path.find('/', 5)
if i > 0:
return path[:i] + '/X'
return re.sub(r'\d+', 'X', path)
# Declare the Django version we need.
from google.appengine.dist import use_library
use_library('django', '1.0')
# Fail early if we can't import Django 1.x. Log identifying information.
import django
logging.info('django.__file__ = %r, django.VERSION = %r',
django.__file__, django.VERSION)
assert django.VERSION[0] >= 1, "This Django version is too old"
Switch Django version from 1.0 to 1.1 | """Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Appstats URL.
# TODO: Drop this once it is the default.
appstats_stats_url = '/_ah/stats'
# Custom Appstats path normalization.
def appstats_normalize_path(path):
if path.startswith('/user/'):
return '/user/X'
if path.startswith('/user_popup/'):
return '/user_popup/X'
if path.startswith('/rss/'):
i = path.find('/', 5)
if i > 0:
return path[:i] + '/X'
return re.sub(r'\d+', 'X', path)
# Declare the Django version we need.
from google.appengine.dist import use_library
use_library('django', '1.1')
# Fail early if we can't import Django 1.x. Log identifying information.
import django
logging.info('django.__file__ = %r, django.VERSION = %r',
django.__file__, django.VERSION)
assert django.VERSION[0] >= 1, "This Django version is too old"
| <commit_before>"""Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Appstats URL.
# TODO: Drop this once it is the default.
appstats_stats_url = '/_ah/stats'
# Custom Appstats path normalization.
def appstats_normalize_path(path):
if path.startswith('/user/'):
return '/user/X'
if path.startswith('/user_popup/'):
return '/user_popup/X'
if path.startswith('/rss/'):
i = path.find('/', 5)
if i > 0:
return path[:i] + '/X'
return re.sub(r'\d+', 'X', path)
# Declare the Django version we need.
from google.appengine.dist import use_library
use_library('django', '1.0')
# Fail early if we can't import Django 1.x. Log identifying information.
import django
logging.info('django.__file__ = %r, django.VERSION = %r',
django.__file__, django.VERSION)
assert django.VERSION[0] >= 1, "This Django version is too old"
<commit_msg>Switch Django version from 1.0 to 1.1<commit_after> | """Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Appstats URL.
# TODO: Drop this once it is the default.
appstats_stats_url = '/_ah/stats'
# Custom Appstats path normalization.
def appstats_normalize_path(path):
if path.startswith('/user/'):
return '/user/X'
if path.startswith('/user_popup/'):
return '/user_popup/X'
if path.startswith('/rss/'):
i = path.find('/', 5)
if i > 0:
return path[:i] + '/X'
return re.sub(r'\d+', 'X', path)
# Declare the Django version we need.
from google.appengine.dist import use_library
use_library('django', '1.1')
# Fail early if we can't import Django 1.x. Log identifying information.
import django
logging.info('django.__file__ = %r, django.VERSION = %r',
django.__file__, django.VERSION)
assert django.VERSION[0] >= 1, "This Django version is too old"
| """Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Appstats URL.
# TODO: Drop this once it is the default.
appstats_stats_url = '/_ah/stats'
# Custom Appstats path normalization.
def appstats_normalize_path(path):
if path.startswith('/user/'):
return '/user/X'
if path.startswith('/user_popup/'):
return '/user_popup/X'
if path.startswith('/rss/'):
i = path.find('/', 5)
if i > 0:
return path[:i] + '/X'
return re.sub(r'\d+', 'X', path)
# Declare the Django version we need.
from google.appengine.dist import use_library
use_library('django', '1.0')
# Fail early if we can't import Django 1.x. Log identifying information.
import django
logging.info('django.__file__ = %r, django.VERSION = %r',
django.__file__, django.VERSION)
assert django.VERSION[0] >= 1, "This Django version is too old"
Switch Django version from 1.0 to 1.1"""Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Appstats URL.
# TODO: Drop this once it is the default.
appstats_stats_url = '/_ah/stats'
# Custom Appstats path normalization.
def appstats_normalize_path(path):
if path.startswith('/user/'):
return '/user/X'
if path.startswith('/user_popup/'):
return '/user_popup/X'
if path.startswith('/rss/'):
i = path.find('/', 5)
if i > 0:
return path[:i] + '/X'
return re.sub(r'\d+', 'X', path)
# Declare the Django version we need.
from google.appengine.dist import use_library
use_library('django', '1.1')
# Fail early if we can't import Django 1.x. Log identifying information.
import django
logging.info('django.__file__ = %r, django.VERSION = %r',
django.__file__, django.VERSION)
assert django.VERSION[0] >= 1, "This Django version is too old"
| <commit_before>"""Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Appstats URL.
# TODO: Drop this once it is the default.
appstats_stats_url = '/_ah/stats'
# Custom Appstats path normalization.
def appstats_normalize_path(path):
if path.startswith('/user/'):
return '/user/X'
if path.startswith('/user_popup/'):
return '/user_popup/X'
if path.startswith('/rss/'):
i = path.find('/', 5)
if i > 0:
return path[:i] + '/X'
return re.sub(r'\d+', 'X', path)
# Declare the Django version we need.
from google.appengine.dist import use_library
use_library('django', '1.0')
# Fail early if we can't import Django 1.x. Log identifying information.
import django
logging.info('django.__file__ = %r, django.VERSION = %r',
django.__file__, django.VERSION)
assert django.VERSION[0] >= 1, "This Django version is too old"
<commit_msg>Switch Django version from 1.0 to 1.1<commit_after>"""Configuration."""
import logging
import os
import re
from google.appengine.ext.appstats import recording
logging.info('Loading %s from %s', __name__, __file__)
# Custom webapp middleware to add Appstats.
def webapp_add_wsgi_middleware(app):
app = recording.appstats_wsgi_middleware(app)
return app
# Appstats URL.
# TODO: Drop this once it is the default.
appstats_stats_url = '/_ah/stats'
# Custom Appstats path normalization.
def appstats_normalize_path(path):
if path.startswith('/user/'):
return '/user/X'
if path.startswith('/user_popup/'):
return '/user_popup/X'
if path.startswith('/rss/'):
i = path.find('/', 5)
if i > 0:
return path[:i] + '/X'
return re.sub(r'\d+', 'X', path)
# Declare the Django version we need.
from google.appengine.dist import use_library
use_library('django', '1.1')
# Fail early if we can't import Django 1.x. Log identifying information.
import django
logging.info('django.__file__ = %r, django.VERSION = %r',
django.__file__, django.VERSION)
assert django.VERSION[0] >= 1, "This Django version is too old"
|
ca8263ecf33798acc01bb4a5f5aeb3d8005da026 | karmaworld/apps/users/views.py | karmaworld/apps/users/views.py | #!/usr/bin/env python
# -*- coding:utf8 -*-
# Copyright (C) 2013 FinalsClub Foundation
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from django.views.generic.detail import SingleObjectMixin
class ProfileView(TemplateView, SingleObjectMixin):
model = User
context_object_name = 'user' # name passed to template
template_name = 'user_profile.html'
def get_object(self, queryset=None):
u = self.request.user
return self.request.user
| #!/usr/bin/env python
# -*- coding:utf8 -*-
# Copyright (C) 2013 FinalsClub Foundation
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from django.views.generic.detail import SingleObjectMixin
class ProfileView(TemplateView, SingleObjectMixin):
model = User
context_object_name = 'user' # name passed to template
template_name = 'user_profile.html'
object = None
def get_object(self, queryset=None):
return self.request.user
| Fix to make user profile display | Fix to make user profile display
| Python | agpl-3.0 | FinalsClub/karmaworld,FinalsClub/karmaworld,FinalsClub/karmaworld,FinalsClub/karmaworld | #!/usr/bin/env python
# -*- coding:utf8 -*-
# Copyright (C) 2013 FinalsClub Foundation
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from django.views.generic.detail import SingleObjectMixin
class ProfileView(TemplateView, SingleObjectMixin):
model = User
context_object_name = 'user' # name passed to template
template_name = 'user_profile.html'
def get_object(self, queryset=None):
u = self.request.user
return self.request.user
Fix to make user profile display | #!/usr/bin/env python
# -*- coding:utf8 -*-
# Copyright (C) 2013 FinalsClub Foundation
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from django.views.generic.detail import SingleObjectMixin
class ProfileView(TemplateView, SingleObjectMixin):
model = User
context_object_name = 'user' # name passed to template
template_name = 'user_profile.html'
object = None
def get_object(self, queryset=None):
return self.request.user
| <commit_before>#!/usr/bin/env python
# -*- coding:utf8 -*-
# Copyright (C) 2013 FinalsClub Foundation
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from django.views.generic.detail import SingleObjectMixin
class ProfileView(TemplateView, SingleObjectMixin):
model = User
context_object_name = 'user' # name passed to template
template_name = 'user_profile.html'
def get_object(self, queryset=None):
u = self.request.user
return self.request.user
<commit_msg>Fix to make user profile display<commit_after> | #!/usr/bin/env python
# -*- coding:utf8 -*-
# Copyright (C) 2013 FinalsClub Foundation
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from django.views.generic.detail import SingleObjectMixin
class ProfileView(TemplateView, SingleObjectMixin):
model = User
context_object_name = 'user' # name passed to template
template_name = 'user_profile.html'
object = None
def get_object(self, queryset=None):
return self.request.user
| #!/usr/bin/env python
# -*- coding:utf8 -*-
# Copyright (C) 2013 FinalsClub Foundation
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from django.views.generic.detail import SingleObjectMixin
class ProfileView(TemplateView, SingleObjectMixin):
model = User
context_object_name = 'user' # name passed to template
template_name = 'user_profile.html'
def get_object(self, queryset=None):
u = self.request.user
return self.request.user
Fix to make user profile display#!/usr/bin/env python
# -*- coding:utf8 -*-
# Copyright (C) 2013 FinalsClub Foundation
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from django.views.generic.detail import SingleObjectMixin
class ProfileView(TemplateView, SingleObjectMixin):
model = User
context_object_name = 'user' # name passed to template
template_name = 'user_profile.html'
object = None
def get_object(self, queryset=None):
return self.request.user
| <commit_before>#!/usr/bin/env python
# -*- coding:utf8 -*-
# Copyright (C) 2013 FinalsClub Foundation
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from django.views.generic.detail import SingleObjectMixin
class ProfileView(TemplateView, SingleObjectMixin):
model = User
context_object_name = 'user' # name passed to template
template_name = 'user_profile.html'
def get_object(self, queryset=None):
u = self.request.user
return self.request.user
<commit_msg>Fix to make user profile display<commit_after>#!/usr/bin/env python
# -*- coding:utf8 -*-
# Copyright (C) 2013 FinalsClub Foundation
from django.contrib.auth.models import User
from django.views.generic import TemplateView
from django.views.generic.detail import SingleObjectMixin
class ProfileView(TemplateView, SingleObjectMixin):
model = User
context_object_name = 'user' # name passed to template
template_name = 'user_profile.html'
object = None
def get_object(self, queryset=None):
return self.request.user
|
b0904677e9687932099406a38cc7cd8f7ba67573 | examples/cifar-autoencoder.py | examples/cifar-autoencoder.py | #!/usr/bin/env python
import climate
import matplotlib.pyplot as plt
import theanets
from utils import load_cifar, plot_layers, plot_images
g = climate.add_arg_group('CIFAR Example')
g.add_argument('--features', type=int, default=32, metavar='N',
help='train a model using N^2 hidden-layer features')
def main(args):
train, valid, _ = load_cifar()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(3072, args.features ** 2, 3072))
e.train(train, valid)
plot_layers(e.network.weights, channels=3)
plt.tight_layout()
plt.show()
valid = valid[:100]
plot_images(valid, 121, 'Sample data', channels=3)
plot_images(e.network.predict(valid), 122, 'Reconstructed data', channels=3)
plt.tight_layout()
plt.show()
if __name__ == '__main__':
climate.call(main)
| #!/usr/bin/env python
import climate
import matplotlib.pyplot as plt
import theanets
from utils import load_cifar, plot_layers, plot_images
g = climate.add_arg_group('CIFAR Example')
g.add_argument('--features', type=int, default=32, metavar='N',
help='train a model using N^2 hidden-layer features')
def main(args):
train, valid, _ = load_cifar()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(3072, args.features ** 2, 3072))
e.train(train, valid)
plot_layers([e.network.get_weights(1), e.network.get_weights('out')], channels=3)
plt.tight_layout()
plt.show()
valid = valid[:100]
plot_images(valid, 121, 'Sample data', channels=3)
plot_images(e.network.predict(valid), 122, 'Reconstructed data', channels=3)
plt.tight_layout()
plt.show()
if __name__ == '__main__':
climate.call(main)
| Access weights using new interface. | Access weights using new interface.
| Python | mit | chrinide/theanets,lmjohns3/theanets,devdoer/theanets | #!/usr/bin/env python
import climate
import matplotlib.pyplot as plt
import theanets
from utils import load_cifar, plot_layers, plot_images
g = climate.add_arg_group('CIFAR Example')
g.add_argument('--features', type=int, default=32, metavar='N',
help='train a model using N^2 hidden-layer features')
def main(args):
train, valid, _ = load_cifar()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(3072, args.features ** 2, 3072))
e.train(train, valid)
plot_layers(e.network.weights, channels=3)
plt.tight_layout()
plt.show()
valid = valid[:100]
plot_images(valid, 121, 'Sample data', channels=3)
plot_images(e.network.predict(valid), 122, 'Reconstructed data', channels=3)
plt.tight_layout()
plt.show()
if __name__ == '__main__':
climate.call(main)
Access weights using new interface. | #!/usr/bin/env python
import climate
import matplotlib.pyplot as plt
import theanets
from utils import load_cifar, plot_layers, plot_images
g = climate.add_arg_group('CIFAR Example')
g.add_argument('--features', type=int, default=32, metavar='N',
help='train a model using N^2 hidden-layer features')
def main(args):
train, valid, _ = load_cifar()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(3072, args.features ** 2, 3072))
e.train(train, valid)
plot_layers([e.network.get_weights(1), e.network.get_weights('out')], channels=3)
plt.tight_layout()
plt.show()
valid = valid[:100]
plot_images(valid, 121, 'Sample data', channels=3)
plot_images(e.network.predict(valid), 122, 'Reconstructed data', channels=3)
plt.tight_layout()
plt.show()
if __name__ == '__main__':
climate.call(main)
| <commit_before>#!/usr/bin/env python
import climate
import matplotlib.pyplot as plt
import theanets
from utils import load_cifar, plot_layers, plot_images
g = climate.add_arg_group('CIFAR Example')
g.add_argument('--features', type=int, default=32, metavar='N',
help='train a model using N^2 hidden-layer features')
def main(args):
train, valid, _ = load_cifar()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(3072, args.features ** 2, 3072))
e.train(train, valid)
plot_layers(e.network.weights, channels=3)
plt.tight_layout()
plt.show()
valid = valid[:100]
plot_images(valid, 121, 'Sample data', channels=3)
plot_images(e.network.predict(valid), 122, 'Reconstructed data', channels=3)
plt.tight_layout()
plt.show()
if __name__ == '__main__':
climate.call(main)
<commit_msg>Access weights using new interface.<commit_after> | #!/usr/bin/env python
import climate
import matplotlib.pyplot as plt
import theanets
from utils import load_cifar, plot_layers, plot_images
g = climate.add_arg_group('CIFAR Example')
g.add_argument('--features', type=int, default=32, metavar='N',
help='train a model using N^2 hidden-layer features')
def main(args):
train, valid, _ = load_cifar()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(3072, args.features ** 2, 3072))
e.train(train, valid)
plot_layers([e.network.get_weights(1), e.network.get_weights('out')], channels=3)
plt.tight_layout()
plt.show()
valid = valid[:100]
plot_images(valid, 121, 'Sample data', channels=3)
plot_images(e.network.predict(valid), 122, 'Reconstructed data', channels=3)
plt.tight_layout()
plt.show()
if __name__ == '__main__':
climate.call(main)
| #!/usr/bin/env python
import climate
import matplotlib.pyplot as plt
import theanets
from utils import load_cifar, plot_layers, plot_images
g = climate.add_arg_group('CIFAR Example')
g.add_argument('--features', type=int, default=32, metavar='N',
help='train a model using N^2 hidden-layer features')
def main(args):
train, valid, _ = load_cifar()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(3072, args.features ** 2, 3072))
e.train(train, valid)
plot_layers(e.network.weights, channels=3)
plt.tight_layout()
plt.show()
valid = valid[:100]
plot_images(valid, 121, 'Sample data', channels=3)
plot_images(e.network.predict(valid), 122, 'Reconstructed data', channels=3)
plt.tight_layout()
plt.show()
if __name__ == '__main__':
climate.call(main)
Access weights using new interface.#!/usr/bin/env python
import climate
import matplotlib.pyplot as plt
import theanets
from utils import load_cifar, plot_layers, plot_images
g = climate.add_arg_group('CIFAR Example')
g.add_argument('--features', type=int, default=32, metavar='N',
help='train a model using N^2 hidden-layer features')
def main(args):
train, valid, _ = load_cifar()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(3072, args.features ** 2, 3072))
e.train(train, valid)
plot_layers([e.network.get_weights(1), e.network.get_weights('out')], channels=3)
plt.tight_layout()
plt.show()
valid = valid[:100]
plot_images(valid, 121, 'Sample data', channels=3)
plot_images(e.network.predict(valid), 122, 'Reconstructed data', channels=3)
plt.tight_layout()
plt.show()
if __name__ == '__main__':
climate.call(main)
| <commit_before>#!/usr/bin/env python
import climate
import matplotlib.pyplot as plt
import theanets
from utils import load_cifar, plot_layers, plot_images
g = climate.add_arg_group('CIFAR Example')
g.add_argument('--features', type=int, default=32, metavar='N',
help='train a model using N^2 hidden-layer features')
def main(args):
train, valid, _ = load_cifar()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(3072, args.features ** 2, 3072))
e.train(train, valid)
plot_layers(e.network.weights, channels=3)
plt.tight_layout()
plt.show()
valid = valid[:100]
plot_images(valid, 121, 'Sample data', channels=3)
plot_images(e.network.predict(valid), 122, 'Reconstructed data', channels=3)
plt.tight_layout()
plt.show()
if __name__ == '__main__':
climate.call(main)
<commit_msg>Access weights using new interface.<commit_after>#!/usr/bin/env python
import climate
import matplotlib.pyplot as plt
import theanets
from utils import load_cifar, plot_layers, plot_images
g = climate.add_arg_group('CIFAR Example')
g.add_argument('--features', type=int, default=32, metavar='N',
help='train a model using N^2 hidden-layer features')
def main(args):
train, valid, _ = load_cifar()
e = theanets.Experiment(
theanets.Autoencoder,
layers=(3072, args.features ** 2, 3072))
e.train(train, valid)
plot_layers([e.network.get_weights(1), e.network.get_weights('out')], channels=3)
plt.tight_layout()
plt.show()
valid = valid[:100]
plot_images(valid, 121, 'Sample data', channels=3)
plot_images(e.network.predict(valid), 122, 'Reconstructed data', channels=3)
plt.tight_layout()
plt.show()
if __name__ == '__main__':
climate.call(main)
|
c99c275e1304335d210054c3838dc4bfe1618ac9 | stl/__init__.py | stl/__init__.py |
import stl.ascii
import stl.binary
def read_ascii_file(file):
return stl.ascii.parse(file)
def read_binary_file(file):
return stl.binary.parse(file)
def read_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def read_binary_string(data):
from StringIO import StringIO
return parse_binary_file(StringIO(data))
|
import stl.ascii
import stl.binary
from stl.types import Solid, Facet, Vector3d
def read_ascii_file(file):
return stl.ascii.parse(file)
def read_binary_file(file):
return stl.binary.parse(file)
def read_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def read_binary_string(data):
from StringIO import StringIO
return parse_binary_file(StringIO(data))
| Make the types available in the main "stl" module. | Make the types available in the main "stl" module.
| Python | mit | ng110/python-stl,apparentlymart/python-stl,zachwick/python-stl |
import stl.ascii
import stl.binary
def read_ascii_file(file):
return stl.ascii.parse(file)
def read_binary_file(file):
return stl.binary.parse(file)
def read_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def read_binary_string(data):
from StringIO import StringIO
return parse_binary_file(StringIO(data))
Make the types available in the main "stl" module. |
import stl.ascii
import stl.binary
from stl.types import Solid, Facet, Vector3d
def read_ascii_file(file):
return stl.ascii.parse(file)
def read_binary_file(file):
return stl.binary.parse(file)
def read_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def read_binary_string(data):
from StringIO import StringIO
return parse_binary_file(StringIO(data))
| <commit_before>
import stl.ascii
import stl.binary
def read_ascii_file(file):
return stl.ascii.parse(file)
def read_binary_file(file):
return stl.binary.parse(file)
def read_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def read_binary_string(data):
from StringIO import StringIO
return parse_binary_file(StringIO(data))
<commit_msg>Make the types available in the main "stl" module.<commit_after> |
import stl.ascii
import stl.binary
from stl.types import Solid, Facet, Vector3d
def read_ascii_file(file):
return stl.ascii.parse(file)
def read_binary_file(file):
return stl.binary.parse(file)
def read_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def read_binary_string(data):
from StringIO import StringIO
return parse_binary_file(StringIO(data))
|
import stl.ascii
import stl.binary
def read_ascii_file(file):
return stl.ascii.parse(file)
def read_binary_file(file):
return stl.binary.parse(file)
def read_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def read_binary_string(data):
from StringIO import StringIO
return parse_binary_file(StringIO(data))
Make the types available in the main "stl" module.
import stl.ascii
import stl.binary
from stl.types import Solid, Facet, Vector3d
def read_ascii_file(file):
return stl.ascii.parse(file)
def read_binary_file(file):
return stl.binary.parse(file)
def read_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def read_binary_string(data):
from StringIO import StringIO
return parse_binary_file(StringIO(data))
| <commit_before>
import stl.ascii
import stl.binary
def read_ascii_file(file):
return stl.ascii.parse(file)
def read_binary_file(file):
return stl.binary.parse(file)
def read_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def read_binary_string(data):
from StringIO import StringIO
return parse_binary_file(StringIO(data))
<commit_msg>Make the types available in the main "stl" module.<commit_after>
import stl.ascii
import stl.binary
from stl.types import Solid, Facet, Vector3d
def read_ascii_file(file):
return stl.ascii.parse(file)
def read_binary_file(file):
return stl.binary.parse(file)
def read_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def read_binary_string(data):
from StringIO import StringIO
return parse_binary_file(StringIO(data))
|
43e6a2e3bf90f5edee214d1511a6805a67f79595 | stl/__init__.py | stl/__init__.py |
import stl.ascii
import stl.binary
def parse_ascii_file(file):
return stl.ascii.parse(file)
def parse_binary_file(file):
return stl.binary.parse(file)
def parse_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def parse_binary_string(data):
from StringIO import StringIO
return parse_binary_file(StringIO(data))
|
import stl.ascii
import stl.binary
def read_ascii_file(file):
return stl.ascii.parse(file)
def read_binary_file(file):
return stl.binary.parse(file)
def read_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def read_binary_string(data):
from StringIO import StringIO
return parse_binary_file(StringIO(data))
| Rename the reading functions "read_" rather than "parse_". | Rename the reading functions "read_" rather than "parse_".
"Parsing" is what they do internally, but "read" is a better opposite to
"write" and matches the name of the underlying raw file operation.
| Python | mit | apparentlymart/python-stl,zachwick/python-stl,ng110/python-stl |
import stl.ascii
import stl.binary
def parse_ascii_file(file):
return stl.ascii.parse(file)
def parse_binary_file(file):
return stl.binary.parse(file)
def parse_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def parse_binary_string(data):
from StringIO import StringIO
return parse_binary_file(StringIO(data))
Rename the reading functions "read_" rather than "parse_".
"Parsing" is what they do internally, but "read" is a better opposite to
"write" and matches the name of the underlying raw file operation. |
import stl.ascii
import stl.binary
def read_ascii_file(file):
return stl.ascii.parse(file)
def read_binary_file(file):
return stl.binary.parse(file)
def read_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def read_binary_string(data):
from StringIO import StringIO
return parse_binary_file(StringIO(data))
| <commit_before>
import stl.ascii
import stl.binary
def parse_ascii_file(file):
return stl.ascii.parse(file)
def parse_binary_file(file):
return stl.binary.parse(file)
def parse_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def parse_binary_string(data):
from StringIO import StringIO
return parse_binary_file(StringIO(data))
<commit_msg>Rename the reading functions "read_" rather than "parse_".
"Parsing" is what they do internally, but "read" is a better opposite to
"write" and matches the name of the underlying raw file operation.<commit_after> |
import stl.ascii
import stl.binary
def read_ascii_file(file):
return stl.ascii.parse(file)
def read_binary_file(file):
return stl.binary.parse(file)
def read_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def read_binary_string(data):
from StringIO import StringIO
return parse_binary_file(StringIO(data))
|
import stl.ascii
import stl.binary
def parse_ascii_file(file):
return stl.ascii.parse(file)
def parse_binary_file(file):
return stl.binary.parse(file)
def parse_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def parse_binary_string(data):
from StringIO import StringIO
return parse_binary_file(StringIO(data))
Rename the reading functions "read_" rather than "parse_".
"Parsing" is what they do internally, but "read" is a better opposite to
"write" and matches the name of the underlying raw file operation.
import stl.ascii
import stl.binary
def read_ascii_file(file):
return stl.ascii.parse(file)
def read_binary_file(file):
return stl.binary.parse(file)
def read_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def read_binary_string(data):
from StringIO import StringIO
return parse_binary_file(StringIO(data))
| <commit_before>
import stl.ascii
import stl.binary
def parse_ascii_file(file):
return stl.ascii.parse(file)
def parse_binary_file(file):
return stl.binary.parse(file)
def parse_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def parse_binary_string(data):
from StringIO import StringIO
return parse_binary_file(StringIO(data))
<commit_msg>Rename the reading functions "read_" rather than "parse_".
"Parsing" is what they do internally, but "read" is a better opposite to
"write" and matches the name of the underlying raw file operation.<commit_after>
import stl.ascii
import stl.binary
def read_ascii_file(file):
return stl.ascii.parse(file)
def read_binary_file(file):
return stl.binary.parse(file)
def read_ascii_string(data):
from StringIO import StringIO
return parse_ascii_file(StringIO(data))
def read_binary_string(data):
from StringIO import StringIO
return parse_binary_file(StringIO(data))
|
dbe8d7a4f43521e7aeba8f2670e70ac91f40ec3c | enthought/mayavi/tests/test_mlab_scene_model.py | enthought/mayavi/tests/test_mlab_scene_model.py | """
Testing the MlabSceneModel
"""
import unittest
from enthought.traits.api import HasTraits, Instance
from enthought.mayavi.tools.mlab_scene_model import MlabSceneModel
from enthought.mayavi import mlab
from test_mlab_integration import TestMlabNullEngine
###############################################################################
# class `TestMlabSceneModel`
###############################################################################
class TestMlabSceneModel(TestMlabNullEngine):
""" Testing the MlabSceneModel, in particular the magic
mlab attribute.
"""
def test_several_scene_models(self):
""" Check that plotting to scene attributes using their
mlab attribute does create objects as children, and does not
unset the current scene
"""
class TestObject(HasTraits):
scene1 = Instance(MlabSceneModel, ())
scene2 = Instance(MlabSceneModel, ())
f = mlab.figure()
test_object = TestObject()
plt = test_object.scene1.mlab.test_plot3d()
pts = test_object.scene2.mlab.test_points3d()
# Check that each figure got the module it should have
self.assertEqual(plt.scene, test_object.scene1)
self.assertEqual(pts.scene, test_object.scene2)
# Check that the current figure was not upset by plotting to the
# object
self.assertEqual(mlab.gcf(), f)
if __name__ == '__main__':
unittest.main()
| """
Testing the MlabSceneModel
"""
import unittest
import numpy as np
from enthought.traits.api import HasTraits, Instance
from enthought.mayavi.tools.mlab_scene_model import MlabSceneModel
from enthought.mayavi import mlab
from test_mlab_integration import TestMlabNullEngine
###############################################################################
# class `TestMlabSceneModel`
###############################################################################
class TestMlabSceneModel(TestMlabNullEngine):
""" Testing the MlabSceneModel, in particular the magic
mlab attribute.
"""
def test_several_scene_models(self):
""" Check that plotting to scene attributes using their
mlab attribute does create objects as children, and does not
unset the current scene
"""
class TestObject(HasTraits):
scene1 = Instance(MlabSceneModel, ())
scene2 = Instance(MlabSceneModel, ())
test_object = TestObject()
x, y, z = np.random.random((3, 10))
plt = mlab.plot3d(x, y, z,
figure=test_object.scene1.mayavi_scene)
pts = mlab.points3d(x, y, z,
figure=test_object.scene2.mayavi_scene)
# Check that each figure got the module it should have
self.assertEqual(plt.scene, test_object.scene1)
self.assertEqual(pts.scene, test_object.scene2)
if __name__ == '__main__':
unittest.main()
| Fix a failing test due to refactor | BUG: Fix a failing test due to refactor
| Python | bsd-3-clause | dmsurti/mayavi,liulion/mayavi,alexandreleroux/mayavi,dmsurti/mayavi,alexandreleroux/mayavi,liulion/mayavi | """
Testing the MlabSceneModel
"""
import unittest
from enthought.traits.api import HasTraits, Instance
from enthought.mayavi.tools.mlab_scene_model import MlabSceneModel
from enthought.mayavi import mlab
from test_mlab_integration import TestMlabNullEngine
###############################################################################
# class `TestMlabSceneModel`
###############################################################################
class TestMlabSceneModel(TestMlabNullEngine):
""" Testing the MlabSceneModel, in particular the magic
mlab attribute.
"""
def test_several_scene_models(self):
""" Check that plotting to scene attributes using their
mlab attribute does create objects as children, and does not
unset the current scene
"""
class TestObject(HasTraits):
scene1 = Instance(MlabSceneModel, ())
scene2 = Instance(MlabSceneModel, ())
f = mlab.figure()
test_object = TestObject()
plt = test_object.scene1.mlab.test_plot3d()
pts = test_object.scene2.mlab.test_points3d()
# Check that each figure got the module it should have
self.assertEqual(plt.scene, test_object.scene1)
self.assertEqual(pts.scene, test_object.scene2)
# Check that the current figure was not upset by plotting to the
# object
self.assertEqual(mlab.gcf(), f)
if __name__ == '__main__':
unittest.main()
BUG: Fix a failing test due to refactor | """
Testing the MlabSceneModel
"""
import unittest
import numpy as np
from enthought.traits.api import HasTraits, Instance
from enthought.mayavi.tools.mlab_scene_model import MlabSceneModel
from enthought.mayavi import mlab
from test_mlab_integration import TestMlabNullEngine
###############################################################################
# class `TestMlabSceneModel`
###############################################################################
class TestMlabSceneModel(TestMlabNullEngine):
""" Testing the MlabSceneModel, in particular the magic
mlab attribute.
"""
def test_several_scene_models(self):
""" Check that plotting to scene attributes using their
mlab attribute does create objects as children, and does not
unset the current scene
"""
class TestObject(HasTraits):
scene1 = Instance(MlabSceneModel, ())
scene2 = Instance(MlabSceneModel, ())
test_object = TestObject()
x, y, z = np.random.random((3, 10))
plt = mlab.plot3d(x, y, z,
figure=test_object.scene1.mayavi_scene)
pts = mlab.points3d(x, y, z,
figure=test_object.scene2.mayavi_scene)
# Check that each figure got the module it should have
self.assertEqual(plt.scene, test_object.scene1)
self.assertEqual(pts.scene, test_object.scene2)
if __name__ == '__main__':
unittest.main()
| <commit_before>"""
Testing the MlabSceneModel
"""
import unittest
from enthought.traits.api import HasTraits, Instance
from enthought.mayavi.tools.mlab_scene_model import MlabSceneModel
from enthought.mayavi import mlab
from test_mlab_integration import TestMlabNullEngine
###############################################################################
# class `TestMlabSceneModel`
###############################################################################
class TestMlabSceneModel(TestMlabNullEngine):
""" Testing the MlabSceneModel, in particular the magic
mlab attribute.
"""
def test_several_scene_models(self):
""" Check that plotting to scene attributes using their
mlab attribute does create objects as children, and does not
unset the current scene
"""
class TestObject(HasTraits):
scene1 = Instance(MlabSceneModel, ())
scene2 = Instance(MlabSceneModel, ())
f = mlab.figure()
test_object = TestObject()
plt = test_object.scene1.mlab.test_plot3d()
pts = test_object.scene2.mlab.test_points3d()
# Check that each figure got the module it should have
self.assertEqual(plt.scene, test_object.scene1)
self.assertEqual(pts.scene, test_object.scene2)
# Check that the current figure was not upset by plotting to the
# object
self.assertEqual(mlab.gcf(), f)
if __name__ == '__main__':
unittest.main()
<commit_msg>BUG: Fix a failing test due to refactor<commit_after> | """
Testing the MlabSceneModel
"""
import unittest
import numpy as np
from enthought.traits.api import HasTraits, Instance
from enthought.mayavi.tools.mlab_scene_model import MlabSceneModel
from enthought.mayavi import mlab
from test_mlab_integration import TestMlabNullEngine
###############################################################################
# class `TestMlabSceneModel`
###############################################################################
class TestMlabSceneModel(TestMlabNullEngine):
""" Testing the MlabSceneModel, in particular the magic
mlab attribute.
"""
def test_several_scene_models(self):
""" Check that plotting to scene attributes using their
mlab attribute does create objects as children, and does not
unset the current scene
"""
class TestObject(HasTraits):
scene1 = Instance(MlabSceneModel, ())
scene2 = Instance(MlabSceneModel, ())
test_object = TestObject()
x, y, z = np.random.random((3, 10))
plt = mlab.plot3d(x, y, z,
figure=test_object.scene1.mayavi_scene)
pts = mlab.points3d(x, y, z,
figure=test_object.scene2.mayavi_scene)
# Check that each figure got the module it should have
self.assertEqual(plt.scene, test_object.scene1)
self.assertEqual(pts.scene, test_object.scene2)
if __name__ == '__main__':
unittest.main()
| """
Testing the MlabSceneModel
"""
import unittest
from enthought.traits.api import HasTraits, Instance
from enthought.mayavi.tools.mlab_scene_model import MlabSceneModel
from enthought.mayavi import mlab
from test_mlab_integration import TestMlabNullEngine
###############################################################################
# class `TestMlabSceneModel`
###############################################################################
class TestMlabSceneModel(TestMlabNullEngine):
""" Testing the MlabSceneModel, in particular the magic
mlab attribute.
"""
def test_several_scene_models(self):
""" Check that plotting to scene attributes using their
mlab attribute does create objects as children, and does not
unset the current scene
"""
class TestObject(HasTraits):
scene1 = Instance(MlabSceneModel, ())
scene2 = Instance(MlabSceneModel, ())
f = mlab.figure()
test_object = TestObject()
plt = test_object.scene1.mlab.test_plot3d()
pts = test_object.scene2.mlab.test_points3d()
# Check that each figure got the module it should have
self.assertEqual(plt.scene, test_object.scene1)
self.assertEqual(pts.scene, test_object.scene2)
# Check that the current figure was not upset by plotting to the
# object
self.assertEqual(mlab.gcf(), f)
if __name__ == '__main__':
unittest.main()
BUG: Fix a failing test due to refactor"""
Testing the MlabSceneModel
"""
import unittest
import numpy as np
from enthought.traits.api import HasTraits, Instance
from enthought.mayavi.tools.mlab_scene_model import MlabSceneModel
from enthought.mayavi import mlab
from test_mlab_integration import TestMlabNullEngine
###############################################################################
# class `TestMlabSceneModel`
###############################################################################
class TestMlabSceneModel(TestMlabNullEngine):
""" Testing the MlabSceneModel, in particular the magic
mlab attribute.
"""
def test_several_scene_models(self):
""" Check that plotting to scene attributes using their
mlab attribute does create objects as children, and does not
unset the current scene
"""
class TestObject(HasTraits):
scene1 = Instance(MlabSceneModel, ())
scene2 = Instance(MlabSceneModel, ())
test_object = TestObject()
x, y, z = np.random.random((3, 10))
plt = mlab.plot3d(x, y, z,
figure=test_object.scene1.mayavi_scene)
pts = mlab.points3d(x, y, z,
figure=test_object.scene2.mayavi_scene)
# Check that each figure got the module it should have
self.assertEqual(plt.scene, test_object.scene1)
self.assertEqual(pts.scene, test_object.scene2)
if __name__ == '__main__':
unittest.main()
| <commit_before>"""
Testing the MlabSceneModel
"""
import unittest
from enthought.traits.api import HasTraits, Instance
from enthought.mayavi.tools.mlab_scene_model import MlabSceneModel
from enthought.mayavi import mlab
from test_mlab_integration import TestMlabNullEngine
###############################################################################
# class `TestMlabSceneModel`
###############################################################################
class TestMlabSceneModel(TestMlabNullEngine):
""" Testing the MlabSceneModel, in particular the magic
mlab attribute.
"""
def test_several_scene_models(self):
""" Check that plotting to scene attributes using their
mlab attribute does create objects as children, and does not
unset the current scene
"""
class TestObject(HasTraits):
scene1 = Instance(MlabSceneModel, ())
scene2 = Instance(MlabSceneModel, ())
f = mlab.figure()
test_object = TestObject()
plt = test_object.scene1.mlab.test_plot3d()
pts = test_object.scene2.mlab.test_points3d()
# Check that each figure got the module it should have
self.assertEqual(plt.scene, test_object.scene1)
self.assertEqual(pts.scene, test_object.scene2)
# Check that the current figure was not upset by plotting to the
# object
self.assertEqual(mlab.gcf(), f)
if __name__ == '__main__':
unittest.main()
<commit_msg>BUG: Fix a failing test due to refactor<commit_after>"""
Testing the MlabSceneModel
"""
import unittest
import numpy as np
from enthought.traits.api import HasTraits, Instance
from enthought.mayavi.tools.mlab_scene_model import MlabSceneModel
from enthought.mayavi import mlab
from test_mlab_integration import TestMlabNullEngine
###############################################################################
# class `TestMlabSceneModel`
###############################################################################
class TestMlabSceneModel(TestMlabNullEngine):
""" Testing the MlabSceneModel, in particular the magic
mlab attribute.
"""
def test_several_scene_models(self):
""" Check that plotting to scene attributes using their
mlab attribute does create objects as children, and does not
unset the current scene
"""
class TestObject(HasTraits):
scene1 = Instance(MlabSceneModel, ())
scene2 = Instance(MlabSceneModel, ())
test_object = TestObject()
x, y, z = np.random.random((3, 10))
plt = mlab.plot3d(x, y, z,
figure=test_object.scene1.mayavi_scene)
pts = mlab.points3d(x, y, z,
figure=test_object.scene2.mayavi_scene)
# Check that each figure got the module it should have
self.assertEqual(plt.scene, test_object.scene1)
self.assertEqual(pts.scene, test_object.scene2)
if __name__ == '__main__':
unittest.main()
|
2c4c527e6bb63f7db7a1c2d32f71b76fad65f92a | src/core/tests/test_callexplorer.py | src/core/tests/test_callexplorer.py | # Copyright (c) 2013 The SAYCBridge Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest2
from core.callexplorer import *
class CallExplorerTest(unittest2.TestCase):
def _assert_histories(self, glob_string, histories):
explorer = CallExplorer()
self.assertEqual(sorted(map(lambda history: history.calls_string(), explorer.history_glob(glob_string))), sorted(histories))
def test_history_glob(self):
self._assert_histories("", [])
self._assert_histories(" ", [])
self._assert_histories("P", ["P"])
self._assert_histories(" P ", ["P"])
self._assert_histories("P 1C", ["P 1C"])
self._assert_histories("* 1C", ["P 1C"])
self._assert_histories("1C * 1H", ["1C 1D 1H", "1C X 1H", "1C P 1H"])
if __name__ == '__main__':
unittest2.main()
| # Copyright (c) 2013 The SAYCBridge Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest2
from core.callexplorer import *
class CallExplorerTest(unittest2.TestCase):
def _assert_histories(self, glob_string, histories):
explorer = CallExplorer()
self.assertEqual(sorted(map(lambda history: history.calls_string(), explorer.history_glob(glob_string))), sorted(histories))
def test_history_glob(self):
self._assert_histories("", [])
self._assert_histories(" ", [])
self._assert_histories("P", ["P"])
self._assert_histories(" P ", ["P"])
self._assert_histories("P 1C", ["P 1C"])
self._assert_histories("* 1C", ["P 1C"])
self._assert_histories("1C * 1H", ["1C 1D 1H", "1C X 1H", "1C P 1H"])
self._assert_histories("* 1C * 1D", ["P 1C X 1D", "P 1C P 1D"])
if __name__ == '__main__':
unittest2.main()
| Add another test for CallExplorer.history_glob | Add another test for CallExplorer.history_glob
| Python | bsd-3-clause | abortz/saycbridge,eseidel/saycbridge,eseidel/saycbridge,abortz/saycbridge,abortz/saycbridge,eseidel/saycbridge,abortz/saycbridge,abortz/saycbridge | # Copyright (c) 2013 The SAYCBridge Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest2
from core.callexplorer import *
class CallExplorerTest(unittest2.TestCase):
def _assert_histories(self, glob_string, histories):
explorer = CallExplorer()
self.assertEqual(sorted(map(lambda history: history.calls_string(), explorer.history_glob(glob_string))), sorted(histories))
def test_history_glob(self):
self._assert_histories("", [])
self._assert_histories(" ", [])
self._assert_histories("P", ["P"])
self._assert_histories(" P ", ["P"])
self._assert_histories("P 1C", ["P 1C"])
self._assert_histories("* 1C", ["P 1C"])
self._assert_histories("1C * 1H", ["1C 1D 1H", "1C X 1H", "1C P 1H"])
if __name__ == '__main__':
unittest2.main()
Add another test for CallExplorer.history_glob | # Copyright (c) 2013 The SAYCBridge Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest2
from core.callexplorer import *
class CallExplorerTest(unittest2.TestCase):
def _assert_histories(self, glob_string, histories):
explorer = CallExplorer()
self.assertEqual(sorted(map(lambda history: history.calls_string(), explorer.history_glob(glob_string))), sorted(histories))
def test_history_glob(self):
self._assert_histories("", [])
self._assert_histories(" ", [])
self._assert_histories("P", ["P"])
self._assert_histories(" P ", ["P"])
self._assert_histories("P 1C", ["P 1C"])
self._assert_histories("* 1C", ["P 1C"])
self._assert_histories("1C * 1H", ["1C 1D 1H", "1C X 1H", "1C P 1H"])
self._assert_histories("* 1C * 1D", ["P 1C X 1D", "P 1C P 1D"])
if __name__ == '__main__':
unittest2.main()
| <commit_before># Copyright (c) 2013 The SAYCBridge Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest2
from core.callexplorer import *
class CallExplorerTest(unittest2.TestCase):
def _assert_histories(self, glob_string, histories):
explorer = CallExplorer()
self.assertEqual(sorted(map(lambda history: history.calls_string(), explorer.history_glob(glob_string))), sorted(histories))
def test_history_glob(self):
self._assert_histories("", [])
self._assert_histories(" ", [])
self._assert_histories("P", ["P"])
self._assert_histories(" P ", ["P"])
self._assert_histories("P 1C", ["P 1C"])
self._assert_histories("* 1C", ["P 1C"])
self._assert_histories("1C * 1H", ["1C 1D 1H", "1C X 1H", "1C P 1H"])
if __name__ == '__main__':
unittest2.main()
<commit_msg>Add another test for CallExplorer.history_glob<commit_after> | # Copyright (c) 2013 The SAYCBridge Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest2
from core.callexplorer import *
class CallExplorerTest(unittest2.TestCase):
def _assert_histories(self, glob_string, histories):
explorer = CallExplorer()
self.assertEqual(sorted(map(lambda history: history.calls_string(), explorer.history_glob(glob_string))), sorted(histories))
def test_history_glob(self):
self._assert_histories("", [])
self._assert_histories(" ", [])
self._assert_histories("P", ["P"])
self._assert_histories(" P ", ["P"])
self._assert_histories("P 1C", ["P 1C"])
self._assert_histories("* 1C", ["P 1C"])
self._assert_histories("1C * 1H", ["1C 1D 1H", "1C X 1H", "1C P 1H"])
self._assert_histories("* 1C * 1D", ["P 1C X 1D", "P 1C P 1D"])
if __name__ == '__main__':
unittest2.main()
| # Copyright (c) 2013 The SAYCBridge Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest2
from core.callexplorer import *
class CallExplorerTest(unittest2.TestCase):
def _assert_histories(self, glob_string, histories):
explorer = CallExplorer()
self.assertEqual(sorted(map(lambda history: history.calls_string(), explorer.history_glob(glob_string))), sorted(histories))
def test_history_glob(self):
self._assert_histories("", [])
self._assert_histories(" ", [])
self._assert_histories("P", ["P"])
self._assert_histories(" P ", ["P"])
self._assert_histories("P 1C", ["P 1C"])
self._assert_histories("* 1C", ["P 1C"])
self._assert_histories("1C * 1H", ["1C 1D 1H", "1C X 1H", "1C P 1H"])
if __name__ == '__main__':
unittest2.main()
Add another test for CallExplorer.history_glob# Copyright (c) 2013 The SAYCBridge Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest2
from core.callexplorer import *
class CallExplorerTest(unittest2.TestCase):
def _assert_histories(self, glob_string, histories):
explorer = CallExplorer()
self.assertEqual(sorted(map(lambda history: history.calls_string(), explorer.history_glob(glob_string))), sorted(histories))
def test_history_glob(self):
self._assert_histories("", [])
self._assert_histories(" ", [])
self._assert_histories("P", ["P"])
self._assert_histories(" P ", ["P"])
self._assert_histories("P 1C", ["P 1C"])
self._assert_histories("* 1C", ["P 1C"])
self._assert_histories("1C * 1H", ["1C 1D 1H", "1C X 1H", "1C P 1H"])
self._assert_histories("* 1C * 1D", ["P 1C X 1D", "P 1C P 1D"])
if __name__ == '__main__':
unittest2.main()
| <commit_before># Copyright (c) 2013 The SAYCBridge Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest2
from core.callexplorer import *
class CallExplorerTest(unittest2.TestCase):
def _assert_histories(self, glob_string, histories):
explorer = CallExplorer()
self.assertEqual(sorted(map(lambda history: history.calls_string(), explorer.history_glob(glob_string))), sorted(histories))
def test_history_glob(self):
self._assert_histories("", [])
self._assert_histories(" ", [])
self._assert_histories("P", ["P"])
self._assert_histories(" P ", ["P"])
self._assert_histories("P 1C", ["P 1C"])
self._assert_histories("* 1C", ["P 1C"])
self._assert_histories("1C * 1H", ["1C 1D 1H", "1C X 1H", "1C P 1H"])
if __name__ == '__main__':
unittest2.main()
<commit_msg>Add another test for CallExplorer.history_glob<commit_after># Copyright (c) 2013 The SAYCBridge Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest2
from core.callexplorer import *
class CallExplorerTest(unittest2.TestCase):
def _assert_histories(self, glob_string, histories):
explorer = CallExplorer()
self.assertEqual(sorted(map(lambda history: history.calls_string(), explorer.history_glob(glob_string))), sorted(histories))
def test_history_glob(self):
self._assert_histories("", [])
self._assert_histories(" ", [])
self._assert_histories("P", ["P"])
self._assert_histories(" P ", ["P"])
self._assert_histories("P 1C", ["P 1C"])
self._assert_histories("* 1C", ["P 1C"])
self._assert_histories("1C * 1H", ["1C 1D 1H", "1C X 1H", "1C P 1H"])
self._assert_histories("* 1C * 1D", ["P 1C X 1D", "P 1C P 1D"])
if __name__ == '__main__':
unittest2.main()
|
a9b22b76203467ec63ce0592e32498cfecdedca3 | tests/config.py | tests/config.py | from ideascaly.auth import AuthNonSSO
from ideascaly.api import API
import ConfigParser
import unittest
config = ConfigParser.ConfigParser()
config.read('config')
class IdeascalyTestCase(unittest.TestCase):
def setUp(self):
self.auth = create_auth()
self.api = API(self.auth)
self.api.community_url = config.get('test', 'community_url')
def create_auth():
auth = AuthNonSSO(config.get('test', 'token'))
return auth | import sys
sys.path.append("../ideascaly")
from ideascaly.auth import AuthNonSSO
from ideascaly.api import API
import ConfigParser
import unittest
config = ConfigParser.ConfigParser()
config.read('config')
class IdeascalyTestCase(unittest.TestCase):
def setUp(self):
self.auth = create_auth()
self.api = API(self.auth)
self.api.community_url = config.get('test', 'community_url')
def create_auth():
auth = AuthNonSSO(config.get('test', 'token'))
return auth | Add the directory of the project module to system path | Add the directory of the project module to system path
| Python | mit | joausaga/ideascaly | from ideascaly.auth import AuthNonSSO
from ideascaly.api import API
import ConfigParser
import unittest
config = ConfigParser.ConfigParser()
config.read('config')
class IdeascalyTestCase(unittest.TestCase):
def setUp(self):
self.auth = create_auth()
self.api = API(self.auth)
self.api.community_url = config.get('test', 'community_url')
def create_auth():
auth = AuthNonSSO(config.get('test', 'token'))
return authAdd the directory of the project module to system path | import sys
sys.path.append("../ideascaly")
from ideascaly.auth import AuthNonSSO
from ideascaly.api import API
import ConfigParser
import unittest
config = ConfigParser.ConfigParser()
config.read('config')
class IdeascalyTestCase(unittest.TestCase):
def setUp(self):
self.auth = create_auth()
self.api = API(self.auth)
self.api.community_url = config.get('test', 'community_url')
def create_auth():
auth = AuthNonSSO(config.get('test', 'token'))
return auth | <commit_before>from ideascaly.auth import AuthNonSSO
from ideascaly.api import API
import ConfigParser
import unittest
config = ConfigParser.ConfigParser()
config.read('config')
class IdeascalyTestCase(unittest.TestCase):
def setUp(self):
self.auth = create_auth()
self.api = API(self.auth)
self.api.community_url = config.get('test', 'community_url')
def create_auth():
auth = AuthNonSSO(config.get('test', 'token'))
return auth<commit_msg>Add the directory of the project module to system path<commit_after> | import sys
sys.path.append("../ideascaly")
from ideascaly.auth import AuthNonSSO
from ideascaly.api import API
import ConfigParser
import unittest
config = ConfigParser.ConfigParser()
config.read('config')
class IdeascalyTestCase(unittest.TestCase):
def setUp(self):
self.auth = create_auth()
self.api = API(self.auth)
self.api.community_url = config.get('test', 'community_url')
def create_auth():
auth = AuthNonSSO(config.get('test', 'token'))
return auth | from ideascaly.auth import AuthNonSSO
from ideascaly.api import API
import ConfigParser
import unittest
config = ConfigParser.ConfigParser()
config.read('config')
class IdeascalyTestCase(unittest.TestCase):
def setUp(self):
self.auth = create_auth()
self.api = API(self.auth)
self.api.community_url = config.get('test', 'community_url')
def create_auth():
auth = AuthNonSSO(config.get('test', 'token'))
return authAdd the directory of the project module to system pathimport sys
sys.path.append("../ideascaly")
from ideascaly.auth import AuthNonSSO
from ideascaly.api import API
import ConfigParser
import unittest
config = ConfigParser.ConfigParser()
config.read('config')
class IdeascalyTestCase(unittest.TestCase):
def setUp(self):
self.auth = create_auth()
self.api = API(self.auth)
self.api.community_url = config.get('test', 'community_url')
def create_auth():
auth = AuthNonSSO(config.get('test', 'token'))
return auth | <commit_before>from ideascaly.auth import AuthNonSSO
from ideascaly.api import API
import ConfigParser
import unittest
config = ConfigParser.ConfigParser()
config.read('config')
class IdeascalyTestCase(unittest.TestCase):
def setUp(self):
self.auth = create_auth()
self.api = API(self.auth)
self.api.community_url = config.get('test', 'community_url')
def create_auth():
auth = AuthNonSSO(config.get('test', 'token'))
return auth<commit_msg>Add the directory of the project module to system path<commit_after>import sys
sys.path.append("../ideascaly")
from ideascaly.auth import AuthNonSSO
from ideascaly.api import API
import ConfigParser
import unittest
config = ConfigParser.ConfigParser()
config.read('config')
class IdeascalyTestCase(unittest.TestCase):
def setUp(self):
self.auth = create_auth()
self.api = API(self.auth)
self.api.community_url = config.get('test', 'community_url')
def create_auth():
auth = AuthNonSSO(config.get('test', 'token'))
return auth |
4f5b171b972b2255dfc3cdb8eea8b4a2745ae437 | centinel/backend.py | centinel/backend.py | import requests
import config
def request(slug):
url = "%s%s" % (config.server_url, slug)
req = requests.get(url)
if req.status_code != requests.codes.ok:
raise req.raise_for_status()
return req.json()
def get_recommended_versions():
return request("/versions")
def get_experiments():
return request("/experiments")
def get_results():
return request("/results")
def get_clients():
return request("/clients")
def submit_result(file_name):
with open(file_name) as result_file:
file = {'result' : result_file}
url = "%s%s" % (config.server_url, "/results")
requests.post(url, files=file)
if req.status_code != requests.codes.ok:
raise req.raise_for_status()
| import os
import glob
import requests
import config
def request(slug):
url = "%s%s" % (config.server_url, slug)
req = requests.get(url)
req.raise_for_status()
return req.json()
def get_recommended_versions():
return request("/versions")
def get_experiments():
return request("/experiments")
def get_results():
return request("/results")
def get_clients():
return request("/clients")
def submit_result(file_name):
with open(file_name) as result_file:
file = {'result' : result_file}
url = "%s%s" % (config.server_url, "/results")
req = requests.post(url, files=file)
req.raise_for_status()
def sync():
# send all results
for path in glob.glob(os.path.join(config.results_dir,'[!_]*.json')):
try:
submit_result(path)
except Exception, e:
logging.error("Unable to send result file %s" % (path))
| Send results to the server | Send results to the server
| Python | mit | rpanah/centinel,rpanah/centinel,lianke123321/centinel,JASONews/centinel,iclab/centinel,iclab/centinel,lianke123321/centinel,rpanah/centinel,iclab/centinel,Ashish1805/centinel,ben-jones/centinel,lianke123321/centinel | import requests
import config
def request(slug):
url = "%s%s" % (config.server_url, slug)
req = requests.get(url)
if req.status_code != requests.codes.ok:
raise req.raise_for_status()
return req.json()
def get_recommended_versions():
return request("/versions")
def get_experiments():
return request("/experiments")
def get_results():
return request("/results")
def get_clients():
return request("/clients")
def submit_result(file_name):
with open(file_name) as result_file:
file = {'result' : result_file}
url = "%s%s" % (config.server_url, "/results")
requests.post(url, files=file)
if req.status_code != requests.codes.ok:
raise req.raise_for_status()
Send results to the server | import os
import glob
import requests
import config
def request(slug):
url = "%s%s" % (config.server_url, slug)
req = requests.get(url)
req.raise_for_status()
return req.json()
def get_recommended_versions():
return request("/versions")
def get_experiments():
return request("/experiments")
def get_results():
return request("/results")
def get_clients():
return request("/clients")
def submit_result(file_name):
with open(file_name) as result_file:
file = {'result' : result_file}
url = "%s%s" % (config.server_url, "/results")
req = requests.post(url, files=file)
req.raise_for_status()
def sync():
# send all results
for path in glob.glob(os.path.join(config.results_dir,'[!_]*.json')):
try:
submit_result(path)
except Exception, e:
logging.error("Unable to send result file %s" % (path))
| <commit_before>import requests
import config
def request(slug):
url = "%s%s" % (config.server_url, slug)
req = requests.get(url)
if req.status_code != requests.codes.ok:
raise req.raise_for_status()
return req.json()
def get_recommended_versions():
return request("/versions")
def get_experiments():
return request("/experiments")
def get_results():
return request("/results")
def get_clients():
return request("/clients")
def submit_result(file_name):
with open(file_name) as result_file:
file = {'result' : result_file}
url = "%s%s" % (config.server_url, "/results")
requests.post(url, files=file)
if req.status_code != requests.codes.ok:
raise req.raise_for_status()
<commit_msg>Send results to the server<commit_after> | import os
import glob
import requests
import config
def request(slug):
url = "%s%s" % (config.server_url, slug)
req = requests.get(url)
req.raise_for_status()
return req.json()
def get_recommended_versions():
return request("/versions")
def get_experiments():
return request("/experiments")
def get_results():
return request("/results")
def get_clients():
return request("/clients")
def submit_result(file_name):
with open(file_name) as result_file:
file = {'result' : result_file}
url = "%s%s" % (config.server_url, "/results")
req = requests.post(url, files=file)
req.raise_for_status()
def sync():
# send all results
for path in glob.glob(os.path.join(config.results_dir,'[!_]*.json')):
try:
submit_result(path)
except Exception, e:
logging.error("Unable to send result file %s" % (path))
| import requests
import config
def request(slug):
url = "%s%s" % (config.server_url, slug)
req = requests.get(url)
if req.status_code != requests.codes.ok:
raise req.raise_for_status()
return req.json()
def get_recommended_versions():
return request("/versions")
def get_experiments():
return request("/experiments")
def get_results():
return request("/results")
def get_clients():
return request("/clients")
def submit_result(file_name):
with open(file_name) as result_file:
file = {'result' : result_file}
url = "%s%s" % (config.server_url, "/results")
requests.post(url, files=file)
if req.status_code != requests.codes.ok:
raise req.raise_for_status()
Send results to the serverimport os
import glob
import requests
import config
def request(slug):
url = "%s%s" % (config.server_url, slug)
req = requests.get(url)
req.raise_for_status()
return req.json()
def get_recommended_versions():
return request("/versions")
def get_experiments():
return request("/experiments")
def get_results():
return request("/results")
def get_clients():
return request("/clients")
def submit_result(file_name):
with open(file_name) as result_file:
file = {'result' : result_file}
url = "%s%s" % (config.server_url, "/results")
req = requests.post(url, files=file)
req.raise_for_status()
def sync():
# send all results
for path in glob.glob(os.path.join(config.results_dir,'[!_]*.json')):
try:
submit_result(path)
except Exception, e:
logging.error("Unable to send result file %s" % (path))
| <commit_before>import requests
import config
def request(slug):
url = "%s%s" % (config.server_url, slug)
req = requests.get(url)
if req.status_code != requests.codes.ok:
raise req.raise_for_status()
return req.json()
def get_recommended_versions():
return request("/versions")
def get_experiments():
return request("/experiments")
def get_results():
return request("/results")
def get_clients():
return request("/clients")
def submit_result(file_name):
with open(file_name) as result_file:
file = {'result' : result_file}
url = "%s%s" % (config.server_url, "/results")
requests.post(url, files=file)
if req.status_code != requests.codes.ok:
raise req.raise_for_status()
<commit_msg>Send results to the server<commit_after>import os
import glob
import requests
import config
def request(slug):
url = "%s%s" % (config.server_url, slug)
req = requests.get(url)
req.raise_for_status()
return req.json()
def get_recommended_versions():
return request("/versions")
def get_experiments():
return request("/experiments")
def get_results():
return request("/results")
def get_clients():
return request("/clients")
def submit_result(file_name):
with open(file_name) as result_file:
file = {'result' : result_file}
url = "%s%s" % (config.server_url, "/results")
req = requests.post(url, files=file)
req.raise_for_status()
def sync():
# send all results
for path in glob.glob(os.path.join(config.results_dir,'[!_]*.json')):
try:
submit_result(path)
except Exception, e:
logging.error("Unable to send result file %s" % (path))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.