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
b52a23c87bed0370c41da39785812b9064688af0
passman/__main__.py
passman/__main__.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' Main driver of the program ''' import sys import random import os import json import argparse import time import getpass import hashlib import ast import threading import base64 import pymongo import pyperclip import Crypto import commandline import database import encryption import functions import JSON import login import menu import offlinemenu from passman.login import handleLogin, handleOfflineLogin from passman.commandline import handleCLArgs from passman.menu import showMenu, welcomeMessage from passman.database import checkConnection from passman.offlinemenu import handleOfflineMenu def main(): if len(sys.argv) > 1: # Run with command line arguments handleCLArgs(sys.argv) else: # Run a menu-based UI instead welcomeMessage() if checkConnection("check"): # Online login and menu handleLogin() while True: showMenu() else: # Offline login and menu handleOfflineLogin() while True: handleOfflineMenu() if __name__ == '__main__': if sys.version_info.major < 3: print("Passman must be run with Python 3 or later") else: main()
#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' Main driver of the program ''' import sys import random import os import json import argparse import time import getpass import hashlib import ast import threading import base64 import pymongo import pyperclip import Crypto from passman.login import handleLogin, handleOfflineLogin from passman.commandline import handleCLArgs from passman.menu import showMenu, welcomeMessage from passman.database import checkConnection from passman.offlinemenu import handleOfflineMenu def main(): if len(sys.argv) > 1: # Run with command line arguments handleCLArgs(sys.argv) else: # Run a menu-based UI instead welcomeMessage() if checkConnection("check"): # Online login and menu handleLogin() while True: showMenu() else: # Offline login and menu handleOfflineLogin() while True: handleOfflineMenu() if __name__ == '__main__': if sys.version_info.major < 3: print("Passman must be run with Python 3 or later") else: main()
Remove unnecessary imports from main
Remove unnecessary imports from main
Python
mit
regexpressyourself/passman
#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' Main driver of the program ''' import sys import random import os import json import argparse import time import getpass import hashlib import ast import threading import base64 import pymongo import pyperclip import Crypto import commandline import database import encryption import functions import JSON import login import menu import offlinemenu from passman.login import handleLogin, handleOfflineLogin from passman.commandline import handleCLArgs from passman.menu import showMenu, welcomeMessage from passman.database import checkConnection from passman.offlinemenu import handleOfflineMenu def main(): if len(sys.argv) > 1: # Run with command line arguments handleCLArgs(sys.argv) else: # Run a menu-based UI instead welcomeMessage() if checkConnection("check"): # Online login and menu handleLogin() while True: showMenu() else: # Offline login and menu handleOfflineLogin() while True: handleOfflineMenu() if __name__ == '__main__': if sys.version_info.major < 3: print("Passman must be run with Python 3 or later") else: main() Remove unnecessary imports from main
#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' Main driver of the program ''' import sys import random import os import json import argparse import time import getpass import hashlib import ast import threading import base64 import pymongo import pyperclip import Crypto from passman.login import handleLogin, handleOfflineLogin from passman.commandline import handleCLArgs from passman.menu import showMenu, welcomeMessage from passman.database import checkConnection from passman.offlinemenu import handleOfflineMenu def main(): if len(sys.argv) > 1: # Run with command line arguments handleCLArgs(sys.argv) else: # Run a menu-based UI instead welcomeMessage() if checkConnection("check"): # Online login and menu handleLogin() while True: showMenu() else: # Offline login and menu handleOfflineLogin() while True: handleOfflineMenu() if __name__ == '__main__': if sys.version_info.major < 3: print("Passman must be run with Python 3 or later") else: main()
<commit_before>#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' Main driver of the program ''' import sys import random import os import json import argparse import time import getpass import hashlib import ast import threading import base64 import pymongo import pyperclip import Crypto import commandline import database import encryption import functions import JSON import login import menu import offlinemenu from passman.login import handleLogin, handleOfflineLogin from passman.commandline import handleCLArgs from passman.menu import showMenu, welcomeMessage from passman.database import checkConnection from passman.offlinemenu import handleOfflineMenu def main(): if len(sys.argv) > 1: # Run with command line arguments handleCLArgs(sys.argv) else: # Run a menu-based UI instead welcomeMessage() if checkConnection("check"): # Online login and menu handleLogin() while True: showMenu() else: # Offline login and menu handleOfflineLogin() while True: handleOfflineMenu() if __name__ == '__main__': if sys.version_info.major < 3: print("Passman must be run with Python 3 or later") else: main() <commit_msg>Remove unnecessary imports from main<commit_after>
#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' Main driver of the program ''' import sys import random import os import json import argparse import time import getpass import hashlib import ast import threading import base64 import pymongo import pyperclip import Crypto from passman.login import handleLogin, handleOfflineLogin from passman.commandline import handleCLArgs from passman.menu import showMenu, welcomeMessage from passman.database import checkConnection from passman.offlinemenu import handleOfflineMenu def main(): if len(sys.argv) > 1: # Run with command line arguments handleCLArgs(sys.argv) else: # Run a menu-based UI instead welcomeMessage() if checkConnection("check"): # Online login and menu handleLogin() while True: showMenu() else: # Offline login and menu handleOfflineLogin() while True: handleOfflineMenu() if __name__ == '__main__': if sys.version_info.major < 3: print("Passman must be run with Python 3 or later") else: main()
#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' Main driver of the program ''' import sys import random import os import json import argparse import time import getpass import hashlib import ast import threading import base64 import pymongo import pyperclip import Crypto import commandline import database import encryption import functions import JSON import login import menu import offlinemenu from passman.login import handleLogin, handleOfflineLogin from passman.commandline import handleCLArgs from passman.menu import showMenu, welcomeMessage from passman.database import checkConnection from passman.offlinemenu import handleOfflineMenu def main(): if len(sys.argv) > 1: # Run with command line arguments handleCLArgs(sys.argv) else: # Run a menu-based UI instead welcomeMessage() if checkConnection("check"): # Online login and menu handleLogin() while True: showMenu() else: # Offline login and menu handleOfflineLogin() while True: handleOfflineMenu() if __name__ == '__main__': if sys.version_info.major < 3: print("Passman must be run with Python 3 or later") else: main() Remove unnecessary imports from main#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' Main driver of the program ''' import sys import random import os import json import argparse import time import getpass import hashlib import ast import threading import base64 import pymongo import pyperclip import Crypto from passman.login import handleLogin, handleOfflineLogin from passman.commandline import handleCLArgs from passman.menu import showMenu, welcomeMessage from passman.database import checkConnection from passman.offlinemenu import handleOfflineMenu def main(): if len(sys.argv) > 1: # Run with command line arguments handleCLArgs(sys.argv) else: # Run a menu-based UI instead welcomeMessage() if checkConnection("check"): # Online login and menu handleLogin() while True: showMenu() else: # Offline login and menu handleOfflineLogin() while True: handleOfflineMenu() if __name__ == '__main__': if sys.version_info.major < 3: print("Passman must be run with Python 3 or later") else: main()
<commit_before>#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' Main driver of the program ''' import sys import random import os import json import argparse import time import getpass import hashlib import ast import threading import base64 import pymongo import pyperclip import Crypto import commandline import database import encryption import functions import JSON import login import menu import offlinemenu from passman.login import handleLogin, handleOfflineLogin from passman.commandline import handleCLArgs from passman.menu import showMenu, welcomeMessage from passman.database import checkConnection from passman.offlinemenu import handleOfflineMenu def main(): if len(sys.argv) > 1: # Run with command line arguments handleCLArgs(sys.argv) else: # Run a menu-based UI instead welcomeMessage() if checkConnection("check"): # Online login and menu handleLogin() while True: showMenu() else: # Offline login and menu handleOfflineLogin() while True: handleOfflineMenu() if __name__ == '__main__': if sys.version_info.major < 3: print("Passman must be run with Python 3 or later") else: main() <commit_msg>Remove unnecessary imports from main<commit_after>#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' Main driver of the program ''' import sys import random import os import json import argparse import time import getpass import hashlib import ast import threading import base64 import pymongo import pyperclip import Crypto from passman.login import handleLogin, handleOfflineLogin from passman.commandline import handleCLArgs from passman.menu import showMenu, welcomeMessage from passman.database import checkConnection from passman.offlinemenu import handleOfflineMenu def main(): if len(sys.argv) > 1: # Run with command line arguments handleCLArgs(sys.argv) else: # Run a menu-based UI instead welcomeMessage() if checkConnection("check"): # Online login and menu handleLogin() while True: showMenu() else: # Offline login and menu handleOfflineLogin() while True: handleOfflineMenu() if __name__ == '__main__': if sys.version_info.major < 3: print("Passman must be run with Python 3 or later") else: main()
9e960b508988c4049eb9f3377c505f506a3af060
example/shutdown_client.py
example/shutdown_client.py
#!/usr/bin/env python import asyncio import signal import websockets async def client(): uri = "ws://localhost:8765" async with websockets.connect(uri) as websocket: # Close the connection when receiving SIGTERM. loop = asyncio.get_running_loop() loop.add_signal_handler( signal.SIGTERM, loop.create_task, websocket.close()) # Process messages received on the connection. async for message in websocket: ... asyncio.run(client())
#!/usr/bin/env python import asyncio import signal import websockets async def client(): uri = "ws://localhost:8765" async with websockets.connect(uri) as websocket: # Close the connection when receiving SIGTERM. loop = asyncio.get_running_loop() loop.add_signal_handler( signal.SIGTERM, loop.create_task, websocket.close) # Process messages received on the connection. async for message in websocket: ... asyncio.run(client())
Fix example of shutting down a client.
Fix example of shutting down a client. Fix #1261.
Python
bsd-3-clause
aaugustin/websockets,aaugustin/websockets,aaugustin/websockets,aaugustin/websockets
#!/usr/bin/env python import asyncio import signal import websockets async def client(): uri = "ws://localhost:8765" async with websockets.connect(uri) as websocket: # Close the connection when receiving SIGTERM. loop = asyncio.get_running_loop() loop.add_signal_handler( signal.SIGTERM, loop.create_task, websocket.close()) # Process messages received on the connection. async for message in websocket: ... asyncio.run(client()) Fix example of shutting down a client. Fix #1261.
#!/usr/bin/env python import asyncio import signal import websockets async def client(): uri = "ws://localhost:8765" async with websockets.connect(uri) as websocket: # Close the connection when receiving SIGTERM. loop = asyncio.get_running_loop() loop.add_signal_handler( signal.SIGTERM, loop.create_task, websocket.close) # Process messages received on the connection. async for message in websocket: ... asyncio.run(client())
<commit_before>#!/usr/bin/env python import asyncio import signal import websockets async def client(): uri = "ws://localhost:8765" async with websockets.connect(uri) as websocket: # Close the connection when receiving SIGTERM. loop = asyncio.get_running_loop() loop.add_signal_handler( signal.SIGTERM, loop.create_task, websocket.close()) # Process messages received on the connection. async for message in websocket: ... asyncio.run(client()) <commit_msg>Fix example of shutting down a client. Fix #1261.<commit_after>
#!/usr/bin/env python import asyncio import signal import websockets async def client(): uri = "ws://localhost:8765" async with websockets.connect(uri) as websocket: # Close the connection when receiving SIGTERM. loop = asyncio.get_running_loop() loop.add_signal_handler( signal.SIGTERM, loop.create_task, websocket.close) # Process messages received on the connection. async for message in websocket: ... asyncio.run(client())
#!/usr/bin/env python import asyncio import signal import websockets async def client(): uri = "ws://localhost:8765" async with websockets.connect(uri) as websocket: # Close the connection when receiving SIGTERM. loop = asyncio.get_running_loop() loop.add_signal_handler( signal.SIGTERM, loop.create_task, websocket.close()) # Process messages received on the connection. async for message in websocket: ... asyncio.run(client()) Fix example of shutting down a client. Fix #1261.#!/usr/bin/env python import asyncio import signal import websockets async def client(): uri = "ws://localhost:8765" async with websockets.connect(uri) as websocket: # Close the connection when receiving SIGTERM. loop = asyncio.get_running_loop() loop.add_signal_handler( signal.SIGTERM, loop.create_task, websocket.close) # Process messages received on the connection. async for message in websocket: ... asyncio.run(client())
<commit_before>#!/usr/bin/env python import asyncio import signal import websockets async def client(): uri = "ws://localhost:8765" async with websockets.connect(uri) as websocket: # Close the connection when receiving SIGTERM. loop = asyncio.get_running_loop() loop.add_signal_handler( signal.SIGTERM, loop.create_task, websocket.close()) # Process messages received on the connection. async for message in websocket: ... asyncio.run(client()) <commit_msg>Fix example of shutting down a client. Fix #1261.<commit_after>#!/usr/bin/env python import asyncio import signal import websockets async def client(): uri = "ws://localhost:8765" async with websockets.connect(uri) as websocket: # Close the connection when receiving SIGTERM. loop = asyncio.get_running_loop() loop.add_signal_handler( signal.SIGTERM, loop.create_task, websocket.close) # Process messages received on the connection. async for message in websocket: ... asyncio.run(client())
72068701db46dc3d66cde295187b7d167cbfd880
gather/account/api.py
gather/account/api.py
# -*- coding:utf-8 -*- from flask import g, jsonify from gather.account.models import Account from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager __all__ = ["bp"] def patch_single_preprocessor(instance_id=None, data=None, **kw): """Accepts two arguments, `instance_id`, the primary key of the instance of the model to patch, and `data`, the dictionary of fields to change on the instance. """ return g.token_user.id == instance_id # 需要一点小 hack .. bp = api_manager.create_api_blueprint( Account, methods=["GET", "PUT"], preprocessors=dict(PUT_SINGLE=[need_auth, patch_single_preprocessor],), exclude_columns=EXCLUDE_COLUMNS ) @bp.route("/account/authorize/", methods=["POST"]) def _account_authorize(): from .forms import LoginForm form = LoginForm() if not form.validate_on_submit(): return jsonify( code=400, msg="Wrong username/password" ) user = form.user if not user.api_token: user.generate_api_token() return jsonify( code=200, token=user.api_token )
# -*- coding:utf-8 -*- from flask import g, jsonify, request from gather.account.models import Account from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager __all__ = ["bp"] def patch_single_preprocessor(instance_id=None, data=None, **kw): """Accepts two arguments, `instance_id`, the primary key of the instance of the model to patch, and `data`, the dictionary of fields to change on the instance. """ return g.token_user.id == instance_id # 需要一点小 hack .. bp = api_manager.create_api_blueprint( Account, methods=["GET", "PUT"], preprocessors=dict(PUT_SINGLE=[need_auth, patch_single_preprocessor],), exclude_columns=EXCLUDE_COLUMNS ) @bp.route("/account/authorize/", methods=["POST"]) def _account_authorize(): from .forms import LoginForm form = LoginForm() if not form.validate_on_submit(): return jsonify( code=400, msg="Wrong username/password" ) user = form.user if not user.api_token: user.generate_api_token() return jsonify( code=200, token=user.api_token ) @bp.route("/account/change_password/", methods=["POST"]) def _change_password(): new_password = request.form["password"] user = Account.query.filter_by(username="Madimo").first_or_404() user.change_password(new_password) user.save return jsonify( code=200, user=user )
Add API to change password
Add API to change password
Python
mit
whtsky/Gather,whtsky/Gather
# -*- coding:utf-8 -*- from flask import g, jsonify from gather.account.models import Account from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager __all__ = ["bp"] def patch_single_preprocessor(instance_id=None, data=None, **kw): """Accepts two arguments, `instance_id`, the primary key of the instance of the model to patch, and `data`, the dictionary of fields to change on the instance. """ return g.token_user.id == instance_id # 需要一点小 hack .. bp = api_manager.create_api_blueprint( Account, methods=["GET", "PUT"], preprocessors=dict(PUT_SINGLE=[need_auth, patch_single_preprocessor],), exclude_columns=EXCLUDE_COLUMNS ) @bp.route("/account/authorize/", methods=["POST"]) def _account_authorize(): from .forms import LoginForm form = LoginForm() if not form.validate_on_submit(): return jsonify( code=400, msg="Wrong username/password" ) user = form.user if not user.api_token: user.generate_api_token() return jsonify( code=200, token=user.api_token ) Add API to change password
# -*- coding:utf-8 -*- from flask import g, jsonify, request from gather.account.models import Account from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager __all__ = ["bp"] def patch_single_preprocessor(instance_id=None, data=None, **kw): """Accepts two arguments, `instance_id`, the primary key of the instance of the model to patch, and `data`, the dictionary of fields to change on the instance. """ return g.token_user.id == instance_id # 需要一点小 hack .. bp = api_manager.create_api_blueprint( Account, methods=["GET", "PUT"], preprocessors=dict(PUT_SINGLE=[need_auth, patch_single_preprocessor],), exclude_columns=EXCLUDE_COLUMNS ) @bp.route("/account/authorize/", methods=["POST"]) def _account_authorize(): from .forms import LoginForm form = LoginForm() if not form.validate_on_submit(): return jsonify( code=400, msg="Wrong username/password" ) user = form.user if not user.api_token: user.generate_api_token() return jsonify( code=200, token=user.api_token ) @bp.route("/account/change_password/", methods=["POST"]) def _change_password(): new_password = request.form["password"] user = Account.query.filter_by(username="Madimo").first_or_404() user.change_password(new_password) user.save return jsonify( code=200, user=user )
<commit_before># -*- coding:utf-8 -*- from flask import g, jsonify from gather.account.models import Account from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager __all__ = ["bp"] def patch_single_preprocessor(instance_id=None, data=None, **kw): """Accepts two arguments, `instance_id`, the primary key of the instance of the model to patch, and `data`, the dictionary of fields to change on the instance. """ return g.token_user.id == instance_id # 需要一点小 hack .. bp = api_manager.create_api_blueprint( Account, methods=["GET", "PUT"], preprocessors=dict(PUT_SINGLE=[need_auth, patch_single_preprocessor],), exclude_columns=EXCLUDE_COLUMNS ) @bp.route("/account/authorize/", methods=["POST"]) def _account_authorize(): from .forms import LoginForm form = LoginForm() if not form.validate_on_submit(): return jsonify( code=400, msg="Wrong username/password" ) user = form.user if not user.api_token: user.generate_api_token() return jsonify( code=200, token=user.api_token ) <commit_msg>Add API to change password<commit_after>
# -*- coding:utf-8 -*- from flask import g, jsonify, request from gather.account.models import Account from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager __all__ = ["bp"] def patch_single_preprocessor(instance_id=None, data=None, **kw): """Accepts two arguments, `instance_id`, the primary key of the instance of the model to patch, and `data`, the dictionary of fields to change on the instance. """ return g.token_user.id == instance_id # 需要一点小 hack .. bp = api_manager.create_api_blueprint( Account, methods=["GET", "PUT"], preprocessors=dict(PUT_SINGLE=[need_auth, patch_single_preprocessor],), exclude_columns=EXCLUDE_COLUMNS ) @bp.route("/account/authorize/", methods=["POST"]) def _account_authorize(): from .forms import LoginForm form = LoginForm() if not form.validate_on_submit(): return jsonify( code=400, msg="Wrong username/password" ) user = form.user if not user.api_token: user.generate_api_token() return jsonify( code=200, token=user.api_token ) @bp.route("/account/change_password/", methods=["POST"]) def _change_password(): new_password = request.form["password"] user = Account.query.filter_by(username="Madimo").first_or_404() user.change_password(new_password) user.save return jsonify( code=200, user=user )
# -*- coding:utf-8 -*- from flask import g, jsonify from gather.account.models import Account from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager __all__ = ["bp"] def patch_single_preprocessor(instance_id=None, data=None, **kw): """Accepts two arguments, `instance_id`, the primary key of the instance of the model to patch, and `data`, the dictionary of fields to change on the instance. """ return g.token_user.id == instance_id # 需要一点小 hack .. bp = api_manager.create_api_blueprint( Account, methods=["GET", "PUT"], preprocessors=dict(PUT_SINGLE=[need_auth, patch_single_preprocessor],), exclude_columns=EXCLUDE_COLUMNS ) @bp.route("/account/authorize/", methods=["POST"]) def _account_authorize(): from .forms import LoginForm form = LoginForm() if not form.validate_on_submit(): return jsonify( code=400, msg="Wrong username/password" ) user = form.user if not user.api_token: user.generate_api_token() return jsonify( code=200, token=user.api_token ) Add API to change password# -*- coding:utf-8 -*- from flask import g, jsonify, request from gather.account.models import Account from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager __all__ = ["bp"] def patch_single_preprocessor(instance_id=None, data=None, **kw): """Accepts two arguments, `instance_id`, the primary key of the instance of the model to patch, and `data`, the dictionary of fields to change on the instance. """ return g.token_user.id == instance_id # 需要一点小 hack .. bp = api_manager.create_api_blueprint( Account, methods=["GET", "PUT"], preprocessors=dict(PUT_SINGLE=[need_auth, patch_single_preprocessor],), exclude_columns=EXCLUDE_COLUMNS ) @bp.route("/account/authorize/", methods=["POST"]) def _account_authorize(): from .forms import LoginForm form = LoginForm() if not form.validate_on_submit(): return jsonify( code=400, msg="Wrong username/password" ) user = form.user if not user.api_token: user.generate_api_token() return jsonify( code=200, token=user.api_token ) @bp.route("/account/change_password/", methods=["POST"]) def _change_password(): new_password = request.form["password"] user = Account.query.filter_by(username="Madimo").first_or_404() user.change_password(new_password) user.save return jsonify( code=200, user=user )
<commit_before># -*- coding:utf-8 -*- from flask import g, jsonify from gather.account.models import Account from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager __all__ = ["bp"] def patch_single_preprocessor(instance_id=None, data=None, **kw): """Accepts two arguments, `instance_id`, the primary key of the instance of the model to patch, and `data`, the dictionary of fields to change on the instance. """ return g.token_user.id == instance_id # 需要一点小 hack .. bp = api_manager.create_api_blueprint( Account, methods=["GET", "PUT"], preprocessors=dict(PUT_SINGLE=[need_auth, patch_single_preprocessor],), exclude_columns=EXCLUDE_COLUMNS ) @bp.route("/account/authorize/", methods=["POST"]) def _account_authorize(): from .forms import LoginForm form = LoginForm() if not form.validate_on_submit(): return jsonify( code=400, msg="Wrong username/password" ) user = form.user if not user.api_token: user.generate_api_token() return jsonify( code=200, token=user.api_token ) <commit_msg>Add API to change password<commit_after># -*- coding:utf-8 -*- from flask import g, jsonify, request from gather.account.models import Account from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager __all__ = ["bp"] def patch_single_preprocessor(instance_id=None, data=None, **kw): """Accepts two arguments, `instance_id`, the primary key of the instance of the model to patch, and `data`, the dictionary of fields to change on the instance. """ return g.token_user.id == instance_id # 需要一点小 hack .. bp = api_manager.create_api_blueprint( Account, methods=["GET", "PUT"], preprocessors=dict(PUT_SINGLE=[need_auth, patch_single_preprocessor],), exclude_columns=EXCLUDE_COLUMNS ) @bp.route("/account/authorize/", methods=["POST"]) def _account_authorize(): from .forms import LoginForm form = LoginForm() if not form.validate_on_submit(): return jsonify( code=400, msg="Wrong username/password" ) user = form.user if not user.api_token: user.generate_api_token() return jsonify( code=200, token=user.api_token ) @bp.route("/account/change_password/", methods=["POST"]) def _change_password(): new_password = request.form["password"] user = Account.query.filter_by(username="Madimo").first_or_404() user.change_password(new_password) user.save return jsonify( code=200, user=user )
5b4049b3aa27a8a2e02c768eb411b35f4518821e
predict_imagenet.py
predict_imagenet.py
from __future__ import print_function from __future__ import absolute_import from keras.applications.imagenet_utils import decode_predictions from keras.preprocessing import image import numpy as np from mobilenets import MobileNets def preprocess_input(x): x /= 255. x -= 0.5 x *= 2. return x if __name__ == '__main__': size = 224 alpha = 1.0 model = MobileNets(input_shape=(size, size, 3), alpha=alpha, weights='imagenet') model.summary() img_path = 'elephant.jpg' img = image.load_img(img_path, target_size=(size, size)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) # decode predictions does not like the 1001th class (UNKNOWN class), # thats why we remove the last prediction and feed it to decode predictions preds = preds[:, 0:1000] print('Predicted:', decode_predictions(preds))
from __future__ import print_function from __future__ import absolute_import from keras.applications.imagenet_utils import decode_predictions from keras.preprocessing import image import numpy as np from mobilenets import MobileNets def preprocess_input(x): x /= 255. x -= 0.5 x *= 2. return x if __name__ == '__main__': size = 224 alpha = 1.0 model = MobileNets(input_shape=(size, size, 3), alpha=alpha, weights='imagenet') model.summary() img_path = 'elephant.jpg' img = image.load_img(img_path, target_size=(size, size)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) print('Predicted:', decode_predictions(preds))
Remove extra support for 1000 classes as no longer needed
Remove extra support for 1000 classes as no longer needed
Python
apache-2.0
titu1994/MobileNetworks
from __future__ import print_function from __future__ import absolute_import from keras.applications.imagenet_utils import decode_predictions from keras.preprocessing import image import numpy as np from mobilenets import MobileNets def preprocess_input(x): x /= 255. x -= 0.5 x *= 2. return x if __name__ == '__main__': size = 224 alpha = 1.0 model = MobileNets(input_shape=(size, size, 3), alpha=alpha, weights='imagenet') model.summary() img_path = 'elephant.jpg' img = image.load_img(img_path, target_size=(size, size)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) # decode predictions does not like the 1001th class (UNKNOWN class), # thats why we remove the last prediction and feed it to decode predictions preds = preds[:, 0:1000] print('Predicted:', decode_predictions(preds)) Remove extra support for 1000 classes as no longer needed
from __future__ import print_function from __future__ import absolute_import from keras.applications.imagenet_utils import decode_predictions from keras.preprocessing import image import numpy as np from mobilenets import MobileNets def preprocess_input(x): x /= 255. x -= 0.5 x *= 2. return x if __name__ == '__main__': size = 224 alpha = 1.0 model = MobileNets(input_shape=(size, size, 3), alpha=alpha, weights='imagenet') model.summary() img_path = 'elephant.jpg' img = image.load_img(img_path, target_size=(size, size)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) print('Predicted:', decode_predictions(preds))
<commit_before>from __future__ import print_function from __future__ import absolute_import from keras.applications.imagenet_utils import decode_predictions from keras.preprocessing import image import numpy as np from mobilenets import MobileNets def preprocess_input(x): x /= 255. x -= 0.5 x *= 2. return x if __name__ == '__main__': size = 224 alpha = 1.0 model = MobileNets(input_shape=(size, size, 3), alpha=alpha, weights='imagenet') model.summary() img_path = 'elephant.jpg' img = image.load_img(img_path, target_size=(size, size)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) # decode predictions does not like the 1001th class (UNKNOWN class), # thats why we remove the last prediction and feed it to decode predictions preds = preds[:, 0:1000] print('Predicted:', decode_predictions(preds)) <commit_msg>Remove extra support for 1000 classes as no longer needed<commit_after>
from __future__ import print_function from __future__ import absolute_import from keras.applications.imagenet_utils import decode_predictions from keras.preprocessing import image import numpy as np from mobilenets import MobileNets def preprocess_input(x): x /= 255. x -= 0.5 x *= 2. return x if __name__ == '__main__': size = 224 alpha = 1.0 model = MobileNets(input_shape=(size, size, 3), alpha=alpha, weights='imagenet') model.summary() img_path = 'elephant.jpg' img = image.load_img(img_path, target_size=(size, size)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) print('Predicted:', decode_predictions(preds))
from __future__ import print_function from __future__ import absolute_import from keras.applications.imagenet_utils import decode_predictions from keras.preprocessing import image import numpy as np from mobilenets import MobileNets def preprocess_input(x): x /= 255. x -= 0.5 x *= 2. return x if __name__ == '__main__': size = 224 alpha = 1.0 model = MobileNets(input_shape=(size, size, 3), alpha=alpha, weights='imagenet') model.summary() img_path = 'elephant.jpg' img = image.load_img(img_path, target_size=(size, size)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) # decode predictions does not like the 1001th class (UNKNOWN class), # thats why we remove the last prediction and feed it to decode predictions preds = preds[:, 0:1000] print('Predicted:', decode_predictions(preds)) Remove extra support for 1000 classes as no longer neededfrom __future__ import print_function from __future__ import absolute_import from keras.applications.imagenet_utils import decode_predictions from keras.preprocessing import image import numpy as np from mobilenets import MobileNets def preprocess_input(x): x /= 255. x -= 0.5 x *= 2. return x if __name__ == '__main__': size = 224 alpha = 1.0 model = MobileNets(input_shape=(size, size, 3), alpha=alpha, weights='imagenet') model.summary() img_path = 'elephant.jpg' img = image.load_img(img_path, target_size=(size, size)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) print('Predicted:', decode_predictions(preds))
<commit_before>from __future__ import print_function from __future__ import absolute_import from keras.applications.imagenet_utils import decode_predictions from keras.preprocessing import image import numpy as np from mobilenets import MobileNets def preprocess_input(x): x /= 255. x -= 0.5 x *= 2. return x if __name__ == '__main__': size = 224 alpha = 1.0 model = MobileNets(input_shape=(size, size, 3), alpha=alpha, weights='imagenet') model.summary() img_path = 'elephant.jpg' img = image.load_img(img_path, target_size=(size, size)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) # decode predictions does not like the 1001th class (UNKNOWN class), # thats why we remove the last prediction and feed it to decode predictions preds = preds[:, 0:1000] print('Predicted:', decode_predictions(preds)) <commit_msg>Remove extra support for 1000 classes as no longer needed<commit_after>from __future__ import print_function from __future__ import absolute_import from keras.applications.imagenet_utils import decode_predictions from keras.preprocessing import image import numpy as np from mobilenets import MobileNets def preprocess_input(x): x /= 255. x -= 0.5 x *= 2. return x if __name__ == '__main__': size = 224 alpha = 1.0 model = MobileNets(input_shape=(size, size, 3), alpha=alpha, weights='imagenet') model.summary() img_path = 'elephant.jpg' img = image.load_img(img_path, target_size=(size, size)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) print('Predicted:', decode_predictions(preds))
f4837fd60ce09b69d334fcad1403b721723d3504
tests/test_conf.py
tests/test_conf.py
import sys from unittest import mock import pytest from bottery.conf import Settings @pytest.fixture def mocked_settings(): settings = mock.MagicMock() sys.modules['settings'] = settings yield settings del sys.modules['settings'] @pytest.mark.skip def test_global_settings(): settings = Settings() assert settings.PLATFORMS == {} assert settings.TEMPLATES == [] @pytest.mark.skip def test_settings_from_module(mocked_settings): mocked_settings.PLATFORM = 'matrix' settings = Settings.from_object('settings') assert settings.PLATFORM == 'matrix' assert settings.PLATFORM == 'matrix'
from unittest import mock import pytest from bottery.conf import Settings @pytest.fixture def mocked_settings(): settings = mock.MagicMock() sys.modules['settings'] = settings yield settings del sys.modules['settings'] @pytest.mark.skip def test_global_settings(): settings = Settings() assert settings.PLATFORMS == {} assert settings.TEMPLATES == [] @pytest.mark.skip def test_settings_from_module(mocked_settings): mocked_settings.PLATFORM = 'matrix' settings = Settings.from_object('settings') assert settings.PLATFORM == 'matrix' assert settings.PLATFORM == 'matrix'
Remove unused sys import from conf tests
Remove unused sys import from conf tests
Python
mit
rougeth/bottery
import sys from unittest import mock import pytest from bottery.conf import Settings @pytest.fixture def mocked_settings(): settings = mock.MagicMock() sys.modules['settings'] = settings yield settings del sys.modules['settings'] @pytest.mark.skip def test_global_settings(): settings = Settings() assert settings.PLATFORMS == {} assert settings.TEMPLATES == [] @pytest.mark.skip def test_settings_from_module(mocked_settings): mocked_settings.PLATFORM = 'matrix' settings = Settings.from_object('settings') assert settings.PLATFORM == 'matrix' assert settings.PLATFORM == 'matrix' Remove unused sys import from conf tests
from unittest import mock import pytest from bottery.conf import Settings @pytest.fixture def mocked_settings(): settings = mock.MagicMock() sys.modules['settings'] = settings yield settings del sys.modules['settings'] @pytest.mark.skip def test_global_settings(): settings = Settings() assert settings.PLATFORMS == {} assert settings.TEMPLATES == [] @pytest.mark.skip def test_settings_from_module(mocked_settings): mocked_settings.PLATFORM = 'matrix' settings = Settings.from_object('settings') assert settings.PLATFORM == 'matrix' assert settings.PLATFORM == 'matrix'
<commit_before>import sys from unittest import mock import pytest from bottery.conf import Settings @pytest.fixture def mocked_settings(): settings = mock.MagicMock() sys.modules['settings'] = settings yield settings del sys.modules['settings'] @pytest.mark.skip def test_global_settings(): settings = Settings() assert settings.PLATFORMS == {} assert settings.TEMPLATES == [] @pytest.mark.skip def test_settings_from_module(mocked_settings): mocked_settings.PLATFORM = 'matrix' settings = Settings.from_object('settings') assert settings.PLATFORM == 'matrix' assert settings.PLATFORM == 'matrix' <commit_msg>Remove unused sys import from conf tests<commit_after>
from unittest import mock import pytest from bottery.conf import Settings @pytest.fixture def mocked_settings(): settings = mock.MagicMock() sys.modules['settings'] = settings yield settings del sys.modules['settings'] @pytest.mark.skip def test_global_settings(): settings = Settings() assert settings.PLATFORMS == {} assert settings.TEMPLATES == [] @pytest.mark.skip def test_settings_from_module(mocked_settings): mocked_settings.PLATFORM = 'matrix' settings = Settings.from_object('settings') assert settings.PLATFORM == 'matrix' assert settings.PLATFORM == 'matrix'
import sys from unittest import mock import pytest from bottery.conf import Settings @pytest.fixture def mocked_settings(): settings = mock.MagicMock() sys.modules['settings'] = settings yield settings del sys.modules['settings'] @pytest.mark.skip def test_global_settings(): settings = Settings() assert settings.PLATFORMS == {} assert settings.TEMPLATES == [] @pytest.mark.skip def test_settings_from_module(mocked_settings): mocked_settings.PLATFORM = 'matrix' settings = Settings.from_object('settings') assert settings.PLATFORM == 'matrix' assert settings.PLATFORM == 'matrix' Remove unused sys import from conf testsfrom unittest import mock import pytest from bottery.conf import Settings @pytest.fixture def mocked_settings(): settings = mock.MagicMock() sys.modules['settings'] = settings yield settings del sys.modules['settings'] @pytest.mark.skip def test_global_settings(): settings = Settings() assert settings.PLATFORMS == {} assert settings.TEMPLATES == [] @pytest.mark.skip def test_settings_from_module(mocked_settings): mocked_settings.PLATFORM = 'matrix' settings = Settings.from_object('settings') assert settings.PLATFORM == 'matrix' assert settings.PLATFORM == 'matrix'
<commit_before>import sys from unittest import mock import pytest from bottery.conf import Settings @pytest.fixture def mocked_settings(): settings = mock.MagicMock() sys.modules['settings'] = settings yield settings del sys.modules['settings'] @pytest.mark.skip def test_global_settings(): settings = Settings() assert settings.PLATFORMS == {} assert settings.TEMPLATES == [] @pytest.mark.skip def test_settings_from_module(mocked_settings): mocked_settings.PLATFORM = 'matrix' settings = Settings.from_object('settings') assert settings.PLATFORM == 'matrix' assert settings.PLATFORM == 'matrix' <commit_msg>Remove unused sys import from conf tests<commit_after>from unittest import mock import pytest from bottery.conf import Settings @pytest.fixture def mocked_settings(): settings = mock.MagicMock() sys.modules['settings'] = settings yield settings del sys.modules['settings'] @pytest.mark.skip def test_global_settings(): settings = Settings() assert settings.PLATFORMS == {} assert settings.TEMPLATES == [] @pytest.mark.skip def test_settings_from_module(mocked_settings): mocked_settings.PLATFORM = 'matrix' settings = Settings.from_object('settings') assert settings.PLATFORM == 'matrix' assert settings.PLATFORM == 'matrix'
b60e76f6d6c5363ed4d07b43338911b3cdb8ca39
ofp_app/demo/conntest.py
ofp_app/demo/conntest.py
from ofp_app import ofp_app, ofp_run import asyncio app = ofp_app('conntest') @app.event('start') async def start(_): while True: await asyncio.sleep(1) # Obtain a list of connections. conns = await app.rpc_call('OFP.LIST_CONNECTIONS', conn_id=0) for conn in conns.stats: if conn.datapath_id: app.logger.info('close %d %s', conn.conn_id, conn.datapath_id) result = await app.rpc_call('OFP.CLOSE', datapath_id=conn.datapath_id) assert result.count == 1 if __name__ == '__main__': ofp_run()
from ofp_app import ofp_app, ofp_run import asyncio app = ofp_app('conntest', kill_on_exception=True) @app.event('start') async def start(_): while True: await asyncio.sleep(1) # Obtain a list of connections. conns = await app.rpc_call('OFP.LIST_CONNECTIONS', conn_id=0) for conn in conns.stats: if conn.datapath_id: app.logger.info('close %d %s', conn.conn_id, conn.datapath_id) result = await app.rpc_call('OFP.CLOSE', datapath_id=conn.datapath_id) assert result.count == 1 if __name__ == '__main__': ofp_run()
Terminate app if handler throws exception.
Terminate app if handler throws exception.
Python
mit
byllyfish/pylibofp,byllyfish/pylibofp
from ofp_app import ofp_app, ofp_run import asyncio app = ofp_app('conntest') @app.event('start') async def start(_): while True: await asyncio.sleep(1) # Obtain a list of connections. conns = await app.rpc_call('OFP.LIST_CONNECTIONS', conn_id=0) for conn in conns.stats: if conn.datapath_id: app.logger.info('close %d %s', conn.conn_id, conn.datapath_id) result = await app.rpc_call('OFP.CLOSE', datapath_id=conn.datapath_id) assert result.count == 1 if __name__ == '__main__': ofp_run() Terminate app if handler throws exception.
from ofp_app import ofp_app, ofp_run import asyncio app = ofp_app('conntest', kill_on_exception=True) @app.event('start') async def start(_): while True: await asyncio.sleep(1) # Obtain a list of connections. conns = await app.rpc_call('OFP.LIST_CONNECTIONS', conn_id=0) for conn in conns.stats: if conn.datapath_id: app.logger.info('close %d %s', conn.conn_id, conn.datapath_id) result = await app.rpc_call('OFP.CLOSE', datapath_id=conn.datapath_id) assert result.count == 1 if __name__ == '__main__': ofp_run()
<commit_before>from ofp_app import ofp_app, ofp_run import asyncio app = ofp_app('conntest') @app.event('start') async def start(_): while True: await asyncio.sleep(1) # Obtain a list of connections. conns = await app.rpc_call('OFP.LIST_CONNECTIONS', conn_id=0) for conn in conns.stats: if conn.datapath_id: app.logger.info('close %d %s', conn.conn_id, conn.datapath_id) result = await app.rpc_call('OFP.CLOSE', datapath_id=conn.datapath_id) assert result.count == 1 if __name__ == '__main__': ofp_run() <commit_msg>Terminate app if handler throws exception.<commit_after>
from ofp_app import ofp_app, ofp_run import asyncio app = ofp_app('conntest', kill_on_exception=True) @app.event('start') async def start(_): while True: await asyncio.sleep(1) # Obtain a list of connections. conns = await app.rpc_call('OFP.LIST_CONNECTIONS', conn_id=0) for conn in conns.stats: if conn.datapath_id: app.logger.info('close %d %s', conn.conn_id, conn.datapath_id) result = await app.rpc_call('OFP.CLOSE', datapath_id=conn.datapath_id) assert result.count == 1 if __name__ == '__main__': ofp_run()
from ofp_app import ofp_app, ofp_run import asyncio app = ofp_app('conntest') @app.event('start') async def start(_): while True: await asyncio.sleep(1) # Obtain a list of connections. conns = await app.rpc_call('OFP.LIST_CONNECTIONS', conn_id=0) for conn in conns.stats: if conn.datapath_id: app.logger.info('close %d %s', conn.conn_id, conn.datapath_id) result = await app.rpc_call('OFP.CLOSE', datapath_id=conn.datapath_id) assert result.count == 1 if __name__ == '__main__': ofp_run() Terminate app if handler throws exception.from ofp_app import ofp_app, ofp_run import asyncio app = ofp_app('conntest', kill_on_exception=True) @app.event('start') async def start(_): while True: await asyncio.sleep(1) # Obtain a list of connections. conns = await app.rpc_call('OFP.LIST_CONNECTIONS', conn_id=0) for conn in conns.stats: if conn.datapath_id: app.logger.info('close %d %s', conn.conn_id, conn.datapath_id) result = await app.rpc_call('OFP.CLOSE', datapath_id=conn.datapath_id) assert result.count == 1 if __name__ == '__main__': ofp_run()
<commit_before>from ofp_app import ofp_app, ofp_run import asyncio app = ofp_app('conntest') @app.event('start') async def start(_): while True: await asyncio.sleep(1) # Obtain a list of connections. conns = await app.rpc_call('OFP.LIST_CONNECTIONS', conn_id=0) for conn in conns.stats: if conn.datapath_id: app.logger.info('close %d %s', conn.conn_id, conn.datapath_id) result = await app.rpc_call('OFP.CLOSE', datapath_id=conn.datapath_id) assert result.count == 1 if __name__ == '__main__': ofp_run() <commit_msg>Terminate app if handler throws exception.<commit_after>from ofp_app import ofp_app, ofp_run import asyncio app = ofp_app('conntest', kill_on_exception=True) @app.event('start') async def start(_): while True: await asyncio.sleep(1) # Obtain a list of connections. conns = await app.rpc_call('OFP.LIST_CONNECTIONS', conn_id=0) for conn in conns.stats: if conn.datapath_id: app.logger.info('close %d %s', conn.conn_id, conn.datapath_id) result = await app.rpc_call('OFP.CLOSE', datapath_id=conn.datapath_id) assert result.count == 1 if __name__ == '__main__': ofp_run()
89b14bd0add6a56d9128f2ce3fa4ca710f64d5d7
opal/tests/test_utils.py
opal/tests/test_utils.py
""" Unittests for opal.utils """ from django.test import TestCase from django.db.models import ForeignKey, CharField from opal import utils class StringportTestCase(TestCase): def test_import(self): import collections self.assertEqual(collections, utils.stringport('collections')) class ItersubclassesTestCase(TestCase): def test_tree_structure(self): class A(object): pass class B(A): pass class C(B, utils.AbstractBase): pass class D(C): pass results = {i for i in utils._itersubclasses(A)} self.assertEqual(results, set([B, D])) class FindTemplateTestCase(TestCase): def test_find_template_first_exists(self): self.assertEqual('base.html', utils.find_template(['base.html', 'baser.html', 'basest.html'])) def test_find_template_one_exists(self): self.assertEqual('base.html', utils.find_template(['baser.html', 'base.html', 'basest.html'])) def test_find_template_none_exists(self): self.assertEqual(None, utils.find_template(['baser.html', 'basest.html']))
""" Unittests for opal.utils """ from django.test import TestCase from django.db.models import ForeignKey, CharField from opal import utils class StringportTestCase(TestCase): def test_import(self): import collections self.assertEqual(collections, utils.stringport('collections')) def test_import_no_period(self): with self.assertRaises(ImportError): utils.stringport('wotcha') def test_import_perioded_thing(self): self.assertEqual(TestCase, utils.stringport('django.test.TestCase')) def test_empty_name_is_valueerror(self): with self.assertRaises(ValueError): utils.stringport('') class ItersubclassesTestCase(TestCase): def test_tree_structure(self): class A(object): pass class B(A): pass class C(B, utils.AbstractBase): pass class D(C): pass results = {i for i in utils._itersubclasses(A)} self.assertEqual(results, set([B, D])) class FindTemplateTestCase(TestCase): def test_find_template_first_exists(self): self.assertEqual('base.html', utils.find_template(['base.html', 'baser.html', 'basest.html'])) def test_find_template_one_exists(self): self.assertEqual('base.html', utils.find_template(['baser.html', 'base.html', 'basest.html'])) def test_find_template_none_exists(self): self.assertEqual(None, utils.find_template(['baser.html', 'basest.html']))
Add some tests for stringport
Add some tests for stringport
Python
agpl-3.0
khchine5/opal,khchine5/opal,khchine5/opal
""" Unittests for opal.utils """ from django.test import TestCase from django.db.models import ForeignKey, CharField from opal import utils class StringportTestCase(TestCase): def test_import(self): import collections self.assertEqual(collections, utils.stringport('collections')) class ItersubclassesTestCase(TestCase): def test_tree_structure(self): class A(object): pass class B(A): pass class C(B, utils.AbstractBase): pass class D(C): pass results = {i for i in utils._itersubclasses(A)} self.assertEqual(results, set([B, D])) class FindTemplateTestCase(TestCase): def test_find_template_first_exists(self): self.assertEqual('base.html', utils.find_template(['base.html', 'baser.html', 'basest.html'])) def test_find_template_one_exists(self): self.assertEqual('base.html', utils.find_template(['baser.html', 'base.html', 'basest.html'])) def test_find_template_none_exists(self): self.assertEqual(None, utils.find_template(['baser.html', 'basest.html'])) Add some tests for stringport
""" Unittests for opal.utils """ from django.test import TestCase from django.db.models import ForeignKey, CharField from opal import utils class StringportTestCase(TestCase): def test_import(self): import collections self.assertEqual(collections, utils.stringport('collections')) def test_import_no_period(self): with self.assertRaises(ImportError): utils.stringport('wotcha') def test_import_perioded_thing(self): self.assertEqual(TestCase, utils.stringport('django.test.TestCase')) def test_empty_name_is_valueerror(self): with self.assertRaises(ValueError): utils.stringport('') class ItersubclassesTestCase(TestCase): def test_tree_structure(self): class A(object): pass class B(A): pass class C(B, utils.AbstractBase): pass class D(C): pass results = {i for i in utils._itersubclasses(A)} self.assertEqual(results, set([B, D])) class FindTemplateTestCase(TestCase): def test_find_template_first_exists(self): self.assertEqual('base.html', utils.find_template(['base.html', 'baser.html', 'basest.html'])) def test_find_template_one_exists(self): self.assertEqual('base.html', utils.find_template(['baser.html', 'base.html', 'basest.html'])) def test_find_template_none_exists(self): self.assertEqual(None, utils.find_template(['baser.html', 'basest.html']))
<commit_before>""" Unittests for opal.utils """ from django.test import TestCase from django.db.models import ForeignKey, CharField from opal import utils class StringportTestCase(TestCase): def test_import(self): import collections self.assertEqual(collections, utils.stringport('collections')) class ItersubclassesTestCase(TestCase): def test_tree_structure(self): class A(object): pass class B(A): pass class C(B, utils.AbstractBase): pass class D(C): pass results = {i for i in utils._itersubclasses(A)} self.assertEqual(results, set([B, D])) class FindTemplateTestCase(TestCase): def test_find_template_first_exists(self): self.assertEqual('base.html', utils.find_template(['base.html', 'baser.html', 'basest.html'])) def test_find_template_one_exists(self): self.assertEqual('base.html', utils.find_template(['baser.html', 'base.html', 'basest.html'])) def test_find_template_none_exists(self): self.assertEqual(None, utils.find_template(['baser.html', 'basest.html'])) <commit_msg>Add some tests for stringport<commit_after>
""" Unittests for opal.utils """ from django.test import TestCase from django.db.models import ForeignKey, CharField from opal import utils class StringportTestCase(TestCase): def test_import(self): import collections self.assertEqual(collections, utils.stringport('collections')) def test_import_no_period(self): with self.assertRaises(ImportError): utils.stringport('wotcha') def test_import_perioded_thing(self): self.assertEqual(TestCase, utils.stringport('django.test.TestCase')) def test_empty_name_is_valueerror(self): with self.assertRaises(ValueError): utils.stringport('') class ItersubclassesTestCase(TestCase): def test_tree_structure(self): class A(object): pass class B(A): pass class C(B, utils.AbstractBase): pass class D(C): pass results = {i for i in utils._itersubclasses(A)} self.assertEqual(results, set([B, D])) class FindTemplateTestCase(TestCase): def test_find_template_first_exists(self): self.assertEqual('base.html', utils.find_template(['base.html', 'baser.html', 'basest.html'])) def test_find_template_one_exists(self): self.assertEqual('base.html', utils.find_template(['baser.html', 'base.html', 'basest.html'])) def test_find_template_none_exists(self): self.assertEqual(None, utils.find_template(['baser.html', 'basest.html']))
""" Unittests for opal.utils """ from django.test import TestCase from django.db.models import ForeignKey, CharField from opal import utils class StringportTestCase(TestCase): def test_import(self): import collections self.assertEqual(collections, utils.stringport('collections')) class ItersubclassesTestCase(TestCase): def test_tree_structure(self): class A(object): pass class B(A): pass class C(B, utils.AbstractBase): pass class D(C): pass results = {i for i in utils._itersubclasses(A)} self.assertEqual(results, set([B, D])) class FindTemplateTestCase(TestCase): def test_find_template_first_exists(self): self.assertEqual('base.html', utils.find_template(['base.html', 'baser.html', 'basest.html'])) def test_find_template_one_exists(self): self.assertEqual('base.html', utils.find_template(['baser.html', 'base.html', 'basest.html'])) def test_find_template_none_exists(self): self.assertEqual(None, utils.find_template(['baser.html', 'basest.html'])) Add some tests for stringport""" Unittests for opal.utils """ from django.test import TestCase from django.db.models import ForeignKey, CharField from opal import utils class StringportTestCase(TestCase): def test_import(self): import collections self.assertEqual(collections, utils.stringport('collections')) def test_import_no_period(self): with self.assertRaises(ImportError): utils.stringport('wotcha') def test_import_perioded_thing(self): self.assertEqual(TestCase, utils.stringport('django.test.TestCase')) def test_empty_name_is_valueerror(self): with self.assertRaises(ValueError): utils.stringport('') class ItersubclassesTestCase(TestCase): def test_tree_structure(self): class A(object): pass class B(A): pass class C(B, utils.AbstractBase): pass class D(C): pass results = {i for i in utils._itersubclasses(A)} self.assertEqual(results, set([B, D])) class FindTemplateTestCase(TestCase): def test_find_template_first_exists(self): self.assertEqual('base.html', utils.find_template(['base.html', 'baser.html', 'basest.html'])) def test_find_template_one_exists(self): self.assertEqual('base.html', utils.find_template(['baser.html', 'base.html', 'basest.html'])) def test_find_template_none_exists(self): self.assertEqual(None, utils.find_template(['baser.html', 'basest.html']))
<commit_before>""" Unittests for opal.utils """ from django.test import TestCase from django.db.models import ForeignKey, CharField from opal import utils class StringportTestCase(TestCase): def test_import(self): import collections self.assertEqual(collections, utils.stringport('collections')) class ItersubclassesTestCase(TestCase): def test_tree_structure(self): class A(object): pass class B(A): pass class C(B, utils.AbstractBase): pass class D(C): pass results = {i for i in utils._itersubclasses(A)} self.assertEqual(results, set([B, D])) class FindTemplateTestCase(TestCase): def test_find_template_first_exists(self): self.assertEqual('base.html', utils.find_template(['base.html', 'baser.html', 'basest.html'])) def test_find_template_one_exists(self): self.assertEqual('base.html', utils.find_template(['baser.html', 'base.html', 'basest.html'])) def test_find_template_none_exists(self): self.assertEqual(None, utils.find_template(['baser.html', 'basest.html'])) <commit_msg>Add some tests for stringport<commit_after>""" Unittests for opal.utils """ from django.test import TestCase from django.db.models import ForeignKey, CharField from opal import utils class StringportTestCase(TestCase): def test_import(self): import collections self.assertEqual(collections, utils.stringport('collections')) def test_import_no_period(self): with self.assertRaises(ImportError): utils.stringport('wotcha') def test_import_perioded_thing(self): self.assertEqual(TestCase, utils.stringport('django.test.TestCase')) def test_empty_name_is_valueerror(self): with self.assertRaises(ValueError): utils.stringport('') class ItersubclassesTestCase(TestCase): def test_tree_structure(self): class A(object): pass class B(A): pass class C(B, utils.AbstractBase): pass class D(C): pass results = {i for i in utils._itersubclasses(A)} self.assertEqual(results, set([B, D])) class FindTemplateTestCase(TestCase): def test_find_template_first_exists(self): self.assertEqual('base.html', utils.find_template(['base.html', 'baser.html', 'basest.html'])) def test_find_template_one_exists(self): self.assertEqual('base.html', utils.find_template(['baser.html', 'base.html', 'basest.html'])) def test_find_template_none_exists(self): self.assertEqual(None, utils.find_template(['baser.html', 'basest.html']))
265e169570db18b53b86a55b94871f1eb25dfd4d
gvi/transactions/models.py
gvi/transactions/models.py
from django.db import models class Category(models.Model): name = models.CharField(max_length=50) number = models.CharField(max_length=50, unique=True) def __str__(self): return self.number class Subcategory(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category) def __str__(self): return self.name class Transaction(models.Model): IN = 'i' OUT = 'o' TYPE_CHOICES = ( (IN, 'Money In'), (OUT, 'Money Out'), ) transaction_type = models.CharField(max_length=5, choices=TYPE_CHOICES, default=OUT) category = models.ForeignKey(Category) date = models.DateTimeField() subcategory = models.ForeignKey(Subcategory, blank=True) comment = models.CharField(max_length=200, blank=True) amount = models.CharField(max_length=50) balance = models.CharField(max_length=50) #Add the ForeignKey to accounts def __str__(self): return self.transaction_type + amount
from django.db import models class Category(models.Model): name = models.CharField(max_length=50) number = models.CharField(max_length=50, unique=True) def __str__(self): return self.number class Subcategory(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category) def __str__(self): return self.name class Transaction(models.Model): IN = 'i' OUT = 'o' TYPE_CHOICES = ( (IN, 'Money In'), (OUT, 'Money Out'), ) transaction_type = models.CharField(max_length=5, choices=TYPE_CHOICES, default=OUT) category = models.ForeignKey(Category) date = models.DateTimeField() subcategory = models.ForeignKey(Subcategory, blank=True) comment = models.CharField(max_length=200, blank=True) amount = models.DecimalField(decimal_places=10, max_digits=19) balance = models.DecimalField(decimal_places=10, max_digits=19) #Add the ForeignKey to accounts def __str__(self): return self.transaction_type + amount
Change the field type of amount and balance to DecimalField
Change the field type of amount and balance to DecimalField
Python
mit
m1k3r/gvi-accounts,m1k3r/gvi-accounts,m1k3r/gvi-accounts
from django.db import models class Category(models.Model): name = models.CharField(max_length=50) number = models.CharField(max_length=50, unique=True) def __str__(self): return self.number class Subcategory(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category) def __str__(self): return self.name class Transaction(models.Model): IN = 'i' OUT = 'o' TYPE_CHOICES = ( (IN, 'Money In'), (OUT, 'Money Out'), ) transaction_type = models.CharField(max_length=5, choices=TYPE_CHOICES, default=OUT) category = models.ForeignKey(Category) date = models.DateTimeField() subcategory = models.ForeignKey(Subcategory, blank=True) comment = models.CharField(max_length=200, blank=True) amount = models.CharField(max_length=50) balance = models.CharField(max_length=50) #Add the ForeignKey to accounts def __str__(self): return self.transaction_type + amount Change the field type of amount and balance to DecimalField
from django.db import models class Category(models.Model): name = models.CharField(max_length=50) number = models.CharField(max_length=50, unique=True) def __str__(self): return self.number class Subcategory(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category) def __str__(self): return self.name class Transaction(models.Model): IN = 'i' OUT = 'o' TYPE_CHOICES = ( (IN, 'Money In'), (OUT, 'Money Out'), ) transaction_type = models.CharField(max_length=5, choices=TYPE_CHOICES, default=OUT) category = models.ForeignKey(Category) date = models.DateTimeField() subcategory = models.ForeignKey(Subcategory, blank=True) comment = models.CharField(max_length=200, blank=True) amount = models.DecimalField(decimal_places=10, max_digits=19) balance = models.DecimalField(decimal_places=10, max_digits=19) #Add the ForeignKey to accounts def __str__(self): return self.transaction_type + amount
<commit_before>from django.db import models class Category(models.Model): name = models.CharField(max_length=50) number = models.CharField(max_length=50, unique=True) def __str__(self): return self.number class Subcategory(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category) def __str__(self): return self.name class Transaction(models.Model): IN = 'i' OUT = 'o' TYPE_CHOICES = ( (IN, 'Money In'), (OUT, 'Money Out'), ) transaction_type = models.CharField(max_length=5, choices=TYPE_CHOICES, default=OUT) category = models.ForeignKey(Category) date = models.DateTimeField() subcategory = models.ForeignKey(Subcategory, blank=True) comment = models.CharField(max_length=200, blank=True) amount = models.CharField(max_length=50) balance = models.CharField(max_length=50) #Add the ForeignKey to accounts def __str__(self): return self.transaction_type + amount <commit_msg>Change the field type of amount and balance to DecimalField<commit_after>
from django.db import models class Category(models.Model): name = models.CharField(max_length=50) number = models.CharField(max_length=50, unique=True) def __str__(self): return self.number class Subcategory(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category) def __str__(self): return self.name class Transaction(models.Model): IN = 'i' OUT = 'o' TYPE_CHOICES = ( (IN, 'Money In'), (OUT, 'Money Out'), ) transaction_type = models.CharField(max_length=5, choices=TYPE_CHOICES, default=OUT) category = models.ForeignKey(Category) date = models.DateTimeField() subcategory = models.ForeignKey(Subcategory, blank=True) comment = models.CharField(max_length=200, blank=True) amount = models.DecimalField(decimal_places=10, max_digits=19) balance = models.DecimalField(decimal_places=10, max_digits=19) #Add the ForeignKey to accounts def __str__(self): return self.transaction_type + amount
from django.db import models class Category(models.Model): name = models.CharField(max_length=50) number = models.CharField(max_length=50, unique=True) def __str__(self): return self.number class Subcategory(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category) def __str__(self): return self.name class Transaction(models.Model): IN = 'i' OUT = 'o' TYPE_CHOICES = ( (IN, 'Money In'), (OUT, 'Money Out'), ) transaction_type = models.CharField(max_length=5, choices=TYPE_CHOICES, default=OUT) category = models.ForeignKey(Category) date = models.DateTimeField() subcategory = models.ForeignKey(Subcategory, blank=True) comment = models.CharField(max_length=200, blank=True) amount = models.CharField(max_length=50) balance = models.CharField(max_length=50) #Add the ForeignKey to accounts def __str__(self): return self.transaction_type + amount Change the field type of amount and balance to DecimalFieldfrom django.db import models class Category(models.Model): name = models.CharField(max_length=50) number = models.CharField(max_length=50, unique=True) def __str__(self): return self.number class Subcategory(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category) def __str__(self): return self.name class Transaction(models.Model): IN = 'i' OUT = 'o' TYPE_CHOICES = ( (IN, 'Money In'), (OUT, 'Money Out'), ) transaction_type = models.CharField(max_length=5, choices=TYPE_CHOICES, default=OUT) category = models.ForeignKey(Category) date = models.DateTimeField() subcategory = models.ForeignKey(Subcategory, blank=True) comment = models.CharField(max_length=200, blank=True) amount = models.DecimalField(decimal_places=10, max_digits=19) balance = models.DecimalField(decimal_places=10, max_digits=19) #Add the ForeignKey to accounts def __str__(self): return self.transaction_type + amount
<commit_before>from django.db import models class Category(models.Model): name = models.CharField(max_length=50) number = models.CharField(max_length=50, unique=True) def __str__(self): return self.number class Subcategory(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category) def __str__(self): return self.name class Transaction(models.Model): IN = 'i' OUT = 'o' TYPE_CHOICES = ( (IN, 'Money In'), (OUT, 'Money Out'), ) transaction_type = models.CharField(max_length=5, choices=TYPE_CHOICES, default=OUT) category = models.ForeignKey(Category) date = models.DateTimeField() subcategory = models.ForeignKey(Subcategory, blank=True) comment = models.CharField(max_length=200, blank=True) amount = models.CharField(max_length=50) balance = models.CharField(max_length=50) #Add the ForeignKey to accounts def __str__(self): return self.transaction_type + amount <commit_msg>Change the field type of amount and balance to DecimalField<commit_after>from django.db import models class Category(models.Model): name = models.CharField(max_length=50) number = models.CharField(max_length=50, unique=True) def __str__(self): return self.number class Subcategory(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category) def __str__(self): return self.name class Transaction(models.Model): IN = 'i' OUT = 'o' TYPE_CHOICES = ( (IN, 'Money In'), (OUT, 'Money Out'), ) transaction_type = models.CharField(max_length=5, choices=TYPE_CHOICES, default=OUT) category = models.ForeignKey(Category) date = models.DateTimeField() subcategory = models.ForeignKey(Subcategory, blank=True) comment = models.CharField(max_length=200, blank=True) amount = models.DecimalField(decimal_places=10, max_digits=19) balance = models.DecimalField(decimal_places=10, max_digits=19) #Add the ForeignKey to accounts def __str__(self): return self.transaction_type + amount
dc47c88d5f1c6f1e78322c5bfcb585e54b3a0c0a
python/colorTest.py
python/colorTest.py
#!/usr/bin/env python from rgbmatrix import RGBMatrix from random import randint import time rows = 16 chains = 1 parallel = 1 ledMatrix = RGBMatrix(rows, chains, parallel) height = ledMatrix.height width = ledMatrix.width for x in range(width): for y in range(height): r = int(y % 8 / 7.0 * 255) g = int(x % 8 / 7.0 * 255) b = int((int(x / 8) + int(y / 8) * 4) / 7.0 * 255) print r ledMatrix.SetPixel(x, y, r, g, b) time.sleep(0.05) time.sleep(5) ledMatrix.Clear()
#!/usr/bin/env python from rgbmatrix import RGBMatrix from random import randint import time rows = 16 chains = 1 parallel = 1 ledMatrix = RGBMatrix(rows, chains, parallel) height = ledMatrix.height width = ledMatrix.width for x in range(width): for y in range(height): r = int(y % 8 / 7.0 * 255) g = int(x % 8 / 7.0 * 255) b = int((int(x / 8) + int(y / 8) * 4) / 7.0 * 255) ledMatrix.SetPixel(x, y, r, g, b) time.sleep(0.02) time.sleep(5) ledMatrix.Clear()
Remove print and increase speed
Remove print and increase speed
Python
mit
DarkAce65/rpi-led-matrix,DarkAce65/rpi-led-matrix
#!/usr/bin/env python from rgbmatrix import RGBMatrix from random import randint import time rows = 16 chains = 1 parallel = 1 ledMatrix = RGBMatrix(rows, chains, parallel) height = ledMatrix.height width = ledMatrix.width for x in range(width): for y in range(height): r = int(y % 8 / 7.0 * 255) g = int(x % 8 / 7.0 * 255) b = int((int(x / 8) + int(y / 8) * 4) / 7.0 * 255) print r ledMatrix.SetPixel(x, y, r, g, b) time.sleep(0.05) time.sleep(5) ledMatrix.Clear() Remove print and increase speed
#!/usr/bin/env python from rgbmatrix import RGBMatrix from random import randint import time rows = 16 chains = 1 parallel = 1 ledMatrix = RGBMatrix(rows, chains, parallel) height = ledMatrix.height width = ledMatrix.width for x in range(width): for y in range(height): r = int(y % 8 / 7.0 * 255) g = int(x % 8 / 7.0 * 255) b = int((int(x / 8) + int(y / 8) * 4) / 7.0 * 255) ledMatrix.SetPixel(x, y, r, g, b) time.sleep(0.02) time.sleep(5) ledMatrix.Clear()
<commit_before>#!/usr/bin/env python from rgbmatrix import RGBMatrix from random import randint import time rows = 16 chains = 1 parallel = 1 ledMatrix = RGBMatrix(rows, chains, parallel) height = ledMatrix.height width = ledMatrix.width for x in range(width): for y in range(height): r = int(y % 8 / 7.0 * 255) g = int(x % 8 / 7.0 * 255) b = int((int(x / 8) + int(y / 8) * 4) / 7.0 * 255) print r ledMatrix.SetPixel(x, y, r, g, b) time.sleep(0.05) time.sleep(5) ledMatrix.Clear() <commit_msg>Remove print and increase speed<commit_after>
#!/usr/bin/env python from rgbmatrix import RGBMatrix from random import randint import time rows = 16 chains = 1 parallel = 1 ledMatrix = RGBMatrix(rows, chains, parallel) height = ledMatrix.height width = ledMatrix.width for x in range(width): for y in range(height): r = int(y % 8 / 7.0 * 255) g = int(x % 8 / 7.0 * 255) b = int((int(x / 8) + int(y / 8) * 4) / 7.0 * 255) ledMatrix.SetPixel(x, y, r, g, b) time.sleep(0.02) time.sleep(5) ledMatrix.Clear()
#!/usr/bin/env python from rgbmatrix import RGBMatrix from random import randint import time rows = 16 chains = 1 parallel = 1 ledMatrix = RGBMatrix(rows, chains, parallel) height = ledMatrix.height width = ledMatrix.width for x in range(width): for y in range(height): r = int(y % 8 / 7.0 * 255) g = int(x % 8 / 7.0 * 255) b = int((int(x / 8) + int(y / 8) * 4) / 7.0 * 255) print r ledMatrix.SetPixel(x, y, r, g, b) time.sleep(0.05) time.sleep(5) ledMatrix.Clear() Remove print and increase speed#!/usr/bin/env python from rgbmatrix import RGBMatrix from random import randint import time rows = 16 chains = 1 parallel = 1 ledMatrix = RGBMatrix(rows, chains, parallel) height = ledMatrix.height width = ledMatrix.width for x in range(width): for y in range(height): r = int(y % 8 / 7.0 * 255) g = int(x % 8 / 7.0 * 255) b = int((int(x / 8) + int(y / 8) * 4) / 7.0 * 255) ledMatrix.SetPixel(x, y, r, g, b) time.sleep(0.02) time.sleep(5) ledMatrix.Clear()
<commit_before>#!/usr/bin/env python from rgbmatrix import RGBMatrix from random import randint import time rows = 16 chains = 1 parallel = 1 ledMatrix = RGBMatrix(rows, chains, parallel) height = ledMatrix.height width = ledMatrix.width for x in range(width): for y in range(height): r = int(y % 8 / 7.0 * 255) g = int(x % 8 / 7.0 * 255) b = int((int(x / 8) + int(y / 8) * 4) / 7.0 * 255) print r ledMatrix.SetPixel(x, y, r, g, b) time.sleep(0.05) time.sleep(5) ledMatrix.Clear() <commit_msg>Remove print and increase speed<commit_after>#!/usr/bin/env python from rgbmatrix import RGBMatrix from random import randint import time rows = 16 chains = 1 parallel = 1 ledMatrix = RGBMatrix(rows, chains, parallel) height = ledMatrix.height width = ledMatrix.width for x in range(width): for y in range(height): r = int(y % 8 / 7.0 * 255) g = int(x % 8 / 7.0 * 255) b = int((int(x / 8) + int(y / 8) * 4) / 7.0 * 255) ledMatrix.SetPixel(x, y, r, g, b) time.sleep(0.02) time.sleep(5) ledMatrix.Clear()
0fa9b1abef3c7310d8f840d35bb417f74093d5cf
src/main.py
src/main.py
#!/usr/bin/python3 import sys import window from PyQt5.QtWidgets import QApplication def main(): startGUI() def startGUI(): app = QApplication(sys.argv) ex = window.MainWindow() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
#!/usr/bin/env python3 import sys import window from PyQt5.QtWidgets import QApplication def main(): startGUI() def startGUI(): app = QApplication(sys.argv) ex = window.MainWindow() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
Fix for use in virtualenv
Fix for use in virtualenv
Python
mit
grsakea/pyt
#!/usr/bin/python3 import sys import window from PyQt5.QtWidgets import QApplication def main(): startGUI() def startGUI(): app = QApplication(sys.argv) ex = window.MainWindow() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main() Fix for use in virtualenv
#!/usr/bin/env python3 import sys import window from PyQt5.QtWidgets import QApplication def main(): startGUI() def startGUI(): app = QApplication(sys.argv) ex = window.MainWindow() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
<commit_before>#!/usr/bin/python3 import sys import window from PyQt5.QtWidgets import QApplication def main(): startGUI() def startGUI(): app = QApplication(sys.argv) ex = window.MainWindow() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main() <commit_msg>Fix for use in virtualenv<commit_after>
#!/usr/bin/env python3 import sys import window from PyQt5.QtWidgets import QApplication def main(): startGUI() def startGUI(): app = QApplication(sys.argv) ex = window.MainWindow() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
#!/usr/bin/python3 import sys import window from PyQt5.QtWidgets import QApplication def main(): startGUI() def startGUI(): app = QApplication(sys.argv) ex = window.MainWindow() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main() Fix for use in virtualenv#!/usr/bin/env python3 import sys import window from PyQt5.QtWidgets import QApplication def main(): startGUI() def startGUI(): app = QApplication(sys.argv) ex = window.MainWindow() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
<commit_before>#!/usr/bin/python3 import sys import window from PyQt5.QtWidgets import QApplication def main(): startGUI() def startGUI(): app = QApplication(sys.argv) ex = window.MainWindow() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main() <commit_msg>Fix for use in virtualenv<commit_after>#!/usr/bin/env python3 import sys import window from PyQt5.QtWidgets import QApplication def main(): startGUI() def startGUI(): app = QApplication(sys.argv) ex = window.MainWindow() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
458f1e269646f432ef52774230114a4b05351211
controllers/default.py
controllers/default.py
import os def index(): def GET(): return locals() @request.restful() def api(): response.view = 'generic.json' def GET(resource,resource_id): if not resource=='study': raise HTTP(400) # return the correct nexson of study_id return _get_nexson(resource_id) def POST(resource,resource_id): if not resource=='study': raise HTTP(400) # overwrite the nexson of study_id with the POSTed data # 1) verify that it is valid json # 2) Update local treenexus git submodule at ./treenexus # 3) See if the hash of the current value of the file matches the hash of the POSTed data. If so, do nothing and return successfully. # 4) If not, overwrite the correct nexson file on disk # 5) Make a git commit with the updated nexson (add as much automated metadata to the commit message as possible) # 6) return successfully return dict() return locals() def _get_nexson(study_id): this_dir = os.path.dirname(os.path.abspath(__file__)) # the internal file structure will change soon to study/study_id/study_id-N.json, where N=0,1,2,3... try: filename = this_dir + "/../treenexus/study/0/" + study_id + ".json" nexson_file = open(filename,'r') except IOError: return '{}' return nexson_file.readlines()
import os def index(): def GET(): return locals() @request.restful() def api(): response.view = 'generic.json' def GET(resource,resource_id): if not resource=='study': raise HTTP(400) # return the correct nexson of study_id return _get_nexson(resource_id) def POST(resource,resource_id): if not resource=='study': raise HTTP(400) # overwrite the nexson of study_id with the POSTed data # 1) verify that it is valid json # 2) Update local treenexus git submodule at ./treenexus # 3) See if the hash of the current value of the file matches the hash of the POSTed data. If so, do nothing and return successfully. # 4) If not, overwrite the correct nexson file on disk # 5) Make a git commit with the updated nexson (add as much automated metadata to the commit message as possible) # 6) return successfully return dict() return locals() def _get_nexson(study_id): this_dir = os.path.dirname(os.path.abspath(__file__)) try: filename = this_dir + "/../treenexus/study/" + study_id + "/" + study_id + ".json" nexson_file = open(filename,'r') except IOError: return '{}' return nexson_file.readlines()
Use the new location of study NexSON
Use the new location of study NexSON Each study now has a distinct directory. Currently we only plan to store a single JSON file in each directory, until one becomes larger than 50MB. Additionally, this allows various metadata/artifacts about a study to live near the actually study data.
Python
bsd-2-clause
leto/new_opentree_api,leto/new_opentree_api
import os def index(): def GET(): return locals() @request.restful() def api(): response.view = 'generic.json' def GET(resource,resource_id): if not resource=='study': raise HTTP(400) # return the correct nexson of study_id return _get_nexson(resource_id) def POST(resource,resource_id): if not resource=='study': raise HTTP(400) # overwrite the nexson of study_id with the POSTed data # 1) verify that it is valid json # 2) Update local treenexus git submodule at ./treenexus # 3) See if the hash of the current value of the file matches the hash of the POSTed data. If so, do nothing and return successfully. # 4) If not, overwrite the correct nexson file on disk # 5) Make a git commit with the updated nexson (add as much automated metadata to the commit message as possible) # 6) return successfully return dict() return locals() def _get_nexson(study_id): this_dir = os.path.dirname(os.path.abspath(__file__)) # the internal file structure will change soon to study/study_id/study_id-N.json, where N=0,1,2,3... try: filename = this_dir + "/../treenexus/study/0/" + study_id + ".json" nexson_file = open(filename,'r') except IOError: return '{}' return nexson_file.readlines() Use the new location of study NexSON Each study now has a distinct directory. Currently we only plan to store a single JSON file in each directory, until one becomes larger than 50MB. Additionally, this allows various metadata/artifacts about a study to live near the actually study data.
import os def index(): def GET(): return locals() @request.restful() def api(): response.view = 'generic.json' def GET(resource,resource_id): if not resource=='study': raise HTTP(400) # return the correct nexson of study_id return _get_nexson(resource_id) def POST(resource,resource_id): if not resource=='study': raise HTTP(400) # overwrite the nexson of study_id with the POSTed data # 1) verify that it is valid json # 2) Update local treenexus git submodule at ./treenexus # 3) See if the hash of the current value of the file matches the hash of the POSTed data. If so, do nothing and return successfully. # 4) If not, overwrite the correct nexson file on disk # 5) Make a git commit with the updated nexson (add as much automated metadata to the commit message as possible) # 6) return successfully return dict() return locals() def _get_nexson(study_id): this_dir = os.path.dirname(os.path.abspath(__file__)) try: filename = this_dir + "/../treenexus/study/" + study_id + "/" + study_id + ".json" nexson_file = open(filename,'r') except IOError: return '{}' return nexson_file.readlines()
<commit_before>import os def index(): def GET(): return locals() @request.restful() def api(): response.view = 'generic.json' def GET(resource,resource_id): if not resource=='study': raise HTTP(400) # return the correct nexson of study_id return _get_nexson(resource_id) def POST(resource,resource_id): if not resource=='study': raise HTTP(400) # overwrite the nexson of study_id with the POSTed data # 1) verify that it is valid json # 2) Update local treenexus git submodule at ./treenexus # 3) See if the hash of the current value of the file matches the hash of the POSTed data. If so, do nothing and return successfully. # 4) If not, overwrite the correct nexson file on disk # 5) Make a git commit with the updated nexson (add as much automated metadata to the commit message as possible) # 6) return successfully return dict() return locals() def _get_nexson(study_id): this_dir = os.path.dirname(os.path.abspath(__file__)) # the internal file structure will change soon to study/study_id/study_id-N.json, where N=0,1,2,3... try: filename = this_dir + "/../treenexus/study/0/" + study_id + ".json" nexson_file = open(filename,'r') except IOError: return '{}' return nexson_file.readlines() <commit_msg>Use the new location of study NexSON Each study now has a distinct directory. Currently we only plan to store a single JSON file in each directory, until one becomes larger than 50MB. Additionally, this allows various metadata/artifacts about a study to live near the actually study data.<commit_after>
import os def index(): def GET(): return locals() @request.restful() def api(): response.view = 'generic.json' def GET(resource,resource_id): if not resource=='study': raise HTTP(400) # return the correct nexson of study_id return _get_nexson(resource_id) def POST(resource,resource_id): if not resource=='study': raise HTTP(400) # overwrite the nexson of study_id with the POSTed data # 1) verify that it is valid json # 2) Update local treenexus git submodule at ./treenexus # 3) See if the hash of the current value of the file matches the hash of the POSTed data. If so, do nothing and return successfully. # 4) If not, overwrite the correct nexson file on disk # 5) Make a git commit with the updated nexson (add as much automated metadata to the commit message as possible) # 6) return successfully return dict() return locals() def _get_nexson(study_id): this_dir = os.path.dirname(os.path.abspath(__file__)) try: filename = this_dir + "/../treenexus/study/" + study_id + "/" + study_id + ".json" nexson_file = open(filename,'r') except IOError: return '{}' return nexson_file.readlines()
import os def index(): def GET(): return locals() @request.restful() def api(): response.view = 'generic.json' def GET(resource,resource_id): if not resource=='study': raise HTTP(400) # return the correct nexson of study_id return _get_nexson(resource_id) def POST(resource,resource_id): if not resource=='study': raise HTTP(400) # overwrite the nexson of study_id with the POSTed data # 1) verify that it is valid json # 2) Update local treenexus git submodule at ./treenexus # 3) See if the hash of the current value of the file matches the hash of the POSTed data. If so, do nothing and return successfully. # 4) If not, overwrite the correct nexson file on disk # 5) Make a git commit with the updated nexson (add as much automated metadata to the commit message as possible) # 6) return successfully return dict() return locals() def _get_nexson(study_id): this_dir = os.path.dirname(os.path.abspath(__file__)) # the internal file structure will change soon to study/study_id/study_id-N.json, where N=0,1,2,3... try: filename = this_dir + "/../treenexus/study/0/" + study_id + ".json" nexson_file = open(filename,'r') except IOError: return '{}' return nexson_file.readlines() Use the new location of study NexSON Each study now has a distinct directory. Currently we only plan to store a single JSON file in each directory, until one becomes larger than 50MB. Additionally, this allows various metadata/artifacts about a study to live near the actually study data.import os def index(): def GET(): return locals() @request.restful() def api(): response.view = 'generic.json' def GET(resource,resource_id): if not resource=='study': raise HTTP(400) # return the correct nexson of study_id return _get_nexson(resource_id) def POST(resource,resource_id): if not resource=='study': raise HTTP(400) # overwrite the nexson of study_id with the POSTed data # 1) verify that it is valid json # 2) Update local treenexus git submodule at ./treenexus # 3) See if the hash of the current value of the file matches the hash of the POSTed data. If so, do nothing and return successfully. # 4) If not, overwrite the correct nexson file on disk # 5) Make a git commit with the updated nexson (add as much automated metadata to the commit message as possible) # 6) return successfully return dict() return locals() def _get_nexson(study_id): this_dir = os.path.dirname(os.path.abspath(__file__)) try: filename = this_dir + "/../treenexus/study/" + study_id + "/" + study_id + ".json" nexson_file = open(filename,'r') except IOError: return '{}' return nexson_file.readlines()
<commit_before>import os def index(): def GET(): return locals() @request.restful() def api(): response.view = 'generic.json' def GET(resource,resource_id): if not resource=='study': raise HTTP(400) # return the correct nexson of study_id return _get_nexson(resource_id) def POST(resource,resource_id): if not resource=='study': raise HTTP(400) # overwrite the nexson of study_id with the POSTed data # 1) verify that it is valid json # 2) Update local treenexus git submodule at ./treenexus # 3) See if the hash of the current value of the file matches the hash of the POSTed data. If so, do nothing and return successfully. # 4) If not, overwrite the correct nexson file on disk # 5) Make a git commit with the updated nexson (add as much automated metadata to the commit message as possible) # 6) return successfully return dict() return locals() def _get_nexson(study_id): this_dir = os.path.dirname(os.path.abspath(__file__)) # the internal file structure will change soon to study/study_id/study_id-N.json, where N=0,1,2,3... try: filename = this_dir + "/../treenexus/study/0/" + study_id + ".json" nexson_file = open(filename,'r') except IOError: return '{}' return nexson_file.readlines() <commit_msg>Use the new location of study NexSON Each study now has a distinct directory. Currently we only plan to store a single JSON file in each directory, until one becomes larger than 50MB. Additionally, this allows various metadata/artifacts about a study to live near the actually study data.<commit_after>import os def index(): def GET(): return locals() @request.restful() def api(): response.view = 'generic.json' def GET(resource,resource_id): if not resource=='study': raise HTTP(400) # return the correct nexson of study_id return _get_nexson(resource_id) def POST(resource,resource_id): if not resource=='study': raise HTTP(400) # overwrite the nexson of study_id with the POSTed data # 1) verify that it is valid json # 2) Update local treenexus git submodule at ./treenexus # 3) See if the hash of the current value of the file matches the hash of the POSTed data. If so, do nothing and return successfully. # 4) If not, overwrite the correct nexson file on disk # 5) Make a git commit with the updated nexson (add as much automated metadata to the commit message as possible) # 6) return successfully return dict() return locals() def _get_nexson(study_id): this_dir = os.path.dirname(os.path.abspath(__file__)) try: filename = this_dir + "/../treenexus/study/" + study_id + "/" + study_id + ".json" nexson_file = open(filename,'r') except IOError: return '{}' return nexson_file.readlines()
57428c3ef4c80733c2309aea2db71624b188a055
oath_toolkit/_compat.py
oath_toolkit/_compat.py
# -*- coding: utf-8 -*- # # Copyright 2013 Mark Lee # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys if sys.version_info < (3,): # pragma: no cover from urllib import quote as url_quote to_bytes = lambda s: s.encode('utf-8') if isinstance(s, unicode) else s else: # pragma: no cover from urllib.parse import quote as url_quote to_bytes = lambda s: bytes(s, 'utf-8') if isinstance(s, str) else s __all__ = ['to_bytes', 'url_quote']
# -*- coding: utf-8 -*- # # Copyright 2013 Mark Lee # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys try: unicode except NameError: unicode = None if sys.version_info < (3,): # pragma: no cover from urllib import quote as url_quote to_bytes = lambda s: s.encode('utf-8') if isinstance(s, unicode) else s else: # pragma: no cover from urllib.parse import quote as url_quote to_bytes = lambda s: bytes(s, 'utf-8') if isinstance(s, str) else s __all__ = ['to_bytes', 'url_quote']
Fix broken test on Python 3.3
Fix broken test on Python 3.3
Python
apache-2.0
malept/pyoath-toolkit,malept/pyoath-toolkit,malept/pyoath-toolkit
# -*- coding: utf-8 -*- # # Copyright 2013 Mark Lee # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys if sys.version_info < (3,): # pragma: no cover from urllib import quote as url_quote to_bytes = lambda s: s.encode('utf-8') if isinstance(s, unicode) else s else: # pragma: no cover from urllib.parse import quote as url_quote to_bytes = lambda s: bytes(s, 'utf-8') if isinstance(s, str) else s __all__ = ['to_bytes', 'url_quote'] Fix broken test on Python 3.3
# -*- coding: utf-8 -*- # # Copyright 2013 Mark Lee # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys try: unicode except NameError: unicode = None if sys.version_info < (3,): # pragma: no cover from urllib import quote as url_quote to_bytes = lambda s: s.encode('utf-8') if isinstance(s, unicode) else s else: # pragma: no cover from urllib.parse import quote as url_quote to_bytes = lambda s: bytes(s, 'utf-8') if isinstance(s, str) else s __all__ = ['to_bytes', 'url_quote']
<commit_before># -*- coding: utf-8 -*- # # Copyright 2013 Mark Lee # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys if sys.version_info < (3,): # pragma: no cover from urllib import quote as url_quote to_bytes = lambda s: s.encode('utf-8') if isinstance(s, unicode) else s else: # pragma: no cover from urllib.parse import quote as url_quote to_bytes = lambda s: bytes(s, 'utf-8') if isinstance(s, str) else s __all__ = ['to_bytes', 'url_quote'] <commit_msg>Fix broken test on Python 3.3<commit_after>
# -*- coding: utf-8 -*- # # Copyright 2013 Mark Lee # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys try: unicode except NameError: unicode = None if sys.version_info < (3,): # pragma: no cover from urllib import quote as url_quote to_bytes = lambda s: s.encode('utf-8') if isinstance(s, unicode) else s else: # pragma: no cover from urllib.parse import quote as url_quote to_bytes = lambda s: bytes(s, 'utf-8') if isinstance(s, str) else s __all__ = ['to_bytes', 'url_quote']
# -*- coding: utf-8 -*- # # Copyright 2013 Mark Lee # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys if sys.version_info < (3,): # pragma: no cover from urllib import quote as url_quote to_bytes = lambda s: s.encode('utf-8') if isinstance(s, unicode) else s else: # pragma: no cover from urllib.parse import quote as url_quote to_bytes = lambda s: bytes(s, 'utf-8') if isinstance(s, str) else s __all__ = ['to_bytes', 'url_quote'] Fix broken test on Python 3.3# -*- coding: utf-8 -*- # # Copyright 2013 Mark Lee # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys try: unicode except NameError: unicode = None if sys.version_info < (3,): # pragma: no cover from urllib import quote as url_quote to_bytes = lambda s: s.encode('utf-8') if isinstance(s, unicode) else s else: # pragma: no cover from urllib.parse import quote as url_quote to_bytes = lambda s: bytes(s, 'utf-8') if isinstance(s, str) else s __all__ = ['to_bytes', 'url_quote']
<commit_before># -*- coding: utf-8 -*- # # Copyright 2013 Mark Lee # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys if sys.version_info < (3,): # pragma: no cover from urllib import quote as url_quote to_bytes = lambda s: s.encode('utf-8') if isinstance(s, unicode) else s else: # pragma: no cover from urllib.parse import quote as url_quote to_bytes = lambda s: bytes(s, 'utf-8') if isinstance(s, str) else s __all__ = ['to_bytes', 'url_quote'] <commit_msg>Fix broken test on Python 3.3<commit_after># -*- coding: utf-8 -*- # # Copyright 2013 Mark Lee # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys try: unicode except NameError: unicode = None if sys.version_info < (3,): # pragma: no cover from urllib import quote as url_quote to_bytes = lambda s: s.encode('utf-8') if isinstance(s, unicode) else s else: # pragma: no cover from urllib.parse import quote as url_quote to_bytes = lambda s: bytes(s, 'utf-8') if isinstance(s, str) else s __all__ = ['to_bytes', 'url_quote']
5b8fe62647eade5d9c060c027e5658cf0eb531f2
pygraphc/clustering/__init__.py
pygraphc/clustering/__init__.py
from pygraphc.clustering.ClusterDistance import * from pygraphc.clustering.ClusterEvaluation import * from pygraphc.clustering.ClusterUtility import * from pygraphc.clustering.ConnectedComponents import * from pygraphc.clustering.KCliquePercolation import * from pygraphc.clustering.MaxCliquesPercolation import * import pygraphc.clustering.ClusterDistance import pygraphc.clustering.ClusterEvaluation import pygraphc.clustering.ClusterUtility import pygraphc.clustering.ConnectedComponents import pygraphc.clustering.KCliquePercolation import pygraphc.clustering.MaxCliquesPercolation
import pygraphc.clustering.ClusterDistance import pygraphc.clustering.ClusterUtility import pygraphc.clustering.ConnectedComponents import pygraphc.clustering.KCliquePercolation import pygraphc.clustering.MaxCliquesPercolation from pygraphc.clustering.ClusterDistance import * from pygraphc.clustering.ClusterUtility import * from pygraphc.clustering.ConnectedComponents import * from pygraphc.clustering.KCliquePercolation import * from pygraphc.clustering.MaxCliquesPercolation import *
Change path for the module ClusterEvaluation
Change path for the module ClusterEvaluation
Python
mit
studiawan/pygraphc
from pygraphc.clustering.ClusterDistance import * from pygraphc.clustering.ClusterEvaluation import * from pygraphc.clustering.ClusterUtility import * from pygraphc.clustering.ConnectedComponents import * from pygraphc.clustering.KCliquePercolation import * from pygraphc.clustering.MaxCliquesPercolation import * import pygraphc.clustering.ClusterDistance import pygraphc.clustering.ClusterEvaluation import pygraphc.clustering.ClusterUtility import pygraphc.clustering.ConnectedComponents import pygraphc.clustering.KCliquePercolation import pygraphc.clustering.MaxCliquesPercolation Change path for the module ClusterEvaluation
import pygraphc.clustering.ClusterDistance import pygraphc.clustering.ClusterUtility import pygraphc.clustering.ConnectedComponents import pygraphc.clustering.KCliquePercolation import pygraphc.clustering.MaxCliquesPercolation from pygraphc.clustering.ClusterDistance import * from pygraphc.clustering.ClusterUtility import * from pygraphc.clustering.ConnectedComponents import * from pygraphc.clustering.KCliquePercolation import * from pygraphc.clustering.MaxCliquesPercolation import *
<commit_before>from pygraphc.clustering.ClusterDistance import * from pygraphc.clustering.ClusterEvaluation import * from pygraphc.clustering.ClusterUtility import * from pygraphc.clustering.ConnectedComponents import * from pygraphc.clustering.KCliquePercolation import * from pygraphc.clustering.MaxCliquesPercolation import * import pygraphc.clustering.ClusterDistance import pygraphc.clustering.ClusterEvaluation import pygraphc.clustering.ClusterUtility import pygraphc.clustering.ConnectedComponents import pygraphc.clustering.KCliquePercolation import pygraphc.clustering.MaxCliquesPercolation <commit_msg>Change path for the module ClusterEvaluation<commit_after>
import pygraphc.clustering.ClusterDistance import pygraphc.clustering.ClusterUtility import pygraphc.clustering.ConnectedComponents import pygraphc.clustering.KCliquePercolation import pygraphc.clustering.MaxCliquesPercolation from pygraphc.clustering.ClusterDistance import * from pygraphc.clustering.ClusterUtility import * from pygraphc.clustering.ConnectedComponents import * from pygraphc.clustering.KCliquePercolation import * from pygraphc.clustering.MaxCliquesPercolation import *
from pygraphc.clustering.ClusterDistance import * from pygraphc.clustering.ClusterEvaluation import * from pygraphc.clustering.ClusterUtility import * from pygraphc.clustering.ConnectedComponents import * from pygraphc.clustering.KCliquePercolation import * from pygraphc.clustering.MaxCliquesPercolation import * import pygraphc.clustering.ClusterDistance import pygraphc.clustering.ClusterEvaluation import pygraphc.clustering.ClusterUtility import pygraphc.clustering.ConnectedComponents import pygraphc.clustering.KCliquePercolation import pygraphc.clustering.MaxCliquesPercolation Change path for the module ClusterEvaluationimport pygraphc.clustering.ClusterDistance import pygraphc.clustering.ClusterUtility import pygraphc.clustering.ConnectedComponents import pygraphc.clustering.KCliquePercolation import pygraphc.clustering.MaxCliquesPercolation from pygraphc.clustering.ClusterDistance import * from pygraphc.clustering.ClusterUtility import * from pygraphc.clustering.ConnectedComponents import * from pygraphc.clustering.KCliquePercolation import * from pygraphc.clustering.MaxCliquesPercolation import *
<commit_before>from pygraphc.clustering.ClusterDistance import * from pygraphc.clustering.ClusterEvaluation import * from pygraphc.clustering.ClusterUtility import * from pygraphc.clustering.ConnectedComponents import * from pygraphc.clustering.KCliquePercolation import * from pygraphc.clustering.MaxCliquesPercolation import * import pygraphc.clustering.ClusterDistance import pygraphc.clustering.ClusterEvaluation import pygraphc.clustering.ClusterUtility import pygraphc.clustering.ConnectedComponents import pygraphc.clustering.KCliquePercolation import pygraphc.clustering.MaxCliquesPercolation <commit_msg>Change path for the module ClusterEvaluation<commit_after>import pygraphc.clustering.ClusterDistance import pygraphc.clustering.ClusterUtility import pygraphc.clustering.ConnectedComponents import pygraphc.clustering.KCliquePercolation import pygraphc.clustering.MaxCliquesPercolation from pygraphc.clustering.ClusterDistance import * from pygraphc.clustering.ClusterUtility import * from pygraphc.clustering.ConnectedComponents import * from pygraphc.clustering.KCliquePercolation import * from pygraphc.clustering.MaxCliquesPercolation import *
4339b61aad98d10f91f44c82b72376bc88c3ec22
pivot/views/data_api.py
pivot/views/data_api.py
import os try: from urllib.parse import urljoin from urllib.request import urlopen except: # for Python 2.7 compatibility from urlparse import urljoin from urllib2 import urlopen from django.shortcuts import render from django.views import View from django.http import HttpResponse from django.conf import settings class DataFileView(View): file_name = None def get(self, request): csv = self._get_csv() return HttpResponse(csv) def _get_csv(self): if hasattr(settings, 'CSV_URL') and settings.CSV_URL is not None and settings.CSV_URL != '': url = urljoin(getattr(settings, 'CSV_URL', None), self.file_name) elif hasattr(settings, 'CSV_ROOT') and settings.CSV_ROOT is not None and settings.CSV_ROOT != '': url = urljoin('file://', getattr(settings, 'CSV_ROOT', None)) url = urljoin(url, self.file_name) with urlopen(url) as response: data = response.read() return data class MajorCourse(DataFileView): file_name = "Majors_and_Courses.csv" class DataMap(DataFileView): file_name = "Data_Map.csv" class StudentData(DataFileView): file_name = "Student_Data_All_Majors.csv" class StatusLookup(DataFileView): file_name = "Status_Lookup.csv"
import os try: from urllib.parse import urljoin from urllib.request import urlopen except: # for Python 2.7 compatibility from urlparse import urljoin from urllib2 import urlopen from django.shortcuts import render from django.views import View from django.http import HttpResponse from django.conf import settings class DataFileView(View): file_name = None def get(self, request): csv = self._get_csv() return HttpResponse(csv) def _get_csv(self): try: url = urljoin(getattr(settings, 'CSV_URL', None), self.file_name) with urlopen(url) as response: data = response.read() except ValueError: url = urljoin('file://', getattr(settings, 'CSV_ROOT', None)) url = urljoin(url, self.file_name) with urlopen(url) as response: data = response.read() except Exception as err: data = "Error: {}".format(err) return data class MajorCourse(DataFileView): file_name = "Majors_and_Courses.csv" class DataMap(DataFileView): file_name = "Data_Map.csv" class StudentData(DataFileView): file_name = "Student_Data_All_Majors.csv" class StatusLookup(DataFileView): file_name = "Status_Lookup.csv"
Clean up now that we're no longer trying to use CSV_URL.
Clean up now that we're no longer trying to use CSV_URL.
Python
apache-2.0
uw-it-aca/pivot,uw-it-aca/pivot,uw-it-aca/pivot,uw-it-aca/pivot,uw-it-aca/pivot
import os try: from urllib.parse import urljoin from urllib.request import urlopen except: # for Python 2.7 compatibility from urlparse import urljoin from urllib2 import urlopen from django.shortcuts import render from django.views import View from django.http import HttpResponse from django.conf import settings class DataFileView(View): file_name = None def get(self, request): csv = self._get_csv() return HttpResponse(csv) def _get_csv(self): if hasattr(settings, 'CSV_URL') and settings.CSV_URL is not None and settings.CSV_URL != '': url = urljoin(getattr(settings, 'CSV_URL', None), self.file_name) elif hasattr(settings, 'CSV_ROOT') and settings.CSV_ROOT is not None and settings.CSV_ROOT != '': url = urljoin('file://', getattr(settings, 'CSV_ROOT', None)) url = urljoin(url, self.file_name) with urlopen(url) as response: data = response.read() return data class MajorCourse(DataFileView): file_name = "Majors_and_Courses.csv" class DataMap(DataFileView): file_name = "Data_Map.csv" class StudentData(DataFileView): file_name = "Student_Data_All_Majors.csv" class StatusLookup(DataFileView): file_name = "Status_Lookup.csv" Clean up now that we're no longer trying to use CSV_URL.
import os try: from urllib.parse import urljoin from urllib.request import urlopen except: # for Python 2.7 compatibility from urlparse import urljoin from urllib2 import urlopen from django.shortcuts import render from django.views import View from django.http import HttpResponse from django.conf import settings class DataFileView(View): file_name = None def get(self, request): csv = self._get_csv() return HttpResponse(csv) def _get_csv(self): try: url = urljoin(getattr(settings, 'CSV_URL', None), self.file_name) with urlopen(url) as response: data = response.read() except ValueError: url = urljoin('file://', getattr(settings, 'CSV_ROOT', None)) url = urljoin(url, self.file_name) with urlopen(url) as response: data = response.read() except Exception as err: data = "Error: {}".format(err) return data class MajorCourse(DataFileView): file_name = "Majors_and_Courses.csv" class DataMap(DataFileView): file_name = "Data_Map.csv" class StudentData(DataFileView): file_name = "Student_Data_All_Majors.csv" class StatusLookup(DataFileView): file_name = "Status_Lookup.csv"
<commit_before>import os try: from urllib.parse import urljoin from urllib.request import urlopen except: # for Python 2.7 compatibility from urlparse import urljoin from urllib2 import urlopen from django.shortcuts import render from django.views import View from django.http import HttpResponse from django.conf import settings class DataFileView(View): file_name = None def get(self, request): csv = self._get_csv() return HttpResponse(csv) def _get_csv(self): if hasattr(settings, 'CSV_URL') and settings.CSV_URL is not None and settings.CSV_URL != '': url = urljoin(getattr(settings, 'CSV_URL', None), self.file_name) elif hasattr(settings, 'CSV_ROOT') and settings.CSV_ROOT is not None and settings.CSV_ROOT != '': url = urljoin('file://', getattr(settings, 'CSV_ROOT', None)) url = urljoin(url, self.file_name) with urlopen(url) as response: data = response.read() return data class MajorCourse(DataFileView): file_name = "Majors_and_Courses.csv" class DataMap(DataFileView): file_name = "Data_Map.csv" class StudentData(DataFileView): file_name = "Student_Data_All_Majors.csv" class StatusLookup(DataFileView): file_name = "Status_Lookup.csv" <commit_msg>Clean up now that we're no longer trying to use CSV_URL.<commit_after>
import os try: from urllib.parse import urljoin from urllib.request import urlopen except: # for Python 2.7 compatibility from urlparse import urljoin from urllib2 import urlopen from django.shortcuts import render from django.views import View from django.http import HttpResponse from django.conf import settings class DataFileView(View): file_name = None def get(self, request): csv = self._get_csv() return HttpResponse(csv) def _get_csv(self): try: url = urljoin(getattr(settings, 'CSV_URL', None), self.file_name) with urlopen(url) as response: data = response.read() except ValueError: url = urljoin('file://', getattr(settings, 'CSV_ROOT', None)) url = urljoin(url, self.file_name) with urlopen(url) as response: data = response.read() except Exception as err: data = "Error: {}".format(err) return data class MajorCourse(DataFileView): file_name = "Majors_and_Courses.csv" class DataMap(DataFileView): file_name = "Data_Map.csv" class StudentData(DataFileView): file_name = "Student_Data_All_Majors.csv" class StatusLookup(DataFileView): file_name = "Status_Lookup.csv"
import os try: from urllib.parse import urljoin from urllib.request import urlopen except: # for Python 2.7 compatibility from urlparse import urljoin from urllib2 import urlopen from django.shortcuts import render from django.views import View from django.http import HttpResponse from django.conf import settings class DataFileView(View): file_name = None def get(self, request): csv = self._get_csv() return HttpResponse(csv) def _get_csv(self): if hasattr(settings, 'CSV_URL') and settings.CSV_URL is not None and settings.CSV_URL != '': url = urljoin(getattr(settings, 'CSV_URL', None), self.file_name) elif hasattr(settings, 'CSV_ROOT') and settings.CSV_ROOT is not None and settings.CSV_ROOT != '': url = urljoin('file://', getattr(settings, 'CSV_ROOT', None)) url = urljoin(url, self.file_name) with urlopen(url) as response: data = response.read() return data class MajorCourse(DataFileView): file_name = "Majors_and_Courses.csv" class DataMap(DataFileView): file_name = "Data_Map.csv" class StudentData(DataFileView): file_name = "Student_Data_All_Majors.csv" class StatusLookup(DataFileView): file_name = "Status_Lookup.csv" Clean up now that we're no longer trying to use CSV_URL.import os try: from urllib.parse import urljoin from urllib.request import urlopen except: # for Python 2.7 compatibility from urlparse import urljoin from urllib2 import urlopen from django.shortcuts import render from django.views import View from django.http import HttpResponse from django.conf import settings class DataFileView(View): file_name = None def get(self, request): csv = self._get_csv() return HttpResponse(csv) def _get_csv(self): try: url = urljoin(getattr(settings, 'CSV_URL', None), self.file_name) with urlopen(url) as response: data = response.read() except ValueError: url = urljoin('file://', getattr(settings, 'CSV_ROOT', None)) url = urljoin(url, self.file_name) with urlopen(url) as response: data = response.read() except Exception as err: data = "Error: {}".format(err) return data class MajorCourse(DataFileView): file_name = "Majors_and_Courses.csv" class DataMap(DataFileView): file_name = "Data_Map.csv" class StudentData(DataFileView): file_name = "Student_Data_All_Majors.csv" class StatusLookup(DataFileView): file_name = "Status_Lookup.csv"
<commit_before>import os try: from urllib.parse import urljoin from urllib.request import urlopen except: # for Python 2.7 compatibility from urlparse import urljoin from urllib2 import urlopen from django.shortcuts import render from django.views import View from django.http import HttpResponse from django.conf import settings class DataFileView(View): file_name = None def get(self, request): csv = self._get_csv() return HttpResponse(csv) def _get_csv(self): if hasattr(settings, 'CSV_URL') and settings.CSV_URL is not None and settings.CSV_URL != '': url = urljoin(getattr(settings, 'CSV_URL', None), self.file_name) elif hasattr(settings, 'CSV_ROOT') and settings.CSV_ROOT is not None and settings.CSV_ROOT != '': url = urljoin('file://', getattr(settings, 'CSV_ROOT', None)) url = urljoin(url, self.file_name) with urlopen(url) as response: data = response.read() return data class MajorCourse(DataFileView): file_name = "Majors_and_Courses.csv" class DataMap(DataFileView): file_name = "Data_Map.csv" class StudentData(DataFileView): file_name = "Student_Data_All_Majors.csv" class StatusLookup(DataFileView): file_name = "Status_Lookup.csv" <commit_msg>Clean up now that we're no longer trying to use CSV_URL.<commit_after>import os try: from urllib.parse import urljoin from urllib.request import urlopen except: # for Python 2.7 compatibility from urlparse import urljoin from urllib2 import urlopen from django.shortcuts import render from django.views import View from django.http import HttpResponse from django.conf import settings class DataFileView(View): file_name = None def get(self, request): csv = self._get_csv() return HttpResponse(csv) def _get_csv(self): try: url = urljoin(getattr(settings, 'CSV_URL', None), self.file_name) with urlopen(url) as response: data = response.read() except ValueError: url = urljoin('file://', getattr(settings, 'CSV_ROOT', None)) url = urljoin(url, self.file_name) with urlopen(url) as response: data = response.read() except Exception as err: data = "Error: {}".format(err) return data class MajorCourse(DataFileView): file_name = "Majors_and_Courses.csv" class DataMap(DataFileView): file_name = "Data_Map.csv" class StudentData(DataFileView): file_name = "Student_Data_All_Majors.csv" class StatusLookup(DataFileView): file_name = "Status_Lookup.csv"
05551b6b7ed1ed9a97be635f3d32b5bd4f26f635
tests/mltils/test_infrequent_value_encoder.py
tests/mltils/test_infrequent_value_encoder.py
# pylint: disable=missing-docstring, invalid-name, import-error import pandas as pd from mltils.encoders import InfrequentValueEncoder def test_infrequent_value_encoder_1(): ive = InfrequentValueEncoder() assert ive is not None def test_infrequent_value_encoder_2(): df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) ive = InfrequentValueEncoder(thrshld=1, str_rpl='ifq') encoded = ive.fit_transform(df) expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'ifq']}) assert expected.equals(encoded)
# pylint: disable=missing-docstring, invalid-name, import-error import pandas as pd from mltils.encoders import InfrequentValueEncoder def test_infrequent_value_encoder_1(): ive = InfrequentValueEncoder() assert ive is not None def test_infrequent_value_encoder_2(): df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) ive = InfrequentValueEncoder(thrshld=1, str_rpl='ifq') encoded = ive.fit_transform(df) expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'ifq']}) assert expected.equals(encoded) def test_infrequent_value_encoder_3(): df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) ive = InfrequentValueEncoder(thrshld=0, str_rpl='ifq') encoded = ive.fit_transform(df) expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) assert expected.equals(encoded) def test_infrequent_value_encoder_4(): df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) ive = InfrequentValueEncoder(thrshld=0, str_rpl='ifq') encoded = ive.fit_transform(df) expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) assert expected.equals(encoded)
Add more unit tests for InfrequentValueEncoder
Add more unit tests for InfrequentValueEncoder
Python
mit
rladeira/mltils
# pylint: disable=missing-docstring, invalid-name, import-error import pandas as pd from mltils.encoders import InfrequentValueEncoder def test_infrequent_value_encoder_1(): ive = InfrequentValueEncoder() assert ive is not None def test_infrequent_value_encoder_2(): df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) ive = InfrequentValueEncoder(thrshld=1, str_rpl='ifq') encoded = ive.fit_transform(df) expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'ifq']}) assert expected.equals(encoded) Add more unit tests for InfrequentValueEncoder
# pylint: disable=missing-docstring, invalid-name, import-error import pandas as pd from mltils.encoders import InfrequentValueEncoder def test_infrequent_value_encoder_1(): ive = InfrequentValueEncoder() assert ive is not None def test_infrequent_value_encoder_2(): df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) ive = InfrequentValueEncoder(thrshld=1, str_rpl='ifq') encoded = ive.fit_transform(df) expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'ifq']}) assert expected.equals(encoded) def test_infrequent_value_encoder_3(): df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) ive = InfrequentValueEncoder(thrshld=0, str_rpl='ifq') encoded = ive.fit_transform(df) expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) assert expected.equals(encoded) def test_infrequent_value_encoder_4(): df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) ive = InfrequentValueEncoder(thrshld=0, str_rpl='ifq') encoded = ive.fit_transform(df) expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) assert expected.equals(encoded)
<commit_before># pylint: disable=missing-docstring, invalid-name, import-error import pandas as pd from mltils.encoders import InfrequentValueEncoder def test_infrequent_value_encoder_1(): ive = InfrequentValueEncoder() assert ive is not None def test_infrequent_value_encoder_2(): df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) ive = InfrequentValueEncoder(thrshld=1, str_rpl='ifq') encoded = ive.fit_transform(df) expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'ifq']}) assert expected.equals(encoded) <commit_msg>Add more unit tests for InfrequentValueEncoder<commit_after>
# pylint: disable=missing-docstring, invalid-name, import-error import pandas as pd from mltils.encoders import InfrequentValueEncoder def test_infrequent_value_encoder_1(): ive = InfrequentValueEncoder() assert ive is not None def test_infrequent_value_encoder_2(): df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) ive = InfrequentValueEncoder(thrshld=1, str_rpl='ifq') encoded = ive.fit_transform(df) expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'ifq']}) assert expected.equals(encoded) def test_infrequent_value_encoder_3(): df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) ive = InfrequentValueEncoder(thrshld=0, str_rpl='ifq') encoded = ive.fit_transform(df) expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) assert expected.equals(encoded) def test_infrequent_value_encoder_4(): df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) ive = InfrequentValueEncoder(thrshld=0, str_rpl='ifq') encoded = ive.fit_transform(df) expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) assert expected.equals(encoded)
# pylint: disable=missing-docstring, invalid-name, import-error import pandas as pd from mltils.encoders import InfrequentValueEncoder def test_infrequent_value_encoder_1(): ive = InfrequentValueEncoder() assert ive is not None def test_infrequent_value_encoder_2(): df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) ive = InfrequentValueEncoder(thrshld=1, str_rpl='ifq') encoded = ive.fit_transform(df) expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'ifq']}) assert expected.equals(encoded) Add more unit tests for InfrequentValueEncoder# pylint: disable=missing-docstring, invalid-name, import-error import pandas as pd from mltils.encoders import InfrequentValueEncoder def test_infrequent_value_encoder_1(): ive = InfrequentValueEncoder() assert ive is not None def test_infrequent_value_encoder_2(): df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) ive = InfrequentValueEncoder(thrshld=1, str_rpl='ifq') encoded = ive.fit_transform(df) expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'ifq']}) assert expected.equals(encoded) def test_infrequent_value_encoder_3(): df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) ive = InfrequentValueEncoder(thrshld=0, str_rpl='ifq') encoded = ive.fit_transform(df) expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) assert expected.equals(encoded) def test_infrequent_value_encoder_4(): df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) ive = InfrequentValueEncoder(thrshld=0, str_rpl='ifq') encoded = ive.fit_transform(df) expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) assert expected.equals(encoded)
<commit_before># pylint: disable=missing-docstring, invalid-name, import-error import pandas as pd from mltils.encoders import InfrequentValueEncoder def test_infrequent_value_encoder_1(): ive = InfrequentValueEncoder() assert ive is not None def test_infrequent_value_encoder_2(): df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) ive = InfrequentValueEncoder(thrshld=1, str_rpl='ifq') encoded = ive.fit_transform(df) expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'ifq']}) assert expected.equals(encoded) <commit_msg>Add more unit tests for InfrequentValueEncoder<commit_after># pylint: disable=missing-docstring, invalid-name, import-error import pandas as pd from mltils.encoders import InfrequentValueEncoder def test_infrequent_value_encoder_1(): ive = InfrequentValueEncoder() assert ive is not None def test_infrequent_value_encoder_2(): df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) ive = InfrequentValueEncoder(thrshld=1, str_rpl='ifq') encoded = ive.fit_transform(df) expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'ifq']}) assert expected.equals(encoded) def test_infrequent_value_encoder_3(): df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) ive = InfrequentValueEncoder(thrshld=0, str_rpl='ifq') encoded = ive.fit_transform(df) expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) assert expected.equals(encoded) def test_infrequent_value_encoder_4(): df = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) ive = InfrequentValueEncoder(thrshld=0, str_rpl='ifq') encoded = ive.fit_transform(df) expected = pd.DataFrame({'A': ['a', 'a', 'b', 'b', 'c']}) assert expected.equals(encoded)
85698cd291753a9ef352250e03a77b14b3f1f9ab
steam/d2.py
steam/d2.py
""" Module for reading DOTA 2 data using the Steam API Copyright (c) 2010, Anthony Garcia <lagg@lavabit.com> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ import items class backpack(items.backpack): _app_id = "570" def __init__(self, sid = None, schema = None): if not schema: schema = item_schema() items.backpack.__init__(self, sid, schema) class item_schema(items.schema): _app_id = "570" _class_map = items.MapDict([ ]) def __init__(self, lang = None): items.schema.__init__(self, lang)
""" Module for reading DOTA 2 data using the Steam API Copyright (c) 2010, Anthony Garcia <lagg@lavabit.com> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ import items class backpack(items.backpack): _app_id = "816" def __init__(self, sid = None, schema = None): if not schema: schema = item_schema() items.backpack.__init__(self, sid, schema) class item_schema(items.schema): _app_id = "816" _class_map = items.MapDict([ ]) def __init__(self, lang = None): items.schema.__init__(self, lang)
Use potential true app ID for D2
Use potential true app ID for D2
Python
isc
miedzinski/steamodd,Lagg/steamodd
""" Module for reading DOTA 2 data using the Steam API Copyright (c) 2010, Anthony Garcia <lagg@lavabit.com> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ import items class backpack(items.backpack): _app_id = "570" def __init__(self, sid = None, schema = None): if not schema: schema = item_schema() items.backpack.__init__(self, sid, schema) class item_schema(items.schema): _app_id = "570" _class_map = items.MapDict([ ]) def __init__(self, lang = None): items.schema.__init__(self, lang) Use potential true app ID for D2
""" Module for reading DOTA 2 data using the Steam API Copyright (c) 2010, Anthony Garcia <lagg@lavabit.com> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ import items class backpack(items.backpack): _app_id = "816" def __init__(self, sid = None, schema = None): if not schema: schema = item_schema() items.backpack.__init__(self, sid, schema) class item_schema(items.schema): _app_id = "816" _class_map = items.MapDict([ ]) def __init__(self, lang = None): items.schema.__init__(self, lang)
<commit_before>""" Module for reading DOTA 2 data using the Steam API Copyright (c) 2010, Anthony Garcia <lagg@lavabit.com> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ import items class backpack(items.backpack): _app_id = "570" def __init__(self, sid = None, schema = None): if not schema: schema = item_schema() items.backpack.__init__(self, sid, schema) class item_schema(items.schema): _app_id = "570" _class_map = items.MapDict([ ]) def __init__(self, lang = None): items.schema.__init__(self, lang) <commit_msg>Use potential true app ID for D2<commit_after>
""" Module for reading DOTA 2 data using the Steam API Copyright (c) 2010, Anthony Garcia <lagg@lavabit.com> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ import items class backpack(items.backpack): _app_id = "816" def __init__(self, sid = None, schema = None): if not schema: schema = item_schema() items.backpack.__init__(self, sid, schema) class item_schema(items.schema): _app_id = "816" _class_map = items.MapDict([ ]) def __init__(self, lang = None): items.schema.__init__(self, lang)
""" Module for reading DOTA 2 data using the Steam API Copyright (c) 2010, Anthony Garcia <lagg@lavabit.com> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ import items class backpack(items.backpack): _app_id = "570" def __init__(self, sid = None, schema = None): if not schema: schema = item_schema() items.backpack.__init__(self, sid, schema) class item_schema(items.schema): _app_id = "570" _class_map = items.MapDict([ ]) def __init__(self, lang = None): items.schema.__init__(self, lang) Use potential true app ID for D2""" Module for reading DOTA 2 data using the Steam API Copyright (c) 2010, Anthony Garcia <lagg@lavabit.com> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ import items class backpack(items.backpack): _app_id = "816" def __init__(self, sid = None, schema = None): if not schema: schema = item_schema() items.backpack.__init__(self, sid, schema) class item_schema(items.schema): _app_id = "816" _class_map = items.MapDict([ ]) def __init__(self, lang = None): items.schema.__init__(self, lang)
<commit_before>""" Module for reading DOTA 2 data using the Steam API Copyright (c) 2010, Anthony Garcia <lagg@lavabit.com> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ import items class backpack(items.backpack): _app_id = "570" def __init__(self, sid = None, schema = None): if not schema: schema = item_schema() items.backpack.__init__(self, sid, schema) class item_schema(items.schema): _app_id = "570" _class_map = items.MapDict([ ]) def __init__(self, lang = None): items.schema.__init__(self, lang) <commit_msg>Use potential true app ID for D2<commit_after>""" Module for reading DOTA 2 data using the Steam API Copyright (c) 2010, Anthony Garcia <lagg@lavabit.com> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ import items class backpack(items.backpack): _app_id = "816" def __init__(self, sid = None, schema = None): if not schema: schema = item_schema() items.backpack.__init__(self, sid, schema) class item_schema(items.schema): _app_id = "816" _class_map = items.MapDict([ ]) def __init__(self, lang = None): items.schema.__init__(self, lang)
d879d74aa078ca5a89a7e7cbd1bebe095449411d
snobol/constants.py
snobol/constants.py
# Coefficients for polynomial fit to bolometric correction - color relation coeff_BminusV = [-0.823, 5.027, -13.409, 20.133, -18.096, 9.084, -1.950] coeff_VminusI = [-1.355, 6.262, -2.676, -22.973, 35.524, -15.340] coeff_BminusI = [-1.096, 3.038, -2.246, -0.497, 0.7078, 0.576, -0.713, 0.239, -0.027] # Ranges of validity for polynomial fits min_BminusV = -0.2 max_BminusV = 1.65 min_VminusI = -0.1 max_VminusI = 1.0 min_BminusI = -0.4 max_BminusI = 3.0 # RMS errors in polynomial fits rms_err_BminusV = 0.113 rms_err_VminusI = 0.109 rms_err_BminusI = 0.091 # Zeropoint for use in the calculation of bolometric magnitude mbol_zeropoint = 11.64
"""Constants for use by the bolometric correction routine """ # Coefficients for polynomial fit to bolometric correction - color relation coeff_BminusV = [-0.823, 5.027, -13.409, 20.133, -18.096, 9.084, -1.950] coeff_VminusI = [-1.355, 6.262, -2.676, -22.973, 35.524, -15.340] coeff_BminusI = [-1.096, 3.038, -2.246, -0.497, 0.7078, 0.576, -0.713, 0.239, -0.027] # Ranges of validity for polynomial fits min_BminusV = -0.2 max_BminusV = 1.65 min_VminusI = -0.1 max_VminusI = 1.0 min_BminusI = -0.4 max_BminusI = 3.0 # RMS errors in polynomial fits rms_err_BminusV = 0.113 rms_err_VminusI = 0.109 rms_err_BminusI = 0.091 # Zeropoint for use in the calculation of bolometric magnitude mbol_zeropoint = 11.64
Add documentation string for cosntants module
Add documentation string for cosntants module
Python
mit
JALusk/SNoBoL,JALusk/SNoBoL,JALusk/SuperBoL
# Coefficients for polynomial fit to bolometric correction - color relation coeff_BminusV = [-0.823, 5.027, -13.409, 20.133, -18.096, 9.084, -1.950] coeff_VminusI = [-1.355, 6.262, -2.676, -22.973, 35.524, -15.340] coeff_BminusI = [-1.096, 3.038, -2.246, -0.497, 0.7078, 0.576, -0.713, 0.239, -0.027] # Ranges of validity for polynomial fits min_BminusV = -0.2 max_BminusV = 1.65 min_VminusI = -0.1 max_VminusI = 1.0 min_BminusI = -0.4 max_BminusI = 3.0 # RMS errors in polynomial fits rms_err_BminusV = 0.113 rms_err_VminusI = 0.109 rms_err_BminusI = 0.091 # Zeropoint for use in the calculation of bolometric magnitude mbol_zeropoint = 11.64 Add documentation string for cosntants module
"""Constants for use by the bolometric correction routine """ # Coefficients for polynomial fit to bolometric correction - color relation coeff_BminusV = [-0.823, 5.027, -13.409, 20.133, -18.096, 9.084, -1.950] coeff_VminusI = [-1.355, 6.262, -2.676, -22.973, 35.524, -15.340] coeff_BminusI = [-1.096, 3.038, -2.246, -0.497, 0.7078, 0.576, -0.713, 0.239, -0.027] # Ranges of validity for polynomial fits min_BminusV = -0.2 max_BminusV = 1.65 min_VminusI = -0.1 max_VminusI = 1.0 min_BminusI = -0.4 max_BminusI = 3.0 # RMS errors in polynomial fits rms_err_BminusV = 0.113 rms_err_VminusI = 0.109 rms_err_BminusI = 0.091 # Zeropoint for use in the calculation of bolometric magnitude mbol_zeropoint = 11.64
<commit_before># Coefficients for polynomial fit to bolometric correction - color relation coeff_BminusV = [-0.823, 5.027, -13.409, 20.133, -18.096, 9.084, -1.950] coeff_VminusI = [-1.355, 6.262, -2.676, -22.973, 35.524, -15.340] coeff_BminusI = [-1.096, 3.038, -2.246, -0.497, 0.7078, 0.576, -0.713, 0.239, -0.027] # Ranges of validity for polynomial fits min_BminusV = -0.2 max_BminusV = 1.65 min_VminusI = -0.1 max_VminusI = 1.0 min_BminusI = -0.4 max_BminusI = 3.0 # RMS errors in polynomial fits rms_err_BminusV = 0.113 rms_err_VminusI = 0.109 rms_err_BminusI = 0.091 # Zeropoint for use in the calculation of bolometric magnitude mbol_zeropoint = 11.64 <commit_msg>Add documentation string for cosntants module<commit_after>
"""Constants for use by the bolometric correction routine """ # Coefficients for polynomial fit to bolometric correction - color relation coeff_BminusV = [-0.823, 5.027, -13.409, 20.133, -18.096, 9.084, -1.950] coeff_VminusI = [-1.355, 6.262, -2.676, -22.973, 35.524, -15.340] coeff_BminusI = [-1.096, 3.038, -2.246, -0.497, 0.7078, 0.576, -0.713, 0.239, -0.027] # Ranges of validity for polynomial fits min_BminusV = -0.2 max_BminusV = 1.65 min_VminusI = -0.1 max_VminusI = 1.0 min_BminusI = -0.4 max_BminusI = 3.0 # RMS errors in polynomial fits rms_err_BminusV = 0.113 rms_err_VminusI = 0.109 rms_err_BminusI = 0.091 # Zeropoint for use in the calculation of bolometric magnitude mbol_zeropoint = 11.64
# Coefficients for polynomial fit to bolometric correction - color relation coeff_BminusV = [-0.823, 5.027, -13.409, 20.133, -18.096, 9.084, -1.950] coeff_VminusI = [-1.355, 6.262, -2.676, -22.973, 35.524, -15.340] coeff_BminusI = [-1.096, 3.038, -2.246, -0.497, 0.7078, 0.576, -0.713, 0.239, -0.027] # Ranges of validity for polynomial fits min_BminusV = -0.2 max_BminusV = 1.65 min_VminusI = -0.1 max_VminusI = 1.0 min_BminusI = -0.4 max_BminusI = 3.0 # RMS errors in polynomial fits rms_err_BminusV = 0.113 rms_err_VminusI = 0.109 rms_err_BminusI = 0.091 # Zeropoint for use in the calculation of bolometric magnitude mbol_zeropoint = 11.64 Add documentation string for cosntants module"""Constants for use by the bolometric correction routine """ # Coefficients for polynomial fit to bolometric correction - color relation coeff_BminusV = [-0.823, 5.027, -13.409, 20.133, -18.096, 9.084, -1.950] coeff_VminusI = [-1.355, 6.262, -2.676, -22.973, 35.524, -15.340] coeff_BminusI = [-1.096, 3.038, -2.246, -0.497, 0.7078, 0.576, -0.713, 0.239, -0.027] # Ranges of validity for polynomial fits min_BminusV = -0.2 max_BminusV = 1.65 min_VminusI = -0.1 max_VminusI = 1.0 min_BminusI = -0.4 max_BminusI = 3.0 # RMS errors in polynomial fits rms_err_BminusV = 0.113 rms_err_VminusI = 0.109 rms_err_BminusI = 0.091 # Zeropoint for use in the calculation of bolometric magnitude mbol_zeropoint = 11.64
<commit_before># Coefficients for polynomial fit to bolometric correction - color relation coeff_BminusV = [-0.823, 5.027, -13.409, 20.133, -18.096, 9.084, -1.950] coeff_VminusI = [-1.355, 6.262, -2.676, -22.973, 35.524, -15.340] coeff_BminusI = [-1.096, 3.038, -2.246, -0.497, 0.7078, 0.576, -0.713, 0.239, -0.027] # Ranges of validity for polynomial fits min_BminusV = -0.2 max_BminusV = 1.65 min_VminusI = -0.1 max_VminusI = 1.0 min_BminusI = -0.4 max_BminusI = 3.0 # RMS errors in polynomial fits rms_err_BminusV = 0.113 rms_err_VminusI = 0.109 rms_err_BminusI = 0.091 # Zeropoint for use in the calculation of bolometric magnitude mbol_zeropoint = 11.64 <commit_msg>Add documentation string for cosntants module<commit_after>"""Constants for use by the bolometric correction routine """ # Coefficients for polynomial fit to bolometric correction - color relation coeff_BminusV = [-0.823, 5.027, -13.409, 20.133, -18.096, 9.084, -1.950] coeff_VminusI = [-1.355, 6.262, -2.676, -22.973, 35.524, -15.340] coeff_BminusI = [-1.096, 3.038, -2.246, -0.497, 0.7078, 0.576, -0.713, 0.239, -0.027] # Ranges of validity for polynomial fits min_BminusV = -0.2 max_BminusV = 1.65 min_VminusI = -0.1 max_VminusI = 1.0 min_BminusI = -0.4 max_BminusI = 3.0 # RMS errors in polynomial fits rms_err_BminusV = 0.113 rms_err_VminusI = 0.109 rms_err_BminusI = 0.091 # Zeropoint for use in the calculation of bolometric magnitude mbol_zeropoint = 11.64
d2e120606d2a6e817f0c20f55dcc4296807f19df
tempdirs.py
tempdirs.py
import functools import tempfile import shutil class makedirs(object): def __init__(self, num): self._num = num def __call__(self, fn): @functools.wraps(fn) def wrapper(*args, **kwargs): def manager(): try: dirs = [ tempfile.mkdtemp() for i in xrange(self._num) ] extra_args = list(args) extra_args += dirs fn(*extra_args, **kwargs) finally: for dir_ in dirs: try: shutil.rmtree(dir_) except OSError, e: # It's OK if dir doesn't exist if e.errno != 2: raise return manager() return wrapper
import functools import tempfile import shutil class makedirs(object): def __init__(self, num=1): self._num = num def __call__(self, fn): @functools.wraps(fn) def wrapper(*args, **kwargs): def manager(): try: dirs = [ tempfile.mkdtemp() for i in xrange(self._num) ] extra_args = list(args) extra_args += dirs fn(*extra_args, **kwargs) finally: for dir_ in dirs: try: shutil.rmtree(dir_) except OSError, e: # It's OK if dir doesn't exist if e.errno != 2: raise return manager() return wrapper
Create 1 temp directory if no number is given
Create 1 temp directory if no number is given
Python
mit
thelinuxkid/tempdirs
import functools import tempfile import shutil class makedirs(object): def __init__(self, num): self._num = num def __call__(self, fn): @functools.wraps(fn) def wrapper(*args, **kwargs): def manager(): try: dirs = [ tempfile.mkdtemp() for i in xrange(self._num) ] extra_args = list(args) extra_args += dirs fn(*extra_args, **kwargs) finally: for dir_ in dirs: try: shutil.rmtree(dir_) except OSError, e: # It's OK if dir doesn't exist if e.errno != 2: raise return manager() return wrapper Create 1 temp directory if no number is given
import functools import tempfile import shutil class makedirs(object): def __init__(self, num=1): self._num = num def __call__(self, fn): @functools.wraps(fn) def wrapper(*args, **kwargs): def manager(): try: dirs = [ tempfile.mkdtemp() for i in xrange(self._num) ] extra_args = list(args) extra_args += dirs fn(*extra_args, **kwargs) finally: for dir_ in dirs: try: shutil.rmtree(dir_) except OSError, e: # It's OK if dir doesn't exist if e.errno != 2: raise return manager() return wrapper
<commit_before>import functools import tempfile import shutil class makedirs(object): def __init__(self, num): self._num = num def __call__(self, fn): @functools.wraps(fn) def wrapper(*args, **kwargs): def manager(): try: dirs = [ tempfile.mkdtemp() for i in xrange(self._num) ] extra_args = list(args) extra_args += dirs fn(*extra_args, **kwargs) finally: for dir_ in dirs: try: shutil.rmtree(dir_) except OSError, e: # It's OK if dir doesn't exist if e.errno != 2: raise return manager() return wrapper <commit_msg>Create 1 temp directory if no number is given<commit_after>
import functools import tempfile import shutil class makedirs(object): def __init__(self, num=1): self._num = num def __call__(self, fn): @functools.wraps(fn) def wrapper(*args, **kwargs): def manager(): try: dirs = [ tempfile.mkdtemp() for i in xrange(self._num) ] extra_args = list(args) extra_args += dirs fn(*extra_args, **kwargs) finally: for dir_ in dirs: try: shutil.rmtree(dir_) except OSError, e: # It's OK if dir doesn't exist if e.errno != 2: raise return manager() return wrapper
import functools import tempfile import shutil class makedirs(object): def __init__(self, num): self._num = num def __call__(self, fn): @functools.wraps(fn) def wrapper(*args, **kwargs): def manager(): try: dirs = [ tempfile.mkdtemp() for i in xrange(self._num) ] extra_args = list(args) extra_args += dirs fn(*extra_args, **kwargs) finally: for dir_ in dirs: try: shutil.rmtree(dir_) except OSError, e: # It's OK if dir doesn't exist if e.errno != 2: raise return manager() return wrapper Create 1 temp directory if no number is givenimport functools import tempfile import shutil class makedirs(object): def __init__(self, num=1): self._num = num def __call__(self, fn): @functools.wraps(fn) def wrapper(*args, **kwargs): def manager(): try: dirs = [ tempfile.mkdtemp() for i in xrange(self._num) ] extra_args = list(args) extra_args += dirs fn(*extra_args, **kwargs) finally: for dir_ in dirs: try: shutil.rmtree(dir_) except OSError, e: # It's OK if dir doesn't exist if e.errno != 2: raise return manager() return wrapper
<commit_before>import functools import tempfile import shutil class makedirs(object): def __init__(self, num): self._num = num def __call__(self, fn): @functools.wraps(fn) def wrapper(*args, **kwargs): def manager(): try: dirs = [ tempfile.mkdtemp() for i in xrange(self._num) ] extra_args = list(args) extra_args += dirs fn(*extra_args, **kwargs) finally: for dir_ in dirs: try: shutil.rmtree(dir_) except OSError, e: # It's OK if dir doesn't exist if e.errno != 2: raise return manager() return wrapper <commit_msg>Create 1 temp directory if no number is given<commit_after>import functools import tempfile import shutil class makedirs(object): def __init__(self, num=1): self._num = num def __call__(self, fn): @functools.wraps(fn) def wrapper(*args, **kwargs): def manager(): try: dirs = [ tempfile.mkdtemp() for i in xrange(self._num) ] extra_args = list(args) extra_args += dirs fn(*extra_args, **kwargs) finally: for dir_ in dirs: try: shutil.rmtree(dir_) except OSError, e: # It's OK if dir doesn't exist if e.errno != 2: raise return manager() return wrapper
07f4d284df18c1e1be7ea9ff490fa14c1974b215
testFile.py
testFile.py
__author__ = 'adrie_000' p = bytes('HELLO') quit('FINISHED') print 'pHELLO'
__author__ = 'adrie_000' p = bytes('HELLO') quit('FINISHED') print 'pHELLO2'
Add features : - Restart software in case of accidental unplug-replug - Minor bug fixes
Add features : - Restart software in case of accidental unplug-replug - Minor bug fixes
Python
apache-2.0
adrien-bellaiche/ia-cdf-rob-2015
__author__ = 'adrie_000' p = bytes('HELLO') quit('FINISHED') print 'pHELLO' Add features : - Restart software in case of accidental unplug-replug - Minor bug fixes
__author__ = 'adrie_000' p = bytes('HELLO') quit('FINISHED') print 'pHELLO2'
<commit_before>__author__ = 'adrie_000' p = bytes('HELLO') quit('FINISHED') print 'pHELLO' <commit_msg>Add features : - Restart software in case of accidental unplug-replug - Minor bug fixes<commit_after>
__author__ = 'adrie_000' p = bytes('HELLO') quit('FINISHED') print 'pHELLO2'
__author__ = 'adrie_000' p = bytes('HELLO') quit('FINISHED') print 'pHELLO' Add features : - Restart software in case of accidental unplug-replug - Minor bug fixes__author__ = 'adrie_000' p = bytes('HELLO') quit('FINISHED') print 'pHELLO2'
<commit_before>__author__ = 'adrie_000' p = bytes('HELLO') quit('FINISHED') print 'pHELLO' <commit_msg>Add features : - Restart software in case of accidental unplug-replug - Minor bug fixes<commit_after>__author__ = 'adrie_000' p = bytes('HELLO') quit('FINISHED') print 'pHELLO2'
39bf1013c5b2b4a18be6de3a3f2002908bf36014
test/all.py
test/all.py
#! /usr/bin/env python ######################################################################## # SimpleFIX # Copyright (C) 2016, David Arnold. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # ######################################################################## import unittest from test_message import MessageTests from test_parser import ParserTests if __name__ == "__main__": unittest.main()
#! /usr/bin/env python ######################################################################## # SimpleFIX # Copyright (C) 2016, David Arnold. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # ######################################################################## import unittest from test_init import InitTests from test_message import MessageTests from test_parser import ParserTests if __name__ == "__main__": unittest.main()
Add init tests to CI.
Add init tests to CI.
Python
mit
da4089/simplefix
#! /usr/bin/env python ######################################################################## # SimpleFIX # Copyright (C) 2016, David Arnold. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # ######################################################################## import unittest from test_message import MessageTests from test_parser import ParserTests if __name__ == "__main__": unittest.main() Add init tests to CI.
#! /usr/bin/env python ######################################################################## # SimpleFIX # Copyright (C) 2016, David Arnold. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # ######################################################################## import unittest from test_init import InitTests from test_message import MessageTests from test_parser import ParserTests if __name__ == "__main__": unittest.main()
<commit_before>#! /usr/bin/env python ######################################################################## # SimpleFIX # Copyright (C) 2016, David Arnold. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # ######################################################################## import unittest from test_message import MessageTests from test_parser import ParserTests if __name__ == "__main__": unittest.main() <commit_msg>Add init tests to CI.<commit_after>
#! /usr/bin/env python ######################################################################## # SimpleFIX # Copyright (C) 2016, David Arnold. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # ######################################################################## import unittest from test_init import InitTests from test_message import MessageTests from test_parser import ParserTests if __name__ == "__main__": unittest.main()
#! /usr/bin/env python ######################################################################## # SimpleFIX # Copyright (C) 2016, David Arnold. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # ######################################################################## import unittest from test_message import MessageTests from test_parser import ParserTests if __name__ == "__main__": unittest.main() Add init tests to CI.#! /usr/bin/env python ######################################################################## # SimpleFIX # Copyright (C) 2016, David Arnold. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # ######################################################################## import unittest from test_init import InitTests from test_message import MessageTests from test_parser import ParserTests if __name__ == "__main__": unittest.main()
<commit_before>#! /usr/bin/env python ######################################################################## # SimpleFIX # Copyright (C) 2016, David Arnold. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # ######################################################################## import unittest from test_message import MessageTests from test_parser import ParserTests if __name__ == "__main__": unittest.main() <commit_msg>Add init tests to CI.<commit_after>#! /usr/bin/env python ######################################################################## # SimpleFIX # Copyright (C) 2016, David Arnold. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # ######################################################################## import unittest from test_init import InitTests from test_message import MessageTests from test_parser import ParserTests if __name__ == "__main__": unittest.main()
86a44c855ebc84d422b2338090f4ca6d0d01cee5
cf_predict/__init__.py
cf_predict/__init__.py
import sys from flask import Flask from .config import config from .api import api_bp __project__ = 'cf-predict' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__) PYTHON_VERSION = 3, 4 if sys.version_info < PYTHON_VERSION: # pragma: no cover (manual test) sys.exit("Python {}.{}+ is required.".format(*PYTHON_VERSION)) def create_app(config_name): """Flask application factory.""" app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) app.register_blueprint(api_bp) return app
import sys from flask import Flask from mockredis import MockRedis from flask_redis import FlaskRedis from .config import config from .api import api_bp __project__ = 'cf-predict' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__) PYTHON_VERSION = 3, 4 if sys.version_info < PYTHON_VERSION: # pragma: no cover (manual test) sys.exit("Python {}.{}+ is required.".format(*PYTHON_VERSION)) class MockRedisWrapper(MockRedis): """A wrapper to add the `from_url` classmethod.""" @classmethod def from_url(cls, *args, **kwargs): return cls() def create_app(config_name): """Flask application factory.""" app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) if app.testing: redis_store = FlaskRedis.from_custom_provider(MockRedisWrapper) else: redis_store = FlaskRedis() redis_store.init_app(app) app.register_blueprint(api_bp) return app
Add Redis client from flask-redis
Add Redis client from flask-redis
Python
mit
ronert/cf-predict,ronert/cf-predict
import sys from flask import Flask from .config import config from .api import api_bp __project__ = 'cf-predict' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__) PYTHON_VERSION = 3, 4 if sys.version_info < PYTHON_VERSION: # pragma: no cover (manual test) sys.exit("Python {}.{}+ is required.".format(*PYTHON_VERSION)) def create_app(config_name): """Flask application factory.""" app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) app.register_blueprint(api_bp) return app Add Redis client from flask-redis
import sys from flask import Flask from mockredis import MockRedis from flask_redis import FlaskRedis from .config import config from .api import api_bp __project__ = 'cf-predict' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__) PYTHON_VERSION = 3, 4 if sys.version_info < PYTHON_VERSION: # pragma: no cover (manual test) sys.exit("Python {}.{}+ is required.".format(*PYTHON_VERSION)) class MockRedisWrapper(MockRedis): """A wrapper to add the `from_url` classmethod.""" @classmethod def from_url(cls, *args, **kwargs): return cls() def create_app(config_name): """Flask application factory.""" app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) if app.testing: redis_store = FlaskRedis.from_custom_provider(MockRedisWrapper) else: redis_store = FlaskRedis() redis_store.init_app(app) app.register_blueprint(api_bp) return app
<commit_before>import sys from flask import Flask from .config import config from .api import api_bp __project__ = 'cf-predict' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__) PYTHON_VERSION = 3, 4 if sys.version_info < PYTHON_VERSION: # pragma: no cover (manual test) sys.exit("Python {}.{}+ is required.".format(*PYTHON_VERSION)) def create_app(config_name): """Flask application factory.""" app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) app.register_blueprint(api_bp) return app <commit_msg>Add Redis client from flask-redis<commit_after>
import sys from flask import Flask from mockredis import MockRedis from flask_redis import FlaskRedis from .config import config from .api import api_bp __project__ = 'cf-predict' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__) PYTHON_VERSION = 3, 4 if sys.version_info < PYTHON_VERSION: # pragma: no cover (manual test) sys.exit("Python {}.{}+ is required.".format(*PYTHON_VERSION)) class MockRedisWrapper(MockRedis): """A wrapper to add the `from_url` classmethod.""" @classmethod def from_url(cls, *args, **kwargs): return cls() def create_app(config_name): """Flask application factory.""" app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) if app.testing: redis_store = FlaskRedis.from_custom_provider(MockRedisWrapper) else: redis_store = FlaskRedis() redis_store.init_app(app) app.register_blueprint(api_bp) return app
import sys from flask import Flask from .config import config from .api import api_bp __project__ = 'cf-predict' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__) PYTHON_VERSION = 3, 4 if sys.version_info < PYTHON_VERSION: # pragma: no cover (manual test) sys.exit("Python {}.{}+ is required.".format(*PYTHON_VERSION)) def create_app(config_name): """Flask application factory.""" app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) app.register_blueprint(api_bp) return app Add Redis client from flask-redisimport sys from flask import Flask from mockredis import MockRedis from flask_redis import FlaskRedis from .config import config from .api import api_bp __project__ = 'cf-predict' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__) PYTHON_VERSION = 3, 4 if sys.version_info < PYTHON_VERSION: # pragma: no cover (manual test) sys.exit("Python {}.{}+ is required.".format(*PYTHON_VERSION)) class MockRedisWrapper(MockRedis): """A wrapper to add the `from_url` classmethod.""" @classmethod def from_url(cls, *args, **kwargs): return cls() def create_app(config_name): """Flask application factory.""" app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) if app.testing: redis_store = FlaskRedis.from_custom_provider(MockRedisWrapper) else: redis_store = FlaskRedis() redis_store.init_app(app) app.register_blueprint(api_bp) return app
<commit_before>import sys from flask import Flask from .config import config from .api import api_bp __project__ = 'cf-predict' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__) PYTHON_VERSION = 3, 4 if sys.version_info < PYTHON_VERSION: # pragma: no cover (manual test) sys.exit("Python {}.{}+ is required.".format(*PYTHON_VERSION)) def create_app(config_name): """Flask application factory.""" app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) app.register_blueprint(api_bp) return app <commit_msg>Add Redis client from flask-redis<commit_after>import sys from flask import Flask from mockredis import MockRedis from flask_redis import FlaskRedis from .config import config from .api import api_bp __project__ = 'cf-predict' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__) PYTHON_VERSION = 3, 4 if sys.version_info < PYTHON_VERSION: # pragma: no cover (manual test) sys.exit("Python {}.{}+ is required.".format(*PYTHON_VERSION)) class MockRedisWrapper(MockRedis): """A wrapper to add the `from_url` classmethod.""" @classmethod def from_url(cls, *args, **kwargs): return cls() def create_app(config_name): """Flask application factory.""" app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) if app.testing: redis_store = FlaskRedis.from_custom_provider(MockRedisWrapper) else: redis_store = FlaskRedis() redis_store.init_app(app) app.register_blueprint(api_bp) return app
c35887025a2127a527862e664d1ef3bb5c4f528a
Constants.py
Constants.py
IRC_numeric_to_name = {"001": "RPL_WELCOME", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "433": "ERR_NICKNAMEINUSE"} CTCP_DELIMITER = chr(1)
IRC_numeric_to_name = {"001": "RPL_WELCOME", "315": "RPL_ENDOFWHO", "352": "RPL_WHOREPLY", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "433": "ERR_NICKNAMEINUSE"} CTCP_DELIMITER = chr(1)
Add some needed IRC numerics
Add some needed IRC numerics
Python
mit
Didero/DideRobot
IRC_numeric_to_name = {"001": "RPL_WELCOME", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "433": "ERR_NICKNAMEINUSE"} CTCP_DELIMITER = chr(1)Add some needed IRC numerics
IRC_numeric_to_name = {"001": "RPL_WELCOME", "315": "RPL_ENDOFWHO", "352": "RPL_WHOREPLY", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "433": "ERR_NICKNAMEINUSE"} CTCP_DELIMITER = chr(1)
<commit_before>IRC_numeric_to_name = {"001": "RPL_WELCOME", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "433": "ERR_NICKNAMEINUSE"} CTCP_DELIMITER = chr(1)<commit_msg>Add some needed IRC numerics<commit_after>
IRC_numeric_to_name = {"001": "RPL_WELCOME", "315": "RPL_ENDOFWHO", "352": "RPL_WHOREPLY", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "433": "ERR_NICKNAMEINUSE"} CTCP_DELIMITER = chr(1)
IRC_numeric_to_name = {"001": "RPL_WELCOME", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "433": "ERR_NICKNAMEINUSE"} CTCP_DELIMITER = chr(1)Add some needed IRC numericsIRC_numeric_to_name = {"001": "RPL_WELCOME", "315": "RPL_ENDOFWHO", "352": "RPL_WHOREPLY", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "433": "ERR_NICKNAMEINUSE"} CTCP_DELIMITER = chr(1)
<commit_before>IRC_numeric_to_name = {"001": "RPL_WELCOME", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "433": "ERR_NICKNAMEINUSE"} CTCP_DELIMITER = chr(1)<commit_msg>Add some needed IRC numerics<commit_after>IRC_numeric_to_name = {"001": "RPL_WELCOME", "315": "RPL_ENDOFWHO", "352": "RPL_WHOREPLY", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "433": "ERR_NICKNAMEINUSE"} CTCP_DELIMITER = chr(1)
b5672d55beb837f21d761f50740b93c5b1e0dc5d
napalm/exceptions.py
napalm/exceptions.py
# Copyright 2015 Spotify AB. All rights reserved. # # The contents of this file are licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with the # License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. class ReplaceConfigException(Exception): pass class MergeConfigException(Exception): pass class SessionLockedException(Exception): pass class CommandTimeoutException(Exception): pass class CommandErrorException(Exception): pass
# Copyright 2015 Spotify AB. All rights reserved. # # The contents of this file are licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with the # License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. class ConnectionException(Exception): pass class ReplaceConfigException(Exception): pass class MergeConfigException(Exception): pass class SessionLockedException(Exception): pass class CommandTimeoutException(Exception): pass class CommandErrorException(Exception): pass
Raise ConnectionException when device unusable
Raise ConnectionException when device unusable
Python
apache-2.0
napalm-automation/napalm-base,napalm-automation/napalm-base,Netflix-Skunkworks/napalm-base,napalm-automation/napalm,Netflix-Skunkworks/napalm-base,spotify/napalm,bewing/napalm-base,spotify/napalm,bewing/napalm-base
# Copyright 2015 Spotify AB. All rights reserved. # # The contents of this file are licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with the # License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. class ReplaceConfigException(Exception): pass class MergeConfigException(Exception): pass class SessionLockedException(Exception): pass class CommandTimeoutException(Exception): pass class CommandErrorException(Exception): pass Raise ConnectionException when device unusable
# Copyright 2015 Spotify AB. All rights reserved. # # The contents of this file are licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with the # License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. class ConnectionException(Exception): pass class ReplaceConfigException(Exception): pass class MergeConfigException(Exception): pass class SessionLockedException(Exception): pass class CommandTimeoutException(Exception): pass class CommandErrorException(Exception): pass
<commit_before># Copyright 2015 Spotify AB. All rights reserved. # # The contents of this file are licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with the # License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. class ReplaceConfigException(Exception): pass class MergeConfigException(Exception): pass class SessionLockedException(Exception): pass class CommandTimeoutException(Exception): pass class CommandErrorException(Exception): pass <commit_msg>Raise ConnectionException when device unusable<commit_after>
# Copyright 2015 Spotify AB. All rights reserved. # # The contents of this file are licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with the # License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. class ConnectionException(Exception): pass class ReplaceConfigException(Exception): pass class MergeConfigException(Exception): pass class SessionLockedException(Exception): pass class CommandTimeoutException(Exception): pass class CommandErrorException(Exception): pass
# Copyright 2015 Spotify AB. All rights reserved. # # The contents of this file are licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with the # License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. class ReplaceConfigException(Exception): pass class MergeConfigException(Exception): pass class SessionLockedException(Exception): pass class CommandTimeoutException(Exception): pass class CommandErrorException(Exception): pass Raise ConnectionException when device unusable# Copyright 2015 Spotify AB. All rights reserved. # # The contents of this file are licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with the # License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. class ConnectionException(Exception): pass class ReplaceConfigException(Exception): pass class MergeConfigException(Exception): pass class SessionLockedException(Exception): pass class CommandTimeoutException(Exception): pass class CommandErrorException(Exception): pass
<commit_before># Copyright 2015 Spotify AB. All rights reserved. # # The contents of this file are licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with the # License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. class ReplaceConfigException(Exception): pass class MergeConfigException(Exception): pass class SessionLockedException(Exception): pass class CommandTimeoutException(Exception): pass class CommandErrorException(Exception): pass <commit_msg>Raise ConnectionException when device unusable<commit_after># Copyright 2015 Spotify AB. All rights reserved. # # The contents of this file are licensed under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with the # License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. class ConnectionException(Exception): pass class ReplaceConfigException(Exception): pass class MergeConfigException(Exception): pass class SessionLockedException(Exception): pass class CommandTimeoutException(Exception): pass class CommandErrorException(Exception): pass
7086b1967c3a3666260e6358c72cb15c74213bea
sunpy/net/tests/test_attr.py
sunpy/net/tests/test_attr.py
# -*- coding: utf-8 -*- # Author: Florian Mayer <florian.mayer@bitsrc.org> from __future__ import absolute_import from sunpy.net import attr def test_dummyattr(): one = attr.DummyAttr() other = attr.ValueAttr({'a': 'b'}) assert (one | other) is other assert (one & other) is other
# -*- coding: utf-8 -*- # Author: Florian Mayer <florian.mayer@bitsrc.org> from __future__ import absolute_import from sunpy.net import attr from sunpy.net.vso import attrs def test_dummyattr(): one = attr.DummyAttr() other = attr.ValueAttr({'a': 'b'}) assert (one | other) is other assert (one & other) is other def test_and_nesting(): a = attr.and_(attrs.Level(0), attr.AttrAnd((attrs.Instrument('EVE'), attrs.Time("2012/1/1", "2012/01/02")))) # Test that the nesting has been removed. assert len(a.attrs) == 3 def test_or_nesting(): a = attr.or_(attrs.Instrument('a'), attr.AttrOr((attrs.Instrument('b'), attrs.Instrument('c')))) # Test that the nesting has been removed. assert len(a.attrs) == 3
Add tests for Attr nesting
Add tests for Attr nesting
Python
bsd-2-clause
dpshelio/sunpy,dpshelio/sunpy,dpshelio/sunpy
# -*- coding: utf-8 -*- # Author: Florian Mayer <florian.mayer@bitsrc.org> from __future__ import absolute_import from sunpy.net import attr def test_dummyattr(): one = attr.DummyAttr() other = attr.ValueAttr({'a': 'b'}) assert (one | other) is other assert (one & other) is other Add tests for Attr nesting
# -*- coding: utf-8 -*- # Author: Florian Mayer <florian.mayer@bitsrc.org> from __future__ import absolute_import from sunpy.net import attr from sunpy.net.vso import attrs def test_dummyattr(): one = attr.DummyAttr() other = attr.ValueAttr({'a': 'b'}) assert (one | other) is other assert (one & other) is other def test_and_nesting(): a = attr.and_(attrs.Level(0), attr.AttrAnd((attrs.Instrument('EVE'), attrs.Time("2012/1/1", "2012/01/02")))) # Test that the nesting has been removed. assert len(a.attrs) == 3 def test_or_nesting(): a = attr.or_(attrs.Instrument('a'), attr.AttrOr((attrs.Instrument('b'), attrs.Instrument('c')))) # Test that the nesting has been removed. assert len(a.attrs) == 3
<commit_before># -*- coding: utf-8 -*- # Author: Florian Mayer <florian.mayer@bitsrc.org> from __future__ import absolute_import from sunpy.net import attr def test_dummyattr(): one = attr.DummyAttr() other = attr.ValueAttr({'a': 'b'}) assert (one | other) is other assert (one & other) is other <commit_msg>Add tests for Attr nesting<commit_after>
# -*- coding: utf-8 -*- # Author: Florian Mayer <florian.mayer@bitsrc.org> from __future__ import absolute_import from sunpy.net import attr from sunpy.net.vso import attrs def test_dummyattr(): one = attr.DummyAttr() other = attr.ValueAttr({'a': 'b'}) assert (one | other) is other assert (one & other) is other def test_and_nesting(): a = attr.and_(attrs.Level(0), attr.AttrAnd((attrs.Instrument('EVE'), attrs.Time("2012/1/1", "2012/01/02")))) # Test that the nesting has been removed. assert len(a.attrs) == 3 def test_or_nesting(): a = attr.or_(attrs.Instrument('a'), attr.AttrOr((attrs.Instrument('b'), attrs.Instrument('c')))) # Test that the nesting has been removed. assert len(a.attrs) == 3
# -*- coding: utf-8 -*- # Author: Florian Mayer <florian.mayer@bitsrc.org> from __future__ import absolute_import from sunpy.net import attr def test_dummyattr(): one = attr.DummyAttr() other = attr.ValueAttr({'a': 'b'}) assert (one | other) is other assert (one & other) is other Add tests for Attr nesting# -*- coding: utf-8 -*- # Author: Florian Mayer <florian.mayer@bitsrc.org> from __future__ import absolute_import from sunpy.net import attr from sunpy.net.vso import attrs def test_dummyattr(): one = attr.DummyAttr() other = attr.ValueAttr({'a': 'b'}) assert (one | other) is other assert (one & other) is other def test_and_nesting(): a = attr.and_(attrs.Level(0), attr.AttrAnd((attrs.Instrument('EVE'), attrs.Time("2012/1/1", "2012/01/02")))) # Test that the nesting has been removed. assert len(a.attrs) == 3 def test_or_nesting(): a = attr.or_(attrs.Instrument('a'), attr.AttrOr((attrs.Instrument('b'), attrs.Instrument('c')))) # Test that the nesting has been removed. assert len(a.attrs) == 3
<commit_before># -*- coding: utf-8 -*- # Author: Florian Mayer <florian.mayer@bitsrc.org> from __future__ import absolute_import from sunpy.net import attr def test_dummyattr(): one = attr.DummyAttr() other = attr.ValueAttr({'a': 'b'}) assert (one | other) is other assert (one & other) is other <commit_msg>Add tests for Attr nesting<commit_after># -*- coding: utf-8 -*- # Author: Florian Mayer <florian.mayer@bitsrc.org> from __future__ import absolute_import from sunpy.net import attr from sunpy.net.vso import attrs def test_dummyattr(): one = attr.DummyAttr() other = attr.ValueAttr({'a': 'b'}) assert (one | other) is other assert (one & other) is other def test_and_nesting(): a = attr.and_(attrs.Level(0), attr.AttrAnd((attrs.Instrument('EVE'), attrs.Time("2012/1/1", "2012/01/02")))) # Test that the nesting has been removed. assert len(a.attrs) == 3 def test_or_nesting(): a = attr.or_(attrs.Instrument('a'), attr.AttrOr((attrs.Instrument('b'), attrs.Instrument('c')))) # Test that the nesting has been removed. assert len(a.attrs) == 3
ecc1713dcd03894cca858910d702c32b0cdf1d42
niceware/__main__.py
niceware/__main__.py
# -*- coding: utf-8 -*- """Utility for generating memorable passwords""" from __future__ import absolute_import from __future__ import print_function import argparse import sys import niceware def main(args=None): if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--count', '-c', type=int, metavar='N', default=1, help="Number of passphrases to generate") parser.add_argument('--length', '-l', type=int, metavar='N', default=16, help="Number of words in each passphrase") args = parser.parse_args(args) size = 2 * args.length for i in range(args.count): passphrase = niceware.generate_passphrase(size) print(' '.join(passphrase)) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- """Utility for generating memorable passwords""" from __future__ import absolute_import from __future__ import print_function import argparse import sys import niceware def main(args=None): if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--count', '-c', type=int, metavar='N', default=1, help="Number of passphrases to generate") parser.add_argument('--length', '-l', type=int, metavar='N', default=8, help="Number of words in each passphrase") args = parser.parse_args(args) size = 2 * args.length for i in range(args.count): passphrase = niceware.generate_passphrase(size) print(' '.join(passphrase)) if __name__ == '__main__': main()
Correct default passphrase length following d9913ce
Correct default passphrase length following d9913ce
Python
mit
moreati/python-niceware
# -*- coding: utf-8 -*- """Utility for generating memorable passwords""" from __future__ import absolute_import from __future__ import print_function import argparse import sys import niceware def main(args=None): if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--count', '-c', type=int, metavar='N', default=1, help="Number of passphrases to generate") parser.add_argument('--length', '-l', type=int, metavar='N', default=16, help="Number of words in each passphrase") args = parser.parse_args(args) size = 2 * args.length for i in range(args.count): passphrase = niceware.generate_passphrase(size) print(' '.join(passphrase)) if __name__ == '__main__': main() Correct default passphrase length following d9913ce
# -*- coding: utf-8 -*- """Utility for generating memorable passwords""" from __future__ import absolute_import from __future__ import print_function import argparse import sys import niceware def main(args=None): if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--count', '-c', type=int, metavar='N', default=1, help="Number of passphrases to generate") parser.add_argument('--length', '-l', type=int, metavar='N', default=8, help="Number of words in each passphrase") args = parser.parse_args(args) size = 2 * args.length for i in range(args.count): passphrase = niceware.generate_passphrase(size) print(' '.join(passphrase)) if __name__ == '__main__': main()
<commit_before># -*- coding: utf-8 -*- """Utility for generating memorable passwords""" from __future__ import absolute_import from __future__ import print_function import argparse import sys import niceware def main(args=None): if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--count', '-c', type=int, metavar='N', default=1, help="Number of passphrases to generate") parser.add_argument('--length', '-l', type=int, metavar='N', default=16, help="Number of words in each passphrase") args = parser.parse_args(args) size = 2 * args.length for i in range(args.count): passphrase = niceware.generate_passphrase(size) print(' '.join(passphrase)) if __name__ == '__main__': main() <commit_msg>Correct default passphrase length following d9913ce<commit_after>
# -*- coding: utf-8 -*- """Utility for generating memorable passwords""" from __future__ import absolute_import from __future__ import print_function import argparse import sys import niceware def main(args=None): if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--count', '-c', type=int, metavar='N', default=1, help="Number of passphrases to generate") parser.add_argument('--length', '-l', type=int, metavar='N', default=8, help="Number of words in each passphrase") args = parser.parse_args(args) size = 2 * args.length for i in range(args.count): passphrase = niceware.generate_passphrase(size) print(' '.join(passphrase)) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- """Utility for generating memorable passwords""" from __future__ import absolute_import from __future__ import print_function import argparse import sys import niceware def main(args=None): if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--count', '-c', type=int, metavar='N', default=1, help="Number of passphrases to generate") parser.add_argument('--length', '-l', type=int, metavar='N', default=16, help="Number of words in each passphrase") args = parser.parse_args(args) size = 2 * args.length for i in range(args.count): passphrase = niceware.generate_passphrase(size) print(' '.join(passphrase)) if __name__ == '__main__': main() Correct default passphrase length following d9913ce# -*- coding: utf-8 -*- """Utility for generating memorable passwords""" from __future__ import absolute_import from __future__ import print_function import argparse import sys import niceware def main(args=None): if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--count', '-c', type=int, metavar='N', default=1, help="Number of passphrases to generate") parser.add_argument('--length', '-l', type=int, metavar='N', default=8, help="Number of words in each passphrase") args = parser.parse_args(args) size = 2 * args.length for i in range(args.count): passphrase = niceware.generate_passphrase(size) print(' '.join(passphrase)) if __name__ == '__main__': main()
<commit_before># -*- coding: utf-8 -*- """Utility for generating memorable passwords""" from __future__ import absolute_import from __future__ import print_function import argparse import sys import niceware def main(args=None): if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--count', '-c', type=int, metavar='N', default=1, help="Number of passphrases to generate") parser.add_argument('--length', '-l', type=int, metavar='N', default=16, help="Number of words in each passphrase") args = parser.parse_args(args) size = 2 * args.length for i in range(args.count): passphrase = niceware.generate_passphrase(size) print(' '.join(passphrase)) if __name__ == '__main__': main() <commit_msg>Correct default passphrase length following d9913ce<commit_after># -*- coding: utf-8 -*- """Utility for generating memorable passwords""" from __future__ import absolute_import from __future__ import print_function import argparse import sys import niceware def main(args=None): if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--count', '-c', type=int, metavar='N', default=1, help="Number of passphrases to generate") parser.add_argument('--length', '-l', type=int, metavar='N', default=8, help="Number of words in each passphrase") args = parser.parse_args(args) size = 2 * args.length for i in range(args.count): passphrase = niceware.generate_passphrase(size) print(' '.join(passphrase)) if __name__ == '__main__': main()
6687d03808c454684c0df3e4b2605f6f86e575b7
exdir/__init__.py
exdir/__init__.py
from . import core from . import plugin_interface from . import plugins from .core import File, validation # TODO remove versioneer from ._version import get_versions __version__ = get_versions()['version'] del get_versions # core.plugin.load_plugins()
from . import core from . import plugin_interface from . import plugins from .core import File, validation, Attribute, Dataset, Group, Raw, Object # TODO remove versioneer from ._version import get_versions __version__ = get_versions()['version'] del get_versions # core.plugin.load_plugins()
Add types to top-level import to simplify porting from h5py
Add types to top-level import to simplify porting from h5py Previously, types like Dataset would have to be imported through exdir.core.Dataset, which exposes an internal implementation detail (everything being in exdir.core). Type-checking by comparing the type to the one imported is common in h5py code, which means porting also is cumbersome whenever a comparison is performed. This changes fixes this issues by exposing the types in the root import.
Python
mit
CINPLA/exdir,CINPLA/exdir,CINPLA/exdir
from . import core from . import plugin_interface from . import plugins from .core import File, validation # TODO remove versioneer from ._version import get_versions __version__ = get_versions()['version'] del get_versions # core.plugin.load_plugins() Add types to top-level import to simplify porting from h5py Previously, types like Dataset would have to be imported through exdir.core.Dataset, which exposes an internal implementation detail (everything being in exdir.core). Type-checking by comparing the type to the one imported is common in h5py code, which means porting also is cumbersome whenever a comparison is performed. This changes fixes this issues by exposing the types in the root import.
from . import core from . import plugin_interface from . import plugins from .core import File, validation, Attribute, Dataset, Group, Raw, Object # TODO remove versioneer from ._version import get_versions __version__ = get_versions()['version'] del get_versions # core.plugin.load_plugins()
<commit_before>from . import core from . import plugin_interface from . import plugins from .core import File, validation # TODO remove versioneer from ._version import get_versions __version__ = get_versions()['version'] del get_versions # core.plugin.load_plugins() <commit_msg>Add types to top-level import to simplify porting from h5py Previously, types like Dataset would have to be imported through exdir.core.Dataset, which exposes an internal implementation detail (everything being in exdir.core). Type-checking by comparing the type to the one imported is common in h5py code, which means porting also is cumbersome whenever a comparison is performed. This changes fixes this issues by exposing the types in the root import.<commit_after>
from . import core from . import plugin_interface from . import plugins from .core import File, validation, Attribute, Dataset, Group, Raw, Object # TODO remove versioneer from ._version import get_versions __version__ = get_versions()['version'] del get_versions # core.plugin.load_plugins()
from . import core from . import plugin_interface from . import plugins from .core import File, validation # TODO remove versioneer from ._version import get_versions __version__ = get_versions()['version'] del get_versions # core.plugin.load_plugins() Add types to top-level import to simplify porting from h5py Previously, types like Dataset would have to be imported through exdir.core.Dataset, which exposes an internal implementation detail (everything being in exdir.core). Type-checking by comparing the type to the one imported is common in h5py code, which means porting also is cumbersome whenever a comparison is performed. This changes fixes this issues by exposing the types in the root import.from . import core from . import plugin_interface from . import plugins from .core import File, validation, Attribute, Dataset, Group, Raw, Object # TODO remove versioneer from ._version import get_versions __version__ = get_versions()['version'] del get_versions # core.plugin.load_plugins()
<commit_before>from . import core from . import plugin_interface from . import plugins from .core import File, validation # TODO remove versioneer from ._version import get_versions __version__ = get_versions()['version'] del get_versions # core.plugin.load_plugins() <commit_msg>Add types to top-level import to simplify porting from h5py Previously, types like Dataset would have to be imported through exdir.core.Dataset, which exposes an internal implementation detail (everything being in exdir.core). Type-checking by comparing the type to the one imported is common in h5py code, which means porting also is cumbersome whenever a comparison is performed. This changes fixes this issues by exposing the types in the root import.<commit_after>from . import core from . import plugin_interface from . import plugins from .core import File, validation, Attribute, Dataset, Group, Raw, Object # TODO remove versioneer from ._version import get_versions __version__ = get_versions()['version'] del get_versions # core.plugin.load_plugins()
af5100682eae8992af0ddfdfc4b8bd8043718bc6
commandment/pki/ssl.py
commandment/pki/ssl.py
import datetime from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa from cryptography import x509 from cryptography.x509 import NameOID, DNSName def generate_self_signed_certificate(cn: str) -> (rsa.RSAPrivateKey, x509.Certificate): """Generate an X.509 Certificate with the given Common Name. Args: cn (string): """ name = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, cn), x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'commandment') ]) private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend(), ) certificate = x509.CertificateBuilder().subject_name( name ).issuer_name( name ).public_key( private_key.public_key() ).serial_number( x509.random_serial_number() ).not_valid_before( datetime.datetime.utcnow() ).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=365) ).add_extension( x509.SubjectAlternativeName( DNSName(cn) ) ).sign(private_key, hashes.SHA256(), default_backend()) return private_key, certificate
import datetime from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa from cryptography import x509 from cryptography.x509 import NameOID, DNSName def generate_self_signed_certificate(cn: str) -> (rsa.RSAPrivateKey, x509.Certificate): """Generate an X.509 Certificate with the given Common Name. Args: cn (string): """ name = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, cn), x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'commandment') ]) private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend(), ) certificate = x509.CertificateBuilder().subject_name( name ).issuer_name( name ).public_key( private_key.public_key() ).serial_number( x509.random_serial_number() ).not_valid_before( datetime.datetime.utcnow() ).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=365) ).add_extension( x509.SubjectAlternativeName([ DNSName(cn) ]), False ).sign(private_key, hashes.SHA256(), default_backend()) return private_key, certificate
Fix invalid statement for SubjectAlternativeName in self signed cert.
Fix invalid statement for SubjectAlternativeName in self signed cert.
Python
mit
mosen/commandment,jessepeterson/commandment,mosen/commandment,mosen/commandment,mosen/commandment,mosen/commandment,jessepeterson/commandment
import datetime from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa from cryptography import x509 from cryptography.x509 import NameOID, DNSName def generate_self_signed_certificate(cn: str) -> (rsa.RSAPrivateKey, x509.Certificate): """Generate an X.509 Certificate with the given Common Name. Args: cn (string): """ name = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, cn), x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'commandment') ]) private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend(), ) certificate = x509.CertificateBuilder().subject_name( name ).issuer_name( name ).public_key( private_key.public_key() ).serial_number( x509.random_serial_number() ).not_valid_before( datetime.datetime.utcnow() ).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=365) ).add_extension( x509.SubjectAlternativeName( DNSName(cn) ) ).sign(private_key, hashes.SHA256(), default_backend()) return private_key, certificate Fix invalid statement for SubjectAlternativeName in self signed cert.
import datetime from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa from cryptography import x509 from cryptography.x509 import NameOID, DNSName def generate_self_signed_certificate(cn: str) -> (rsa.RSAPrivateKey, x509.Certificate): """Generate an X.509 Certificate with the given Common Name. Args: cn (string): """ name = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, cn), x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'commandment') ]) private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend(), ) certificate = x509.CertificateBuilder().subject_name( name ).issuer_name( name ).public_key( private_key.public_key() ).serial_number( x509.random_serial_number() ).not_valid_before( datetime.datetime.utcnow() ).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=365) ).add_extension( x509.SubjectAlternativeName([ DNSName(cn) ]), False ).sign(private_key, hashes.SHA256(), default_backend()) return private_key, certificate
<commit_before>import datetime from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa from cryptography import x509 from cryptography.x509 import NameOID, DNSName def generate_self_signed_certificate(cn: str) -> (rsa.RSAPrivateKey, x509.Certificate): """Generate an X.509 Certificate with the given Common Name. Args: cn (string): """ name = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, cn), x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'commandment') ]) private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend(), ) certificate = x509.CertificateBuilder().subject_name( name ).issuer_name( name ).public_key( private_key.public_key() ).serial_number( x509.random_serial_number() ).not_valid_before( datetime.datetime.utcnow() ).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=365) ).add_extension( x509.SubjectAlternativeName( DNSName(cn) ) ).sign(private_key, hashes.SHA256(), default_backend()) return private_key, certificate <commit_msg>Fix invalid statement for SubjectAlternativeName in self signed cert.<commit_after>
import datetime from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa from cryptography import x509 from cryptography.x509 import NameOID, DNSName def generate_self_signed_certificate(cn: str) -> (rsa.RSAPrivateKey, x509.Certificate): """Generate an X.509 Certificate with the given Common Name. Args: cn (string): """ name = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, cn), x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'commandment') ]) private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend(), ) certificate = x509.CertificateBuilder().subject_name( name ).issuer_name( name ).public_key( private_key.public_key() ).serial_number( x509.random_serial_number() ).not_valid_before( datetime.datetime.utcnow() ).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=365) ).add_extension( x509.SubjectAlternativeName([ DNSName(cn) ]), False ).sign(private_key, hashes.SHA256(), default_backend()) return private_key, certificate
import datetime from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa from cryptography import x509 from cryptography.x509 import NameOID, DNSName def generate_self_signed_certificate(cn: str) -> (rsa.RSAPrivateKey, x509.Certificate): """Generate an X.509 Certificate with the given Common Name. Args: cn (string): """ name = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, cn), x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'commandment') ]) private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend(), ) certificate = x509.CertificateBuilder().subject_name( name ).issuer_name( name ).public_key( private_key.public_key() ).serial_number( x509.random_serial_number() ).not_valid_before( datetime.datetime.utcnow() ).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=365) ).add_extension( x509.SubjectAlternativeName( DNSName(cn) ) ).sign(private_key, hashes.SHA256(), default_backend()) return private_key, certificate Fix invalid statement for SubjectAlternativeName in self signed cert.import datetime from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa from cryptography import x509 from cryptography.x509 import NameOID, DNSName def generate_self_signed_certificate(cn: str) -> (rsa.RSAPrivateKey, x509.Certificate): """Generate an X.509 Certificate with the given Common Name. Args: cn (string): """ name = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, cn), x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'commandment') ]) private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend(), ) certificate = x509.CertificateBuilder().subject_name( name ).issuer_name( name ).public_key( private_key.public_key() ).serial_number( x509.random_serial_number() ).not_valid_before( datetime.datetime.utcnow() ).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=365) ).add_extension( x509.SubjectAlternativeName([ DNSName(cn) ]), False ).sign(private_key, hashes.SHA256(), default_backend()) return private_key, certificate
<commit_before>import datetime from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa from cryptography import x509 from cryptography.x509 import NameOID, DNSName def generate_self_signed_certificate(cn: str) -> (rsa.RSAPrivateKey, x509.Certificate): """Generate an X.509 Certificate with the given Common Name. Args: cn (string): """ name = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, cn), x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'commandment') ]) private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend(), ) certificate = x509.CertificateBuilder().subject_name( name ).issuer_name( name ).public_key( private_key.public_key() ).serial_number( x509.random_serial_number() ).not_valid_before( datetime.datetime.utcnow() ).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=365) ).add_extension( x509.SubjectAlternativeName( DNSName(cn) ) ).sign(private_key, hashes.SHA256(), default_backend()) return private_key, certificate <commit_msg>Fix invalid statement for SubjectAlternativeName in self signed cert.<commit_after>import datetime from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa from cryptography import x509 from cryptography.x509 import NameOID, DNSName def generate_self_signed_certificate(cn: str) -> (rsa.RSAPrivateKey, x509.Certificate): """Generate an X.509 Certificate with the given Common Name. Args: cn (string): """ name = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, cn), x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'commandment') ]) private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend(), ) certificate = x509.CertificateBuilder().subject_name( name ).issuer_name( name ).public_key( private_key.public_key() ).serial_number( x509.random_serial_number() ).not_valid_before( datetime.datetime.utcnow() ).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=365) ).add_extension( x509.SubjectAlternativeName([ DNSName(cn) ]), False ).sign(private_key, hashes.SHA256(), default_backend()) return private_key, certificate
b0699b4683a241449889ee712ae57bb13f0e3eaa
tests/backends/gstreamer.py
tests/backends/gstreamer.py
import unittest from mopidy.backends.gstreamer import GStreamerBackend from tests.backends.basetests import (BasePlaybackControllerTest, BaseCurrentPlaylistControllerTest) class GStreamerCurrentPlaylistHandlerTest(BaseCurrentPlaylistControllerTest, unittest.TestCase): uris = ['file://data/song1.mp3', 'file://data/song2.mp3', 'file://data/song3.mp3', ] backend_class = GStreamerBackend class GStreamerPlaybackControllerTest(BasePlaybackControllerTest, unittest.TestCase): uris = ['file://data/song1.mp3', 'file://data/song2.mp3', 'file://data/song3.mp3', ] backend_class = GStreamerBackend supports_volume = True if __name__ == '__main__': unittest.main()
import unittest import os from mopidy.backends.gstreamer import GStreamerBackend from tests.backends.basetests import (BasePlaybackControllerTest, BaseCurrentPlaylistControllerTest) folder = os.path.dirname(__file__) folder = os.path.join(folder, '..', 'data') folder = os.path.abspath(folder) song = os.path.join(folder, 'song%s.mp3') song = 'file://' + song class GStreamerCurrentPlaylistHandlerTest(BaseCurrentPlaylistControllerTest, unittest.TestCase): uris = [song % i for i in range(1, 4)] backend_class = GStreamerBackend class GStreamerPlaybackControllerTest(BasePlaybackControllerTest, unittest.TestCase): uris = [song % i for i in range(1, 4)] backend_class = GStreamerBackend supports_volume = True if __name__ == '__main__': unittest.main()
Use actuall mp3s for testing
Use actuall mp3s for testing
Python
apache-2.0
dbrgn/mopidy,SuperStarPL/mopidy,kingosticks/mopidy,adamcik/mopidy,hkariti/mopidy,ali/mopidy,jodal/mopidy,jmarsik/mopidy,rawdlite/mopidy,tkem/mopidy,priestd09/mopidy,abarisain/mopidy,pacificIT/mopidy,vrs01/mopidy,diandiankan/mopidy,quartz55/mopidy,mopidy/mopidy,swak/mopidy,liamw9534/mopidy,mokieyue/mopidy,bencevans/mopidy,jcass77/mopidy,jmarsik/mopidy,bencevans/mopidy,bacontext/mopidy,pacificIT/mopidy,bacontext/mopidy,tkem/mopidy,SuperStarPL/mopidy,glogiotatidis/mopidy,quartz55/mopidy,priestd09/mopidy,mokieyue/mopidy,kingosticks/mopidy,pacificIT/mopidy,jcass77/mopidy,tkem/mopidy,diandiankan/mopidy,swak/mopidy,quartz55/mopidy,kingosticks/mopidy,tkem/mopidy,ZenithDK/mopidy,glogiotatidis/mopidy,jcass77/mopidy,woutervanwijk/mopidy,hkariti/mopidy,swak/mopidy,ZenithDK/mopidy,bencevans/mopidy,jmarsik/mopidy,priestd09/mopidy,vrs01/mopidy,bacontext/mopidy,rawdlite/mopidy,vrs01/mopidy,SuperStarPL/mopidy,quartz55/mopidy,dbrgn/mopidy,glogiotatidis/mopidy,adamcik/mopidy,vrs01/mopidy,diandiankan/mopidy,ali/mopidy,bencevans/mopidy,bacontext/mopidy,mokieyue/mopidy,hkariti/mopidy,ali/mopidy,woutervanwijk/mopidy,pacificIT/mopidy,diandiankan/mopidy,abarisain/mopidy,mopidy/mopidy,adamcik/mopidy,glogiotatidis/mopidy,dbrgn/mopidy,jmarsik/mopidy,ZenithDK/mopidy,jodal/mopidy,ZenithDK/mopidy,SuperStarPL/mopidy,swak/mopidy,jodal/mopidy,rawdlite/mopidy,mokieyue/mopidy,rawdlite/mopidy,dbrgn/mopidy,hkariti/mopidy,ali/mopidy,mopidy/mopidy,liamw9534/mopidy
import unittest from mopidy.backends.gstreamer import GStreamerBackend from tests.backends.basetests import (BasePlaybackControllerTest, BaseCurrentPlaylistControllerTest) class GStreamerCurrentPlaylistHandlerTest(BaseCurrentPlaylistControllerTest, unittest.TestCase): uris = ['file://data/song1.mp3', 'file://data/song2.mp3', 'file://data/song3.mp3', ] backend_class = GStreamerBackend class GStreamerPlaybackControllerTest(BasePlaybackControllerTest, unittest.TestCase): uris = ['file://data/song1.mp3', 'file://data/song2.mp3', 'file://data/song3.mp3', ] backend_class = GStreamerBackend supports_volume = True if __name__ == '__main__': unittest.main() Use actuall mp3s for testing
import unittest import os from mopidy.backends.gstreamer import GStreamerBackend from tests.backends.basetests import (BasePlaybackControllerTest, BaseCurrentPlaylistControllerTest) folder = os.path.dirname(__file__) folder = os.path.join(folder, '..', 'data') folder = os.path.abspath(folder) song = os.path.join(folder, 'song%s.mp3') song = 'file://' + song class GStreamerCurrentPlaylistHandlerTest(BaseCurrentPlaylistControllerTest, unittest.TestCase): uris = [song % i for i in range(1, 4)] backend_class = GStreamerBackend class GStreamerPlaybackControllerTest(BasePlaybackControllerTest, unittest.TestCase): uris = [song % i for i in range(1, 4)] backend_class = GStreamerBackend supports_volume = True if __name__ == '__main__': unittest.main()
<commit_before>import unittest from mopidy.backends.gstreamer import GStreamerBackend from tests.backends.basetests import (BasePlaybackControllerTest, BaseCurrentPlaylistControllerTest) class GStreamerCurrentPlaylistHandlerTest(BaseCurrentPlaylistControllerTest, unittest.TestCase): uris = ['file://data/song1.mp3', 'file://data/song2.mp3', 'file://data/song3.mp3', ] backend_class = GStreamerBackend class GStreamerPlaybackControllerTest(BasePlaybackControllerTest, unittest.TestCase): uris = ['file://data/song1.mp3', 'file://data/song2.mp3', 'file://data/song3.mp3', ] backend_class = GStreamerBackend supports_volume = True if __name__ == '__main__': unittest.main() <commit_msg>Use actuall mp3s for testing<commit_after>
import unittest import os from mopidy.backends.gstreamer import GStreamerBackend from tests.backends.basetests import (BasePlaybackControllerTest, BaseCurrentPlaylistControllerTest) folder = os.path.dirname(__file__) folder = os.path.join(folder, '..', 'data') folder = os.path.abspath(folder) song = os.path.join(folder, 'song%s.mp3') song = 'file://' + song class GStreamerCurrentPlaylistHandlerTest(BaseCurrentPlaylistControllerTest, unittest.TestCase): uris = [song % i for i in range(1, 4)] backend_class = GStreamerBackend class GStreamerPlaybackControllerTest(BasePlaybackControllerTest, unittest.TestCase): uris = [song % i for i in range(1, 4)] backend_class = GStreamerBackend supports_volume = True if __name__ == '__main__': unittest.main()
import unittest from mopidy.backends.gstreamer import GStreamerBackend from tests.backends.basetests import (BasePlaybackControllerTest, BaseCurrentPlaylistControllerTest) class GStreamerCurrentPlaylistHandlerTest(BaseCurrentPlaylistControllerTest, unittest.TestCase): uris = ['file://data/song1.mp3', 'file://data/song2.mp3', 'file://data/song3.mp3', ] backend_class = GStreamerBackend class GStreamerPlaybackControllerTest(BasePlaybackControllerTest, unittest.TestCase): uris = ['file://data/song1.mp3', 'file://data/song2.mp3', 'file://data/song3.mp3', ] backend_class = GStreamerBackend supports_volume = True if __name__ == '__main__': unittest.main() Use actuall mp3s for testingimport unittest import os from mopidy.backends.gstreamer import GStreamerBackend from tests.backends.basetests import (BasePlaybackControllerTest, BaseCurrentPlaylistControllerTest) folder = os.path.dirname(__file__) folder = os.path.join(folder, '..', 'data') folder = os.path.abspath(folder) song = os.path.join(folder, 'song%s.mp3') song = 'file://' + song class GStreamerCurrentPlaylistHandlerTest(BaseCurrentPlaylistControllerTest, unittest.TestCase): uris = [song % i for i in range(1, 4)] backend_class = GStreamerBackend class GStreamerPlaybackControllerTest(BasePlaybackControllerTest, unittest.TestCase): uris = [song % i for i in range(1, 4)] backend_class = GStreamerBackend supports_volume = True if __name__ == '__main__': unittest.main()
<commit_before>import unittest from mopidy.backends.gstreamer import GStreamerBackend from tests.backends.basetests import (BasePlaybackControllerTest, BaseCurrentPlaylistControllerTest) class GStreamerCurrentPlaylistHandlerTest(BaseCurrentPlaylistControllerTest, unittest.TestCase): uris = ['file://data/song1.mp3', 'file://data/song2.mp3', 'file://data/song3.mp3', ] backend_class = GStreamerBackend class GStreamerPlaybackControllerTest(BasePlaybackControllerTest, unittest.TestCase): uris = ['file://data/song1.mp3', 'file://data/song2.mp3', 'file://data/song3.mp3', ] backend_class = GStreamerBackend supports_volume = True if __name__ == '__main__': unittest.main() <commit_msg>Use actuall mp3s for testing<commit_after>import unittest import os from mopidy.backends.gstreamer import GStreamerBackend from tests.backends.basetests import (BasePlaybackControllerTest, BaseCurrentPlaylistControllerTest) folder = os.path.dirname(__file__) folder = os.path.join(folder, '..', 'data') folder = os.path.abspath(folder) song = os.path.join(folder, 'song%s.mp3') song = 'file://' + song class GStreamerCurrentPlaylistHandlerTest(BaseCurrentPlaylistControllerTest, unittest.TestCase): uris = [song % i for i in range(1, 4)] backend_class = GStreamerBackend class GStreamerPlaybackControllerTest(BasePlaybackControllerTest, unittest.TestCase): uris = [song % i for i in range(1, 4)] backend_class = GStreamerBackend supports_volume = True if __name__ == '__main__': unittest.main()
430246e54add2ef99fd3d8e87b05ba4b178e0336
tests/test_subgenerators.py
tests/test_subgenerators.py
import pytest from resumeback import send_self from . import CustomError, defer, wait_until_finished, State def test_subgenerator_next(): ts = State() def subgenerator(this): yield defer(this.next) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_send(): ts = State() val = 123 def subgenerator(this): assert (yield defer(this.send, val)) == val ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_throw(): ts = State() def subgenerator(this): with pytest.raises(CustomError): yield defer(this.throw, CustomError) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_repurpose(): ts = State() val = 1234 @send_self def func2(this): assert (yield defer(this.send, val)) == val ts.run = True @send_self def func(this): yield from func2.func(this) wrapper = func() wait_until_finished(wrapper) assert ts.run
import pytest from resumeback import send_self from . import CustomError, defer, wait_until_finished, State def test_subgenerator_next(): ts = State() def subgenerator(this): yield defer(this.next) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_send(): ts = State() val = 123 def subgenerator(this): assert (yield defer(this.send, val)) == val ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_throw(): ts = State() def subgenerator(this): with pytest.raises(CustomError): yield defer(this.throw, CustomError) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_repurpose(): ts = State() val = 1234 @send_self def func2(this): assert (yield defer(this.send, val)) == val return val + 2 @send_self def func(this): ret = yield from func2.func(this) assert ret == val + 2 ts.run = True wrapper = func() wait_until_finished(wrapper) assert ts.run
Use return value in subgenerator test
Use return value in subgenerator test
Python
mit
FichteFoll/resumeback
import pytest from resumeback import send_self from . import CustomError, defer, wait_until_finished, State def test_subgenerator_next(): ts = State() def subgenerator(this): yield defer(this.next) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_send(): ts = State() val = 123 def subgenerator(this): assert (yield defer(this.send, val)) == val ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_throw(): ts = State() def subgenerator(this): with pytest.raises(CustomError): yield defer(this.throw, CustomError) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_repurpose(): ts = State() val = 1234 @send_self def func2(this): assert (yield defer(this.send, val)) == val ts.run = True @send_self def func(this): yield from func2.func(this) wrapper = func() wait_until_finished(wrapper) assert ts.run Use return value in subgenerator test
import pytest from resumeback import send_self from . import CustomError, defer, wait_until_finished, State def test_subgenerator_next(): ts = State() def subgenerator(this): yield defer(this.next) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_send(): ts = State() val = 123 def subgenerator(this): assert (yield defer(this.send, val)) == val ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_throw(): ts = State() def subgenerator(this): with pytest.raises(CustomError): yield defer(this.throw, CustomError) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_repurpose(): ts = State() val = 1234 @send_self def func2(this): assert (yield defer(this.send, val)) == val return val + 2 @send_self def func(this): ret = yield from func2.func(this) assert ret == val + 2 ts.run = True wrapper = func() wait_until_finished(wrapper) assert ts.run
<commit_before>import pytest from resumeback import send_self from . import CustomError, defer, wait_until_finished, State def test_subgenerator_next(): ts = State() def subgenerator(this): yield defer(this.next) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_send(): ts = State() val = 123 def subgenerator(this): assert (yield defer(this.send, val)) == val ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_throw(): ts = State() def subgenerator(this): with pytest.raises(CustomError): yield defer(this.throw, CustomError) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_repurpose(): ts = State() val = 1234 @send_self def func2(this): assert (yield defer(this.send, val)) == val ts.run = True @send_self def func(this): yield from func2.func(this) wrapper = func() wait_until_finished(wrapper) assert ts.run <commit_msg>Use return value in subgenerator test<commit_after>
import pytest from resumeback import send_self from . import CustomError, defer, wait_until_finished, State def test_subgenerator_next(): ts = State() def subgenerator(this): yield defer(this.next) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_send(): ts = State() val = 123 def subgenerator(this): assert (yield defer(this.send, val)) == val ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_throw(): ts = State() def subgenerator(this): with pytest.raises(CustomError): yield defer(this.throw, CustomError) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_repurpose(): ts = State() val = 1234 @send_self def func2(this): assert (yield defer(this.send, val)) == val return val + 2 @send_self def func(this): ret = yield from func2.func(this) assert ret == val + 2 ts.run = True wrapper = func() wait_until_finished(wrapper) assert ts.run
import pytest from resumeback import send_self from . import CustomError, defer, wait_until_finished, State def test_subgenerator_next(): ts = State() def subgenerator(this): yield defer(this.next) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_send(): ts = State() val = 123 def subgenerator(this): assert (yield defer(this.send, val)) == val ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_throw(): ts = State() def subgenerator(this): with pytest.raises(CustomError): yield defer(this.throw, CustomError) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_repurpose(): ts = State() val = 1234 @send_self def func2(this): assert (yield defer(this.send, val)) == val ts.run = True @send_self def func(this): yield from func2.func(this) wrapper = func() wait_until_finished(wrapper) assert ts.run Use return value in subgenerator testimport pytest from resumeback import send_self from . import CustomError, defer, wait_until_finished, State def test_subgenerator_next(): ts = State() def subgenerator(this): yield defer(this.next) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_send(): ts = State() val = 123 def subgenerator(this): assert (yield defer(this.send, val)) == val ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_throw(): ts = State() def subgenerator(this): with pytest.raises(CustomError): yield defer(this.throw, CustomError) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_repurpose(): ts = State() val = 1234 @send_self def func2(this): assert (yield defer(this.send, val)) == val return val + 2 @send_self def func(this): ret = yield from func2.func(this) assert ret == val + 2 ts.run = True wrapper = func() wait_until_finished(wrapper) assert ts.run
<commit_before>import pytest from resumeback import send_self from . import CustomError, defer, wait_until_finished, State def test_subgenerator_next(): ts = State() def subgenerator(this): yield defer(this.next) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_send(): ts = State() val = 123 def subgenerator(this): assert (yield defer(this.send, val)) == val ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_throw(): ts = State() def subgenerator(this): with pytest.raises(CustomError): yield defer(this.throw, CustomError) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_repurpose(): ts = State() val = 1234 @send_self def func2(this): assert (yield defer(this.send, val)) == val ts.run = True @send_self def func(this): yield from func2.func(this) wrapper = func() wait_until_finished(wrapper) assert ts.run <commit_msg>Use return value in subgenerator test<commit_after>import pytest from resumeback import send_self from . import CustomError, defer, wait_until_finished, State def test_subgenerator_next(): ts = State() def subgenerator(this): yield defer(this.next) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_send(): ts = State() val = 123 def subgenerator(this): assert (yield defer(this.send, val)) == val ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_throw(): ts = State() def subgenerator(this): with pytest.raises(CustomError): yield defer(this.throw, CustomError) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_repurpose(): ts = State() val = 1234 @send_self def func2(this): assert (yield defer(this.send, val)) == val return val + 2 @send_self def func(this): ret = yield from func2.func(this) assert ret == val + 2 ts.run = True wrapper = func() wait_until_finished(wrapper) assert ts.run
fea7a2c0e4f4f3da50935d03db4b9e19a0fc477c
shakespearelang/utils.py
shakespearelang/utils.py
def parseinfo_context(parseinfo, context_amount = 3): buffer = parseinfo.buffer context_start_line = max(parseinfo.line - 1 - context_amount, 0) before_context_lines = buffer.get_lines(context_start_line, parseinfo.line - 1) lines = buffer.get_lines(parseinfo.line, parseinfo.endline) after_context_lines = buffer.get_lines(parseinfo.endline + 1, parseinfo.endline + 1 + context_amount) lines[0] = _add_char_at(lines[0], '>', buffer.poscol(parseinfo.pos)) lines[-1] = _add_char_at_before_whitespace(lines[-1], '<', buffer.poscol(parseinfo.endpos) + 1) return "".join(before_context_lines + lines + after_context_lines) def _add_char_at_before_whitespace(string, character, index): while string[index - 1].isspace(): index = index - 1 return _add_char_at(string, character, index) def _add_char_at(string, character, index): return string[:index] + character + string[index:]
def parseinfo_context(parseinfo, context_amount = 3): buffer = parseinfo.buffer context_start_line = max(parseinfo.line - 1 - context_amount, 0) before_context_lines = buffer.get_lines(context_start_line, parseinfo.line - 1) lines = buffer.get_lines(parseinfo.line, parseinfo.endline) after_context_lines = buffer.get_lines(parseinfo.endline + 1, parseinfo.endline + 1 + context_amount) # Must insert later characters first; if you start with earlier characters, they change # the indices for later inserts. lines[-1] = _add_str_at_before_whitespace(lines[-1], '<<', buffer.poscol(parseinfo.endpos)) lines[0] = _add_str_at(lines[0], '>>', buffer.poscol(parseinfo.pos)) return "".join(before_context_lines + lines + after_context_lines) def _add_str_at_before_whitespace(string, character, index): while string[index - 1].isspace(): index = index - 1 return _add_str_at(string, character, index) def _add_str_at(string, character, index): return string[:index] + character + string[index:]
Use ">>" for indicating next event, fix bug with indexing
Use ">>" for indicating next event, fix bug with indexing
Python
mit
zmbc/shakespearelang,zmbc/shakespearelang,zmbc/shakespearelang
def parseinfo_context(parseinfo, context_amount = 3): buffer = parseinfo.buffer context_start_line = max(parseinfo.line - 1 - context_amount, 0) before_context_lines = buffer.get_lines(context_start_line, parseinfo.line - 1) lines = buffer.get_lines(parseinfo.line, parseinfo.endline) after_context_lines = buffer.get_lines(parseinfo.endline + 1, parseinfo.endline + 1 + context_amount) lines[0] = _add_char_at(lines[0], '>', buffer.poscol(parseinfo.pos)) lines[-1] = _add_char_at_before_whitespace(lines[-1], '<', buffer.poscol(parseinfo.endpos) + 1) return "".join(before_context_lines + lines + after_context_lines) def _add_char_at_before_whitespace(string, character, index): while string[index - 1].isspace(): index = index - 1 return _add_char_at(string, character, index) def _add_char_at(string, character, index): return string[:index] + character + string[index:] Use ">>" for indicating next event, fix bug with indexing
def parseinfo_context(parseinfo, context_amount = 3): buffer = parseinfo.buffer context_start_line = max(parseinfo.line - 1 - context_amount, 0) before_context_lines = buffer.get_lines(context_start_line, parseinfo.line - 1) lines = buffer.get_lines(parseinfo.line, parseinfo.endline) after_context_lines = buffer.get_lines(parseinfo.endline + 1, parseinfo.endline + 1 + context_amount) # Must insert later characters first; if you start with earlier characters, they change # the indices for later inserts. lines[-1] = _add_str_at_before_whitespace(lines[-1], '<<', buffer.poscol(parseinfo.endpos)) lines[0] = _add_str_at(lines[0], '>>', buffer.poscol(parseinfo.pos)) return "".join(before_context_lines + lines + after_context_lines) def _add_str_at_before_whitespace(string, character, index): while string[index - 1].isspace(): index = index - 1 return _add_str_at(string, character, index) def _add_str_at(string, character, index): return string[:index] + character + string[index:]
<commit_before>def parseinfo_context(parseinfo, context_amount = 3): buffer = parseinfo.buffer context_start_line = max(parseinfo.line - 1 - context_amount, 0) before_context_lines = buffer.get_lines(context_start_line, parseinfo.line - 1) lines = buffer.get_lines(parseinfo.line, parseinfo.endline) after_context_lines = buffer.get_lines(parseinfo.endline + 1, parseinfo.endline + 1 + context_amount) lines[0] = _add_char_at(lines[0], '>', buffer.poscol(parseinfo.pos)) lines[-1] = _add_char_at_before_whitespace(lines[-1], '<', buffer.poscol(parseinfo.endpos) + 1) return "".join(before_context_lines + lines + after_context_lines) def _add_char_at_before_whitespace(string, character, index): while string[index - 1].isspace(): index = index - 1 return _add_char_at(string, character, index) def _add_char_at(string, character, index): return string[:index] + character + string[index:] <commit_msg>Use ">>" for indicating next event, fix bug with indexing<commit_after>
def parseinfo_context(parseinfo, context_amount = 3): buffer = parseinfo.buffer context_start_line = max(parseinfo.line - 1 - context_amount, 0) before_context_lines = buffer.get_lines(context_start_line, parseinfo.line - 1) lines = buffer.get_lines(parseinfo.line, parseinfo.endline) after_context_lines = buffer.get_lines(parseinfo.endline + 1, parseinfo.endline + 1 + context_amount) # Must insert later characters first; if you start with earlier characters, they change # the indices for later inserts. lines[-1] = _add_str_at_before_whitespace(lines[-1], '<<', buffer.poscol(parseinfo.endpos)) lines[0] = _add_str_at(lines[0], '>>', buffer.poscol(parseinfo.pos)) return "".join(before_context_lines + lines + after_context_lines) def _add_str_at_before_whitespace(string, character, index): while string[index - 1].isspace(): index = index - 1 return _add_str_at(string, character, index) def _add_str_at(string, character, index): return string[:index] + character + string[index:]
def parseinfo_context(parseinfo, context_amount = 3): buffer = parseinfo.buffer context_start_line = max(parseinfo.line - 1 - context_amount, 0) before_context_lines = buffer.get_lines(context_start_line, parseinfo.line - 1) lines = buffer.get_lines(parseinfo.line, parseinfo.endline) after_context_lines = buffer.get_lines(parseinfo.endline + 1, parseinfo.endline + 1 + context_amount) lines[0] = _add_char_at(lines[0], '>', buffer.poscol(parseinfo.pos)) lines[-1] = _add_char_at_before_whitespace(lines[-1], '<', buffer.poscol(parseinfo.endpos) + 1) return "".join(before_context_lines + lines + after_context_lines) def _add_char_at_before_whitespace(string, character, index): while string[index - 1].isspace(): index = index - 1 return _add_char_at(string, character, index) def _add_char_at(string, character, index): return string[:index] + character + string[index:] Use ">>" for indicating next event, fix bug with indexingdef parseinfo_context(parseinfo, context_amount = 3): buffer = parseinfo.buffer context_start_line = max(parseinfo.line - 1 - context_amount, 0) before_context_lines = buffer.get_lines(context_start_line, parseinfo.line - 1) lines = buffer.get_lines(parseinfo.line, parseinfo.endline) after_context_lines = buffer.get_lines(parseinfo.endline + 1, parseinfo.endline + 1 + context_amount) # Must insert later characters first; if you start with earlier characters, they change # the indices for later inserts. lines[-1] = _add_str_at_before_whitespace(lines[-1], '<<', buffer.poscol(parseinfo.endpos)) lines[0] = _add_str_at(lines[0], '>>', buffer.poscol(parseinfo.pos)) return "".join(before_context_lines + lines + after_context_lines) def _add_str_at_before_whitespace(string, character, index): while string[index - 1].isspace(): index = index - 1 return _add_str_at(string, character, index) def _add_str_at(string, character, index): return string[:index] + character + string[index:]
<commit_before>def parseinfo_context(parseinfo, context_amount = 3): buffer = parseinfo.buffer context_start_line = max(parseinfo.line - 1 - context_amount, 0) before_context_lines = buffer.get_lines(context_start_line, parseinfo.line - 1) lines = buffer.get_lines(parseinfo.line, parseinfo.endline) after_context_lines = buffer.get_lines(parseinfo.endline + 1, parseinfo.endline + 1 + context_amount) lines[0] = _add_char_at(lines[0], '>', buffer.poscol(parseinfo.pos)) lines[-1] = _add_char_at_before_whitespace(lines[-1], '<', buffer.poscol(parseinfo.endpos) + 1) return "".join(before_context_lines + lines + after_context_lines) def _add_char_at_before_whitespace(string, character, index): while string[index - 1].isspace(): index = index - 1 return _add_char_at(string, character, index) def _add_char_at(string, character, index): return string[:index] + character + string[index:] <commit_msg>Use ">>" for indicating next event, fix bug with indexing<commit_after>def parseinfo_context(parseinfo, context_amount = 3): buffer = parseinfo.buffer context_start_line = max(parseinfo.line - 1 - context_amount, 0) before_context_lines = buffer.get_lines(context_start_line, parseinfo.line - 1) lines = buffer.get_lines(parseinfo.line, parseinfo.endline) after_context_lines = buffer.get_lines(parseinfo.endline + 1, parseinfo.endline + 1 + context_amount) # Must insert later characters first; if you start with earlier characters, they change # the indices for later inserts. lines[-1] = _add_str_at_before_whitespace(lines[-1], '<<', buffer.poscol(parseinfo.endpos)) lines[0] = _add_str_at(lines[0], '>>', buffer.poscol(parseinfo.pos)) return "".join(before_context_lines + lines + after_context_lines) def _add_str_at_before_whitespace(string, character, index): while string[index - 1].isspace(): index = index - 1 return _add_str_at(string, character, index) def _add_str_at(string, character, index): return string[:index] + character + string[index:]
da097ed41010961cc0814d55d8784787f3ea8a63
skimage/util/arraypad.py
skimage/util/arraypad.py
from __future__ import division, absolute_import, print_function from numpy import pad as numpy_pad def pad(array, pad_width, mode, **kwargs): return numpy_pad(array, pad_width, mode, **kwargs) # Pull function info / docs from NumPy pad.__doc__ = numpy_pad.__doc__
from __future__ import division, absolute_import, print_function import numpy as np def pad(array, pad_width, mode, **kwargs): return np.pad(array, pad_width, mode, **kwargs) # Pull function info / docs from NumPy pad.__doc__ = np.pad.__doc__
Change import structure for doctests
Change import structure for doctests
Python
bsd-3-clause
rjeli/scikit-image,paalge/scikit-image,rjeli/scikit-image,vighneshbirodkar/scikit-image,vighneshbirodkar/scikit-image,vighneshbirodkar/scikit-image,paalge/scikit-image,rjeli/scikit-image,paalge/scikit-image
from __future__ import division, absolute_import, print_function from numpy import pad as numpy_pad def pad(array, pad_width, mode, **kwargs): return numpy_pad(array, pad_width, mode, **kwargs) # Pull function info / docs from NumPy pad.__doc__ = numpy_pad.__doc__ Change import structure for doctests
from __future__ import division, absolute_import, print_function import numpy as np def pad(array, pad_width, mode, **kwargs): return np.pad(array, pad_width, mode, **kwargs) # Pull function info / docs from NumPy pad.__doc__ = np.pad.__doc__
<commit_before>from __future__ import division, absolute_import, print_function from numpy import pad as numpy_pad def pad(array, pad_width, mode, **kwargs): return numpy_pad(array, pad_width, mode, **kwargs) # Pull function info / docs from NumPy pad.__doc__ = numpy_pad.__doc__ <commit_msg>Change import structure for doctests<commit_after>
from __future__ import division, absolute_import, print_function import numpy as np def pad(array, pad_width, mode, **kwargs): return np.pad(array, pad_width, mode, **kwargs) # Pull function info / docs from NumPy pad.__doc__ = np.pad.__doc__
from __future__ import division, absolute_import, print_function from numpy import pad as numpy_pad def pad(array, pad_width, mode, **kwargs): return numpy_pad(array, pad_width, mode, **kwargs) # Pull function info / docs from NumPy pad.__doc__ = numpy_pad.__doc__ Change import structure for doctestsfrom __future__ import division, absolute_import, print_function import numpy as np def pad(array, pad_width, mode, **kwargs): return np.pad(array, pad_width, mode, **kwargs) # Pull function info / docs from NumPy pad.__doc__ = np.pad.__doc__
<commit_before>from __future__ import division, absolute_import, print_function from numpy import pad as numpy_pad def pad(array, pad_width, mode, **kwargs): return numpy_pad(array, pad_width, mode, **kwargs) # Pull function info / docs from NumPy pad.__doc__ = numpy_pad.__doc__ <commit_msg>Change import structure for doctests<commit_after>from __future__ import division, absolute_import, print_function import numpy as np def pad(array, pad_width, mode, **kwargs): return np.pad(array, pad_width, mode, **kwargs) # Pull function info / docs from NumPy pad.__doc__ = np.pad.__doc__
14110deb4d31d27f74d16ff062030ee9dccc221e
multi_schema/middleware.py
multi_schema/middleware.py
""" Middleware to automatically set the schema (namespace). if request.user.is_superuser, then look for a ?schema=XXX and set the schema to that. Otherwise, set the schema to the one associated with the logged in user. """ from models import Schema class SchemaMiddleware: def process_request(self, request): if request.user.is_anonymous(): return None if request.user.is_superuser and '__schema' in request.GET: request.session['schema'] = request.GET['__schema'] if request.user.is_superuser and 'schema' in request.session: Schema.objects.get(pk=request.session['schema']).activate() else: request.user.schema.schema.activate() def process_response(self, request): pass
""" Middleware to automatically set the schema (namespace). if request.user.is_superuser, then look for a ?schema=XXX and set the schema to that. Otherwise, set the schema to the one associated with the logged in user. """ from django.core.exceptions import ObjectDoesNotExist from models import Schema class SchemaMiddleware: def process_request(self, request): if request.user.is_anonymous(): return None if request.user.is_superuser: if '__schema' in request.GET: request.session['schema'] = request.GET['__schema'] if 'schema' in request.session: Schema.objects.get(pk=request.session['schema']).activate() else: try: request.user.schema.schema.activate() except ObjectDoesNotExist: pass def process_template_response(self, request, response): if request.user.is_superuser: response.context_data['schemata'] = Schema.objects.all() response.context_data['selected_schema'] = request.session['schema'] return response
Add some data into the request context. Better handling of missing Schema objects when logging in (should we raise an error?).
Add some data into the request context. Better handling of missing Schema objects when logging in (should we raise an error?).
Python
bsd-3-clause
luzfcb/django-boardinghouse,luzfcb/django-boardinghouse,luzfcb/django-boardinghouse
""" Middleware to automatically set the schema (namespace). if request.user.is_superuser, then look for a ?schema=XXX and set the schema to that. Otherwise, set the schema to the one associated with the logged in user. """ from models import Schema class SchemaMiddleware: def process_request(self, request): if request.user.is_anonymous(): return None if request.user.is_superuser and '__schema' in request.GET: request.session['schema'] = request.GET['__schema'] if request.user.is_superuser and 'schema' in request.session: Schema.objects.get(pk=request.session['schema']).activate() else: request.user.schema.schema.activate() def process_response(self, request): passAdd some data into the request context. Better handling of missing Schema objects when logging in (should we raise an error?).
""" Middleware to automatically set the schema (namespace). if request.user.is_superuser, then look for a ?schema=XXX and set the schema to that. Otherwise, set the schema to the one associated with the logged in user. """ from django.core.exceptions import ObjectDoesNotExist from models import Schema class SchemaMiddleware: def process_request(self, request): if request.user.is_anonymous(): return None if request.user.is_superuser: if '__schema' in request.GET: request.session['schema'] = request.GET['__schema'] if 'schema' in request.session: Schema.objects.get(pk=request.session['schema']).activate() else: try: request.user.schema.schema.activate() except ObjectDoesNotExist: pass def process_template_response(self, request, response): if request.user.is_superuser: response.context_data['schemata'] = Schema.objects.all() response.context_data['selected_schema'] = request.session['schema'] return response
<commit_before>""" Middleware to automatically set the schema (namespace). if request.user.is_superuser, then look for a ?schema=XXX and set the schema to that. Otherwise, set the schema to the one associated with the logged in user. """ from models import Schema class SchemaMiddleware: def process_request(self, request): if request.user.is_anonymous(): return None if request.user.is_superuser and '__schema' in request.GET: request.session['schema'] = request.GET['__schema'] if request.user.is_superuser and 'schema' in request.session: Schema.objects.get(pk=request.session['schema']).activate() else: request.user.schema.schema.activate() def process_response(self, request): pass<commit_msg>Add some data into the request context. Better handling of missing Schema objects when logging in (should we raise an error?).<commit_after>
""" Middleware to automatically set the schema (namespace). if request.user.is_superuser, then look for a ?schema=XXX and set the schema to that. Otherwise, set the schema to the one associated with the logged in user. """ from django.core.exceptions import ObjectDoesNotExist from models import Schema class SchemaMiddleware: def process_request(self, request): if request.user.is_anonymous(): return None if request.user.is_superuser: if '__schema' in request.GET: request.session['schema'] = request.GET['__schema'] if 'schema' in request.session: Schema.objects.get(pk=request.session['schema']).activate() else: try: request.user.schema.schema.activate() except ObjectDoesNotExist: pass def process_template_response(self, request, response): if request.user.is_superuser: response.context_data['schemata'] = Schema.objects.all() response.context_data['selected_schema'] = request.session['schema'] return response
""" Middleware to automatically set the schema (namespace). if request.user.is_superuser, then look for a ?schema=XXX and set the schema to that. Otherwise, set the schema to the one associated with the logged in user. """ from models import Schema class SchemaMiddleware: def process_request(self, request): if request.user.is_anonymous(): return None if request.user.is_superuser and '__schema' in request.GET: request.session['schema'] = request.GET['__schema'] if request.user.is_superuser and 'schema' in request.session: Schema.objects.get(pk=request.session['schema']).activate() else: request.user.schema.schema.activate() def process_response(self, request): passAdd some data into the request context. Better handling of missing Schema objects when logging in (should we raise an error?).""" Middleware to automatically set the schema (namespace). if request.user.is_superuser, then look for a ?schema=XXX and set the schema to that. Otherwise, set the schema to the one associated with the logged in user. """ from django.core.exceptions import ObjectDoesNotExist from models import Schema class SchemaMiddleware: def process_request(self, request): if request.user.is_anonymous(): return None if request.user.is_superuser: if '__schema' in request.GET: request.session['schema'] = request.GET['__schema'] if 'schema' in request.session: Schema.objects.get(pk=request.session['schema']).activate() else: try: request.user.schema.schema.activate() except ObjectDoesNotExist: pass def process_template_response(self, request, response): if request.user.is_superuser: response.context_data['schemata'] = Schema.objects.all() response.context_data['selected_schema'] = request.session['schema'] return response
<commit_before>""" Middleware to automatically set the schema (namespace). if request.user.is_superuser, then look for a ?schema=XXX and set the schema to that. Otherwise, set the schema to the one associated with the logged in user. """ from models import Schema class SchemaMiddleware: def process_request(self, request): if request.user.is_anonymous(): return None if request.user.is_superuser and '__schema' in request.GET: request.session['schema'] = request.GET['__schema'] if request.user.is_superuser and 'schema' in request.session: Schema.objects.get(pk=request.session['schema']).activate() else: request.user.schema.schema.activate() def process_response(self, request): pass<commit_msg>Add some data into the request context. Better handling of missing Schema objects when logging in (should we raise an error?).<commit_after>""" Middleware to automatically set the schema (namespace). if request.user.is_superuser, then look for a ?schema=XXX and set the schema to that. Otherwise, set the schema to the one associated with the logged in user. """ from django.core.exceptions import ObjectDoesNotExist from models import Schema class SchemaMiddleware: def process_request(self, request): if request.user.is_anonymous(): return None if request.user.is_superuser: if '__schema' in request.GET: request.session['schema'] = request.GET['__schema'] if 'schema' in request.session: Schema.objects.get(pk=request.session['schema']).activate() else: try: request.user.schema.schema.activate() except ObjectDoesNotExist: pass def process_template_response(self, request, response): if request.user.is_superuser: response.context_data['schemata'] = Schema.objects.all() response.context_data['selected_schema'] = request.session['schema'] return response
eb90169c2d38244af61e135ed279b8d42f1a8ef5
test/test_sampling.py
test/test_sampling.py
# -*- coding: utf-8 -*- from __future__ import division import sys import pytest from profiling.sampling import SamplingProfiler from profiling.sampling.samplers import ItimerSampler from utils import find_stats, spin def spin_100ms(): spin(0.1) def spin_500ms(): spin(0.5) @pytest.mark.flaky(reruns=10) def test_profiler(): profiler = SamplingProfiler(top_frame=sys._getframe(), sampler=ItimerSampler(0.0001)) with profiler: spin_100ms() spin_500ms() stat1 = find_stats(profiler.stats, 'spin_100ms') stat2 = find_stats(profiler.stats, 'spin_500ms') ratio = stat1.deep_hits / stat2.deep_hits assert 0.8 <= ratio * 5 <= 1.2 # 1:5 expaected, but tolerate (0.8~1.2):5
# -*- coding: utf-8 -*- from __future__ import division import sys import pytest from profiling.sampling import SamplingProfiler from profiling.sampling.samplers import ItimerSampler from utils import find_stats, spin def spin_100ms(): spin(0.1) def spin_500ms(): spin(0.5) @pytest.mark.flaky(reruns=10) def test_profiler(): profiler = SamplingProfiler(top_frame=sys._getframe(), sampler=ItimerSampler(0.0001)) with profiler: spin_100ms() spin_500ms() stat1 = find_stats(profiler.stats, 'spin_100ms') stat2 = find_stats(profiler.stats, 'spin_500ms') ratio = stat1.deep_hits / stat2.deep_hits assert 0.8 <= ratio * 5 <= 1.2 # 1:5 expaected, but tolerate (0.8~1.2):5 def test_not_sampler(): with pytest.raises(TypeError): SamplingProfiler(sampler=123) def test_sample_1_depth(): frame = sys._getframe() while frame.f_back is not None: frame = frame.f_back assert frame.f_back is None profiler = SamplingProfiler() profiler.sample(frame)
Increase test coverage of `profiling.sampling`
Increase test coverage of `profiling.sampling`
Python
bsd-3-clause
sublee/profiling,JeanPaulShapo/profiling,JeanPaulShapo/profiling,what-studio/profiling,sublee/profiling,what-studio/profiling
# -*- coding: utf-8 -*- from __future__ import division import sys import pytest from profiling.sampling import SamplingProfiler from profiling.sampling.samplers import ItimerSampler from utils import find_stats, spin def spin_100ms(): spin(0.1) def spin_500ms(): spin(0.5) @pytest.mark.flaky(reruns=10) def test_profiler(): profiler = SamplingProfiler(top_frame=sys._getframe(), sampler=ItimerSampler(0.0001)) with profiler: spin_100ms() spin_500ms() stat1 = find_stats(profiler.stats, 'spin_100ms') stat2 = find_stats(profiler.stats, 'spin_500ms') ratio = stat1.deep_hits / stat2.deep_hits assert 0.8 <= ratio * 5 <= 1.2 # 1:5 expaected, but tolerate (0.8~1.2):5 Increase test coverage of `profiling.sampling`
# -*- coding: utf-8 -*- from __future__ import division import sys import pytest from profiling.sampling import SamplingProfiler from profiling.sampling.samplers import ItimerSampler from utils import find_stats, spin def spin_100ms(): spin(0.1) def spin_500ms(): spin(0.5) @pytest.mark.flaky(reruns=10) def test_profiler(): profiler = SamplingProfiler(top_frame=sys._getframe(), sampler=ItimerSampler(0.0001)) with profiler: spin_100ms() spin_500ms() stat1 = find_stats(profiler.stats, 'spin_100ms') stat2 = find_stats(profiler.stats, 'spin_500ms') ratio = stat1.deep_hits / stat2.deep_hits assert 0.8 <= ratio * 5 <= 1.2 # 1:5 expaected, but tolerate (0.8~1.2):5 def test_not_sampler(): with pytest.raises(TypeError): SamplingProfiler(sampler=123) def test_sample_1_depth(): frame = sys._getframe() while frame.f_back is not None: frame = frame.f_back assert frame.f_back is None profiler = SamplingProfiler() profiler.sample(frame)
<commit_before># -*- coding: utf-8 -*- from __future__ import division import sys import pytest from profiling.sampling import SamplingProfiler from profiling.sampling.samplers import ItimerSampler from utils import find_stats, spin def spin_100ms(): spin(0.1) def spin_500ms(): spin(0.5) @pytest.mark.flaky(reruns=10) def test_profiler(): profiler = SamplingProfiler(top_frame=sys._getframe(), sampler=ItimerSampler(0.0001)) with profiler: spin_100ms() spin_500ms() stat1 = find_stats(profiler.stats, 'spin_100ms') stat2 = find_stats(profiler.stats, 'spin_500ms') ratio = stat1.deep_hits / stat2.deep_hits assert 0.8 <= ratio * 5 <= 1.2 # 1:5 expaected, but tolerate (0.8~1.2):5 <commit_msg>Increase test coverage of `profiling.sampling`<commit_after>
# -*- coding: utf-8 -*- from __future__ import division import sys import pytest from profiling.sampling import SamplingProfiler from profiling.sampling.samplers import ItimerSampler from utils import find_stats, spin def spin_100ms(): spin(0.1) def spin_500ms(): spin(0.5) @pytest.mark.flaky(reruns=10) def test_profiler(): profiler = SamplingProfiler(top_frame=sys._getframe(), sampler=ItimerSampler(0.0001)) with profiler: spin_100ms() spin_500ms() stat1 = find_stats(profiler.stats, 'spin_100ms') stat2 = find_stats(profiler.stats, 'spin_500ms') ratio = stat1.deep_hits / stat2.deep_hits assert 0.8 <= ratio * 5 <= 1.2 # 1:5 expaected, but tolerate (0.8~1.2):5 def test_not_sampler(): with pytest.raises(TypeError): SamplingProfiler(sampler=123) def test_sample_1_depth(): frame = sys._getframe() while frame.f_back is not None: frame = frame.f_back assert frame.f_back is None profiler = SamplingProfiler() profiler.sample(frame)
# -*- coding: utf-8 -*- from __future__ import division import sys import pytest from profiling.sampling import SamplingProfiler from profiling.sampling.samplers import ItimerSampler from utils import find_stats, spin def spin_100ms(): spin(0.1) def spin_500ms(): spin(0.5) @pytest.mark.flaky(reruns=10) def test_profiler(): profiler = SamplingProfiler(top_frame=sys._getframe(), sampler=ItimerSampler(0.0001)) with profiler: spin_100ms() spin_500ms() stat1 = find_stats(profiler.stats, 'spin_100ms') stat2 = find_stats(profiler.stats, 'spin_500ms') ratio = stat1.deep_hits / stat2.deep_hits assert 0.8 <= ratio * 5 <= 1.2 # 1:5 expaected, but tolerate (0.8~1.2):5 Increase test coverage of `profiling.sampling`# -*- coding: utf-8 -*- from __future__ import division import sys import pytest from profiling.sampling import SamplingProfiler from profiling.sampling.samplers import ItimerSampler from utils import find_stats, spin def spin_100ms(): spin(0.1) def spin_500ms(): spin(0.5) @pytest.mark.flaky(reruns=10) def test_profiler(): profiler = SamplingProfiler(top_frame=sys._getframe(), sampler=ItimerSampler(0.0001)) with profiler: spin_100ms() spin_500ms() stat1 = find_stats(profiler.stats, 'spin_100ms') stat2 = find_stats(profiler.stats, 'spin_500ms') ratio = stat1.deep_hits / stat2.deep_hits assert 0.8 <= ratio * 5 <= 1.2 # 1:5 expaected, but tolerate (0.8~1.2):5 def test_not_sampler(): with pytest.raises(TypeError): SamplingProfiler(sampler=123) def test_sample_1_depth(): frame = sys._getframe() while frame.f_back is not None: frame = frame.f_back assert frame.f_back is None profiler = SamplingProfiler() profiler.sample(frame)
<commit_before># -*- coding: utf-8 -*- from __future__ import division import sys import pytest from profiling.sampling import SamplingProfiler from profiling.sampling.samplers import ItimerSampler from utils import find_stats, spin def spin_100ms(): spin(0.1) def spin_500ms(): spin(0.5) @pytest.mark.flaky(reruns=10) def test_profiler(): profiler = SamplingProfiler(top_frame=sys._getframe(), sampler=ItimerSampler(0.0001)) with profiler: spin_100ms() spin_500ms() stat1 = find_stats(profiler.stats, 'spin_100ms') stat2 = find_stats(profiler.stats, 'spin_500ms') ratio = stat1.deep_hits / stat2.deep_hits assert 0.8 <= ratio * 5 <= 1.2 # 1:5 expaected, but tolerate (0.8~1.2):5 <commit_msg>Increase test coverage of `profiling.sampling`<commit_after># -*- coding: utf-8 -*- from __future__ import division import sys import pytest from profiling.sampling import SamplingProfiler from profiling.sampling.samplers import ItimerSampler from utils import find_stats, spin def spin_100ms(): spin(0.1) def spin_500ms(): spin(0.5) @pytest.mark.flaky(reruns=10) def test_profiler(): profiler = SamplingProfiler(top_frame=sys._getframe(), sampler=ItimerSampler(0.0001)) with profiler: spin_100ms() spin_500ms() stat1 = find_stats(profiler.stats, 'spin_100ms') stat2 = find_stats(profiler.stats, 'spin_500ms') ratio = stat1.deep_hits / stat2.deep_hits assert 0.8 <= ratio * 5 <= 1.2 # 1:5 expaected, but tolerate (0.8~1.2):5 def test_not_sampler(): with pytest.raises(TypeError): SamplingProfiler(sampler=123) def test_sample_1_depth(): frame = sys._getframe() while frame.f_back is not None: frame = frame.f_back assert frame.f_back is None profiler = SamplingProfiler() profiler.sample(frame)
504ae635e08ccf0784db0a0586e8796f5bd360bb
test_chatbot_brain.py
test_chatbot_brain.py
import chatbot_brain def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_lexicon) > 0 def test_compose_response(): bot = chatbot_brain.Chatbot() output = bot.compose_response(input_sent="How are you doing?") assert "," not in output[0] for sentence in output: assert "." not in sentence[:-1] def test_i_filter_random_empty_words(): u"""Assert the returned word is in the lexicon and is not a stop char.""" bot = chatbot_brain.Chatbot() words = [""] assert bot.i_filter_random(words) == u"What a funny thing to say!" # untested methods: # i_filter_random # o_filter_random # _create_chains # _pair_seed # _chain_filters # _filter_recursive
import chatbot_brain stock = u"What a funny thing to say!" def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_lexicon) > 0 def test_compose_response(): bot = chatbot_brain.Chatbot() output = bot.compose_response(input_sent="How are you doing?") assert "," not in output[0] for sentence in output: assert "." not in sentence[:-1] def test_i_filter_random_empty_words(): u"""Assert an empty string is not found in the default lexicon.""" bot = chatbot_brain.Chatbot() words = [""] assert bot.i_filter_random(words) == stock def test_i_filter_random_words_not_in_lexicon(): u"""Assert that if all words are not in lexicon the default is returned.""" bot = chatbot_brain.Chatbot() words = ["moose", "bear", "eagle"] lexicon = {"car": "mercedes", "boat": "sail", "train": "track"} assert bot.i_filter_random(words, lexicon) == stock # untested methods: # i_filter_random # o_filter_random # _create_chains # _pair_seed # _chain_filters # _filter_recursive
Add test_i_filter_random_words_not_in_lexicon() to assert the stock phrase is returned if all the words are not in the lexicon
Add test_i_filter_random_words_not_in_lexicon() to assert the stock phrase is returned if all the words are not in the lexicon
Python
mit
corinnelhh/chatbot,corinnelhh/chatbot
import chatbot_brain def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_lexicon) > 0 def test_compose_response(): bot = chatbot_brain.Chatbot() output = bot.compose_response(input_sent="How are you doing?") assert "," not in output[0] for sentence in output: assert "." not in sentence[:-1] def test_i_filter_random_empty_words(): u"""Assert the returned word is in the lexicon and is not a stop char.""" bot = chatbot_brain.Chatbot() words = [""] assert bot.i_filter_random(words) == u"What a funny thing to say!" # untested methods: # i_filter_random # o_filter_random # _create_chains # _pair_seed # _chain_filters # _filter_recursive Add test_i_filter_random_words_not_in_lexicon() to assert the stock phrase is returned if all the words are not in the lexicon
import chatbot_brain stock = u"What a funny thing to say!" def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_lexicon) > 0 def test_compose_response(): bot = chatbot_brain.Chatbot() output = bot.compose_response(input_sent="How are you doing?") assert "," not in output[0] for sentence in output: assert "." not in sentence[:-1] def test_i_filter_random_empty_words(): u"""Assert an empty string is not found in the default lexicon.""" bot = chatbot_brain.Chatbot() words = [""] assert bot.i_filter_random(words) == stock def test_i_filter_random_words_not_in_lexicon(): u"""Assert that if all words are not in lexicon the default is returned.""" bot = chatbot_brain.Chatbot() words = ["moose", "bear", "eagle"] lexicon = {"car": "mercedes", "boat": "sail", "train": "track"} assert bot.i_filter_random(words, lexicon) == stock # untested methods: # i_filter_random # o_filter_random # _create_chains # _pair_seed # _chain_filters # _filter_recursive
<commit_before>import chatbot_brain def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_lexicon) > 0 def test_compose_response(): bot = chatbot_brain.Chatbot() output = bot.compose_response(input_sent="How are you doing?") assert "," not in output[0] for sentence in output: assert "." not in sentence[:-1] def test_i_filter_random_empty_words(): u"""Assert the returned word is in the lexicon and is not a stop char.""" bot = chatbot_brain.Chatbot() words = [""] assert bot.i_filter_random(words) == u"What a funny thing to say!" # untested methods: # i_filter_random # o_filter_random # _create_chains # _pair_seed # _chain_filters # _filter_recursive <commit_msg>Add test_i_filter_random_words_not_in_lexicon() to assert the stock phrase is returned if all the words are not in the lexicon<commit_after>
import chatbot_brain stock = u"What a funny thing to say!" def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_lexicon) > 0 def test_compose_response(): bot = chatbot_brain.Chatbot() output = bot.compose_response(input_sent="How are you doing?") assert "," not in output[0] for sentence in output: assert "." not in sentence[:-1] def test_i_filter_random_empty_words(): u"""Assert an empty string is not found in the default lexicon.""" bot = chatbot_brain.Chatbot() words = [""] assert bot.i_filter_random(words) == stock def test_i_filter_random_words_not_in_lexicon(): u"""Assert that if all words are not in lexicon the default is returned.""" bot = chatbot_brain.Chatbot() words = ["moose", "bear", "eagle"] lexicon = {"car": "mercedes", "boat": "sail", "train": "track"} assert bot.i_filter_random(words, lexicon) == stock # untested methods: # i_filter_random # o_filter_random # _create_chains # _pair_seed # _chain_filters # _filter_recursive
import chatbot_brain def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_lexicon) > 0 def test_compose_response(): bot = chatbot_brain.Chatbot() output = bot.compose_response(input_sent="How are you doing?") assert "," not in output[0] for sentence in output: assert "." not in sentence[:-1] def test_i_filter_random_empty_words(): u"""Assert the returned word is in the lexicon and is not a stop char.""" bot = chatbot_brain.Chatbot() words = [""] assert bot.i_filter_random(words) == u"What a funny thing to say!" # untested methods: # i_filter_random # o_filter_random # _create_chains # _pair_seed # _chain_filters # _filter_recursive Add test_i_filter_random_words_not_in_lexicon() to assert the stock phrase is returned if all the words are not in the lexiconimport chatbot_brain stock = u"What a funny thing to say!" def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_lexicon) > 0 def test_compose_response(): bot = chatbot_brain.Chatbot() output = bot.compose_response(input_sent="How are you doing?") assert "," not in output[0] for sentence in output: assert "." not in sentence[:-1] def test_i_filter_random_empty_words(): u"""Assert an empty string is not found in the default lexicon.""" bot = chatbot_brain.Chatbot() words = [""] assert bot.i_filter_random(words) == stock def test_i_filter_random_words_not_in_lexicon(): u"""Assert that if all words are not in lexicon the default is returned.""" bot = chatbot_brain.Chatbot() words = ["moose", "bear", "eagle"] lexicon = {"car": "mercedes", "boat": "sail", "train": "track"} assert bot.i_filter_random(words, lexicon) == stock # untested methods: # i_filter_random # o_filter_random # _create_chains # _pair_seed # _chain_filters # _filter_recursive
<commit_before>import chatbot_brain def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_lexicon) > 0 def test_compose_response(): bot = chatbot_brain.Chatbot() output = bot.compose_response(input_sent="How are you doing?") assert "," not in output[0] for sentence in output: assert "." not in sentence[:-1] def test_i_filter_random_empty_words(): u"""Assert the returned word is in the lexicon and is not a stop char.""" bot = chatbot_brain.Chatbot() words = [""] assert bot.i_filter_random(words) == u"What a funny thing to say!" # untested methods: # i_filter_random # o_filter_random # _create_chains # _pair_seed # _chain_filters # _filter_recursive <commit_msg>Add test_i_filter_random_words_not_in_lexicon() to assert the stock phrase is returned if all the words are not in the lexicon<commit_after>import chatbot_brain stock = u"What a funny thing to say!" def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_lexicon) > 0 def test_compose_response(): bot = chatbot_brain.Chatbot() output = bot.compose_response(input_sent="How are you doing?") assert "," not in output[0] for sentence in output: assert "." not in sentence[:-1] def test_i_filter_random_empty_words(): u"""Assert an empty string is not found in the default lexicon.""" bot = chatbot_brain.Chatbot() words = [""] assert bot.i_filter_random(words) == stock def test_i_filter_random_words_not_in_lexicon(): u"""Assert that if all words are not in lexicon the default is returned.""" bot = chatbot_brain.Chatbot() words = ["moose", "bear", "eagle"] lexicon = {"car": "mercedes", "boat": "sail", "train": "track"} assert bot.i_filter_random(words, lexicon) == stock # untested methods: # i_filter_random # o_filter_random # _create_chains # _pair_seed # _chain_filters # _filter_recursive
20147b8b8a80ef8ab202d916bf1cdfb67d4753d3
SelfTests.py
SelfTests.py
import os import unittest from Logger import Logger class TestLogger(unittest.TestCase): def test_file_handling(self): testLog = Logger("testLog") ## Check if program can create and open file self.assertTrue(testLog.opened) returns = testLog.close() ## Check if logger correctly signs bool OPENED and returns ## 0 as succes. self.assertFalse(testLog.opened) self.assertEqual(returns,0) returns = testLog.close() ## Check if logger returns 1 when trying to close already ## closed file self.assertEqual(returns,1) ## Do cleanup: os.remove(testLog.name) def test_logging(self): testLog = Logger("testLog") testLog.save_line("TestLine") testLog.close() logfile = open(testLog.name) content = logfile.read() logfile.close() saved = content.split(" : ") self.assertEqual(saved[1],"TestLine") ## cleanup os.remove(testLog.name) if __name__ == '__main__': unittest.main()
import os import unittest from Logger import Logger class TestLogger(unittest.TestCase): def test_file_handling(self): testLog = Logger("testLog") ## Check if program can create and open file self.assertTrue(testLog.opened) returns = testLog.close() ## Check if logger correctly signs bool OPENED and returns ## 0 as succes. self.assertFalse(testLog.opened) self.assertEqual(returns,0) returns = testLog.close() ## Check if logger returns 1 when trying to close already ## closed file self.assertEqual(returns,1) ## Do cleanup: os.remove(testLog.name) def test_logging(self): testLog = Logger("testLog") testPhrase = "TestLine\r\n" testLog.save_line(testPhrase) testLog.close() logfile = open(testLog.name) content = logfile.read() logfile.close() saved = content.split(" : ") ## Check if saved data corresponds self.assertEqual(saved[1],testPhrase) ## cleanup os.remove(testLog.name) if __name__ == '__main__': unittest.main()
Test of logger is testing an testPhrase instead of two manually writen strings
Test of logger is testing an testPhrase instead of two manually writen strings Signed-off-by: TeaPackCZ <a78d8486eff6e2cb08b2d9907449b92187b8e215@gmail.com>
Python
mit
TeaPackCZ/RobotZed,TeaPackCZ/RobotZed
import os import unittest from Logger import Logger class TestLogger(unittest.TestCase): def test_file_handling(self): testLog = Logger("testLog") ## Check if program can create and open file self.assertTrue(testLog.opened) returns = testLog.close() ## Check if logger correctly signs bool OPENED and returns ## 0 as succes. self.assertFalse(testLog.opened) self.assertEqual(returns,0) returns = testLog.close() ## Check if logger returns 1 when trying to close already ## closed file self.assertEqual(returns,1) ## Do cleanup: os.remove(testLog.name) def test_logging(self): testLog = Logger("testLog") testLog.save_line("TestLine") testLog.close() logfile = open(testLog.name) content = logfile.read() logfile.close() saved = content.split(" : ") self.assertEqual(saved[1],"TestLine") ## cleanup os.remove(testLog.name) if __name__ == '__main__': unittest.main() Test of logger is testing an testPhrase instead of two manually writen strings Signed-off-by: TeaPackCZ <a78d8486eff6e2cb08b2d9907449b92187b8e215@gmail.com>
import os import unittest from Logger import Logger class TestLogger(unittest.TestCase): def test_file_handling(self): testLog = Logger("testLog") ## Check if program can create and open file self.assertTrue(testLog.opened) returns = testLog.close() ## Check if logger correctly signs bool OPENED and returns ## 0 as succes. self.assertFalse(testLog.opened) self.assertEqual(returns,0) returns = testLog.close() ## Check if logger returns 1 when trying to close already ## closed file self.assertEqual(returns,1) ## Do cleanup: os.remove(testLog.name) def test_logging(self): testLog = Logger("testLog") testPhrase = "TestLine\r\n" testLog.save_line(testPhrase) testLog.close() logfile = open(testLog.name) content = logfile.read() logfile.close() saved = content.split(" : ") ## Check if saved data corresponds self.assertEqual(saved[1],testPhrase) ## cleanup os.remove(testLog.name) if __name__ == '__main__': unittest.main()
<commit_before>import os import unittest from Logger import Logger class TestLogger(unittest.TestCase): def test_file_handling(self): testLog = Logger("testLog") ## Check if program can create and open file self.assertTrue(testLog.opened) returns = testLog.close() ## Check if logger correctly signs bool OPENED and returns ## 0 as succes. self.assertFalse(testLog.opened) self.assertEqual(returns,0) returns = testLog.close() ## Check if logger returns 1 when trying to close already ## closed file self.assertEqual(returns,1) ## Do cleanup: os.remove(testLog.name) def test_logging(self): testLog = Logger("testLog") testLog.save_line("TestLine") testLog.close() logfile = open(testLog.name) content = logfile.read() logfile.close() saved = content.split(" : ") self.assertEqual(saved[1],"TestLine") ## cleanup os.remove(testLog.name) if __name__ == '__main__': unittest.main() <commit_msg>Test of logger is testing an testPhrase instead of two manually writen strings Signed-off-by: TeaPackCZ <a78d8486eff6e2cb08b2d9907449b92187b8e215@gmail.com><commit_after>
import os import unittest from Logger import Logger class TestLogger(unittest.TestCase): def test_file_handling(self): testLog = Logger("testLog") ## Check if program can create and open file self.assertTrue(testLog.opened) returns = testLog.close() ## Check if logger correctly signs bool OPENED and returns ## 0 as succes. self.assertFalse(testLog.opened) self.assertEqual(returns,0) returns = testLog.close() ## Check if logger returns 1 when trying to close already ## closed file self.assertEqual(returns,1) ## Do cleanup: os.remove(testLog.name) def test_logging(self): testLog = Logger("testLog") testPhrase = "TestLine\r\n" testLog.save_line(testPhrase) testLog.close() logfile = open(testLog.name) content = logfile.read() logfile.close() saved = content.split(" : ") ## Check if saved data corresponds self.assertEqual(saved[1],testPhrase) ## cleanup os.remove(testLog.name) if __name__ == '__main__': unittest.main()
import os import unittest from Logger import Logger class TestLogger(unittest.TestCase): def test_file_handling(self): testLog = Logger("testLog") ## Check if program can create and open file self.assertTrue(testLog.opened) returns = testLog.close() ## Check if logger correctly signs bool OPENED and returns ## 0 as succes. self.assertFalse(testLog.opened) self.assertEqual(returns,0) returns = testLog.close() ## Check if logger returns 1 when trying to close already ## closed file self.assertEqual(returns,1) ## Do cleanup: os.remove(testLog.name) def test_logging(self): testLog = Logger("testLog") testLog.save_line("TestLine") testLog.close() logfile = open(testLog.name) content = logfile.read() logfile.close() saved = content.split(" : ") self.assertEqual(saved[1],"TestLine") ## cleanup os.remove(testLog.name) if __name__ == '__main__': unittest.main() Test of logger is testing an testPhrase instead of two manually writen strings Signed-off-by: TeaPackCZ <a78d8486eff6e2cb08b2d9907449b92187b8e215@gmail.com>import os import unittest from Logger import Logger class TestLogger(unittest.TestCase): def test_file_handling(self): testLog = Logger("testLog") ## Check if program can create and open file self.assertTrue(testLog.opened) returns = testLog.close() ## Check if logger correctly signs bool OPENED and returns ## 0 as succes. self.assertFalse(testLog.opened) self.assertEqual(returns,0) returns = testLog.close() ## Check if logger returns 1 when trying to close already ## closed file self.assertEqual(returns,1) ## Do cleanup: os.remove(testLog.name) def test_logging(self): testLog = Logger("testLog") testPhrase = "TestLine\r\n" testLog.save_line(testPhrase) testLog.close() logfile = open(testLog.name) content = logfile.read() logfile.close() saved = content.split(" : ") ## Check if saved data corresponds self.assertEqual(saved[1],testPhrase) ## cleanup os.remove(testLog.name) if __name__ == '__main__': unittest.main()
<commit_before>import os import unittest from Logger import Logger class TestLogger(unittest.TestCase): def test_file_handling(self): testLog = Logger("testLog") ## Check if program can create and open file self.assertTrue(testLog.opened) returns = testLog.close() ## Check if logger correctly signs bool OPENED and returns ## 0 as succes. self.assertFalse(testLog.opened) self.assertEqual(returns,0) returns = testLog.close() ## Check if logger returns 1 when trying to close already ## closed file self.assertEqual(returns,1) ## Do cleanup: os.remove(testLog.name) def test_logging(self): testLog = Logger("testLog") testLog.save_line("TestLine") testLog.close() logfile = open(testLog.name) content = logfile.read() logfile.close() saved = content.split(" : ") self.assertEqual(saved[1],"TestLine") ## cleanup os.remove(testLog.name) if __name__ == '__main__': unittest.main() <commit_msg>Test of logger is testing an testPhrase instead of two manually writen strings Signed-off-by: TeaPackCZ <a78d8486eff6e2cb08b2d9907449b92187b8e215@gmail.com><commit_after>import os import unittest from Logger import Logger class TestLogger(unittest.TestCase): def test_file_handling(self): testLog = Logger("testLog") ## Check if program can create and open file self.assertTrue(testLog.opened) returns = testLog.close() ## Check if logger correctly signs bool OPENED and returns ## 0 as succes. self.assertFalse(testLog.opened) self.assertEqual(returns,0) returns = testLog.close() ## Check if logger returns 1 when trying to close already ## closed file self.assertEqual(returns,1) ## Do cleanup: os.remove(testLog.name) def test_logging(self): testLog = Logger("testLog") testPhrase = "TestLine\r\n" testLog.save_line(testPhrase) testLog.close() logfile = open(testLog.name) content = logfile.read() logfile.close() saved = content.split(" : ") ## Check if saved data corresponds self.assertEqual(saved[1],testPhrase) ## cleanup os.remove(testLog.name) if __name__ == '__main__': unittest.main()
0c00acb19274626241f901ea85a124511dfe4526
server/lepton_server.py
server/lepton_server.py
#!/usr/bin/env python import sys import time import zmq import numpy as np try: import progressbar except ImportError: progressbar = None try: import pylepton except ImportError: print "Couldn't import pylepton, using Dummy data!" Lepton = None # importing packages in parent folders is voodoo from common.Frame import Frame port = "5556" context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind("tcp://*:{}".format(port)) widgets = ['Got ', progressbar.Counter(), ' frames (', progressbar.Timer(), ')'] pbar = progressbar.ProgressBar(widgets=widgets, maxval=progressbar.UnknownLength).start() if pylepton is not None: with pylepton.Lepton("/dev/spidev0.1") as lepton: n = 0 while True: arr, idx = lepton.capture() frame = Frame(idx, arr) #frame = Frame(-1, np.random.random_integers(4095, size=(60.,80.))) socket.send(frame.encode()) pbar.update(n) n += 1
#!/usr/bin/env python import sys import time import zmq import numpy as np try: import progressbar except ImportError: progressbar = None try: import pylepton except ImportError: print "Couldn't import pylepton, using Dummy data!" Lepton = None # importing packages in parent folders is voodoo from common.Frame import Frame port = "5556" context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind("tcp://*:{}".format(port)) widgets = ['Got ', progressbar.Counter(), ' frames (', progressbar.Timer(), ')'] pbar = progressbar.ProgressBar(widgets=widgets, maxval=progressbar.UnknownLength).start() if pylepton is not None: with pylepton.Lepton("/dev/spidev0.1") as lepton: n = 0 while True: arr, idx = lepton.capture() frame = Frame(idx, np.squeeze(arr)) #frame = Frame(-1, np.random.random_integers(4095, size=(60.,80.))) socket.send(frame.encode()) pbar.update(n) n += 1
Remove third dimension from image array
Remove third dimension from image array
Python
mit
wonkoderverstaendige/raspi_lepton
#!/usr/bin/env python import sys import time import zmq import numpy as np try: import progressbar except ImportError: progressbar = None try: import pylepton except ImportError: print "Couldn't import pylepton, using Dummy data!" Lepton = None # importing packages in parent folders is voodoo from common.Frame import Frame port = "5556" context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind("tcp://*:{}".format(port)) widgets = ['Got ', progressbar.Counter(), ' frames (', progressbar.Timer(), ')'] pbar = progressbar.ProgressBar(widgets=widgets, maxval=progressbar.UnknownLength).start() if pylepton is not None: with pylepton.Lepton("/dev/spidev0.1") as lepton: n = 0 while True: arr, idx = lepton.capture() frame = Frame(idx, arr) #frame = Frame(-1, np.random.random_integers(4095, size=(60.,80.))) socket.send(frame.encode()) pbar.update(n) n += 1 Remove third dimension from image array
#!/usr/bin/env python import sys import time import zmq import numpy as np try: import progressbar except ImportError: progressbar = None try: import pylepton except ImportError: print "Couldn't import pylepton, using Dummy data!" Lepton = None # importing packages in parent folders is voodoo from common.Frame import Frame port = "5556" context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind("tcp://*:{}".format(port)) widgets = ['Got ', progressbar.Counter(), ' frames (', progressbar.Timer(), ')'] pbar = progressbar.ProgressBar(widgets=widgets, maxval=progressbar.UnknownLength).start() if pylepton is not None: with pylepton.Lepton("/dev/spidev0.1") as lepton: n = 0 while True: arr, idx = lepton.capture() frame = Frame(idx, np.squeeze(arr)) #frame = Frame(-1, np.random.random_integers(4095, size=(60.,80.))) socket.send(frame.encode()) pbar.update(n) n += 1
<commit_before>#!/usr/bin/env python import sys import time import zmq import numpy as np try: import progressbar except ImportError: progressbar = None try: import pylepton except ImportError: print "Couldn't import pylepton, using Dummy data!" Lepton = None # importing packages in parent folders is voodoo from common.Frame import Frame port = "5556" context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind("tcp://*:{}".format(port)) widgets = ['Got ', progressbar.Counter(), ' frames (', progressbar.Timer(), ')'] pbar = progressbar.ProgressBar(widgets=widgets, maxval=progressbar.UnknownLength).start() if pylepton is not None: with pylepton.Lepton("/dev/spidev0.1") as lepton: n = 0 while True: arr, idx = lepton.capture() frame = Frame(idx, arr) #frame = Frame(-1, np.random.random_integers(4095, size=(60.,80.))) socket.send(frame.encode()) pbar.update(n) n += 1 <commit_msg>Remove third dimension from image array<commit_after>
#!/usr/bin/env python import sys import time import zmq import numpy as np try: import progressbar except ImportError: progressbar = None try: import pylepton except ImportError: print "Couldn't import pylepton, using Dummy data!" Lepton = None # importing packages in parent folders is voodoo from common.Frame import Frame port = "5556" context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind("tcp://*:{}".format(port)) widgets = ['Got ', progressbar.Counter(), ' frames (', progressbar.Timer(), ')'] pbar = progressbar.ProgressBar(widgets=widgets, maxval=progressbar.UnknownLength).start() if pylepton is not None: with pylepton.Lepton("/dev/spidev0.1") as lepton: n = 0 while True: arr, idx = lepton.capture() frame = Frame(idx, np.squeeze(arr)) #frame = Frame(-1, np.random.random_integers(4095, size=(60.,80.))) socket.send(frame.encode()) pbar.update(n) n += 1
#!/usr/bin/env python import sys import time import zmq import numpy as np try: import progressbar except ImportError: progressbar = None try: import pylepton except ImportError: print "Couldn't import pylepton, using Dummy data!" Lepton = None # importing packages in parent folders is voodoo from common.Frame import Frame port = "5556" context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind("tcp://*:{}".format(port)) widgets = ['Got ', progressbar.Counter(), ' frames (', progressbar.Timer(), ')'] pbar = progressbar.ProgressBar(widgets=widgets, maxval=progressbar.UnknownLength).start() if pylepton is not None: with pylepton.Lepton("/dev/spidev0.1") as lepton: n = 0 while True: arr, idx = lepton.capture() frame = Frame(idx, arr) #frame = Frame(-1, np.random.random_integers(4095, size=(60.,80.))) socket.send(frame.encode()) pbar.update(n) n += 1 Remove third dimension from image array#!/usr/bin/env python import sys import time import zmq import numpy as np try: import progressbar except ImportError: progressbar = None try: import pylepton except ImportError: print "Couldn't import pylepton, using Dummy data!" Lepton = None # importing packages in parent folders is voodoo from common.Frame import Frame port = "5556" context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind("tcp://*:{}".format(port)) widgets = ['Got ', progressbar.Counter(), ' frames (', progressbar.Timer(), ')'] pbar = progressbar.ProgressBar(widgets=widgets, maxval=progressbar.UnknownLength).start() if pylepton is not None: with pylepton.Lepton("/dev/spidev0.1") as lepton: n = 0 while True: arr, idx = lepton.capture() frame = Frame(idx, np.squeeze(arr)) #frame = Frame(-1, np.random.random_integers(4095, size=(60.,80.))) socket.send(frame.encode()) pbar.update(n) n += 1
<commit_before>#!/usr/bin/env python import sys import time import zmq import numpy as np try: import progressbar except ImportError: progressbar = None try: import pylepton except ImportError: print "Couldn't import pylepton, using Dummy data!" Lepton = None # importing packages in parent folders is voodoo from common.Frame import Frame port = "5556" context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind("tcp://*:{}".format(port)) widgets = ['Got ', progressbar.Counter(), ' frames (', progressbar.Timer(), ')'] pbar = progressbar.ProgressBar(widgets=widgets, maxval=progressbar.UnknownLength).start() if pylepton is not None: with pylepton.Lepton("/dev/spidev0.1") as lepton: n = 0 while True: arr, idx = lepton.capture() frame = Frame(idx, arr) #frame = Frame(-1, np.random.random_integers(4095, size=(60.,80.))) socket.send(frame.encode()) pbar.update(n) n += 1 <commit_msg>Remove third dimension from image array<commit_after>#!/usr/bin/env python import sys import time import zmq import numpy as np try: import progressbar except ImportError: progressbar = None try: import pylepton except ImportError: print "Couldn't import pylepton, using Dummy data!" Lepton = None # importing packages in parent folders is voodoo from common.Frame import Frame port = "5556" context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind("tcp://*:{}".format(port)) widgets = ['Got ', progressbar.Counter(), ' frames (', progressbar.Timer(), ')'] pbar = progressbar.ProgressBar(widgets=widgets, maxval=progressbar.UnknownLength).start() if pylepton is not None: with pylepton.Lepton("/dev/spidev0.1") as lepton: n = 0 while True: arr, idx = lepton.capture() frame = Frame(idx, np.squeeze(arr)) #frame = Frame(-1, np.random.random_integers(4095, size=(60.,80.))) socket.send(frame.encode()) pbar.update(n) n += 1
822ae0442bf5091be234dc9470a79c83f909ff35
txircd/modules/conn_join.py
txircd/modules/conn_join.py
from txircd.channel import IRCChannel from txircd.modbase import Module class Autojoin(Module): def joinOnConnect(self, user): if "client_join_on_connect" in self.ircd.servconfig: for channel in self.ircd.servconfig["client_join_on_connect"]: user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel)) class Spawner(object): def __init__(self, ircd): self.ircd = ircd self.conn_join = None def spawn(self): self.conn_join = Autojoin().hook(self.ircd) return { "actions": { "register": self.conn_join.joinOnConnect } } def cleanup(self): self.ircd.actions["register"].remove(self.conn_join.joinOnConnect)
from txircd.channel import IRCChannel from txircd.modbase import Module class Autojoin(Module): def joinOnConnect(self, user): if "client_join_on_connect" in self.ircd.servconfig: for channel in self.ircd.servconfig["client_join_on_connect"]: user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel)) return True class Spawner(object): def __init__(self, ircd): self.ircd = ircd self.conn_join = None def spawn(self): self.conn_join = Autojoin().hook(self.ircd) return { "actions": { "register": [self.conn_join.joinOnConnect] } } def cleanup(self): self.ircd.actions["register"].remove(self.conn_join.joinOnConnect)
Fix once again nobody being allowed to connect
Fix once again nobody being allowed to connect
Python
bsd-3-clause
Heufneutje/txircd,DesertBus/txircd,ElementalAlchemist/txircd
from txircd.channel import IRCChannel from txircd.modbase import Module class Autojoin(Module): def joinOnConnect(self, user): if "client_join_on_connect" in self.ircd.servconfig: for channel in self.ircd.servconfig["client_join_on_connect"]: user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel)) class Spawner(object): def __init__(self, ircd): self.ircd = ircd self.conn_join = None def spawn(self): self.conn_join = Autojoin().hook(self.ircd) return { "actions": { "register": self.conn_join.joinOnConnect } } def cleanup(self): self.ircd.actions["register"].remove(self.conn_join.joinOnConnect)Fix once again nobody being allowed to connect
from txircd.channel import IRCChannel from txircd.modbase import Module class Autojoin(Module): def joinOnConnect(self, user): if "client_join_on_connect" in self.ircd.servconfig: for channel in self.ircd.servconfig["client_join_on_connect"]: user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel)) return True class Spawner(object): def __init__(self, ircd): self.ircd = ircd self.conn_join = None def spawn(self): self.conn_join = Autojoin().hook(self.ircd) return { "actions": { "register": [self.conn_join.joinOnConnect] } } def cleanup(self): self.ircd.actions["register"].remove(self.conn_join.joinOnConnect)
<commit_before>from txircd.channel import IRCChannel from txircd.modbase import Module class Autojoin(Module): def joinOnConnect(self, user): if "client_join_on_connect" in self.ircd.servconfig: for channel in self.ircd.servconfig["client_join_on_connect"]: user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel)) class Spawner(object): def __init__(self, ircd): self.ircd = ircd self.conn_join = None def spawn(self): self.conn_join = Autojoin().hook(self.ircd) return { "actions": { "register": self.conn_join.joinOnConnect } } def cleanup(self): self.ircd.actions["register"].remove(self.conn_join.joinOnConnect)<commit_msg>Fix once again nobody being allowed to connect<commit_after>
from txircd.channel import IRCChannel from txircd.modbase import Module class Autojoin(Module): def joinOnConnect(self, user): if "client_join_on_connect" in self.ircd.servconfig: for channel in self.ircd.servconfig["client_join_on_connect"]: user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel)) return True class Spawner(object): def __init__(self, ircd): self.ircd = ircd self.conn_join = None def spawn(self): self.conn_join = Autojoin().hook(self.ircd) return { "actions": { "register": [self.conn_join.joinOnConnect] } } def cleanup(self): self.ircd.actions["register"].remove(self.conn_join.joinOnConnect)
from txircd.channel import IRCChannel from txircd.modbase import Module class Autojoin(Module): def joinOnConnect(self, user): if "client_join_on_connect" in self.ircd.servconfig: for channel in self.ircd.servconfig["client_join_on_connect"]: user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel)) class Spawner(object): def __init__(self, ircd): self.ircd = ircd self.conn_join = None def spawn(self): self.conn_join = Autojoin().hook(self.ircd) return { "actions": { "register": self.conn_join.joinOnConnect } } def cleanup(self): self.ircd.actions["register"].remove(self.conn_join.joinOnConnect)Fix once again nobody being allowed to connectfrom txircd.channel import IRCChannel from txircd.modbase import Module class Autojoin(Module): def joinOnConnect(self, user): if "client_join_on_connect" in self.ircd.servconfig: for channel in self.ircd.servconfig["client_join_on_connect"]: user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel)) return True class Spawner(object): def __init__(self, ircd): self.ircd = ircd self.conn_join = None def spawn(self): self.conn_join = Autojoin().hook(self.ircd) return { "actions": { "register": [self.conn_join.joinOnConnect] } } def cleanup(self): self.ircd.actions["register"].remove(self.conn_join.joinOnConnect)
<commit_before>from txircd.channel import IRCChannel from txircd.modbase import Module class Autojoin(Module): def joinOnConnect(self, user): if "client_join_on_connect" in self.ircd.servconfig: for channel in self.ircd.servconfig["client_join_on_connect"]: user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel)) class Spawner(object): def __init__(self, ircd): self.ircd = ircd self.conn_join = None def spawn(self): self.conn_join = Autojoin().hook(self.ircd) return { "actions": { "register": self.conn_join.joinOnConnect } } def cleanup(self): self.ircd.actions["register"].remove(self.conn_join.joinOnConnect)<commit_msg>Fix once again nobody being allowed to connect<commit_after>from txircd.channel import IRCChannel from txircd.modbase import Module class Autojoin(Module): def joinOnConnect(self, user): if "client_join_on_connect" in self.ircd.servconfig: for channel in self.ircd.servconfig["client_join_on_connect"]: user.join(self.ircd.channels[channel] if channel in self.ircd.channels else IRCChannel(self.ircd, channel)) return True class Spawner(object): def __init__(self, ircd): self.ircd = ircd self.conn_join = None def spawn(self): self.conn_join = Autojoin().hook(self.ircd) return { "actions": { "register": [self.conn_join.joinOnConnect] } } def cleanup(self): self.ircd.actions["register"].remove(self.conn_join.joinOnConnect)
cb1d686d5d0bb96e5a22f079aca34678167c19b1
tweets/api.py
tweets/api.py
from rest_framework import viewsets, authentication from tweets import models from tweets import serializers from tweets.permissions import MessagePermission, ProfilePermissions from django.contrib.auth import get_user_model class UserViewSet(viewsets.ModelViewSet): queryset = get_user_model().objects.all() serializer_class = serializers.UserSerializer permission_classes = [ProfilePermissions] authentication_classes = [authentication.BasicAuthentication, authentication.SessionAuthentication] class HashtagViewSet(viewsets.ReadOnlyModelViewSet): queryset = models.Hashtag.objects.all() serializer_class = serializers.HashtagSerializer permission_classes = [] authentication_classes = [] class MessageViewSet(viewsets.ModelViewSet): queryset = models.Message.objects.all() serializer_class = serializers.MessageSerializer permission_classes = [MessagePermission] authentication_classes = [authentication.BasicAuthentication, authentication.SessionAuthentication] def get_queryset(self): hashtag = self.request.QUERY_PARAMS.get('hashtag') user = self.request.QUERY_PARAMS.get('username') queryset = self.queryset if hashtag: queryset = queryset.filter(hashtags__text=hashtag) if user: queryset = queryset.filter(tagged_users__username=user) return queryset
from rest_framework import viewsets, authentication from tweets import models from tweets import serializers from tweets.permissions import MessagePermission, ProfilePermissions from django.contrib.auth import get_user_model class UserViewSet(viewsets.ModelViewSet): queryset = get_user_model().objects.all() serializer_class = serializers.UserSerializer permission_classes = [ProfilePermissions] authentication_classes = [authentication.BasicAuthentication, authentication.SessionAuthentication] class HashtagViewSet(viewsets.ReadOnlyModelViewSet): queryset = models.Hashtag.objects.all() serializer_class = serializers.HashtagSerializer permission_classes = [] authentication_classes = [] class MessageViewSet(viewsets.ModelViewSet): queryset = models.Message.objects.all() serializer_class = serializers.MessageSerializer permission_classes = [MessagePermission] authentication_classes = [authentication.BasicAuthentication, authentication.SessionAuthentication] def get_queryset(self): hashtag = self.request.QUERY_PARAMS.get('hashtag') user = self.request.QUERY_PARAMS.get('username') queryset = self.queryset if hashtag: queryset = queryset.filter(hashtags__text=hashtag) if user: queryset = queryset.filter(user__username=user) return queryset
Adjust user filter to author, not related
Adjust user filter to author, not related
Python
mit
pennomi/openwest2015-twitter-clone,pennomi/openwest2015-twitter-clone,pennomi/openwest2015-twitter-clone
from rest_framework import viewsets, authentication from tweets import models from tweets import serializers from tweets.permissions import MessagePermission, ProfilePermissions from django.contrib.auth import get_user_model class UserViewSet(viewsets.ModelViewSet): queryset = get_user_model().objects.all() serializer_class = serializers.UserSerializer permission_classes = [ProfilePermissions] authentication_classes = [authentication.BasicAuthentication, authentication.SessionAuthentication] class HashtagViewSet(viewsets.ReadOnlyModelViewSet): queryset = models.Hashtag.objects.all() serializer_class = serializers.HashtagSerializer permission_classes = [] authentication_classes = [] class MessageViewSet(viewsets.ModelViewSet): queryset = models.Message.objects.all() serializer_class = serializers.MessageSerializer permission_classes = [MessagePermission] authentication_classes = [authentication.BasicAuthentication, authentication.SessionAuthentication] def get_queryset(self): hashtag = self.request.QUERY_PARAMS.get('hashtag') user = self.request.QUERY_PARAMS.get('username') queryset = self.queryset if hashtag: queryset = queryset.filter(hashtags__text=hashtag) if user: queryset = queryset.filter(tagged_users__username=user) return queryset Adjust user filter to author, not related
from rest_framework import viewsets, authentication from tweets import models from tweets import serializers from tweets.permissions import MessagePermission, ProfilePermissions from django.contrib.auth import get_user_model class UserViewSet(viewsets.ModelViewSet): queryset = get_user_model().objects.all() serializer_class = serializers.UserSerializer permission_classes = [ProfilePermissions] authentication_classes = [authentication.BasicAuthentication, authentication.SessionAuthentication] class HashtagViewSet(viewsets.ReadOnlyModelViewSet): queryset = models.Hashtag.objects.all() serializer_class = serializers.HashtagSerializer permission_classes = [] authentication_classes = [] class MessageViewSet(viewsets.ModelViewSet): queryset = models.Message.objects.all() serializer_class = serializers.MessageSerializer permission_classes = [MessagePermission] authentication_classes = [authentication.BasicAuthentication, authentication.SessionAuthentication] def get_queryset(self): hashtag = self.request.QUERY_PARAMS.get('hashtag') user = self.request.QUERY_PARAMS.get('username') queryset = self.queryset if hashtag: queryset = queryset.filter(hashtags__text=hashtag) if user: queryset = queryset.filter(user__username=user) return queryset
<commit_before>from rest_framework import viewsets, authentication from tweets import models from tweets import serializers from tweets.permissions import MessagePermission, ProfilePermissions from django.contrib.auth import get_user_model class UserViewSet(viewsets.ModelViewSet): queryset = get_user_model().objects.all() serializer_class = serializers.UserSerializer permission_classes = [ProfilePermissions] authentication_classes = [authentication.BasicAuthentication, authentication.SessionAuthentication] class HashtagViewSet(viewsets.ReadOnlyModelViewSet): queryset = models.Hashtag.objects.all() serializer_class = serializers.HashtagSerializer permission_classes = [] authentication_classes = [] class MessageViewSet(viewsets.ModelViewSet): queryset = models.Message.objects.all() serializer_class = serializers.MessageSerializer permission_classes = [MessagePermission] authentication_classes = [authentication.BasicAuthentication, authentication.SessionAuthentication] def get_queryset(self): hashtag = self.request.QUERY_PARAMS.get('hashtag') user = self.request.QUERY_PARAMS.get('username') queryset = self.queryset if hashtag: queryset = queryset.filter(hashtags__text=hashtag) if user: queryset = queryset.filter(tagged_users__username=user) return queryset <commit_msg>Adjust user filter to author, not related<commit_after>
from rest_framework import viewsets, authentication from tweets import models from tweets import serializers from tweets.permissions import MessagePermission, ProfilePermissions from django.contrib.auth import get_user_model class UserViewSet(viewsets.ModelViewSet): queryset = get_user_model().objects.all() serializer_class = serializers.UserSerializer permission_classes = [ProfilePermissions] authentication_classes = [authentication.BasicAuthentication, authentication.SessionAuthentication] class HashtagViewSet(viewsets.ReadOnlyModelViewSet): queryset = models.Hashtag.objects.all() serializer_class = serializers.HashtagSerializer permission_classes = [] authentication_classes = [] class MessageViewSet(viewsets.ModelViewSet): queryset = models.Message.objects.all() serializer_class = serializers.MessageSerializer permission_classes = [MessagePermission] authentication_classes = [authentication.BasicAuthentication, authentication.SessionAuthentication] def get_queryset(self): hashtag = self.request.QUERY_PARAMS.get('hashtag') user = self.request.QUERY_PARAMS.get('username') queryset = self.queryset if hashtag: queryset = queryset.filter(hashtags__text=hashtag) if user: queryset = queryset.filter(user__username=user) return queryset
from rest_framework import viewsets, authentication from tweets import models from tweets import serializers from tweets.permissions import MessagePermission, ProfilePermissions from django.contrib.auth import get_user_model class UserViewSet(viewsets.ModelViewSet): queryset = get_user_model().objects.all() serializer_class = serializers.UserSerializer permission_classes = [ProfilePermissions] authentication_classes = [authentication.BasicAuthentication, authentication.SessionAuthentication] class HashtagViewSet(viewsets.ReadOnlyModelViewSet): queryset = models.Hashtag.objects.all() serializer_class = serializers.HashtagSerializer permission_classes = [] authentication_classes = [] class MessageViewSet(viewsets.ModelViewSet): queryset = models.Message.objects.all() serializer_class = serializers.MessageSerializer permission_classes = [MessagePermission] authentication_classes = [authentication.BasicAuthentication, authentication.SessionAuthentication] def get_queryset(self): hashtag = self.request.QUERY_PARAMS.get('hashtag') user = self.request.QUERY_PARAMS.get('username') queryset = self.queryset if hashtag: queryset = queryset.filter(hashtags__text=hashtag) if user: queryset = queryset.filter(tagged_users__username=user) return queryset Adjust user filter to author, not relatedfrom rest_framework import viewsets, authentication from tweets import models from tweets import serializers from tweets.permissions import MessagePermission, ProfilePermissions from django.contrib.auth import get_user_model class UserViewSet(viewsets.ModelViewSet): queryset = get_user_model().objects.all() serializer_class = serializers.UserSerializer permission_classes = [ProfilePermissions] authentication_classes = [authentication.BasicAuthentication, authentication.SessionAuthentication] class HashtagViewSet(viewsets.ReadOnlyModelViewSet): queryset = models.Hashtag.objects.all() serializer_class = serializers.HashtagSerializer permission_classes = [] authentication_classes = [] class MessageViewSet(viewsets.ModelViewSet): queryset = models.Message.objects.all() serializer_class = serializers.MessageSerializer permission_classes = [MessagePermission] authentication_classes = [authentication.BasicAuthentication, authentication.SessionAuthentication] def get_queryset(self): hashtag = self.request.QUERY_PARAMS.get('hashtag') user = self.request.QUERY_PARAMS.get('username') queryset = self.queryset if hashtag: queryset = queryset.filter(hashtags__text=hashtag) if user: queryset = queryset.filter(user__username=user) return queryset
<commit_before>from rest_framework import viewsets, authentication from tweets import models from tweets import serializers from tweets.permissions import MessagePermission, ProfilePermissions from django.contrib.auth import get_user_model class UserViewSet(viewsets.ModelViewSet): queryset = get_user_model().objects.all() serializer_class = serializers.UserSerializer permission_classes = [ProfilePermissions] authentication_classes = [authentication.BasicAuthentication, authentication.SessionAuthentication] class HashtagViewSet(viewsets.ReadOnlyModelViewSet): queryset = models.Hashtag.objects.all() serializer_class = serializers.HashtagSerializer permission_classes = [] authentication_classes = [] class MessageViewSet(viewsets.ModelViewSet): queryset = models.Message.objects.all() serializer_class = serializers.MessageSerializer permission_classes = [MessagePermission] authentication_classes = [authentication.BasicAuthentication, authentication.SessionAuthentication] def get_queryset(self): hashtag = self.request.QUERY_PARAMS.get('hashtag') user = self.request.QUERY_PARAMS.get('username') queryset = self.queryset if hashtag: queryset = queryset.filter(hashtags__text=hashtag) if user: queryset = queryset.filter(tagged_users__username=user) return queryset <commit_msg>Adjust user filter to author, not related<commit_after>from rest_framework import viewsets, authentication from tweets import models from tweets import serializers from tweets.permissions import MessagePermission, ProfilePermissions from django.contrib.auth import get_user_model class UserViewSet(viewsets.ModelViewSet): queryset = get_user_model().objects.all() serializer_class = serializers.UserSerializer permission_classes = [ProfilePermissions] authentication_classes = [authentication.BasicAuthentication, authentication.SessionAuthentication] class HashtagViewSet(viewsets.ReadOnlyModelViewSet): queryset = models.Hashtag.objects.all() serializer_class = serializers.HashtagSerializer permission_classes = [] authentication_classes = [] class MessageViewSet(viewsets.ModelViewSet): queryset = models.Message.objects.all() serializer_class = serializers.MessageSerializer permission_classes = [MessagePermission] authentication_classes = [authentication.BasicAuthentication, authentication.SessionAuthentication] def get_queryset(self): hashtag = self.request.QUERY_PARAMS.get('hashtag') user = self.request.QUERY_PARAMS.get('username') queryset = self.queryset if hashtag: queryset = queryset.filter(hashtags__text=hashtag) if user: queryset = queryset.filter(user__username=user) return queryset
c498bb6ac7a80ac2668fef22fa6600de6fc9af89
dakota/plugins/base.py
dakota/plugins/base.py
#! /usr/bin/env python """An abstract base class for all Dakota component plugins.""" from abc import ABCMeta, abstractmethod class PluginBase(object): """Describe features common to all Dakota plugins.""" __metaclass__ = ABCMeta @abstractmethod def __init__(self, **kwargs): """Define default attributes.""" pass @abstractmethod def setup(self): """Configure component inputs.""" pass @abstractmethod def call(self): """Call the component through the shell.""" pass @abstractmethod def load(self): """Read data from a component output file.""" pass @abstractmethod def calculate(self): """Calculate Dakota response functions.""" pass @abstractmethod def write(self): """Write a Dakota results file.""" pass
#! /usr/bin/env python """An abstract base class for all Dakota component plugins.""" from abc import ABCMeta, abstractmethod class PluginBase(object): """Describe features common to all Dakota plugins.""" __metaclass__ = ABCMeta @abstractmethod def __init__(self, **kwargs): """Define default attributes.""" pass @abstractmethod def setup(self, config): """Configure component inputs. Sets attributes using information from the run configuration file. The Dakota parsing utility ``dprepro`` reads parameters from Dakota to create a new input file from a template. Parameters ---------- config : dict Stores configuration settings for a Dakota experiment. """ pass @abstractmethod def call(self): """Call the component through the shell.""" pass @abstractmethod def load(self, output_file): """Read data from a component output file. Parameters ---------- output_file : str The path to a component output file. Returns ------- array_like A numpy array, or None on an error. """ pass @abstractmethod def calculate(self): """Calculate Dakota response functions.""" pass @abstractmethod def write(self, params_file, results_file): """Write a Dakota results file. Parameters ---------- params_file : str A Dakota parameters file. results_file : str A Dakota results file. """ pass
Update argument lists for abstract methods
Update argument lists for abstract methods
Python
mit
csdms/dakota,csdms/dakota
#! /usr/bin/env python """An abstract base class for all Dakota component plugins.""" from abc import ABCMeta, abstractmethod class PluginBase(object): """Describe features common to all Dakota plugins.""" __metaclass__ = ABCMeta @abstractmethod def __init__(self, **kwargs): """Define default attributes.""" pass @abstractmethod def setup(self): """Configure component inputs.""" pass @abstractmethod def call(self): """Call the component through the shell.""" pass @abstractmethod def load(self): """Read data from a component output file.""" pass @abstractmethod def calculate(self): """Calculate Dakota response functions.""" pass @abstractmethod def write(self): """Write a Dakota results file.""" pass Update argument lists for abstract methods
#! /usr/bin/env python """An abstract base class for all Dakota component plugins.""" from abc import ABCMeta, abstractmethod class PluginBase(object): """Describe features common to all Dakota plugins.""" __metaclass__ = ABCMeta @abstractmethod def __init__(self, **kwargs): """Define default attributes.""" pass @abstractmethod def setup(self, config): """Configure component inputs. Sets attributes using information from the run configuration file. The Dakota parsing utility ``dprepro`` reads parameters from Dakota to create a new input file from a template. Parameters ---------- config : dict Stores configuration settings for a Dakota experiment. """ pass @abstractmethod def call(self): """Call the component through the shell.""" pass @abstractmethod def load(self, output_file): """Read data from a component output file. Parameters ---------- output_file : str The path to a component output file. Returns ------- array_like A numpy array, or None on an error. """ pass @abstractmethod def calculate(self): """Calculate Dakota response functions.""" pass @abstractmethod def write(self, params_file, results_file): """Write a Dakota results file. Parameters ---------- params_file : str A Dakota parameters file. results_file : str A Dakota results file. """ pass
<commit_before>#! /usr/bin/env python """An abstract base class for all Dakota component plugins.""" from abc import ABCMeta, abstractmethod class PluginBase(object): """Describe features common to all Dakota plugins.""" __metaclass__ = ABCMeta @abstractmethod def __init__(self, **kwargs): """Define default attributes.""" pass @abstractmethod def setup(self): """Configure component inputs.""" pass @abstractmethod def call(self): """Call the component through the shell.""" pass @abstractmethod def load(self): """Read data from a component output file.""" pass @abstractmethod def calculate(self): """Calculate Dakota response functions.""" pass @abstractmethod def write(self): """Write a Dakota results file.""" pass <commit_msg>Update argument lists for abstract methods<commit_after>
#! /usr/bin/env python """An abstract base class for all Dakota component plugins.""" from abc import ABCMeta, abstractmethod class PluginBase(object): """Describe features common to all Dakota plugins.""" __metaclass__ = ABCMeta @abstractmethod def __init__(self, **kwargs): """Define default attributes.""" pass @abstractmethod def setup(self, config): """Configure component inputs. Sets attributes using information from the run configuration file. The Dakota parsing utility ``dprepro`` reads parameters from Dakota to create a new input file from a template. Parameters ---------- config : dict Stores configuration settings for a Dakota experiment. """ pass @abstractmethod def call(self): """Call the component through the shell.""" pass @abstractmethod def load(self, output_file): """Read data from a component output file. Parameters ---------- output_file : str The path to a component output file. Returns ------- array_like A numpy array, or None on an error. """ pass @abstractmethod def calculate(self): """Calculate Dakota response functions.""" pass @abstractmethod def write(self, params_file, results_file): """Write a Dakota results file. Parameters ---------- params_file : str A Dakota parameters file. results_file : str A Dakota results file. """ pass
#! /usr/bin/env python """An abstract base class for all Dakota component plugins.""" from abc import ABCMeta, abstractmethod class PluginBase(object): """Describe features common to all Dakota plugins.""" __metaclass__ = ABCMeta @abstractmethod def __init__(self, **kwargs): """Define default attributes.""" pass @abstractmethod def setup(self): """Configure component inputs.""" pass @abstractmethod def call(self): """Call the component through the shell.""" pass @abstractmethod def load(self): """Read data from a component output file.""" pass @abstractmethod def calculate(self): """Calculate Dakota response functions.""" pass @abstractmethod def write(self): """Write a Dakota results file.""" pass Update argument lists for abstract methods#! /usr/bin/env python """An abstract base class for all Dakota component plugins.""" from abc import ABCMeta, abstractmethod class PluginBase(object): """Describe features common to all Dakota plugins.""" __metaclass__ = ABCMeta @abstractmethod def __init__(self, **kwargs): """Define default attributes.""" pass @abstractmethod def setup(self, config): """Configure component inputs. Sets attributes using information from the run configuration file. The Dakota parsing utility ``dprepro`` reads parameters from Dakota to create a new input file from a template. Parameters ---------- config : dict Stores configuration settings for a Dakota experiment. """ pass @abstractmethod def call(self): """Call the component through the shell.""" pass @abstractmethod def load(self, output_file): """Read data from a component output file. Parameters ---------- output_file : str The path to a component output file. Returns ------- array_like A numpy array, or None on an error. """ pass @abstractmethod def calculate(self): """Calculate Dakota response functions.""" pass @abstractmethod def write(self, params_file, results_file): """Write a Dakota results file. Parameters ---------- params_file : str A Dakota parameters file. results_file : str A Dakota results file. """ pass
<commit_before>#! /usr/bin/env python """An abstract base class for all Dakota component plugins.""" from abc import ABCMeta, abstractmethod class PluginBase(object): """Describe features common to all Dakota plugins.""" __metaclass__ = ABCMeta @abstractmethod def __init__(self, **kwargs): """Define default attributes.""" pass @abstractmethod def setup(self): """Configure component inputs.""" pass @abstractmethod def call(self): """Call the component through the shell.""" pass @abstractmethod def load(self): """Read data from a component output file.""" pass @abstractmethod def calculate(self): """Calculate Dakota response functions.""" pass @abstractmethod def write(self): """Write a Dakota results file.""" pass <commit_msg>Update argument lists for abstract methods<commit_after>#! /usr/bin/env python """An abstract base class for all Dakota component plugins.""" from abc import ABCMeta, abstractmethod class PluginBase(object): """Describe features common to all Dakota plugins.""" __metaclass__ = ABCMeta @abstractmethod def __init__(self, **kwargs): """Define default attributes.""" pass @abstractmethod def setup(self, config): """Configure component inputs. Sets attributes using information from the run configuration file. The Dakota parsing utility ``dprepro`` reads parameters from Dakota to create a new input file from a template. Parameters ---------- config : dict Stores configuration settings for a Dakota experiment. """ pass @abstractmethod def call(self): """Call the component through the shell.""" pass @abstractmethod def load(self, output_file): """Read data from a component output file. Parameters ---------- output_file : str The path to a component output file. Returns ------- array_like A numpy array, or None on an error. """ pass @abstractmethod def calculate(self): """Calculate Dakota response functions.""" pass @abstractmethod def write(self, params_file, results_file): """Write a Dakota results file. Parameters ---------- params_file : str A Dakota parameters file. results_file : str A Dakota results file. """ pass
8ae102a99b4dab4d4b6273eaacd83db7616640c2
api/setup.py
api/setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import humbug import glob import os from distutils.core import setup setup(name='humbug', version=humbug.__version__, description='Bindings for the Humbug message API', author='Humbug, Inc.', author_email='humbug@humbughq.com', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Communications :: Chat', ], url='https://humbughq.com/dist/api/', packages=['humbug'], data_files=[('share/humbug/examples', glob.glob('examples/*'))] + \ [(os.path.join('share/humbug/', relpath), glob.glob(os.path.join(relpath, '*'))) for relpath in glob.glob("integrations/*")] + \ [('share/humbug/demos', [os.path.join("demos", relpath) for relpath in os.listdir("demos")])], scripts=glob.glob("bin/*"), )
#!/usr/bin/env python # -*- coding: utf-8 -*- import humbug import glob import os from distutils.core import setup setup(name='humbug', version=humbug.__version__, description='Bindings for the Humbug message API', author='Humbug, Inc.', author_email='humbug@humbughq.com', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Communications :: Chat', ], url='https://humbughq.com/dist/api/', packages=['humbug'], data_files=[('share/humbug/examples', ["examples/humbugrc", "examples/send-message"])] + \ [(os.path.join('share/humbug/', relpath), glob.glob(os.path.join(relpath, '*'))) for relpath in glob.glob("integrations/*")] + \ [('share/humbug/demos', [os.path.join("demos", relpath) for relpath in os.listdir("demos")])], scripts=["bin/humbug-send"], )
Revert "Ship all of our examples in the API update tarball."
Revert "Ship all of our examples in the API update tarball." This reverts commit 4162114707f69bcfb6ecea95d7bdf4c080b4b168. (imported from commit a4d68bc2a68209bed8e00e6d58dd5f5d3a3187f9)
Python
apache-2.0
avastu/zulip,brainwane/zulip,eastlhu/zulip,MariaFaBella85/zulip,hayderimran7/zulip,willingc/zulip,jainayush975/zulip,vaidap/zulip,voidException/zulip,alliejones/zulip,jessedhillon/zulip,bowlofstew/zulip,firstblade/zulip,suxinde2009/zulip,zofuthan/zulip,JPJPJPOPOP/zulip,huangkebo/zulip,hayderimran7/zulip,babbage/zulip,MariaFaBella85/zulip,fw1121/zulip,hafeez3000/zulip,bssrdf/zulip,voidException/zulip,zulip/zulip,tiansiyuan/zulip,JPJPJPOPOP/zulip,wangdeshui/zulip,eeshangarg/zulip,adnanh/zulip,wweiradio/zulip,jerryge/zulip,themass/zulip,calvinleenyc/zulip,lfranchi/zulip,Diptanshu8/zulip,LAndreas/zulip,alliejones/zulip,zacps/zulip,MayB/zulip,glovebx/zulip,dxq-git/zulip,moria/zulip,dnmfarrell/zulip,jonesgithub/zulip,ryansnowboarder/zulip,jimmy54/zulip,kou/zulip,niftynei/zulip,hj3938/zulip,hackerkid/zulip,Jianchun1/zulip,JanzTam/zulip,ikasumiwt/zulip,JanzTam/zulip,vakila/zulip,wangdeshui/zulip,peguin40/zulip,susansls/zulip,vikas-parashar/zulip,Drooids/zulip,kaiyuanheshang/zulip,mahim97/zulip,glovebx/zulip,firstblade/zulip,zacps/zulip,timabbott/zulip,hackerkid/zulip,amyliu345/zulip,itnihao/zulip,kaiyuanheshang/zulip,pradiptad/zulip,dawran6/zulip,hustlzp/zulip,easyfmxu/zulip,tdr130/zulip,umkay/zulip,wweiradio/zulip,willingc/zulip,he15his/zulip,joyhchen/zulip,esander91/zulip,andersk/zulip,punchagan/zulip,Drooids/zulip,bastianh/zulip,wavelets/zulip,reyha/zulip,souravbadami/zulip,grave-w-grave/zulip,mansilladev/zulip,wdaher/zulip,jessedhillon/zulip,dawran6/zulip,mdavid/zulip,hustlzp/zulip,schatt/zulip,bluesea/zulip,PhilSk/zulip,wweiradio/zulip,shrikrishnaholla/zulip,zacps/zulip,so0k/zulip,akuseru/zulip,akuseru/zulip,punchagan/zulip,hayderimran7/zulip,voidException/zulip,Galexrt/zulip,jackrzhang/zulip,suxinde2009/zulip,akuseru/zulip,aps-sids/zulip,SmartPeople/zulip,j831/zulip,tiansiyuan/zulip,saitodisse/zulip,armooo/zulip,themass/zulip,jphilipsen05/zulip,christi3k/zulip,moria/zulip,moria/zulip,hj3938/zulip,hengqujushi/zulip,sup95/zulip,xuxiao/zulip,alliejones/zulip,showell/zulip,yuvipanda/zulip,jonesgithub/zulip,sonali0901/zulip,johnnygaddarr/zulip,levixie/zulip,timabbott/zulip,Gabriel0402/zulip,shaunstanislaus/zulip,pradiptad/zulip,EasonYi/zulip,m1ssou/zulip,johnny9/zulip,lfranchi/zulip,vabs22/zulip,zwily/zulip,udxxabp/zulip,krtkmj/zulip,ahmadassaf/zulip,Juanvulcano/zulip,m1ssou/zulip,praveenaki/zulip,dnmfarrell/zulip,bluesea/zulip,shubhamdhama/zulip,peiwei/zulip,stamhe/zulip,ipernet/zulip,zofuthan/zulip,dhcrzf/zulip,souravbadami/zulip,vabs22/zulip,amyliu345/zulip,PaulPetring/zulip,alliejones/zulip,developerfm/zulip,PhilSk/zulip,dxq-git/zulip,Diptanshu8/zulip,gkotian/zulip,ikasumiwt/zulip,paxapy/zulip,shrikrishnaholla/zulip,verma-varsha/zulip,cosmicAsymmetry/zulip,RobotCaleb/zulip,johnny9/zulip,blaze225/zulip,Jianchun1/zulip,synicalsyntax/zulip,proliming/zulip,hengqujushi/zulip,gigawhitlocks/zulip,souravbadami/zulip,kokoar/zulip,ikasumiwt/zulip,ahmadassaf/zulip,johnny9/zulip,itnihao/zulip,Galexrt/zulip,armooo/zulip,tiansiyuan/zulip,Suninus/zulip,qq1012803704/zulip,zhaoweigg/zulip,isht3/zulip,tiansiyuan/zulip,jeffcao/zulip,jerryge/zulip,hafeez3000/zulip,amyliu345/zulip,sup95/zulip,yocome/zulip,deer-hope/zulip,MayB/zulip,eeshangarg/zulip,developerfm/zulip,glovebx/zulip,MariaFaBella85/zulip,wdaher/zulip,brainwane/zulip,easyfmxu/zulip,Diptanshu8/zulip,luyifan/zulip,vabs22/zulip,so0k/zulip,amallia/zulip,PaulPetring/zulip,glovebx/zulip,Frouk/zulip,dotcool/zulip,reyha/zulip,aakash-cr7/zulip,shubhamdhama/zulip,Vallher/zulip,gigawhitlocks/zulip,lfranchi/zulip,ericzhou2008/zulip,rht/zulip,jerryge/zulip,levixie/zulip,natanovia/zulip,Vallher/zulip,Batterfii/zulip,MayB/zulip,xuxiao/zulip,EasonYi/zulip,punchagan/zulip,isht3/zulip,joyhchen/zulip,thomasboyt/zulip,zorojean/zulip,ApsOps/zulip,aps-sids/zulip,akuseru/zulip,deer-hope/zulip,ahmadassaf/zulip,qq1012803704/zulip,gkotian/zulip,tbutter/zulip,RobotCaleb/zulip,saitodisse/zulip,isht3/zulip,joshisa/zulip,zofuthan/zulip,lfranchi/zulip,yocome/zulip,hj3938/zulip,ipernet/zulip,pradiptad/zulip,shrikrishnaholla/zulip,jainayush975/zulip,mahim97/zulip,technicalpickles/zulip,blaze225/zulip,mdavid/zulip,zachallaun/zulip,themass/zulip,reyha/zulip,cosmicAsymmetry/zulip,brainwane/zulip,shubhamdhama/zulip,KJin99/zulip,luyifan/zulip,xuxiao/zulip,themass/zulip,KJin99/zulip,suxinde2009/zulip,ikasumiwt/zulip,karamcnair/zulip,jeffcao/zulip,zofuthan/zulip,paxapy/zulip,suxinde2009/zulip,fw1121/zulip,littledogboy/zulip,KingxBanana/zulip,avastu/zulip,aps-sids/zulip,wangdeshui/zulip,developerfm/zulip,brainwane/zulip,bastianh/zulip,showell/zulip,zachallaun/zulip,tommyip/zulip,johnny9/zulip,easyfmxu/zulip,tbutter/zulip,gigawhitlocks/zulip,tdr130/zulip,ahmadassaf/zulip,Cheppers/zulip,eastlhu/zulip,dawran6/zulip,niftynei/zulip,eastlhu/zulip,jainayush975/zulip,babbage/zulip,levixie/zulip,technicalpickles/zulip,so0k/zulip,verma-varsha/zulip,dotcool/zulip,jonesgithub/zulip,kokoar/zulip,yocome/zulip,vabs22/zulip,timabbott/zulip,synicalsyntax/zulip,voidException/zulip,kaiyuanheshang/zulip,suxinde2009/zulip,jerryge/zulip,jessedhillon/zulip,dxq-git/zulip,thomasboyt/zulip,developerfm/zulip,tommyip/zulip,grave-w-grave/zulip,seapasulli/zulip,aps-sids/zulip,huangkebo/zulip,dwrpayne/zulip,firstblade/zulip,dhcrzf/zulip,MayB/zulip,proliming/zulip,dnmfarrell/zulip,j831/zulip,jessedhillon/zulip,timabbott/zulip,fw1121/zulip,LeeRisk/zulip,andersk/zulip,seapasulli/zulip,mansilladev/zulip,joshisa/zulip,krtkmj/zulip,dnmfarrell/zulip,vaidap/zulip,zacps/zulip,glovebx/zulip,LeeRisk/zulip,hustlzp/zulip,easyfmxu/zulip,guiquanz/zulip,bastianh/zulip,bastianh/zulip,pradiptad/zulip,JanzTam/zulip,bowlofstew/zulip,ericzhou2008/zulip,zorojean/zulip,umkay/zulip,bastianh/zulip,dhcrzf/zulip,Cheppers/zulip,Batterfii/zulip,vakila/zulip,amallia/zulip,wavelets/zulip,Cheppers/zulip,vikas-parashar/zulip,developerfm/zulip,amanharitsh123/zulip,mohsenSy/zulip,luyifan/zulip,mahim97/zulip,dawran6/zulip,andersk/zulip,themass/zulip,schatt/zulip,zachallaun/zulip,dattatreya303/zulip,rht/zulip,aliceriot/zulip,firstblade/zulip,zwily/zulip,bowlofstew/zulip,bitemyapp/zulip,grave-w-grave/zulip,lfranchi/zulip,reyha/zulip,mansilladev/zulip,karamcnair/zulip,jeffcao/zulip,ikasumiwt/zulip,kaiyuanheshang/zulip,nicholasbs/zulip,amallia/zulip,willingc/zulip,hj3938/zulip,brainwane/zulip,arpith/zulip,grave-w-grave/zulip,j831/zulip,jimmy54/zulip,hackerkid/zulip,bssrdf/zulip,deer-hope/zulip,TigorC/zulip,saitodisse/zulip,so0k/zulip,blaze225/zulip,zorojean/zulip,jimmy54/zulip,showell/zulip,christi3k/zulip,LAndreas/zulip,zofuthan/zulip,qq1012803704/zulip,praveenaki/zulip,verma-varsha/zulip,yuvipanda/zulip,Suninus/zulip,sup95/zulip,ashwinirudrappa/zulip,easyfmxu/zulip,Gabriel0402/zulip,aliceriot/zulip,bitemyapp/zulip,huangkebo/zulip,noroot/zulip,yuvipanda/zulip,ryansnowboarder/zulip,EasonYi/zulip,krtkmj/zulip,esander91/zulip,armooo/zulip,grave-w-grave/zulip,jerryge/zulip,Cheppers/zulip,tdr130/zulip,SmartPeople/zulip,brainwane/zulip,dxq-git/zulip,swinghu/zulip,amallia/zulip,kou/zulip,hayderimran7/zulip,akuseru/zulip,aliceriot/zulip,Gabriel0402/zulip,peiwei/zulip,KJin99/zulip,ryanbackman/zulip,peguin40/zulip,krtkmj/zulip,so0k/zulip,fw1121/zulip,grave-w-grave/zulip,vaidap/zulip,littledogboy/zulip,codeKonami/zulip,bluesea/zulip,punchagan/zulip,udxxabp/zulip,Juanvulcano/zulip,zwily/zulip,Vallher/zulip,yocome/zulip,TigorC/zulip,ikasumiwt/zulip,stamhe/zulip,suxinde2009/zulip,joyhchen/zulip,xuxiao/zulip,showell/zulip,DazWorrall/zulip,JPJPJPOPOP/zulip,jeffcao/zulip,Batterfii/zulip,ashwinirudrappa/zulip,AZtheAsian/zulip,cosmicAsymmetry/zulip,LeeRisk/zulip,sharmaeklavya2/zulip,karamcnair/zulip,Drooids/zulip,voidException/zulip,akuseru/zulip,guiquanz/zulip,MariaFaBella85/zulip,brockwhittaker/zulip,rht/zulip,JanzTam/zulip,littledogboy/zulip,niftynei/zulip,gigawhitlocks/zulip,amanharitsh123/zulip,seapasulli/zulip,amanharitsh123/zulip,m1ssou/zulip,karamcnair/zulip,wweiradio/zulip,PaulPetring/zulip,dhcrzf/zulip,sharmaeklavya2/zulip,qq1012803704/zulip,verma-varsha/zulip,mdavid/zulip,praveenaki/zulip,sharmaeklavya2/zulip,ryansnowboarder/zulip,ryanbackman/zulip,deer-hope/zulip,DazWorrall/zulip,sonali0901/zulip,Vallher/zulip,zorojean/zulip,AZtheAsian/zulip,lfranchi/zulip,ashwinirudrappa/zulip,udxxabp/zulip,adnanh/zulip,atomic-labs/zulip,arpith/zulip,xuanhan863/zulip,bowlofstew/zulip,technicalpickles/zulip,tbutter/zulip,zhaoweigg/zulip,bluesea/zulip,calvinleenyc/zulip,j831/zulip,brainwane/zulip,yuvipanda/zulip,jackrzhang/zulip,armooo/zulip,zachallaun/zulip,JPJPJPOPOP/zulip,adnanh/zulip,Suninus/zulip,PaulPetring/zulip,gigawhitlocks/zulip,jackrzhang/zulip,hackerkid/zulip,nicholasbs/zulip,showell/zulip,akuseru/zulip,proliming/zulip,christi3k/zulip,krtkmj/zulip,EasonYi/zulip,he15his/zulip,seapasulli/zulip,tbutter/zulip,xuxiao/zulip,peguin40/zulip,swinghu/zulip,DazWorrall/zulip,punchagan/zulip,shaunstanislaus/zulip,aps-sids/zulip,joshisa/zulip,zorojean/zulip,jeffcao/zulip,vikas-parashar/zulip,levixie/zulip,aliceriot/zulip,deer-hope/zulip,susansls/zulip,easyfmxu/zulip,Qgap/zulip,proliming/zulip,seapasulli/zulip,noroot/zulip,MariaFaBella85/zulip,zulip/zulip,dnmfarrell/zulip,zorojean/zulip,itnihao/zulip,tdr130/zulip,kou/zulip,tdr130/zulip,joshisa/zulip,amyliu345/zulip,isht3/zulip,adnanh/zulip,seapasulli/zulip,noroot/zulip,bitemyapp/zulip,thomasboyt/zulip,gkotian/zulip,MariaFaBella85/zulip,Suninus/zulip,wavelets/zulip,hengqujushi/zulip,schatt/zulip,rht/zulip,wdaher/zulip,arpitpanwar/zulip,verma-varsha/zulip,paxapy/zulip,avastu/zulip,eastlhu/zulip,littledogboy/zulip,eeshangarg/zulip,ApsOps/zulip,jrowan/zulip,rht/zulip,xuanhan863/zulip,noroot/zulip,hengqujushi/zulip,ryanbackman/zulip,ashwinirudrappa/zulip,tommyip/zulip,littledogboy/zulip,xuanhan863/zulip,jessedhillon/zulip,nicholasbs/zulip,hayderimran7/zulip,Galexrt/zulip,zhaoweigg/zulip,jimmy54/zulip,wweiradio/zulip,dawran6/zulip,Batterfii/zulip,JPJPJPOPOP/zulip,shrikrishnaholla/zulip,arpitpanwar/zulip,dxq-git/zulip,dwrpayne/zulip,RobotCaleb/zulip,tbutter/zulip,jeffcao/zulip,ryanbackman/zulip,kou/zulip,dattatreya303/zulip,Diptanshu8/zulip,eastlhu/zulip,ericzhou2008/zulip,mansilladev/zulip,samatdav/zulip,udxxabp/zulip,MayB/zulip,shubhamdhama/zulip,nicholasbs/zulip,qq1012803704/zulip,RobotCaleb/zulip,babbage/zulip,ryanbackman/zulip,technicalpickles/zulip,atomic-labs/zulip,jackrzhang/zulip,zofuthan/zulip,dwrpayne/zulip,noroot/zulip,vabs22/zulip,andersk/zulip,jonesgithub/zulip,firstblade/zulip,itnihao/zulip,jainayush975/zulip,moria/zulip,stamhe/zulip,dattatreya303/zulip,sonali0901/zulip,tdr130/zulip,noroot/zulip,levixie/zulip,zwily/zulip,shrikrishnaholla/zulip,andersk/zulip,souravbadami/zulip,developerfm/zulip,thomasboyt/zulip,ApsOps/zulip,hj3938/zulip,hengqujushi/zulip,themass/zulip,mohsenSy/zulip,joyhchen/zulip,KJin99/zulip,TigorC/zulip,Vallher/zulip,mahim97/zulip,jrowan/zulip,SmartPeople/zulip,Drooids/zulip,shaunstanislaus/zulip,xuanhan863/zulip,qq1012803704/zulip,johnny9/zulip,tiansiyuan/zulip,vaidap/zulip,mansilladev/zulip,TigorC/zulip,peguin40/zulip,hustlzp/zulip,gkotian/zulip,yocome/zulip,KingxBanana/zulip,deer-hope/zulip,cosmicAsymmetry/zulip,jphilipsen05/zulip,wavelets/zulip,aakash-cr7/zulip,bitemyapp/zulip,KJin99/zulip,natanovia/zulip,KingxBanana/zulip,pradiptad/zulip,luyifan/zulip,amallia/zulip,samatdav/zulip,zachallaun/zulip,joshisa/zulip,zulip/zulip,joshisa/zulip,babbage/zulip,zofuthan/zulip,Frouk/zulip,bowlofstew/zulip,so0k/zulip,Batterfii/zulip,samatdav/zulip,vakila/zulip,sup95/zulip,punchagan/zulip,SmartPeople/zulip,KJin99/zulip,LAndreas/zulip,m1ssou/zulip,JanzTam/zulip,rishig/zulip,LeeRisk/zulip,hackerkid/zulip,bluesea/zulip,vabs22/zulip,TigorC/zulip,j831/zulip,ufosky-server/zulip,proliming/zulip,zulip/zulip,hackerkid/zulip,amyliu345/zulip,saitodisse/zulip,natanovia/zulip,nicholasbs/zulip,hustlzp/zulip,guiquanz/zulip,Drooids/zulip,stamhe/zulip,vakila/zulip,ahmadassaf/zulip,paxapy/zulip,wangdeshui/zulip,calvinleenyc/zulip,xuanhan863/zulip,jonesgithub/zulip,praveenaki/zulip,christi3k/zulip,thomasboyt/zulip,bssrdf/zulip,guiquanz/zulip,jimmy54/zulip,PhilSk/zulip,swinghu/zulip,christi3k/zulip,dotcool/zulip,LAndreas/zulip,johnnygaddarr/zulip,moria/zulip,ApsOps/zulip,Drooids/zulip,amallia/zulip,dattatreya303/zulip,j831/zulip,arpith/zulip,souravbadami/zulip,jphilipsen05/zulip,dhcrzf/zulip,Qgap/zulip,hafeez3000/zulip,PaulPetring/zulip,timabbott/zulip,KJin99/zulip,yocome/zulip,dattatreya303/zulip,ufosky-server/zulip,ufosky-server/zulip,zhaoweigg/zulip,zachallaun/zulip,ericzhou2008/zulip,ikasumiwt/zulip,sonali0901/zulip,arpitpanwar/zulip,kaiyuanheshang/zulip,Gabriel0402/zulip,reyha/zulip,dwrpayne/zulip,saitodisse/zulip,dhcrzf/zulip,alliejones/zulip,johnnygaddarr/zulip,eeshangarg/zulip,krtkmj/zulip,kokoar/zulip,arpitpanwar/zulip,ashwinirudrappa/zulip,amanharitsh123/zulip,arpith/zulip,wdaher/zulip,jrowan/zulip,seapasulli/zulip,Jianchun1/zulip,johnnygaddarr/zulip,tiansiyuan/zulip,babbage/zulip,Qgap/zulip,Frouk/zulip,brockwhittaker/zulip,bowlofstew/zulip,kou/zulip,jrowan/zulip,atomic-labs/zulip,peiwei/zulip,LAndreas/zulip,ApsOps/zulip,mohsenSy/zulip,blaze225/zulip,jackrzhang/zulip,yuvipanda/zulip,Juanvulcano/zulip,joyhchen/zulip,dhcrzf/zulip,rishig/zulip,shaunstanislaus/zulip,jrowan/zulip,wangdeshui/zulip,xuanhan863/zulip,synicalsyntax/zulip,mdavid/zulip,firstblade/zulip,peiwei/zulip,so0k/zulip,zhaoweigg/zulip,shrikrishnaholla/zulip,Galexrt/zulip,avastu/zulip,adnanh/zulip,fw1121/zulip,jphilipsen05/zulip,dnmfarrell/zulip,brockwhittaker/zulip,EasonYi/zulip,armooo/zulip,KingxBanana/zulip,PhilSk/zulip,he15his/zulip,MariaFaBella85/zulip,rishig/zulip,saitodisse/zulip,huangkebo/zulip,samatdav/zulip,swinghu/zulip,LeeRisk/zulip,willingc/zulip,AZtheAsian/zulip,KingxBanana/zulip,Diptanshu8/zulip,natanovia/zulip,ericzhou2008/zulip,atomic-labs/zulip,mansilladev/zulip,thomasboyt/zulip,Gabriel0402/zulip,schatt/zulip,bssrdf/zulip,hustlzp/zulip,JPJPJPOPOP/zulip,brockwhittaker/zulip,hafeez3000/zulip,babbage/zulip,vaidap/zulip,m1ssou/zulip,sharmaeklavya2/zulip,MayB/zulip,schatt/zulip,PhilSk/zulip,jeffcao/zulip,DazWorrall/zulip,natanovia/zulip,jimmy54/zulip,arpitpanwar/zulip,vikas-parashar/zulip,codeKonami/zulip,LAndreas/zulip,dattatreya303/zulip,zacps/zulip,he15his/zulip,peiwei/zulip,huangkebo/zulip,susansls/zulip,moria/zulip,glovebx/zulip,ryansnowboarder/zulip,LeeRisk/zulip,bssrdf/zulip,littledogboy/zulip,susansls/zulip,krtkmj/zulip,schatt/zulip,natanovia/zulip,Frouk/zulip,DazWorrall/zulip,eeshangarg/zulip,hengqujushi/zulip,luyifan/zulip,swinghu/zulip,johnnygaddarr/zulip,ApsOps/zulip,codeKonami/zulip,AZtheAsian/zulip,technicalpickles/zulip,stamhe/zulip,calvinleenyc/zulip,wangdeshui/zulip,mdavid/zulip,huangkebo/zulip,ashwinirudrappa/zulip,tommyip/zulip,DazWorrall/zulip,vikas-parashar/zulip,Qgap/zulip,Suninus/zulip,peiwei/zulip,Juanvulcano/zulip,sonali0901/zulip,nicholasbs/zulip,JanzTam/zulip,armooo/zulip,willingc/zulip,praveenaki/zulip,wavelets/zulip,guiquanz/zulip,jainayush975/zulip,Drooids/zulip,thomasboyt/zulip,shubhamdhama/zulip,swinghu/zulip,christi3k/zulip,bluesea/zulip,samatdav/zulip,joyhchen/zulip,tiansiyuan/zulip,codeKonami/zulip,luyifan/zulip,dwrpayne/zulip,EasonYi/zulip,hj3938/zulip,saitodisse/zulip,zwily/zulip,shaunstanislaus/zulip,littledogboy/zulip,Suninus/zulip,hustlzp/zulip,PaulPetring/zulip,SmartPeople/zulip,technicalpickles/zulip,shrikrishnaholla/zulip,wangdeshui/zulip,shaunstanislaus/zulip,Galexrt/zulip,eastlhu/zulip,tbutter/zulip,showell/zulip,synicalsyntax/zulip,qq1012803704/zulip,zwily/zulip,Frouk/zulip,paxapy/zulip,tommyip/zulip,codeKonami/zulip,Qgap/zulip,johnnygaddarr/zulip,dwrpayne/zulip,wdaher/zulip,blaze225/zulip,bitemyapp/zulip,zacps/zulip,umkay/zulip,susansls/zulip,RobotCaleb/zulip,zulip/zulip,Jianchun1/zulip,JanzTam/zulip,hj3938/zulip,deer-hope/zulip,avastu/zulip,atomic-labs/zulip,dwrpayne/zulip,m1ssou/zulip,armooo/zulip,umkay/zulip,natanovia/zulip,isht3/zulip,PhilSk/zulip,tdr130/zulip,hafeez3000/zulip,jphilipsen05/zulip,shubhamdhama/zulip,ufosky-server/zulip,levixie/zulip,jessedhillon/zulip,arpitpanwar/zulip,rht/zulip,xuanhan863/zulip,noroot/zulip,technicalpickles/zulip,dxq-git/zulip,yuvipanda/zulip,rht/zulip,schatt/zulip,susansls/zulip,peguin40/zulip,calvinleenyc/zulip,sup95/zulip,willingc/zulip,suxinde2009/zulip,aliceriot/zulip,shubhamdhama/zulip,brockwhittaker/zulip,mansilladev/zulip,kou/zulip,alliejones/zulip,kokoar/zulip,mohsenSy/zulip,karamcnair/zulip,ryanbackman/zulip,willingc/zulip,jainayush975/zulip,Juanvulcano/zulip,timabbott/zulip,karamcnair/zulip,Qgap/zulip,gigawhitlocks/zulip,ufosky-server/zulip,m1ssou/zulip,EasonYi/zulip,Batterfii/zulip,dxq-git/zulip,cosmicAsymmetry/zulip,zachallaun/zulip,isht3/zulip,amallia/zulip,calvinleenyc/zulip,rishig/zulip,easyfmxu/zulip,ryansnowboarder/zulip,aakash-cr7/zulip,rishig/zulip,souravbadami/zulip,jimmy54/zulip,ericzhou2008/zulip,praveenaki/zulip,zhaoweigg/zulip,Vallher/zulip,avastu/zulip,jerryge/zulip,ipernet/zulip,yuvipanda/zulip,vakila/zulip,zwily/zulip,johnnygaddarr/zulip,bastianh/zulip,guiquanz/zulip,wdaher/zulip,jonesgithub/zulip,dawran6/zulip,dotcool/zulip,voidException/zulip,tbutter/zulip,Frouk/zulip,alliejones/zulip,he15his/zulip,peiwei/zulip,kou/zulip,hengqujushi/zulip,niftynei/zulip,aliceriot/zulip,jphilipsen05/zulip,showell/zulip,punchagan/zulip,ashwinirudrappa/zulip,aps-sids/zulip,hackerkid/zulip,niftynei/zulip,joshisa/zulip,KingxBanana/zulip,eeshangarg/zulip,Jianchun1/zulip,hafeez3000/zulip,johnny9/zulip,synicalsyntax/zulip,glovebx/zulip,rishig/zulip,TigorC/zulip,andersk/zulip,aakash-cr7/zulip,jackrzhang/zulip,guiquanz/zulip,mohsenSy/zulip,aakash-cr7/zulip,wweiradio/zulip,wdaher/zulip,sonali0901/zulip,amanharitsh123/zulip,xuxiao/zulip,vakila/zulip,themass/zulip,vakila/zulip,jonesgithub/zulip,timabbott/zulip,aliceriot/zulip,peguin40/zulip,gigawhitlocks/zulip,bluesea/zulip,he15his/zulip,kaiyuanheshang/zulip,huangkebo/zulip,amyliu345/zulip,umkay/zulip,gkotian/zulip,andersk/zulip,tommyip/zulip,arpith/zulip,udxxabp/zulip,zorojean/zulip,RobotCaleb/zulip,esander91/zulip,proliming/zulip,mdavid/zulip,bitemyapp/zulip,codeKonami/zulip,tommyip/zulip,RobotCaleb/zulip,udxxabp/zulip,sharmaeklavya2/zulip,ahmadassaf/zulip,zhaoweigg/zulip,mohsenSy/zulip,mdavid/zulip,udxxabp/zulip,mahim97/zulip,Cheppers/zulip,jessedhillon/zulip,zulip/zulip,AZtheAsian/zulip,dotcool/zulip,levixie/zulip,stamhe/zulip,wweiradio/zulip,samatdav/zulip,he15his/zulip,vaidap/zulip,adnanh/zulip,bastianh/zulip,firstblade/zulip,esander91/zulip,synicalsyntax/zulip,Gabriel0402/zulip,voidException/zulip,niftynei/zulip,atomic-labs/zulip,bssrdf/zulip,kaiyuanheshang/zulip,LAndreas/zulip,Batterfii/zulip,ipernet/zulip,Cheppers/zulip,cosmicAsymmetry/zulip,esander91/zulip,synicalsyntax/zulip,Diptanshu8/zulip,nicholasbs/zulip,ipernet/zulip,ipernet/zulip,kokoar/zulip,MayB/zulip,blaze225/zulip,ApsOps/zulip,fw1121/zulip,yocome/zulip,Juanvulcano/zulip,gkotian/zulip,avastu/zulip,wavelets/zulip,sharmaeklavya2/zulip,ryansnowboarder/zulip,stamhe/zulip,LeeRisk/zulip,babbage/zulip,adnanh/zulip,johnny9/zulip,eeshangarg/zulip,paxapy/zulip,ufosky-server/zulip,Galexrt/zulip,jackrzhang/zulip,Vallher/zulip,mahim97/zulip,eastlhu/zulip,PaulPetring/zulip,ahmadassaf/zulip,atomic-labs/zulip,proliming/zulip,luyifan/zulip,aakash-cr7/zulip,bowlofstew/zulip,swinghu/zulip,kokoar/zulip,aps-sids/zulip,Suninus/zulip,developerfm/zulip,DazWorrall/zulip,verma-varsha/zulip,hafeez3000/zulip,moria/zulip,vikas-parashar/zulip,praveenaki/zulip,AZtheAsian/zulip,zulip/zulip,Galexrt/zulip,Gabriel0402/zulip,dnmfarrell/zulip,esander91/zulip,dotcool/zulip,hayderimran7/zulip,kokoar/zulip,bitemyapp/zulip,ericzhou2008/zulip,jerryge/zulip,umkay/zulip,Frouk/zulip,Qgap/zulip,hayderimran7/zulip,rishig/zulip,arpith/zulip,jrowan/zulip,sup95/zulip,fw1121/zulip,SmartPeople/zulip,ryansnowboarder/zulip,arpitpanwar/zulip,umkay/zulip,reyha/zulip,ipernet/zulip,lfranchi/zulip,brockwhittaker/zulip,itnihao/zulip,Cheppers/zulip,Jianchun1/zulip,dotcool/zulip,gkotian/zulip,karamcnair/zulip,amanharitsh123/zulip,ufosky-server/zulip,wavelets/zulip,shaunstanislaus/zulip,xuxiao/zulip,bssrdf/zulip,itnihao/zulip,itnihao/zulip,codeKonami/zulip,pradiptad/zulip,pradiptad/zulip,esander91/zulip
#!/usr/bin/env python # -*- coding: utf-8 -*- import humbug import glob import os from distutils.core import setup setup(name='humbug', version=humbug.__version__, description='Bindings for the Humbug message API', author='Humbug, Inc.', author_email='humbug@humbughq.com', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Communications :: Chat', ], url='https://humbughq.com/dist/api/', packages=['humbug'], data_files=[('share/humbug/examples', glob.glob('examples/*'))] + \ [(os.path.join('share/humbug/', relpath), glob.glob(os.path.join(relpath, '*'))) for relpath in glob.glob("integrations/*")] + \ [('share/humbug/demos', [os.path.join("demos", relpath) for relpath in os.listdir("demos")])], scripts=glob.glob("bin/*"), ) Revert "Ship all of our examples in the API update tarball." This reverts commit 4162114707f69bcfb6ecea95d7bdf4c080b4b168. (imported from commit a4d68bc2a68209bed8e00e6d58dd5f5d3a3187f9)
#!/usr/bin/env python # -*- coding: utf-8 -*- import humbug import glob import os from distutils.core import setup setup(name='humbug', version=humbug.__version__, description='Bindings for the Humbug message API', author='Humbug, Inc.', author_email='humbug@humbughq.com', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Communications :: Chat', ], url='https://humbughq.com/dist/api/', packages=['humbug'], data_files=[('share/humbug/examples', ["examples/humbugrc", "examples/send-message"])] + \ [(os.path.join('share/humbug/', relpath), glob.glob(os.path.join(relpath, '*'))) for relpath in glob.glob("integrations/*")] + \ [('share/humbug/demos', [os.path.join("demos", relpath) for relpath in os.listdir("demos")])], scripts=["bin/humbug-send"], )
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- import humbug import glob import os from distutils.core import setup setup(name='humbug', version=humbug.__version__, description='Bindings for the Humbug message API', author='Humbug, Inc.', author_email='humbug@humbughq.com', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Communications :: Chat', ], url='https://humbughq.com/dist/api/', packages=['humbug'], data_files=[('share/humbug/examples', glob.glob('examples/*'))] + \ [(os.path.join('share/humbug/', relpath), glob.glob(os.path.join(relpath, '*'))) for relpath in glob.glob("integrations/*")] + \ [('share/humbug/demos', [os.path.join("demos", relpath) for relpath in os.listdir("demos")])], scripts=glob.glob("bin/*"), ) <commit_msg>Revert "Ship all of our examples in the API update tarball." This reverts commit 4162114707f69bcfb6ecea95d7bdf4c080b4b168. (imported from commit a4d68bc2a68209bed8e00e6d58dd5f5d3a3187f9)<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- import humbug import glob import os from distutils.core import setup setup(name='humbug', version=humbug.__version__, description='Bindings for the Humbug message API', author='Humbug, Inc.', author_email='humbug@humbughq.com', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Communications :: Chat', ], url='https://humbughq.com/dist/api/', packages=['humbug'], data_files=[('share/humbug/examples', ["examples/humbugrc", "examples/send-message"])] + \ [(os.path.join('share/humbug/', relpath), glob.glob(os.path.join(relpath, '*'))) for relpath in glob.glob("integrations/*")] + \ [('share/humbug/demos', [os.path.join("demos", relpath) for relpath in os.listdir("demos")])], scripts=["bin/humbug-send"], )
#!/usr/bin/env python # -*- coding: utf-8 -*- import humbug import glob import os from distutils.core import setup setup(name='humbug', version=humbug.__version__, description='Bindings for the Humbug message API', author='Humbug, Inc.', author_email='humbug@humbughq.com', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Communications :: Chat', ], url='https://humbughq.com/dist/api/', packages=['humbug'], data_files=[('share/humbug/examples', glob.glob('examples/*'))] + \ [(os.path.join('share/humbug/', relpath), glob.glob(os.path.join(relpath, '*'))) for relpath in glob.glob("integrations/*")] + \ [('share/humbug/demos', [os.path.join("demos", relpath) for relpath in os.listdir("demos")])], scripts=glob.glob("bin/*"), ) Revert "Ship all of our examples in the API update tarball." This reverts commit 4162114707f69bcfb6ecea95d7bdf4c080b4b168. (imported from commit a4d68bc2a68209bed8e00e6d58dd5f5d3a3187f9)#!/usr/bin/env python # -*- coding: utf-8 -*- import humbug import glob import os from distutils.core import setup setup(name='humbug', version=humbug.__version__, description='Bindings for the Humbug message API', author='Humbug, Inc.', author_email='humbug@humbughq.com', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Communications :: Chat', ], url='https://humbughq.com/dist/api/', packages=['humbug'], data_files=[('share/humbug/examples', ["examples/humbugrc", "examples/send-message"])] + \ [(os.path.join('share/humbug/', relpath), glob.glob(os.path.join(relpath, '*'))) for relpath in glob.glob("integrations/*")] + \ [('share/humbug/demos', [os.path.join("demos", relpath) for relpath in os.listdir("demos")])], scripts=["bin/humbug-send"], )
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- import humbug import glob import os from distutils.core import setup setup(name='humbug', version=humbug.__version__, description='Bindings for the Humbug message API', author='Humbug, Inc.', author_email='humbug@humbughq.com', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Communications :: Chat', ], url='https://humbughq.com/dist/api/', packages=['humbug'], data_files=[('share/humbug/examples', glob.glob('examples/*'))] + \ [(os.path.join('share/humbug/', relpath), glob.glob(os.path.join(relpath, '*'))) for relpath in glob.glob("integrations/*")] + \ [('share/humbug/demos', [os.path.join("demos", relpath) for relpath in os.listdir("demos")])], scripts=glob.glob("bin/*"), ) <commit_msg>Revert "Ship all of our examples in the API update tarball." This reverts commit 4162114707f69bcfb6ecea95d7bdf4c080b4b168. (imported from commit a4d68bc2a68209bed8e00e6d58dd5f5d3a3187f9)<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- import humbug import glob import os from distutils.core import setup setup(name='humbug', version=humbug.__version__, description='Bindings for the Humbug message API', author='Humbug, Inc.', author_email='humbug@humbughq.com', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Communications :: Chat', ], url='https://humbughq.com/dist/api/', packages=['humbug'], data_files=[('share/humbug/examples', ["examples/humbugrc", "examples/send-message"])] + \ [(os.path.join('share/humbug/', relpath), glob.glob(os.path.join(relpath, '*'))) for relpath in glob.glob("integrations/*")] + \ [('share/humbug/demos', [os.path.join("demos", relpath) for relpath in os.listdir("demos")])], scripts=["bin/humbug-send"], )
81fa7c857b9c7fc7cf0c48028be22071da5cb318
test/execute-steps.py
test/execute-steps.py
# -*- coding: utf-8 -*- from lettuce import world, step from nose.tools import assert_equals, assert_true @step(u'Then I see no results') def then_i_see_spo_results(step): cell = world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/tbody/tr/td[@colspan="3"]') assert_equals(cell.text, 'None') @step(u'Then I see SPO results') def then_i_see_spo_results(step): head = world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/thead') assert_equals(head.text, 'spo') # Make sure we find more than the "None" entry return world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/tbody[count(tr)>1]')
# -*- coding: utf-8 -*- from lettuce import world, step from nose.tools import assert_equals, assert_true @step(u'Then I see no results') def then_i_see_spo_results(step): cell = world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/tbody/tr/td[@colspan="3"]') assert_equals(cell.text, 'None') @step(u'Then I see SPO results') def then_i_see_spo_results(step): head = world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/thead') assert_equals(head.text, 's p o') # Make sure we find more than the "None" entry return world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/tbody[count(tr)>1]')
Fix test to work with new selenium release
Fix test to work with new selenium release Currently testing needs bleeding edge of lettuce_webdriver which can be installed via pip install -e git+git://github.com/bbangert/lettuce_webdriver.git
Python
bsd-2-clause
cburgmer/deniz,cburgmer/deniz
# -*- coding: utf-8 -*- from lettuce import world, step from nose.tools import assert_equals, assert_true @step(u'Then I see no results') def then_i_see_spo_results(step): cell = world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/tbody/tr/td[@colspan="3"]') assert_equals(cell.text, 'None') @step(u'Then I see SPO results') def then_i_see_spo_results(step): head = world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/thead') assert_equals(head.text, 'spo') # Make sure we find more than the "None" entry return world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/tbody[count(tr)>1]') Fix test to work with new selenium release Currently testing needs bleeding edge of lettuce_webdriver which can be installed via pip install -e git+git://github.com/bbangert/lettuce_webdriver.git
# -*- coding: utf-8 -*- from lettuce import world, step from nose.tools import assert_equals, assert_true @step(u'Then I see no results') def then_i_see_spo_results(step): cell = world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/tbody/tr/td[@colspan="3"]') assert_equals(cell.text, 'None') @step(u'Then I see SPO results') def then_i_see_spo_results(step): head = world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/thead') assert_equals(head.text, 's p o') # Make sure we find more than the "None" entry return world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/tbody[count(tr)>1]')
<commit_before># -*- coding: utf-8 -*- from lettuce import world, step from nose.tools import assert_equals, assert_true @step(u'Then I see no results') def then_i_see_spo_results(step): cell = world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/tbody/tr/td[@colspan="3"]') assert_equals(cell.text, 'None') @step(u'Then I see SPO results') def then_i_see_spo_results(step): head = world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/thead') assert_equals(head.text, 'spo') # Make sure we find more than the "None" entry return world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/tbody[count(tr)>1]') <commit_msg>Fix test to work with new selenium release Currently testing needs bleeding edge of lettuce_webdriver which can be installed via pip install -e git+git://github.com/bbangert/lettuce_webdriver.git<commit_after>
# -*- coding: utf-8 -*- from lettuce import world, step from nose.tools import assert_equals, assert_true @step(u'Then I see no results') def then_i_see_spo_results(step): cell = world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/tbody/tr/td[@colspan="3"]') assert_equals(cell.text, 'None') @step(u'Then I see SPO results') def then_i_see_spo_results(step): head = world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/thead') assert_equals(head.text, 's p o') # Make sure we find more than the "None" entry return world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/tbody[count(tr)>1]')
# -*- coding: utf-8 -*- from lettuce import world, step from nose.tools import assert_equals, assert_true @step(u'Then I see no results') def then_i_see_spo_results(step): cell = world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/tbody/tr/td[@colspan="3"]') assert_equals(cell.text, 'None') @step(u'Then I see SPO results') def then_i_see_spo_results(step): head = world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/thead') assert_equals(head.text, 'spo') # Make sure we find more than the "None" entry return world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/tbody[count(tr)>1]') Fix test to work with new selenium release Currently testing needs bleeding edge of lettuce_webdriver which can be installed via pip install -e git+git://github.com/bbangert/lettuce_webdriver.git# -*- coding: utf-8 -*- from lettuce import world, step from nose.tools import assert_equals, assert_true @step(u'Then I see no results') def then_i_see_spo_results(step): cell = world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/tbody/tr/td[@colspan="3"]') assert_equals(cell.text, 'None') @step(u'Then I see SPO results') def then_i_see_spo_results(step): head = world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/thead') assert_equals(head.text, 's p o') # Make sure we find more than the "None" entry return world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/tbody[count(tr)>1]')
<commit_before># -*- coding: utf-8 -*- from lettuce import world, step from nose.tools import assert_equals, assert_true @step(u'Then I see no results') def then_i_see_spo_results(step): cell = world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/tbody/tr/td[@colspan="3"]') assert_equals(cell.text, 'None') @step(u'Then I see SPO results') def then_i_see_spo_results(step): head = world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/thead') assert_equals(head.text, 'spo') # Make sure we find more than the "None" entry return world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/tbody[count(tr)>1]') <commit_msg>Fix test to work with new selenium release Currently testing needs bleeding edge of lettuce_webdriver which can be installed via pip install -e git+git://github.com/bbangert/lettuce_webdriver.git<commit_after># -*- coding: utf-8 -*- from lettuce import world, step from nose.tools import assert_equals, assert_true @step(u'Then I see no results') def then_i_see_spo_results(step): cell = world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/tbody/tr/td[@colspan="3"]') assert_equals(cell.text, 'None') @step(u'Then I see SPO results') def then_i_see_spo_results(step): head = world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/thead') assert_equals(head.text, 's p o') # Make sure we find more than the "None" entry return world.browser.find_element_by_xpath('//*[@id="query_results"]//table[@class="resulttable"]/tbody[count(tr)>1]')
883ec0d68140995cfedc2d64d7d80cac1e234f39
app/oauth.py
app/oauth.py
# -*- coding: utf-8 -*- import logging import httplib2 import json import time import random from apiclient import errors from apiclient.discovery import build from oauth2client.client import SignedJwtAssertionCredentials class OAuth(): __services = dict() @staticmethod def getCredentials(email, scopes, client_secret, client_id): key = file(client_secret, 'rb') privateKey = key.read() key.close() credentials = SignedJwtAssertionCredentials(client_id, privateKey, scope=scopes, sub=email) http = httplib2.Http() http = credentials.authorize(http) credentials.refresh(http) return credentials, http @staticmethod def getService(email, api, version, scopes, client_secret, client_id, discoveryUrl=None): """ Return the service with constant credential @param email: email to execute the action @return: the drive service """ if not email.strip(): raise Exception("OAuth.getService : Email for service is missing") key = email + "/" + api + "/" + version if key not in OAuth.__services: credentials, http = OAuth.getCredentials(email, scopes, client_secret, client_id) if discoveryUrl: OAuth.__services[key] = build(api, version, http=http, discoveryServiceUrl=discoveryUrl) else: OAuth.__services[key] = build(api, version, http=http) logging.info("OAuth.getService : Service request by - " + email) return OAuth.__services[key]
# -*- coding: utf-8 -*- import logging import httplib2 import json import time import random from apiclient import errors from apiclient.discovery import build from oauth2client.client import SignedJwtAssertionCredentials class OAuth(): __services = dict() @staticmethod def getCredentials(email, scopes, client_secret, client_id): key = file(client_secret, 'rb') privateKey = key.read() key.close() credentials = SignedJwtAssertionCredentials(client_id, privateKey, scope=scopes, sub=email) http = httplib2.Http() http = credentials.authorize(http) credentials.refresh(http) return credentials, http @staticmethod def getService(email, api, version, scopes, client_secret, client_id, discoveryUrl=None): """ Return the service with constant credential @param email: email to execute the action @return: the drive service """ if not email.strip(): raise Exception("OAuth.getService : Email for service is missing") key = email + "/" + api + "/" + version if key not in OAuth.__services: credentials, http = OAuth.getCredentials(email, scopes, client_secret, client_id) if discoveryUrl: OAuth.__services[key] = build(api, version, http=http, discoveryServiceUrl=discoveryUrl, cache_discovery=False, cache=None) else: OAuth.__services[key] = build(api, version, http=http, cache_discovery=False, cache=None) logging.info("OAuth.getService : Service request by - " + email) return OAuth.__services[key]
Revert "Revert "Do not cache discovery""
Revert "Revert "Do not cache discovery"" This reverts commit e8aca80abcf8c309c13360c386b9505a595e1998.
Python
mit
lumapps/lumRest
# -*- coding: utf-8 -*- import logging import httplib2 import json import time import random from apiclient import errors from apiclient.discovery import build from oauth2client.client import SignedJwtAssertionCredentials class OAuth(): __services = dict() @staticmethod def getCredentials(email, scopes, client_secret, client_id): key = file(client_secret, 'rb') privateKey = key.read() key.close() credentials = SignedJwtAssertionCredentials(client_id, privateKey, scope=scopes, sub=email) http = httplib2.Http() http = credentials.authorize(http) credentials.refresh(http) return credentials, http @staticmethod def getService(email, api, version, scopes, client_secret, client_id, discoveryUrl=None): """ Return the service with constant credential @param email: email to execute the action @return: the drive service """ if not email.strip(): raise Exception("OAuth.getService : Email for service is missing") key = email + "/" + api + "/" + version if key not in OAuth.__services: credentials, http = OAuth.getCredentials(email, scopes, client_secret, client_id) if discoveryUrl: OAuth.__services[key] = build(api, version, http=http, discoveryServiceUrl=discoveryUrl) else: OAuth.__services[key] = build(api, version, http=http) logging.info("OAuth.getService : Service request by - " + email) return OAuth.__services[key] Revert "Revert "Do not cache discovery"" This reverts commit e8aca80abcf8c309c13360c386b9505a595e1998.
# -*- coding: utf-8 -*- import logging import httplib2 import json import time import random from apiclient import errors from apiclient.discovery import build from oauth2client.client import SignedJwtAssertionCredentials class OAuth(): __services = dict() @staticmethod def getCredentials(email, scopes, client_secret, client_id): key = file(client_secret, 'rb') privateKey = key.read() key.close() credentials = SignedJwtAssertionCredentials(client_id, privateKey, scope=scopes, sub=email) http = httplib2.Http() http = credentials.authorize(http) credentials.refresh(http) return credentials, http @staticmethod def getService(email, api, version, scopes, client_secret, client_id, discoveryUrl=None): """ Return the service with constant credential @param email: email to execute the action @return: the drive service """ if not email.strip(): raise Exception("OAuth.getService : Email for service is missing") key = email + "/" + api + "/" + version if key not in OAuth.__services: credentials, http = OAuth.getCredentials(email, scopes, client_secret, client_id) if discoveryUrl: OAuth.__services[key] = build(api, version, http=http, discoveryServiceUrl=discoveryUrl, cache_discovery=False, cache=None) else: OAuth.__services[key] = build(api, version, http=http, cache_discovery=False, cache=None) logging.info("OAuth.getService : Service request by - " + email) return OAuth.__services[key]
<commit_before># -*- coding: utf-8 -*- import logging import httplib2 import json import time import random from apiclient import errors from apiclient.discovery import build from oauth2client.client import SignedJwtAssertionCredentials class OAuth(): __services = dict() @staticmethod def getCredentials(email, scopes, client_secret, client_id): key = file(client_secret, 'rb') privateKey = key.read() key.close() credentials = SignedJwtAssertionCredentials(client_id, privateKey, scope=scopes, sub=email) http = httplib2.Http() http = credentials.authorize(http) credentials.refresh(http) return credentials, http @staticmethod def getService(email, api, version, scopes, client_secret, client_id, discoveryUrl=None): """ Return the service with constant credential @param email: email to execute the action @return: the drive service """ if not email.strip(): raise Exception("OAuth.getService : Email for service is missing") key = email + "/" + api + "/" + version if key not in OAuth.__services: credentials, http = OAuth.getCredentials(email, scopes, client_secret, client_id) if discoveryUrl: OAuth.__services[key] = build(api, version, http=http, discoveryServiceUrl=discoveryUrl) else: OAuth.__services[key] = build(api, version, http=http) logging.info("OAuth.getService : Service request by - " + email) return OAuth.__services[key] <commit_msg>Revert "Revert "Do not cache discovery"" This reverts commit e8aca80abcf8c309c13360c386b9505a595e1998.<commit_after>
# -*- coding: utf-8 -*- import logging import httplib2 import json import time import random from apiclient import errors from apiclient.discovery import build from oauth2client.client import SignedJwtAssertionCredentials class OAuth(): __services = dict() @staticmethod def getCredentials(email, scopes, client_secret, client_id): key = file(client_secret, 'rb') privateKey = key.read() key.close() credentials = SignedJwtAssertionCredentials(client_id, privateKey, scope=scopes, sub=email) http = httplib2.Http() http = credentials.authorize(http) credentials.refresh(http) return credentials, http @staticmethod def getService(email, api, version, scopes, client_secret, client_id, discoveryUrl=None): """ Return the service with constant credential @param email: email to execute the action @return: the drive service """ if not email.strip(): raise Exception("OAuth.getService : Email for service is missing") key = email + "/" + api + "/" + version if key not in OAuth.__services: credentials, http = OAuth.getCredentials(email, scopes, client_secret, client_id) if discoveryUrl: OAuth.__services[key] = build(api, version, http=http, discoveryServiceUrl=discoveryUrl, cache_discovery=False, cache=None) else: OAuth.__services[key] = build(api, version, http=http, cache_discovery=False, cache=None) logging.info("OAuth.getService : Service request by - " + email) return OAuth.__services[key]
# -*- coding: utf-8 -*- import logging import httplib2 import json import time import random from apiclient import errors from apiclient.discovery import build from oauth2client.client import SignedJwtAssertionCredentials class OAuth(): __services = dict() @staticmethod def getCredentials(email, scopes, client_secret, client_id): key = file(client_secret, 'rb') privateKey = key.read() key.close() credentials = SignedJwtAssertionCredentials(client_id, privateKey, scope=scopes, sub=email) http = httplib2.Http() http = credentials.authorize(http) credentials.refresh(http) return credentials, http @staticmethod def getService(email, api, version, scopes, client_secret, client_id, discoveryUrl=None): """ Return the service with constant credential @param email: email to execute the action @return: the drive service """ if not email.strip(): raise Exception("OAuth.getService : Email for service is missing") key = email + "/" + api + "/" + version if key not in OAuth.__services: credentials, http = OAuth.getCredentials(email, scopes, client_secret, client_id) if discoveryUrl: OAuth.__services[key] = build(api, version, http=http, discoveryServiceUrl=discoveryUrl) else: OAuth.__services[key] = build(api, version, http=http) logging.info("OAuth.getService : Service request by - " + email) return OAuth.__services[key] Revert "Revert "Do not cache discovery"" This reverts commit e8aca80abcf8c309c13360c386b9505a595e1998.# -*- coding: utf-8 -*- import logging import httplib2 import json import time import random from apiclient import errors from apiclient.discovery import build from oauth2client.client import SignedJwtAssertionCredentials class OAuth(): __services = dict() @staticmethod def getCredentials(email, scopes, client_secret, client_id): key = file(client_secret, 'rb') privateKey = key.read() key.close() credentials = SignedJwtAssertionCredentials(client_id, privateKey, scope=scopes, sub=email) http = httplib2.Http() http = credentials.authorize(http) credentials.refresh(http) return credentials, http @staticmethod def getService(email, api, version, scopes, client_secret, client_id, discoveryUrl=None): """ Return the service with constant credential @param email: email to execute the action @return: the drive service """ if not email.strip(): raise Exception("OAuth.getService : Email for service is missing") key = email + "/" + api + "/" + version if key not in OAuth.__services: credentials, http = OAuth.getCredentials(email, scopes, client_secret, client_id) if discoveryUrl: OAuth.__services[key] = build(api, version, http=http, discoveryServiceUrl=discoveryUrl, cache_discovery=False, cache=None) else: OAuth.__services[key] = build(api, version, http=http, cache_discovery=False, cache=None) logging.info("OAuth.getService : Service request by - " + email) return OAuth.__services[key]
<commit_before># -*- coding: utf-8 -*- import logging import httplib2 import json import time import random from apiclient import errors from apiclient.discovery import build from oauth2client.client import SignedJwtAssertionCredentials class OAuth(): __services = dict() @staticmethod def getCredentials(email, scopes, client_secret, client_id): key = file(client_secret, 'rb') privateKey = key.read() key.close() credentials = SignedJwtAssertionCredentials(client_id, privateKey, scope=scopes, sub=email) http = httplib2.Http() http = credentials.authorize(http) credentials.refresh(http) return credentials, http @staticmethod def getService(email, api, version, scopes, client_secret, client_id, discoveryUrl=None): """ Return the service with constant credential @param email: email to execute the action @return: the drive service """ if not email.strip(): raise Exception("OAuth.getService : Email for service is missing") key = email + "/" + api + "/" + version if key not in OAuth.__services: credentials, http = OAuth.getCredentials(email, scopes, client_secret, client_id) if discoveryUrl: OAuth.__services[key] = build(api, version, http=http, discoveryServiceUrl=discoveryUrl) else: OAuth.__services[key] = build(api, version, http=http) logging.info("OAuth.getService : Service request by - " + email) return OAuth.__services[key] <commit_msg>Revert "Revert "Do not cache discovery"" This reverts commit e8aca80abcf8c309c13360c386b9505a595e1998.<commit_after># -*- coding: utf-8 -*- import logging import httplib2 import json import time import random from apiclient import errors from apiclient.discovery import build from oauth2client.client import SignedJwtAssertionCredentials class OAuth(): __services = dict() @staticmethod def getCredentials(email, scopes, client_secret, client_id): key = file(client_secret, 'rb') privateKey = key.read() key.close() credentials = SignedJwtAssertionCredentials(client_id, privateKey, scope=scopes, sub=email) http = httplib2.Http() http = credentials.authorize(http) credentials.refresh(http) return credentials, http @staticmethod def getService(email, api, version, scopes, client_secret, client_id, discoveryUrl=None): """ Return the service with constant credential @param email: email to execute the action @return: the drive service """ if not email.strip(): raise Exception("OAuth.getService : Email for service is missing") key = email + "/" + api + "/" + version if key not in OAuth.__services: credentials, http = OAuth.getCredentials(email, scopes, client_secret, client_id) if discoveryUrl: OAuth.__services[key] = build(api, version, http=http, discoveryServiceUrl=discoveryUrl, cache_discovery=False, cache=None) else: OAuth.__services[key] = build(api, version, http=http, cache_discovery=False, cache=None) logging.info("OAuth.getService : Service request by - " + email) return OAuth.__services[key]
1eaae78c14b26378a606221eb61f97ec15134baa
src/gpl/test/simple01-td.py
src/gpl/test/simple01-td.py
from openroad import Design, Tech import helpers import gpl_aux tech = Tech() tech.readLiberty("./library/nangate45/NangateOpenCellLibrary_typical.lib") tech.readLef("./nangate45.lef") design = Design(tech) design.readDef("./simple01-td.def") design.evalTclString("create_clock -name core_clock -period 2 clk") design.evalTclString("set_wire_rc -signal -layer metal3") design.evalTclString("set_wire_rc -clock -layer metal5") gpl_aux.global_placement(design, timing_driven=True) design.evalTclString("estimate_parasitics -placement") design.evalTclString("report_worst_slack") def_file = helpers.make_result_file("simple01-td.def") design.writeDef(def_file) helpers.diff_files(def_file, "simple01-td.defok") # source helpers.tcl # set test_name simple01-td # read_liberty ./library/nangate45/NangateOpenCellLibrary_typical.lib # read_lef ./nangate45.lef # read_def ./$test_name.def # create_clock -name core_clock -period 2 clk # set_wire_rc -signal -layer metal3 # set_wire_rc -clock -layer metal5 # global_placement -timing_driven # # check reported wns # estimate_parasitics -placement # report_worst_slack # set def_file [make_result_file $test_name.def] # write_def $def_file # diff_file $def_file $test_name.defok
from openroad import Design, Tech import helpers import gpl_aux tech = Tech() tech.readLiberty("./library/nangate45/NangateOpenCellLibrary_typical.lib") tech.readLef("./nangate45.lef") design = Design(tech) design.readDef("./simple01-td.def") design.evalTclString("create_clock -name core_clock -period 2 clk") design.evalTclString("set_wire_rc -signal -layer metal3") design.evalTclString("set_wire_rc -clock -layer metal5") gpl_aux.global_placement(design, timing_driven=True) design.evalTclString("estimate_parasitics -placement") design.evalTclString("report_worst_slack") def_file = helpers.make_result_file("simple01-td.def") design.writeDef(def_file) helpers.diff_files(def_file, "simple01-td.defok")
Remove dead code from test
Remove dead code from test Signed-off-by: Don MacMillen <1f1e67e5fdb25d2e5cd18ddc0fee425272daab56@macmillen.net>
Python
bsd-3-clause
The-OpenROAD-Project/OpenROAD,The-OpenROAD-Project/OpenROAD,The-OpenROAD-Project/OpenROAD,The-OpenROAD-Project/OpenROAD,QuantamHD/OpenROAD,The-OpenROAD-Project/OpenROAD,QuantamHD/OpenROAD,QuantamHD/OpenROAD,QuantamHD/OpenROAD,QuantamHD/OpenROAD
from openroad import Design, Tech import helpers import gpl_aux tech = Tech() tech.readLiberty("./library/nangate45/NangateOpenCellLibrary_typical.lib") tech.readLef("./nangate45.lef") design = Design(tech) design.readDef("./simple01-td.def") design.evalTclString("create_clock -name core_clock -period 2 clk") design.evalTclString("set_wire_rc -signal -layer metal3") design.evalTclString("set_wire_rc -clock -layer metal5") gpl_aux.global_placement(design, timing_driven=True) design.evalTclString("estimate_parasitics -placement") design.evalTclString("report_worst_slack") def_file = helpers.make_result_file("simple01-td.def") design.writeDef(def_file) helpers.diff_files(def_file, "simple01-td.defok") # source helpers.tcl # set test_name simple01-td # read_liberty ./library/nangate45/NangateOpenCellLibrary_typical.lib # read_lef ./nangate45.lef # read_def ./$test_name.def # create_clock -name core_clock -period 2 clk # set_wire_rc -signal -layer metal3 # set_wire_rc -clock -layer metal5 # global_placement -timing_driven # # check reported wns # estimate_parasitics -placement # report_worst_slack # set def_file [make_result_file $test_name.def] # write_def $def_file # diff_file $def_file $test_name.defok Remove dead code from test Signed-off-by: Don MacMillen <1f1e67e5fdb25d2e5cd18ddc0fee425272daab56@macmillen.net>
from openroad import Design, Tech import helpers import gpl_aux tech = Tech() tech.readLiberty("./library/nangate45/NangateOpenCellLibrary_typical.lib") tech.readLef("./nangate45.lef") design = Design(tech) design.readDef("./simple01-td.def") design.evalTclString("create_clock -name core_clock -period 2 clk") design.evalTclString("set_wire_rc -signal -layer metal3") design.evalTclString("set_wire_rc -clock -layer metal5") gpl_aux.global_placement(design, timing_driven=True) design.evalTclString("estimate_parasitics -placement") design.evalTclString("report_worst_slack") def_file = helpers.make_result_file("simple01-td.def") design.writeDef(def_file) helpers.diff_files(def_file, "simple01-td.defok")
<commit_before>from openroad import Design, Tech import helpers import gpl_aux tech = Tech() tech.readLiberty("./library/nangate45/NangateOpenCellLibrary_typical.lib") tech.readLef("./nangate45.lef") design = Design(tech) design.readDef("./simple01-td.def") design.evalTclString("create_clock -name core_clock -period 2 clk") design.evalTclString("set_wire_rc -signal -layer metal3") design.evalTclString("set_wire_rc -clock -layer metal5") gpl_aux.global_placement(design, timing_driven=True) design.evalTclString("estimate_parasitics -placement") design.evalTclString("report_worst_slack") def_file = helpers.make_result_file("simple01-td.def") design.writeDef(def_file) helpers.diff_files(def_file, "simple01-td.defok") # source helpers.tcl # set test_name simple01-td # read_liberty ./library/nangate45/NangateOpenCellLibrary_typical.lib # read_lef ./nangate45.lef # read_def ./$test_name.def # create_clock -name core_clock -period 2 clk # set_wire_rc -signal -layer metal3 # set_wire_rc -clock -layer metal5 # global_placement -timing_driven # # check reported wns # estimate_parasitics -placement # report_worst_slack # set def_file [make_result_file $test_name.def] # write_def $def_file # diff_file $def_file $test_name.defok <commit_msg>Remove dead code from test Signed-off-by: Don MacMillen <1f1e67e5fdb25d2e5cd18ddc0fee425272daab56@macmillen.net><commit_after>
from openroad import Design, Tech import helpers import gpl_aux tech = Tech() tech.readLiberty("./library/nangate45/NangateOpenCellLibrary_typical.lib") tech.readLef("./nangate45.lef") design = Design(tech) design.readDef("./simple01-td.def") design.evalTclString("create_clock -name core_clock -period 2 clk") design.evalTclString("set_wire_rc -signal -layer metal3") design.evalTclString("set_wire_rc -clock -layer metal5") gpl_aux.global_placement(design, timing_driven=True) design.evalTclString("estimate_parasitics -placement") design.evalTclString("report_worst_slack") def_file = helpers.make_result_file("simple01-td.def") design.writeDef(def_file) helpers.diff_files(def_file, "simple01-td.defok")
from openroad import Design, Tech import helpers import gpl_aux tech = Tech() tech.readLiberty("./library/nangate45/NangateOpenCellLibrary_typical.lib") tech.readLef("./nangate45.lef") design = Design(tech) design.readDef("./simple01-td.def") design.evalTclString("create_clock -name core_clock -period 2 clk") design.evalTclString("set_wire_rc -signal -layer metal3") design.evalTclString("set_wire_rc -clock -layer metal5") gpl_aux.global_placement(design, timing_driven=True) design.evalTclString("estimate_parasitics -placement") design.evalTclString("report_worst_slack") def_file = helpers.make_result_file("simple01-td.def") design.writeDef(def_file) helpers.diff_files(def_file, "simple01-td.defok") # source helpers.tcl # set test_name simple01-td # read_liberty ./library/nangate45/NangateOpenCellLibrary_typical.lib # read_lef ./nangate45.lef # read_def ./$test_name.def # create_clock -name core_clock -period 2 clk # set_wire_rc -signal -layer metal3 # set_wire_rc -clock -layer metal5 # global_placement -timing_driven # # check reported wns # estimate_parasitics -placement # report_worst_slack # set def_file [make_result_file $test_name.def] # write_def $def_file # diff_file $def_file $test_name.defok Remove dead code from test Signed-off-by: Don MacMillen <1f1e67e5fdb25d2e5cd18ddc0fee425272daab56@macmillen.net>from openroad import Design, Tech import helpers import gpl_aux tech = Tech() tech.readLiberty("./library/nangate45/NangateOpenCellLibrary_typical.lib") tech.readLef("./nangate45.lef") design = Design(tech) design.readDef("./simple01-td.def") design.evalTclString("create_clock -name core_clock -period 2 clk") design.evalTclString("set_wire_rc -signal -layer metal3") design.evalTclString("set_wire_rc -clock -layer metal5") gpl_aux.global_placement(design, timing_driven=True) design.evalTclString("estimate_parasitics -placement") design.evalTclString("report_worst_slack") def_file = helpers.make_result_file("simple01-td.def") design.writeDef(def_file) helpers.diff_files(def_file, "simple01-td.defok")
<commit_before>from openroad import Design, Tech import helpers import gpl_aux tech = Tech() tech.readLiberty("./library/nangate45/NangateOpenCellLibrary_typical.lib") tech.readLef("./nangate45.lef") design = Design(tech) design.readDef("./simple01-td.def") design.evalTclString("create_clock -name core_clock -period 2 clk") design.evalTclString("set_wire_rc -signal -layer metal3") design.evalTclString("set_wire_rc -clock -layer metal5") gpl_aux.global_placement(design, timing_driven=True) design.evalTclString("estimate_parasitics -placement") design.evalTclString("report_worst_slack") def_file = helpers.make_result_file("simple01-td.def") design.writeDef(def_file) helpers.diff_files(def_file, "simple01-td.defok") # source helpers.tcl # set test_name simple01-td # read_liberty ./library/nangate45/NangateOpenCellLibrary_typical.lib # read_lef ./nangate45.lef # read_def ./$test_name.def # create_clock -name core_clock -period 2 clk # set_wire_rc -signal -layer metal3 # set_wire_rc -clock -layer metal5 # global_placement -timing_driven # # check reported wns # estimate_parasitics -placement # report_worst_slack # set def_file [make_result_file $test_name.def] # write_def $def_file # diff_file $def_file $test_name.defok <commit_msg>Remove dead code from test Signed-off-by: Don MacMillen <1f1e67e5fdb25d2e5cd18ddc0fee425272daab56@macmillen.net><commit_after>from openroad import Design, Tech import helpers import gpl_aux tech = Tech() tech.readLiberty("./library/nangate45/NangateOpenCellLibrary_typical.lib") tech.readLef("./nangate45.lef") design = Design(tech) design.readDef("./simple01-td.def") design.evalTclString("create_clock -name core_clock -period 2 clk") design.evalTclString("set_wire_rc -signal -layer metal3") design.evalTclString("set_wire_rc -clock -layer metal5") gpl_aux.global_placement(design, timing_driven=True) design.evalTclString("estimate_parasitics -placement") design.evalTclString("report_worst_slack") def_file = helpers.make_result_file("simple01-td.def") design.writeDef(def_file) helpers.diff_files(def_file, "simple01-td.defok")
d1bd82008c21942dee0ed29ba6d4f9eb54f2af33
issues/signals.py
issues/signals.py
from django.dispatch import Signal #: Signal fired when a new issue is posted via the API. issue_posted = Signal(providing_args=('request', 'issue'))
from django.dispatch import Signal #: Signal fired when a new issue is posted via the API. issue_posted = Signal() # Provides arguments: ('request', 'issue')
Remove documenting argument from Signal
Remove documenting argument from Signal
Python
mit
6aika/issue-reporting,6aika/issue-reporting,6aika/issue-reporting
from django.dispatch import Signal #: Signal fired when a new issue is posted via the API. issue_posted = Signal(providing_args=('request', 'issue')) Remove documenting argument from Signal
from django.dispatch import Signal #: Signal fired when a new issue is posted via the API. issue_posted = Signal() # Provides arguments: ('request', 'issue')
<commit_before>from django.dispatch import Signal #: Signal fired when a new issue is posted via the API. issue_posted = Signal(providing_args=('request', 'issue')) <commit_msg>Remove documenting argument from Signal<commit_after>
from django.dispatch import Signal #: Signal fired when a new issue is posted via the API. issue_posted = Signal() # Provides arguments: ('request', 'issue')
from django.dispatch import Signal #: Signal fired when a new issue is posted via the API. issue_posted = Signal(providing_args=('request', 'issue')) Remove documenting argument from Signalfrom django.dispatch import Signal #: Signal fired when a new issue is posted via the API. issue_posted = Signal() # Provides arguments: ('request', 'issue')
<commit_before>from django.dispatch import Signal #: Signal fired when a new issue is posted via the API. issue_posted = Signal(providing_args=('request', 'issue')) <commit_msg>Remove documenting argument from Signal<commit_after>from django.dispatch import Signal #: Signal fired when a new issue is posted via the API. issue_posted = Signal() # Provides arguments: ('request', 'issue')
c36c4e36c5f2ef5f270923172be04d528ad37090
script/lib/config.py
script/lib/config.py
#!/usr/bin/env python import platform import sys BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '44c71d88d9c098ece5dbf3e1fcc93ab87d8193cd' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform]
#!/usr/bin/env python import platform import sys BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '7e0bebc8666de8438c5baf4967fdabfc7646b3ed' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform]
Upgrade libchromiumcontent to fix linking error
Upgrade libchromiumcontent to fix linking error
Python
mit
pombredanne/electron,thompsonemerson/electron,jjz/electron,tonyganch/electron,bobwol/electron,electron/electron,voidbridge/electron,howmuchcomputer/electron,gbn972/electron,Jacobichou/electron,leftstick/electron,wolfflow/electron,jlord/electron,robinvandernoord/electron,eriser/electron,destan/electron,Jonekee/electron,faizalpribadi/electron,jcblw/electron,vHanda/electron,joaomoreno/atom-shell,nagyistoce/electron-atom-shell,saronwei/electron,beni55/electron,mrwizard82d1/electron,abhishekgahlot/electron,icattlecoder/electron,bpasero/electron,mrwizard82d1/electron,saronwei/electron,MaxWhere/electron,simonfork/electron,maxogden/atom-shell,shennushi/electron,carsonmcdonald/electron,dahal/electron,thomsonreuters/electron,voidbridge/electron,vipulroxx/electron,rsvip/electron,twolfson/electron,JesselJohn/electron,thompsonemerson/electron,RIAEvangelist/electron,bruce/electron,jjz/electron,aliib/electron,cqqccqc/electron,mubassirhayat/electron,baiwyc119/electron,destan/electron,shennushi/electron,jcblw/electron,astoilkov/electron,neutrous/electron,pirafrank/electron,chriskdon/electron,biblerule/UMCTelnetHub,xiruibing/electron,astoilkov/electron,faizalpribadi/electron,anko/electron,brave/electron,RobertJGabriel/electron,zhakui/electron,sky7sea/electron,bwiggs/electron,xfstudio/electron,pombredanne/electron,DivyaKMenon/electron,trigrass2/electron,rsvip/electron,biblerule/UMCTelnetHub,shiftkey/electron,vHanda/electron,jacksondc/electron,gerhardberger/electron,adamjgray/electron,leolujuyi/electron,wolfflow/electron,anko/electron,the-ress/electron,GoooIce/electron,takashi/electron,bruce/electron,arturts/electron,shiftkey/electron,Rokt33r/electron,nagyistoce/electron-atom-shell,subblue/electron,yan-foto/electron,shockone/electron,fireball-x/atom-shell,aecca/electron,takashi/electron,robinvandernoord/electron,Neron-X5/electron,RobertJGabriel/electron,RobertJGabriel/electron,ianscrivener/electron,jtburke/electron,hokein/atom-shell,icattlecoder/electron,adamjgray/electron,micalan/electron,rajatsingla28/electron,synaptek/electron,ervinb/electron,pirafrank/electron,gabriel/electron,Neron-X5/electron,evgenyzinoviev/electron,joaomoreno/atom-shell,JussMee15/electron,Ivshti/electron,jaanus/electron,abhishekgahlot/electron,mirrh/electron,voidbridge/electron,nicholasess/electron,lrlna/electron,gerhardberger/electron,jannishuebl/electron,etiktin/electron,yan-foto/electron,abhishekgahlot/electron,Gerhut/electron,cqqccqc/electron,chrisswk/electron,miniak/electron,benweissmann/electron,beni55/electron,stevekinney/electron,natgolov/electron,the-ress/electron,lzpfmh/electron,kcrt/electron,micalan/electron,sshiting/electron,iftekeriba/electron,Andrey-Pavlov/electron,coderhaoxin/electron,dkfiresky/electron,sshiting/electron,tomashanacek/electron,tonyganch/electron,SufianHassan/electron,vHanda/electron,brave/muon,jiaz/electron,greyhwndz/electron,bruce/electron,deed02392/electron,aichingm/electron,Faiz7412/electron,brave/muon,aecca/electron,sircharleswatson/electron,shockone/electron,trankmichael/electron,joneit/electron,jlhbaseball15/electron,aecca/electron,howmuchcomputer/electron,shockone/electron,leftstick/electron,ervinb/electron,fireball-x/atom-shell,rreimann/electron,gamedevsam/electron,jiaz/electron,mattdesl/electron,BionicClick/electron,tylergibson/electron,nagyistoce/electron-atom-shell,tincan24/electron,vaginessa/electron,lzpfmh/electron,tylergibson/electron,michaelchiche/electron,lzpfmh/electron,benweissmann/electron,brave/electron,aichingm/electron,electron/electron,christian-bromann/electron,bbondy/electron,shaundunne/electron,etiktin/electron,kazupon/electron,beni55/electron,arusakov/electron,felixrieseberg/electron,d-salas/electron,beni55/electron,Jacobichou/electron,synaptek/electron,Gerhut/electron,chrisswk/electron,Rokt33r/electron,natgolov/electron,leolujuyi/electron,John-Lin/electron,MaxWhere/electron,darwin/electron,voidbridge/electron,eriser/electron,fffej/electron,arusakov/electron,JussMee15/electron,kokdemo/electron,leolujuyi/electron,shiftkey/electron,coderhaoxin/electron,xiruibing/electron,felixrieseberg/electron,stevemao/electron,smczk/electron,Gerhut/electron,bitemyapp/electron,xiruibing/electron,JesselJohn/electron,adcentury/electron,aichingm/electron,thomsonreuters/electron,jjz/electron,John-Lin/electron,setzer777/electron,kcrt/electron,biblerule/UMCTelnetHub,posix4e/electron,jonatasfreitasv/electron,edulan/electron,nicobot/electron,davazp/electron,rhencke/electron,chriskdon/electron,John-Lin/electron,bitemyapp/electron,Neron-X5/electron,deepak1556/atom-shell,aichingm/electron,noikiy/electron,farmisen/electron,bitemyapp/electron,cos2004/electron,fomojola/electron,RIAEvangelist/electron,simonfork/electron,aichingm/electron,eric-seekas/electron,takashi/electron,SufianHassan/electron,Zagorakiss/electron,anko/electron,shennushi/electron,JesselJohn/electron,rajatsingla28/electron,baiwyc119/electron,Floato/electron,seanchas116/electron,bpasero/electron,dongjoon-hyun/electron,posix4e/electron,dongjoon-hyun/electron,setzer777/electron,gstack/infinium-shell,wolfflow/electron,DivyaKMenon/electron,egoist/electron,thingsinjars/electron,voidbridge/electron,vHanda/electron,Faiz7412/electron,smczk/electron,arusakov/electron,stevemao/electron,robinvandernoord/electron,mirrh/electron,simongregory/electron,carsonmcdonald/electron,vipulroxx/electron,twolfson/electron,Zagorakiss/electron,Jonekee/electron,voidbridge/electron,cqqccqc/electron,etiktin/electron,jtburke/electron,dahal/electron,SufianHassan/electron,LadyNaggaga/electron,darwin/electron,Rokt33r/electron,kikong/electron,jacksondc/electron,saronwei/electron,gabriel/electron,destan/electron,gabrielPeart/electron,leethomas/electron,gerhardberger/electron,christian-bromann/electron,bbondy/electron,saronwei/electron,BionicClick/electron,jsutcodes/electron,brave/muon,webmechanicx/electron,Evercoder/electron,sky7sea/electron,Ivshti/electron,evgenyzinoviev/electron,BionicClick/electron,deepak1556/atom-shell,joneit/electron,gerhardberger/electron,mirrh/electron,Evercoder/electron,ianscrivener/electron,thompsonemerson/electron,RIAEvangelist/electron,wan-qy/electron,oiledCode/electron,Gerhut/electron,timruffles/electron,leethomas/electron,adamjgray/electron,jsutcodes/electron,fomojola/electron,arturts/electron,kcrt/electron,farmisen/electron,synaptek/electron,trankmichael/electron,neutrous/electron,JesselJohn/electron,yan-foto/electron,jonatasfreitasv/electron,jjz/electron,saronwei/electron,sircharleswatson/electron,cos2004/electron,DivyaKMenon/electron,felixrieseberg/electron,brave/electron,biblerule/UMCTelnetHub,cqqccqc/electron,matiasinsaurralde/electron,coderhaoxin/electron,cos2004/electron,micalan/electron,leolujuyi/electron,icattlecoder/electron,Floato/electron,digideskio/electron,twolfson/electron,matiasinsaurralde/electron,soulteary/electron,RIAEvangelist/electron,davazp/electron,brenca/electron,jtburke/electron,adamjgray/electron,ankitaggarwal011/electron,bpasero/electron,leethomas/electron,subblue/electron,RIAEvangelist/electron,kokdemo/electron,shennushi/electron,mirrh/electron,greyhwndz/electron,MaxGraey/electron,leolujuyi/electron,deed02392/electron,digideskio/electron,John-Lin/electron,jacksondc/electron,coderhaoxin/electron,oiledCode/electron,eriser/electron,michaelchiche/electron,minggo/electron,Ivshti/electron,bruce/electron,Jacobichou/electron,webmechanicx/electron,tylergibson/electron,stevemao/electron,Floato/electron,mattotodd/electron,tomashanacek/electron,christian-bromann/electron,bitemyapp/electron,yalexx/electron,fritx/electron,bitemyapp/electron,gabrielPeart/electron,fireball-x/atom-shell,iftekeriba/electron,IonicaBizauKitchen/electron,leftstick/electron,pandoraui/electron,aichingm/electron,matiasinsaurralde/electron,the-ress/electron,jhen0409/electron,timruffles/electron,gbn972/electron,shennushi/electron,electron/electron,nicholasess/electron,yalexx/electron,tincan24/electron,ankitaggarwal011/electron,minggo/electron,mhkeller/electron,evgenyzinoviev/electron,deed02392/electron,IonicaBizauKitchen/electron,cos2004/electron,sky7sea/electron,tomashanacek/electron,lzpfmh/electron,jiaz/electron,preco21/electron,bobwol/electron,pandoraui/electron,thingsinjars/electron,nekuz0r/electron,jiaz/electron,shennushi/electron,yan-foto/electron,jiaz/electron,pombredanne/electron,twolfson/electron,JussMee15/electron,subblue/electron,systembugtj/electron,webmechanicx/electron,mhkeller/electron,abhishekgahlot/electron,joaomoreno/atom-shell,astoilkov/electron,ervinb/electron,mattotodd/electron,bpasero/electron,Zagorakiss/electron,John-Lin/electron,jlord/electron,gamedevsam/electron,davazp/electron,aaron-goshine/electron,jsutcodes/electron,JussMee15/electron,webmechanicx/electron,gbn972/electron,tincan24/electron,yalexx/electron,digideskio/electron,posix4e/electron,renaesop/electron,preco21/electron,GoooIce/electron,mjaniszew/electron,mubassirhayat/electron,brenca/electron,gabrielPeart/electron,IonicaBizauKitchen/electron,pandoraui/electron,preco21/electron,adamjgray/electron,kokdemo/electron,kokdemo/electron,arusakov/electron,fritx/electron,jonatasfreitasv/electron,jhen0409/electron,fomojola/electron,synaptek/electron,faizalpribadi/electron,shaundunne/electron,mattotodd/electron,RobertJGabriel/electron,trigrass2/electron,d-salas/electron,noikiy/electron,astoilkov/electron,jaanus/electron,adcentury/electron,dkfiresky/electron,ianscrivener/electron,jacksondc/electron,gabriel/electron,electron/electron,benweissmann/electron,MaxWhere/electron,nekuz0r/electron,synaptek/electron,brave/muon,aaron-goshine/electron,rhencke/electron,MaxGraey/electron,sircharleswatson/electron,oiledCode/electron,Jonekee/electron,sshiting/electron,tincan24/electron,eric-seekas/electron,shaundunne/electron,roadev/electron,iftekeriba/electron,JesselJohn/electron,edulan/electron,trankmichael/electron,edulan/electron,nicobot/electron,davazp/electron,bpasero/electron,webmechanicx/electron,brenca/electron,Ivshti/electron,Jonekee/electron,thompsonemerson/electron,rprichard/electron,jonatasfreitasv/electron,jsutcodes/electron,pandoraui/electron,gabrielPeart/electron,takashi/electron,pirafrank/electron,Andrey-Pavlov/electron,rprichard/electron,farmisen/electron,sircharleswatson/electron,jannishuebl/electron,nekuz0r/electron,egoist/electron,xfstudio/electron,thompsonemerson/electron,Evercoder/electron,JesselJohn/electron,jcblw/electron,joaomoreno/atom-shell,matiasinsaurralde/electron,tonyganch/electron,sircharleswatson/electron,edulan/electron,aliib/electron,jannishuebl/electron,oiledCode/electron,wan-qy/electron,dahal/electron,greyhwndz/electron,kazupon/electron,preco21/electron,deepak1556/atom-shell,Andrey-Pavlov/electron,Evercoder/electron,leftstick/electron,shiftkey/electron,wan-qy/electron,LadyNaggaga/electron,medixdev/electron,mattotodd/electron,tinydew4/electron,tinydew4/electron,joaomoreno/atom-shell,carsonmcdonald/electron,timruffles/electron,rsvip/electron,tonyganch/electron,gbn972/electron,tonyganch/electron,bbondy/electron,kokdemo/electron,mattotodd/electron,kostia/electron,matiasinsaurralde/electron,kikong/electron,arturts/electron,systembugtj/electron,leethomas/electron,John-Lin/electron,michaelchiche/electron,destan/electron,Zagorakiss/electron,aliib/electron,kostia/electron,vipulroxx/electron,simonfork/electron,mrwizard82d1/electron,pirafrank/electron,wan-qy/electron,pombredanne/electron,benweissmann/electron,rreimann/electron,twolfson/electron,pandoraui/electron,sky7sea/electron,vaginessa/electron,timruffles/electron,smczk/electron,chriskdon/electron,jacksondc/electron,icattlecoder/electron,ankitaggarwal011/electron,jsutcodes/electron,MaxGraey/electron,xfstudio/electron,aaron-goshine/electron,yalexx/electron,Faiz7412/electron,meowlab/electron,fritx/electron,sshiting/electron,hokein/atom-shell,saronwei/electron,pombredanne/electron,jiaz/electron,aliib/electron,deepak1556/atom-shell,smczk/electron,egoist/electron,BionicClick/electron,lrlna/electron,jcblw/electron,howmuchcomputer/electron,beni55/electron,vaginessa/electron,leolujuyi/electron,kenmozi/electron,thingsinjars/electron,fabien-d/electron,fabien-d/electron,posix4e/electron,egoist/electron,jaanus/electron,baiwyc119/electron,jtburke/electron,Rokt33r/electron,sky7sea/electron,Floato/electron,kikong/electron,lrlna/electron,fomojola/electron,jaanus/electron,shockone/electron,Jacobichou/electron,bwiggs/electron,jhen0409/electron,fffej/electron,timruffles/electron,oiledCode/electron,pirafrank/electron,Rokt33r/electron,xfstudio/electron,zhakui/electron,robinvandernoord/electron,cqqccqc/electron,Faiz7412/electron,kokdemo/electron,vaginessa/electron,simongregory/electron,preco21/electron,xfstudio/electron,gerhardberger/electron,anko/electron,eriser/electron,seanchas116/electron,aecca/electron,kcrt/electron,jhen0409/electron,joneit/electron,aaron-goshine/electron,roadev/electron,gstack/infinium-shell,trigrass2/electron,nicholasess/electron,Andrey-Pavlov/electron,vipulroxx/electron,LadyNaggaga/electron,chrisswk/electron,gstack/infinium-shell,rajatsingla28/electron,shaundunne/electron,natgolov/electron,gerhardberger/electron,vHanda/electron,kazupon/electron,LadyNaggaga/electron,minggo/electron,subblue/electron,dahal/electron,egoist/electron,wolfflow/electron,soulteary/electron,eric-seekas/electron,minggo/electron,wan-qy/electron,noikiy/electron,gabrielPeart/electron,stevemao/electron,stevekinney/electron,nicobot/electron,destan/electron,vipulroxx/electron,simongregory/electron,bright-sparks/electron,mattdesl/electron,ankitaggarwal011/electron,shiftkey/electron,vipulroxx/electron,trigrass2/electron,ianscrivener/electron,jtburke/electron,natgolov/electron,vaginessa/electron,deed02392/electron,electron/electron,digideskio/electron,davazp/electron,howmuchcomputer/electron,eriser/electron,nicobot/electron,systembugtj/electron,takashi/electron,baiwyc119/electron,kcrt/electron,pirafrank/electron,noikiy/electron,iftekeriba/electron,lrlna/electron,sky7sea/electron,renaesop/electron,darwin/electron,digideskio/electron,renaesop/electron,posix4e/electron,thingsinjars/electron,simonfork/electron,maxogden/atom-shell,destan/electron,kcrt/electron,GoooIce/electron,neutrous/electron,mjaniszew/electron,matiasinsaurralde/electron,Gerhut/electron,DivyaKMenon/electron,Zagorakiss/electron,etiktin/electron,jannishuebl/electron,Faiz7412/electron,miniak/electron,rreimann/electron,astoilkov/electron,seanchas116/electron,MaxWhere/electron,stevekinney/electron,brave/electron,rreimann/electron,d-salas/electron,aliib/electron,mrwizard82d1/electron,shiftkey/electron,oiledCode/electron,leethomas/electron,yalexx/electron,aecca/electron,joneit/electron,nicobot/electron,bwiggs/electron,deed02392/electron,digideskio/electron,thomsonreuters/electron,dongjoon-hyun/electron,evgenyzinoviev/electron,mubassirhayat/electron,nicholasess/electron,faizalpribadi/electron,medixdev/electron,soulteary/electron,kenmozi/electron,dkfiresky/electron,Neron-X5/electron,ervinb/electron,mhkeller/electron,simongregory/electron,jonatasfreitasv/electron,astoilkov/electron,gabriel/electron,carsonmcdonald/electron,GoooIce/electron,vHanda/electron,howmuchcomputer/electron,stevekinney/electron,miniak/electron,mirrh/electron,wan-qy/electron,bright-sparks/electron,nekuz0r/electron,ianscrivener/electron,brenca/electron,gstack/infinium-shell,Andrey-Pavlov/electron,kostia/electron,nekuz0r/electron,wolfflow/electron,micalan/electron,mjaniszew/electron,kazupon/electron,medixdev/electron,fritx/electron,davazp/electron,fritx/electron,yalexx/electron,jaanus/electron,maxogden/atom-shell,dkfiresky/electron,smczk/electron,miniak/electron,the-ress/electron,anko/electron,IonicaBizauKitchen/electron,stevemao/electron,arturts/electron,farmisen/electron,baiwyc119/electron,icattlecoder/electron,rhencke/electron,bpasero/electron,RobertJGabriel/electron,baiwyc119/electron,hokein/atom-shell,bbondy/electron,carsonmcdonald/electron,arusakov/electron,bobwol/electron,systembugtj/electron,tylergibson/electron,simonfork/electron,thingsinjars/electron,fffej/electron,kenmozi/electron,dkfiresky/electron,eric-seekas/electron,sshiting/electron,jhen0409/electron,miniak/electron,Floato/electron,felixrieseberg/electron,chriskdon/electron,Gerhut/electron,mattdesl/electron,greyhwndz/electron,biblerule/UMCTelnetHub,cos2004/electron,electron/electron,eriser/electron,tomashanacek/electron,rhencke/electron,LadyNaggaga/electron,ianscrivener/electron,renaesop/electron,meowlab/electron,zhakui/electron,Neron-X5/electron,maxogden/atom-shell,bitemyapp/electron,iftekeriba/electron,icattlecoder/electron,brenca/electron,deed02392/electron,gabriel/electron,kenmozi/electron,nicholasess/electron,bbondy/electron,beni55/electron,aecca/electron,farmisen/electron,arturts/electron,lzpfmh/electron,tomashanacek/electron,medixdev/electron,mattdesl/electron,Evercoder/electron,edulan/electron,the-ress/electron,gamedevsam/electron,SufianHassan/electron,biblerule/UMCTelnetHub,carsonmcdonald/electron,jcblw/electron,joneit/electron,evgenyzinoviev/electron,the-ress/electron,DivyaKMenon/electron,setzer777/electron,darwin/electron,minggo/electron,etiktin/electron,setzer777/electron,renaesop/electron,roadev/electron,adcentury/electron,seanchas116/electron,tonyganch/electron,MaxGraey/electron,mjaniszew/electron,jlhbaseball15/electron,tinydew4/electron,fritx/electron,bright-sparks/electron,natgolov/electron,fffej/electron,Jonekee/electron,bruce/electron,fabien-d/electron,gbn972/electron,meowlab/electron,dongjoon-hyun/electron,medixdev/electron,leftstick/electron,jtburke/electron,rhencke/electron,roadev/electron,JussMee15/electron,dahal/electron,felixrieseberg/electron,nekuz0r/electron,rhencke/electron,neutrous/electron,fffej/electron,yan-foto/electron,shaundunne/electron,bwiggs/electron,aaron-goshine/electron,christian-bromann/electron,kazupon/electron,kenmozi/electron,trankmichael/electron,LadyNaggaga/electron,gamedevsam/electron,Andrey-Pavlov/electron,mubassirhayat/electron,cos2004/electron,ervinb/electron,gstack/infinium-shell,hokein/atom-shell,jlord/electron,greyhwndz/electron,dahal/electron,stevemao/electron,greyhwndz/electron,cqqccqc/electron,tylergibson/electron,fomojola/electron,d-salas/electron,preco21/electron,abhishekgahlot/electron,anko/electron,fabien-d/electron,jaanus/electron,BionicClick/electron,JussMee15/electron,howmuchcomputer/electron,shockone/electron,jacksondc/electron,seanchas116/electron,fireball-x/atom-shell,gabrielPeart/electron,RobertJGabriel/electron,soulteary/electron,rajatsingla28/electron,IonicaBizauKitchen/electron,fabien-d/electron,brave/muon,bobwol/electron,stevekinney/electron,eric-seekas/electron,bbondy/electron,rprichard/electron,adcentury/electron,abhishekgahlot/electron,zhakui/electron,nicholasess/electron,kazupon/electron,thomsonreuters/electron,jlhbaseball15/electron,robinvandernoord/electron,etiktin/electron,gamedevsam/electron,mattotodd/electron,bwiggs/electron,tylergibson/electron,nicobot/electron,michaelchiche/electron,BionicClick/electron,nagyistoce/electron-atom-shell,DivyaKMenon/electron,GoooIce/electron,systembugtj/electron,dkfiresky/electron,adcentury/electron,jlhbaseball15/electron,robinvandernoord/electron,sircharleswatson/electron,ankitaggarwal011/electron,soulteary/electron,MaxWhere/electron,jjz/electron,meowlab/electron,leethomas/electron,thompsonemerson/electron,jhen0409/electron,zhakui/electron,christian-bromann/electron,rsvip/electron,smczk/electron,fffej/electron,lrlna/electron,coderhaoxin/electron,kikong/electron,rsvip/electron,jlord/electron,micalan/electron,arusakov/electron,Neron-X5/electron,Zagorakiss/electron,SufianHassan/electron,thomsonreuters/electron,bright-sparks/electron,bruce/electron,simonfork/electron,xiruibing/electron,xfstudio/electron,bright-sparks/electron,evgenyzinoviev/electron,chrisswk/electron,twolfson/electron,gabriel/electron,faizalpribadi/electron,maxogden/atom-shell,tomashanacek/electron,mjaniszew/electron,lzpfmh/electron,electron/electron,webmechanicx/electron,edulan/electron,felixrieseberg/electron,roadev/electron,mattdesl/electron,rajatsingla28/electron,jjz/electron,MaxGraey/electron,mrwizard82d1/electron,meowlab/electron,bpasero/electron,rprichard/electron,jlhbaseball15/electron,bwiggs/electron,adcentury/electron,MaxWhere/electron,seanchas116/electron,thingsinjars/electron,michaelchiche/electron,kikong/electron,bright-sparks/electron,trankmichael/electron,Rokt33r/electron,sshiting/electron,ervinb/electron,mhkeller/electron,mjaniszew/electron,gbn972/electron,jlord/electron,leftstick/electron,jsutcodes/electron,iftekeriba/electron,shockone/electron,tinydew4/electron,zhakui/electron,brave/muon,trigrass2/electron,benweissmann/electron,subblue/electron,mattdesl/electron,medixdev/electron,gerhardberger/electron,the-ress/electron,jannishuebl/electron,IonicaBizauKitchen/electron,lrlna/electron,roadev/electron,pombredanne/electron,coderhaoxin/electron,joneit/electron,nagyistoce/electron-atom-shell,shaundunne/electron,brave/electron,jcblw/electron,mirrh/electron,farmisen/electron,xiruibing/electron,neutrous/electron,mhkeller/electron,noikiy/electron,soulteary/electron,chrisswk/electron,yan-foto/electron,Jonekee/electron,tinydew4/electron,chriskdon/electron,brenca/electron,kostia/electron,gamedevsam/electron,mubassirhayat/electron,rajatsingla28/electron,trankmichael/electron,rreimann/electron,dongjoon-hyun/electron,Ivshti/electron,aaron-goshine/electron,bobwol/electron,takashi/electron,mhkeller/electron,rreimann/electron,setzer777/electron,xiruibing/electron,meowlab/electron,tinydew4/electron,Floato/electron,aliib/electron,Evercoder/electron,trigrass2/electron,bobwol/electron,dongjoon-hyun/electron,joaomoreno/atom-shell,ankitaggarwal011/electron,setzer777/electron,adamjgray/electron,chriskdon/electron,stevekinney/electron,kostia/electron,fomojola/electron,posix4e/electron,christian-bromann/electron,d-salas/electron,arturts/electron,GoooIce/electron,renaesop/electron,faizalpribadi/electron,darwin/electron,natgolov/electron,michaelchiche/electron,fireball-x/atom-shell,eric-seekas/electron,tincan24/electron,tincan24/electron,vaginessa/electron,wolfflow/electron,kenmozi/electron,simongregory/electron,kostia/electron,jlhbaseball15/electron,systembugtj/electron,brave/electron,deepak1556/atom-shell,minggo/electron,SufianHassan/electron,RIAEvangelist/electron,mrwizard82d1/electron,egoist/electron,noikiy/electron,pandoraui/electron,synaptek/electron,Jacobichou/electron,miniak/electron,simongregory/electron,Jacobichou/electron,hokein/atom-shell,d-salas/electron,thomsonreuters/electron,subblue/electron,benweissmann/electron,micalan/electron,jonatasfreitasv/electron,neutrous/electron,jannishuebl/electron
#!/usr/bin/env python import platform import sys BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '44c71d88d9c098ece5dbf3e1fcc93ab87d8193cd' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] Upgrade libchromiumcontent to fix linking error
#!/usr/bin/env python import platform import sys BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '7e0bebc8666de8438c5baf4967fdabfc7646b3ed' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform]
<commit_before>#!/usr/bin/env python import platform import sys BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '44c71d88d9c098ece5dbf3e1fcc93ab87d8193cd' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] <commit_msg>Upgrade libchromiumcontent to fix linking error<commit_after>
#!/usr/bin/env python import platform import sys BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '7e0bebc8666de8438c5baf4967fdabfc7646b3ed' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform]
#!/usr/bin/env python import platform import sys BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '44c71d88d9c098ece5dbf3e1fcc93ab87d8193cd' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] Upgrade libchromiumcontent to fix linking error#!/usr/bin/env python import platform import sys BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '7e0bebc8666de8438c5baf4967fdabfc7646b3ed' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform]
<commit_before>#!/usr/bin/env python import platform import sys BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '44c71d88d9c098ece5dbf3e1fcc93ab87d8193cd' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] <commit_msg>Upgrade libchromiumcontent to fix linking error<commit_after>#!/usr/bin/env python import platform import sys BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '7e0bebc8666de8438c5baf4967fdabfc7646b3ed' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform]
85c9206dd0a4af52a31d7b6e9283bc7c103e3953
demos/dlgr/demos/iterated_drawing/models.py
demos/dlgr/demos/iterated_drawing/models.py
import base64 import json import os import random from dallinger.nodes import Source class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = {"polymorphic_identity": "drawing_source"} def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = ["owl.png"] # We're selecting from a list of only one item here, but it's a useful # technique to demonstrate: image = random.choice(images) image_path = os.path.join("static", "stimuli", image) uri_encoded_image = "data:image/png;base64," + base64.b64encode( open(image_path, "rb").read() ) return json.dumps({"image": uri_encoded_image, "sketch": ""})
import base64 import json import os import random from dallinger.nodes import Source class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = {"polymorphic_identity": "drawing_source"} def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = ["owl.png"] # We're selecting from a list of only one item here, but it's a useful # technique to demonstrate: image = random.choice(images) image_path = os.path.join("static", "stimuli", image) uri_encoded_image = u"data:image/png;base64," + base64.b64encode( open(image_path, "rb").read() ).decode("ascii") return json.dumps({"image": uri_encoded_image, "sketch": ""})
Fix encoding of source image to work on Python3
Fix encoding of source image to work on Python3
Python
mit
Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger
import base64 import json import os import random from dallinger.nodes import Source class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = {"polymorphic_identity": "drawing_source"} def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = ["owl.png"] # We're selecting from a list of only one item here, but it's a useful # technique to demonstrate: image = random.choice(images) image_path = os.path.join("static", "stimuli", image) uri_encoded_image = "data:image/png;base64," + base64.b64encode( open(image_path, "rb").read() ) return json.dumps({"image": uri_encoded_image, "sketch": ""}) Fix encoding of source image to work on Python3
import base64 import json import os import random from dallinger.nodes import Source class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = {"polymorphic_identity": "drawing_source"} def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = ["owl.png"] # We're selecting from a list of only one item here, but it's a useful # technique to demonstrate: image = random.choice(images) image_path = os.path.join("static", "stimuli", image) uri_encoded_image = u"data:image/png;base64," + base64.b64encode( open(image_path, "rb").read() ).decode("ascii") return json.dumps({"image": uri_encoded_image, "sketch": ""})
<commit_before>import base64 import json import os import random from dallinger.nodes import Source class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = {"polymorphic_identity": "drawing_source"} def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = ["owl.png"] # We're selecting from a list of only one item here, but it's a useful # technique to demonstrate: image = random.choice(images) image_path = os.path.join("static", "stimuli", image) uri_encoded_image = "data:image/png;base64," + base64.b64encode( open(image_path, "rb").read() ) return json.dumps({"image": uri_encoded_image, "sketch": ""}) <commit_msg>Fix encoding of source image to work on Python3<commit_after>
import base64 import json import os import random from dallinger.nodes import Source class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = {"polymorphic_identity": "drawing_source"} def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = ["owl.png"] # We're selecting from a list of only one item here, but it's a useful # technique to demonstrate: image = random.choice(images) image_path = os.path.join("static", "stimuli", image) uri_encoded_image = u"data:image/png;base64," + base64.b64encode( open(image_path, "rb").read() ).decode("ascii") return json.dumps({"image": uri_encoded_image, "sketch": ""})
import base64 import json import os import random from dallinger.nodes import Source class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = {"polymorphic_identity": "drawing_source"} def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = ["owl.png"] # We're selecting from a list of only one item here, but it's a useful # technique to demonstrate: image = random.choice(images) image_path = os.path.join("static", "stimuli", image) uri_encoded_image = "data:image/png;base64," + base64.b64encode( open(image_path, "rb").read() ) return json.dumps({"image": uri_encoded_image, "sketch": ""}) Fix encoding of source image to work on Python3import base64 import json import os import random from dallinger.nodes import Source class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = {"polymorphic_identity": "drawing_source"} def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = ["owl.png"] # We're selecting from a list of only one item here, but it's a useful # technique to demonstrate: image = random.choice(images) image_path = os.path.join("static", "stimuli", image) uri_encoded_image = u"data:image/png;base64," + base64.b64encode( open(image_path, "rb").read() ).decode("ascii") return json.dumps({"image": uri_encoded_image, "sketch": ""})
<commit_before>import base64 import json import os import random from dallinger.nodes import Source class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = {"polymorphic_identity": "drawing_source"} def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = ["owl.png"] # We're selecting from a list of only one item here, but it's a useful # technique to demonstrate: image = random.choice(images) image_path = os.path.join("static", "stimuli", image) uri_encoded_image = "data:image/png;base64," + base64.b64encode( open(image_path, "rb").read() ) return json.dumps({"image": uri_encoded_image, "sketch": ""}) <commit_msg>Fix encoding of source image to work on Python3<commit_after>import base64 import json import os import random from dallinger.nodes import Source class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = {"polymorphic_identity": "drawing_source"} def _contents(self): """Define the contents of new Infos. transmit() -> _what() -> create_information() -> _contents(). """ images = ["owl.png"] # We're selecting from a list of only one item here, but it's a useful # technique to demonstrate: image = random.choice(images) image_path = os.path.join("static", "stimuli", image) uri_encoded_image = u"data:image/png;base64," + base64.b64encode( open(image_path, "rb").read() ).decode("ascii") return json.dumps({"image": uri_encoded_image, "sketch": ""})
0230c94110e99f31aea413230a908bae8cce467d
testfixtures/tests/test_docs.py
testfixtures/tests/test_docs.py
# Copyright (c) 2009-2012 Simplistix Ltd # # See license.txt for more details. from doctest import REPORT_NDIFF,ELLIPSIS from glob import glob from manuel import doctest, capture from manuel.testing import TestSuite from os.path import dirname,join,pardir from . import compat def test_suite(): m = doctest.Manuel(optionflags=REPORT_NDIFF|ELLIPSIS) m += compat.Manuel() m += capture.Manuel() return TestSuite( m, *glob(join(dirname(__file__),pardir,pardir,'docs','*.txt')) )
# Copyright (c) 2009-2012 Simplistix Ltd # # See license.txt for more details. from doctest import REPORT_NDIFF,ELLIPSIS from glob import glob from manuel import doctest, capture from manuel.testing import TestSuite from nose.plugins.skip import SkipTest from os.path import dirname, join, pardir import os from . import compat path = os.environ.get('DOCPATH', join(dirname(__file__),pardir,pardir,'docs')) tests = glob(join(path,'*.txt')) if not tests: raise SkipTest('No docs found to test') # pragma: no cover def test_suite(): m = doctest.Manuel(optionflags=REPORT_NDIFF|ELLIPSIS) m += compat.Manuel() m += capture.Manuel() return TestSuite(m, *tests)
Allow docs to test to be found elsewhere. (they're not unpacked by installing the sdist)
Allow docs to test to be found elsewhere. (they're not unpacked by installing the sdist)
Python
mit
nebulans/testfixtures,Simplistix/testfixtures
# Copyright (c) 2009-2012 Simplistix Ltd # # See license.txt for more details. from doctest import REPORT_NDIFF,ELLIPSIS from glob import glob from manuel import doctest, capture from manuel.testing import TestSuite from os.path import dirname,join,pardir from . import compat def test_suite(): m = doctest.Manuel(optionflags=REPORT_NDIFF|ELLIPSIS) m += compat.Manuel() m += capture.Manuel() return TestSuite( m, *glob(join(dirname(__file__),pardir,pardir,'docs','*.txt')) ) Allow docs to test to be found elsewhere. (they're not unpacked by installing the sdist)
# Copyright (c) 2009-2012 Simplistix Ltd # # See license.txt for more details. from doctest import REPORT_NDIFF,ELLIPSIS from glob import glob from manuel import doctest, capture from manuel.testing import TestSuite from nose.plugins.skip import SkipTest from os.path import dirname, join, pardir import os from . import compat path = os.environ.get('DOCPATH', join(dirname(__file__),pardir,pardir,'docs')) tests = glob(join(path,'*.txt')) if not tests: raise SkipTest('No docs found to test') # pragma: no cover def test_suite(): m = doctest.Manuel(optionflags=REPORT_NDIFF|ELLIPSIS) m += compat.Manuel() m += capture.Manuel() return TestSuite(m, *tests)
<commit_before># Copyright (c) 2009-2012 Simplistix Ltd # # See license.txt for more details. from doctest import REPORT_NDIFF,ELLIPSIS from glob import glob from manuel import doctest, capture from manuel.testing import TestSuite from os.path import dirname,join,pardir from . import compat def test_suite(): m = doctest.Manuel(optionflags=REPORT_NDIFF|ELLIPSIS) m += compat.Manuel() m += capture.Manuel() return TestSuite( m, *glob(join(dirname(__file__),pardir,pardir,'docs','*.txt')) ) <commit_msg>Allow docs to test to be found elsewhere. (they're not unpacked by installing the sdist)<commit_after>
# Copyright (c) 2009-2012 Simplistix Ltd # # See license.txt for more details. from doctest import REPORT_NDIFF,ELLIPSIS from glob import glob from manuel import doctest, capture from manuel.testing import TestSuite from nose.plugins.skip import SkipTest from os.path import dirname, join, pardir import os from . import compat path = os.environ.get('DOCPATH', join(dirname(__file__),pardir,pardir,'docs')) tests = glob(join(path,'*.txt')) if not tests: raise SkipTest('No docs found to test') # pragma: no cover def test_suite(): m = doctest.Manuel(optionflags=REPORT_NDIFF|ELLIPSIS) m += compat.Manuel() m += capture.Manuel() return TestSuite(m, *tests)
# Copyright (c) 2009-2012 Simplistix Ltd # # See license.txt for more details. from doctest import REPORT_NDIFF,ELLIPSIS from glob import glob from manuel import doctest, capture from manuel.testing import TestSuite from os.path import dirname,join,pardir from . import compat def test_suite(): m = doctest.Manuel(optionflags=REPORT_NDIFF|ELLIPSIS) m += compat.Manuel() m += capture.Manuel() return TestSuite( m, *glob(join(dirname(__file__),pardir,pardir,'docs','*.txt')) ) Allow docs to test to be found elsewhere. (they're not unpacked by installing the sdist)# Copyright (c) 2009-2012 Simplistix Ltd # # See license.txt for more details. from doctest import REPORT_NDIFF,ELLIPSIS from glob import glob from manuel import doctest, capture from manuel.testing import TestSuite from nose.plugins.skip import SkipTest from os.path import dirname, join, pardir import os from . import compat path = os.environ.get('DOCPATH', join(dirname(__file__),pardir,pardir,'docs')) tests = glob(join(path,'*.txt')) if not tests: raise SkipTest('No docs found to test') # pragma: no cover def test_suite(): m = doctest.Manuel(optionflags=REPORT_NDIFF|ELLIPSIS) m += compat.Manuel() m += capture.Manuel() return TestSuite(m, *tests)
<commit_before># Copyright (c) 2009-2012 Simplistix Ltd # # See license.txt for more details. from doctest import REPORT_NDIFF,ELLIPSIS from glob import glob from manuel import doctest, capture from manuel.testing import TestSuite from os.path import dirname,join,pardir from . import compat def test_suite(): m = doctest.Manuel(optionflags=REPORT_NDIFF|ELLIPSIS) m += compat.Manuel() m += capture.Manuel() return TestSuite( m, *glob(join(dirname(__file__),pardir,pardir,'docs','*.txt')) ) <commit_msg>Allow docs to test to be found elsewhere. (they're not unpacked by installing the sdist)<commit_after># Copyright (c) 2009-2012 Simplistix Ltd # # See license.txt for more details. from doctest import REPORT_NDIFF,ELLIPSIS from glob import glob from manuel import doctest, capture from manuel.testing import TestSuite from nose.plugins.skip import SkipTest from os.path import dirname, join, pardir import os from . import compat path = os.environ.get('DOCPATH', join(dirname(__file__),pardir,pardir,'docs')) tests = glob(join(path,'*.txt')) if not tests: raise SkipTest('No docs found to test') # pragma: no cover def test_suite(): m = doctest.Manuel(optionflags=REPORT_NDIFF|ELLIPSIS) m += compat.Manuel() m += capture.Manuel() return TestSuite(m, *tests)
18910b6cfa94a88763d2295c4b4644ed099ef382
tests/test_options.py
tests/test_options.py
from av.option import Option from common import * class TestOptions(TestCase): def test_mov_options(self): mov = av.ContainerFormat('mov') options = mov.descriptor.options by_name = {opt.name: opt for opt in options} opt = by_name.get('use_absolute_path') self.assertIsInstance(opt, Option) self.assertEqual(opt.name, 'use_absolute_path') # This was not a good option to actually test. self.assertIn(opt.type, ('BOOL', 'INT'))
from common import * from av.option import Option, OptionTypes as types class TestOptions(TestCase): def test_mov_options(self): mov = av.ContainerFormat('mov') options = mov.descriptor.options by_name = {opt.name: opt for opt in options} opt = by_name.get('use_absolute_path') self.assertIsInstance(opt, Option) self.assertEqual(opt.name, 'use_absolute_path') # This was not a good option to actually test. self.assertIn(opt.type, (types.BOOL, types.INT))
Fix the one broken test due to OptionType enum.
Fix the one broken test due to OptionType enum.
Python
bsd-3-clause
pupil-labs/PyAV,pupil-labs/PyAV,pupil-labs/PyAV,PyAV-Org/PyAV,pupil-labs/PyAV,mikeboers/PyAV,mikeboers/PyAV,PyAV-Org/PyAV
from av.option import Option from common import * class TestOptions(TestCase): def test_mov_options(self): mov = av.ContainerFormat('mov') options = mov.descriptor.options by_name = {opt.name: opt for opt in options} opt = by_name.get('use_absolute_path') self.assertIsInstance(opt, Option) self.assertEqual(opt.name, 'use_absolute_path') # This was not a good option to actually test. self.assertIn(opt.type, ('BOOL', 'INT')) Fix the one broken test due to OptionType enum.
from common import * from av.option import Option, OptionTypes as types class TestOptions(TestCase): def test_mov_options(self): mov = av.ContainerFormat('mov') options = mov.descriptor.options by_name = {opt.name: opt for opt in options} opt = by_name.get('use_absolute_path') self.assertIsInstance(opt, Option) self.assertEqual(opt.name, 'use_absolute_path') # This was not a good option to actually test. self.assertIn(opt.type, (types.BOOL, types.INT))
<commit_before>from av.option import Option from common import * class TestOptions(TestCase): def test_mov_options(self): mov = av.ContainerFormat('mov') options = mov.descriptor.options by_name = {opt.name: opt for opt in options} opt = by_name.get('use_absolute_path') self.assertIsInstance(opt, Option) self.assertEqual(opt.name, 'use_absolute_path') # This was not a good option to actually test. self.assertIn(opt.type, ('BOOL', 'INT')) <commit_msg>Fix the one broken test due to OptionType enum.<commit_after>
from common import * from av.option import Option, OptionTypes as types class TestOptions(TestCase): def test_mov_options(self): mov = av.ContainerFormat('mov') options = mov.descriptor.options by_name = {opt.name: opt for opt in options} opt = by_name.get('use_absolute_path') self.assertIsInstance(opt, Option) self.assertEqual(opt.name, 'use_absolute_path') # This was not a good option to actually test. self.assertIn(opt.type, (types.BOOL, types.INT))
from av.option import Option from common import * class TestOptions(TestCase): def test_mov_options(self): mov = av.ContainerFormat('mov') options = mov.descriptor.options by_name = {opt.name: opt for opt in options} opt = by_name.get('use_absolute_path') self.assertIsInstance(opt, Option) self.assertEqual(opt.name, 'use_absolute_path') # This was not a good option to actually test. self.assertIn(opt.type, ('BOOL', 'INT')) Fix the one broken test due to OptionType enum.from common import * from av.option import Option, OptionTypes as types class TestOptions(TestCase): def test_mov_options(self): mov = av.ContainerFormat('mov') options = mov.descriptor.options by_name = {opt.name: opt for opt in options} opt = by_name.get('use_absolute_path') self.assertIsInstance(opt, Option) self.assertEqual(opt.name, 'use_absolute_path') # This was not a good option to actually test. self.assertIn(opt.type, (types.BOOL, types.INT))
<commit_before>from av.option import Option from common import * class TestOptions(TestCase): def test_mov_options(self): mov = av.ContainerFormat('mov') options = mov.descriptor.options by_name = {opt.name: opt for opt in options} opt = by_name.get('use_absolute_path') self.assertIsInstance(opt, Option) self.assertEqual(opt.name, 'use_absolute_path') # This was not a good option to actually test. self.assertIn(opt.type, ('BOOL', 'INT')) <commit_msg>Fix the one broken test due to OptionType enum.<commit_after>from common import * from av.option import Option, OptionTypes as types class TestOptions(TestCase): def test_mov_options(self): mov = av.ContainerFormat('mov') options = mov.descriptor.options by_name = {opt.name: opt for opt in options} opt = by_name.get('use_absolute_path') self.assertIsInstance(opt, Option) self.assertEqual(opt.name, 'use_absolute_path') # This was not a good option to actually test. self.assertIn(opt.type, (types.BOOL, types.INT))
35c9740826d2b7636647e45afab4ec87075647a6
timm/utils/metrics.py
timm/utils/metrics.py
""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def accuracy(output, target, topk=(1,)): """Computes the accuracy over the k top predictions for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.reshape(1, -1).expand_as(pred)) return [correct[:k].reshape(-1).float().sum(0) * 100. / batch_size for k in topk]
""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ import torch class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def accuracy(output, target, topk=(1,)): """Computes the accuracy over the k top predictions for the specified values of k""" maxk = min(max(topk), output.size()[1]) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.reshape(1, -1).expand_as(pred)) return [ correct[:k].reshape(-1).float().sum(0) * 100. / batch_size if k <= maxk else torch.tensor(100.) for k in topk ]
Fix accuracy when topk > num_classes
Fix accuracy when topk > num_classes
Python
apache-2.0
rwightman/pytorch-image-models,rwightman/pytorch-image-models
""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def accuracy(output, target, topk=(1,)): """Computes the accuracy over the k top predictions for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.reshape(1, -1).expand_as(pred)) return [correct[:k].reshape(-1).float().sum(0) * 100. / batch_size for k in topk] Fix accuracy when topk > num_classes
""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ import torch class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def accuracy(output, target, topk=(1,)): """Computes the accuracy over the k top predictions for the specified values of k""" maxk = min(max(topk), output.size()[1]) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.reshape(1, -1).expand_as(pred)) return [ correct[:k].reshape(-1).float().sum(0) * 100. / batch_size if k <= maxk else torch.tensor(100.) for k in topk ]
<commit_before>""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def accuracy(output, target, topk=(1,)): """Computes the accuracy over the k top predictions for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.reshape(1, -1).expand_as(pred)) return [correct[:k].reshape(-1).float().sum(0) * 100. / batch_size for k in topk] <commit_msg>Fix accuracy when topk > num_classes<commit_after>
""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ import torch class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def accuracy(output, target, topk=(1,)): """Computes the accuracy over the k top predictions for the specified values of k""" maxk = min(max(topk), output.size()[1]) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.reshape(1, -1).expand_as(pred)) return [ correct[:k].reshape(-1).float().sum(0) * 100. / batch_size if k <= maxk else torch.tensor(100.) for k in topk ]
""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def accuracy(output, target, topk=(1,)): """Computes the accuracy over the k top predictions for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.reshape(1, -1).expand_as(pred)) return [correct[:k].reshape(-1).float().sum(0) * 100. / batch_size for k in topk] Fix accuracy when topk > num_classes""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ import torch class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def accuracy(output, target, topk=(1,)): """Computes the accuracy over the k top predictions for the specified values of k""" maxk = min(max(topk), output.size()[1]) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.reshape(1, -1).expand_as(pred)) return [ correct[:k].reshape(-1).float().sum(0) * 100. / batch_size if k <= maxk else torch.tensor(100.) for k in topk ]
<commit_before>""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def accuracy(output, target, topk=(1,)): """Computes the accuracy over the k top predictions for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.reshape(1, -1).expand_as(pred)) return [correct[:k].reshape(-1).float().sum(0) * 100. / batch_size for k in topk] <commit_msg>Fix accuracy when topk > num_classes<commit_after>""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ import torch class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def accuracy(output, target, topk=(1,)): """Computes the accuracy over the k top predictions for the specified values of k""" maxk = min(max(topk), output.size()[1]) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.reshape(1, -1).expand_as(pred)) return [ correct[:k].reshape(-1).float().sum(0) * 100. / batch_size if k <= maxk else torch.tensor(100.) for k in topk ]
0f35d965b19ce52fc1f3fd633dc9edae0a2e7fe7
tests/test_django_admin/urls.py
tests/test_django_admin/urls.py
from django.conf.urls import patterns, url, include from django.contrib import admin from tests.urls import urlpatterns admin.autodiscover() urlpatterns += patterns('', url(r'^admin/', include(admin.site.urls), )
from django.conf.urls import patterns, url, include from django.contrib import admin from tests.urls import urlpatterns admin.autodiscover() urlpatterns += patterns('', url(r'^admin/', include(admin.site.urls)), )
Fix syntax error in tests
Fix syntax error in tests
Python
isc
trilan/lemon-robots,trilan/lemon-robots
from django.conf.urls import patterns, url, include from django.contrib import admin from tests.urls import urlpatterns admin.autodiscover() urlpatterns += patterns('', url(r'^admin/', include(admin.site.urls), ) Fix syntax error in tests
from django.conf.urls import patterns, url, include from django.contrib import admin from tests.urls import urlpatterns admin.autodiscover() urlpatterns += patterns('', url(r'^admin/', include(admin.site.urls)), )
<commit_before>from django.conf.urls import patterns, url, include from django.contrib import admin from tests.urls import urlpatterns admin.autodiscover() urlpatterns += patterns('', url(r'^admin/', include(admin.site.urls), ) <commit_msg>Fix syntax error in tests<commit_after>
from django.conf.urls import patterns, url, include from django.contrib import admin from tests.urls import urlpatterns admin.autodiscover() urlpatterns += patterns('', url(r'^admin/', include(admin.site.urls)), )
from django.conf.urls import patterns, url, include from django.contrib import admin from tests.urls import urlpatterns admin.autodiscover() urlpatterns += patterns('', url(r'^admin/', include(admin.site.urls), ) Fix syntax error in testsfrom django.conf.urls import patterns, url, include from django.contrib import admin from tests.urls import urlpatterns admin.autodiscover() urlpatterns += patterns('', url(r'^admin/', include(admin.site.urls)), )
<commit_before>from django.conf.urls import patterns, url, include from django.contrib import admin from tests.urls import urlpatterns admin.autodiscover() urlpatterns += patterns('', url(r'^admin/', include(admin.site.urls), ) <commit_msg>Fix syntax error in tests<commit_after>from django.conf.urls import patterns, url, include from django.contrib import admin from tests.urls import urlpatterns admin.autodiscover() urlpatterns += patterns('', url(r'^admin/', include(admin.site.urls)), )
f935a14967f8b66342d34efca9ceff9eecd384be
app.py
app.py
#!/usr/bin/env python import os from flask import Flask, render_template app = Flask(__name__) @app.route('/') def root(): genres = ('Hip Hop', 'Electronic', 'R&B') songs = [\ { 'rank':'1', 'title':'The Motto', 'artist':'Drake', 'year':'2013', 'genre':'Rap' },\ { 'rank':'2', 'title':'Started from the Bottom', 'artist':'Drake', 'year':'2012', 'genre':'Hip Hop' },\ { 'rank':'3', 'title':'Thrift Shop', 'artist':'Macklemore', 'year':'2013', 'genre':'House' }\ ] return render_template('index.html', genres=genres, genre=genres[0], songs=songs) if __name__ == "__main__": # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
#!/usr/bin/env python import os from flask import Flask, render_template, request, redirect, url_for app = Flask(__name__) genres = ('Hip Hop', 'Electronic', 'R&B') songs = [\ { 'rank':'1', 'title':'The Motto', 'artist':'Drake', 'year':'2013', 'genre':'Hip Hop' },\ { 'rank':'2', 'title':'Started from the Bottom', 'artist':'Drake', 'year':'2012', 'genre':'Hip Hop' },\ { 'rank':'3', 'title':'Thrift Shop', 'artist':'Macklemore', 'year':'2013', 'genre':'Electronic' }\ ] @app.route('/') def index(): return render_template('index.html', genres=genres, genre=genres[0], songs=songs) @app.route('/submit') def submit(): title = request.args.get('Song Title') artist = request.args.get('Artist') year = request.args.get('Year') genre = request.args.get('Genre') songs.append({ 'rank':str(len(songs) + 1), 'title':title, 'artist':artist, 'year':year, 'genre':genre }) return redirect(url_for('index')) if __name__ == "__main__": # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
Enable submission of new songs via form.
Enable submission of new songs via form.
Python
mit
alykhank/Tunezout,alykhank/Tunezout
#!/usr/bin/env python import os from flask import Flask, render_template app = Flask(__name__) @app.route('/') def root(): genres = ('Hip Hop', 'Electronic', 'R&B') songs = [\ { 'rank':'1', 'title':'The Motto', 'artist':'Drake', 'year':'2013', 'genre':'Rap' },\ { 'rank':'2', 'title':'Started from the Bottom', 'artist':'Drake', 'year':'2012', 'genre':'Hip Hop' },\ { 'rank':'3', 'title':'Thrift Shop', 'artist':'Macklemore', 'year':'2013', 'genre':'House' }\ ] return render_template('index.html', genres=genres, genre=genres[0], songs=songs) if __name__ == "__main__": # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port) Enable submission of new songs via form.
#!/usr/bin/env python import os from flask import Flask, render_template, request, redirect, url_for app = Flask(__name__) genres = ('Hip Hop', 'Electronic', 'R&B') songs = [\ { 'rank':'1', 'title':'The Motto', 'artist':'Drake', 'year':'2013', 'genre':'Hip Hop' },\ { 'rank':'2', 'title':'Started from the Bottom', 'artist':'Drake', 'year':'2012', 'genre':'Hip Hop' },\ { 'rank':'3', 'title':'Thrift Shop', 'artist':'Macklemore', 'year':'2013', 'genre':'Electronic' }\ ] @app.route('/') def index(): return render_template('index.html', genres=genres, genre=genres[0], songs=songs) @app.route('/submit') def submit(): title = request.args.get('Song Title') artist = request.args.get('Artist') year = request.args.get('Year') genre = request.args.get('Genre') songs.append({ 'rank':str(len(songs) + 1), 'title':title, 'artist':artist, 'year':year, 'genre':genre }) return redirect(url_for('index')) if __name__ == "__main__": # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
<commit_before>#!/usr/bin/env python import os from flask import Flask, render_template app = Flask(__name__) @app.route('/') def root(): genres = ('Hip Hop', 'Electronic', 'R&B') songs = [\ { 'rank':'1', 'title':'The Motto', 'artist':'Drake', 'year':'2013', 'genre':'Rap' },\ { 'rank':'2', 'title':'Started from the Bottom', 'artist':'Drake', 'year':'2012', 'genre':'Hip Hop' },\ { 'rank':'3', 'title':'Thrift Shop', 'artist':'Macklemore', 'year':'2013', 'genre':'House' }\ ] return render_template('index.html', genres=genres, genre=genres[0], songs=songs) if __name__ == "__main__": # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port) <commit_msg>Enable submission of new songs via form.<commit_after>
#!/usr/bin/env python import os from flask import Flask, render_template, request, redirect, url_for app = Flask(__name__) genres = ('Hip Hop', 'Electronic', 'R&B') songs = [\ { 'rank':'1', 'title':'The Motto', 'artist':'Drake', 'year':'2013', 'genre':'Hip Hop' },\ { 'rank':'2', 'title':'Started from the Bottom', 'artist':'Drake', 'year':'2012', 'genre':'Hip Hop' },\ { 'rank':'3', 'title':'Thrift Shop', 'artist':'Macklemore', 'year':'2013', 'genre':'Electronic' }\ ] @app.route('/') def index(): return render_template('index.html', genres=genres, genre=genres[0], songs=songs) @app.route('/submit') def submit(): title = request.args.get('Song Title') artist = request.args.get('Artist') year = request.args.get('Year') genre = request.args.get('Genre') songs.append({ 'rank':str(len(songs) + 1), 'title':title, 'artist':artist, 'year':year, 'genre':genre }) return redirect(url_for('index')) if __name__ == "__main__": # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
#!/usr/bin/env python import os from flask import Flask, render_template app = Flask(__name__) @app.route('/') def root(): genres = ('Hip Hop', 'Electronic', 'R&B') songs = [\ { 'rank':'1', 'title':'The Motto', 'artist':'Drake', 'year':'2013', 'genre':'Rap' },\ { 'rank':'2', 'title':'Started from the Bottom', 'artist':'Drake', 'year':'2012', 'genre':'Hip Hop' },\ { 'rank':'3', 'title':'Thrift Shop', 'artist':'Macklemore', 'year':'2013', 'genre':'House' }\ ] return render_template('index.html', genres=genres, genre=genres[0], songs=songs) if __name__ == "__main__": # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port) Enable submission of new songs via form.#!/usr/bin/env python import os from flask import Flask, render_template, request, redirect, url_for app = Flask(__name__) genres = ('Hip Hop', 'Electronic', 'R&B') songs = [\ { 'rank':'1', 'title':'The Motto', 'artist':'Drake', 'year':'2013', 'genre':'Hip Hop' },\ { 'rank':'2', 'title':'Started from the Bottom', 'artist':'Drake', 'year':'2012', 'genre':'Hip Hop' },\ { 'rank':'3', 'title':'Thrift Shop', 'artist':'Macklemore', 'year':'2013', 'genre':'Electronic' }\ ] @app.route('/') def index(): return render_template('index.html', genres=genres, genre=genres[0], songs=songs) @app.route('/submit') def submit(): title = request.args.get('Song Title') artist = request.args.get('Artist') year = request.args.get('Year') genre = request.args.get('Genre') songs.append({ 'rank':str(len(songs) + 1), 'title':title, 'artist':artist, 'year':year, 'genre':genre }) return redirect(url_for('index')) if __name__ == "__main__": # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
<commit_before>#!/usr/bin/env python import os from flask import Flask, render_template app = Flask(__name__) @app.route('/') def root(): genres = ('Hip Hop', 'Electronic', 'R&B') songs = [\ { 'rank':'1', 'title':'The Motto', 'artist':'Drake', 'year':'2013', 'genre':'Rap' },\ { 'rank':'2', 'title':'Started from the Bottom', 'artist':'Drake', 'year':'2012', 'genre':'Hip Hop' },\ { 'rank':'3', 'title':'Thrift Shop', 'artist':'Macklemore', 'year':'2013', 'genre':'House' }\ ] return render_template('index.html', genres=genres, genre=genres[0], songs=songs) if __name__ == "__main__": # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port) <commit_msg>Enable submission of new songs via form.<commit_after>#!/usr/bin/env python import os from flask import Flask, render_template, request, redirect, url_for app = Flask(__name__) genres = ('Hip Hop', 'Electronic', 'R&B') songs = [\ { 'rank':'1', 'title':'The Motto', 'artist':'Drake', 'year':'2013', 'genre':'Hip Hop' },\ { 'rank':'2', 'title':'Started from the Bottom', 'artist':'Drake', 'year':'2012', 'genre':'Hip Hop' },\ { 'rank':'3', 'title':'Thrift Shop', 'artist':'Macklemore', 'year':'2013', 'genre':'Electronic' }\ ] @app.route('/') def index(): return render_template('index.html', genres=genres, genre=genres[0], songs=songs) @app.route('/submit') def submit(): title = request.args.get('Song Title') artist = request.args.get('Artist') year = request.args.get('Year') genre = request.args.get('Genre') songs.append({ 'rank':str(len(songs) + 1), 'title':title, 'artist':artist, 'year':year, 'genre':genre }) return redirect(url_for('index')) if __name__ == "__main__": # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
c873fa541f58e2c8be35d0854da7d5aa3491267a
src/sentry/status_checks/celery_alive.py
src/sentry/status_checks/celery_alive.py
from __future__ import absolute_import from time import time from sentry import options from .base import StatusCheck, Problem class CeleryAliveCheck(StatusCheck): def check(self): last_ping = options.get('sentry:last_worker_ping') or 0 if last_ping >= time() - 300: return [] return [ Problem("Background workers haven't checked in recently. This can mean an issue with your configuration or a serious backlog in tasks."), ]
from __future__ import absolute_import from time import time from django.core.urlresolvers import reverse from sentry import options from sentry.utils.http import absolute_uri from .base import Problem, StatusCheck class CeleryAliveCheck(StatusCheck): def check(self): last_ping = options.get('sentry:last_worker_ping') or 0 if last_ping >= time() - 300: return [] return [ Problem( "Background workers haven't checked in recently. This can mean an issue with your configuration or a serious backlog in tasks.", url=absolute_uri(reverse('sentry-admin-queue')), ), ]
Add link to queue graphs for `CeleryAliveCheck` result.
Add link to queue graphs for `CeleryAliveCheck` result.
Python
bsd-3-clause
mvaled/sentry,beeftornado/sentry,mvaled/sentry,BuildingLink/sentry,mitsuhiko/sentry,BuildingLink/sentry,mvaled/sentry,fotinakis/sentry,jean/sentry,JamesMura/sentry,alexm92/sentry,zenefits/sentry,mvaled/sentry,mitsuhiko/sentry,jean/sentry,JamesMura/sentry,beeftornado/sentry,JackDanger/sentry,looker/sentry,jean/sentry,looker/sentry,mvaled/sentry,ifduyue/sentry,ifduyue/sentry,alexm92/sentry,fotinakis/sentry,JamesMura/sentry,jean/sentry,BuildingLink/sentry,zenefits/sentry,fotinakis/sentry,JackDanger/sentry,looker/sentry,zenefits/sentry,zenefits/sentry,ifduyue/sentry,beeftornado/sentry,looker/sentry,JamesMura/sentry,ifduyue/sentry,alexm92/sentry,gencer/sentry,fotinakis/sentry,ifduyue/sentry,zenefits/sentry,JackDanger/sentry,gencer/sentry,gencer/sentry,gencer/sentry,gencer/sentry,jean/sentry,looker/sentry,mvaled/sentry,BuildingLink/sentry,JamesMura/sentry,BuildingLink/sentry
from __future__ import absolute_import from time import time from sentry import options from .base import StatusCheck, Problem class CeleryAliveCheck(StatusCheck): def check(self): last_ping = options.get('sentry:last_worker_ping') or 0 if last_ping >= time() - 300: return [] return [ Problem("Background workers haven't checked in recently. This can mean an issue with your configuration or a serious backlog in tasks."), ] Add link to queue graphs for `CeleryAliveCheck` result.
from __future__ import absolute_import from time import time from django.core.urlresolvers import reverse from sentry import options from sentry.utils.http import absolute_uri from .base import Problem, StatusCheck class CeleryAliveCheck(StatusCheck): def check(self): last_ping = options.get('sentry:last_worker_ping') or 0 if last_ping >= time() - 300: return [] return [ Problem( "Background workers haven't checked in recently. This can mean an issue with your configuration or a serious backlog in tasks.", url=absolute_uri(reverse('sentry-admin-queue')), ), ]
<commit_before>from __future__ import absolute_import from time import time from sentry import options from .base import StatusCheck, Problem class CeleryAliveCheck(StatusCheck): def check(self): last_ping = options.get('sentry:last_worker_ping') or 0 if last_ping >= time() - 300: return [] return [ Problem("Background workers haven't checked in recently. This can mean an issue with your configuration or a serious backlog in tasks."), ] <commit_msg>Add link to queue graphs for `CeleryAliveCheck` result.<commit_after>
from __future__ import absolute_import from time import time from django.core.urlresolvers import reverse from sentry import options from sentry.utils.http import absolute_uri from .base import Problem, StatusCheck class CeleryAliveCheck(StatusCheck): def check(self): last_ping = options.get('sentry:last_worker_ping') or 0 if last_ping >= time() - 300: return [] return [ Problem( "Background workers haven't checked in recently. This can mean an issue with your configuration or a serious backlog in tasks.", url=absolute_uri(reverse('sentry-admin-queue')), ), ]
from __future__ import absolute_import from time import time from sentry import options from .base import StatusCheck, Problem class CeleryAliveCheck(StatusCheck): def check(self): last_ping = options.get('sentry:last_worker_ping') or 0 if last_ping >= time() - 300: return [] return [ Problem("Background workers haven't checked in recently. This can mean an issue with your configuration or a serious backlog in tasks."), ] Add link to queue graphs for `CeleryAliveCheck` result.from __future__ import absolute_import from time import time from django.core.urlresolvers import reverse from sentry import options from sentry.utils.http import absolute_uri from .base import Problem, StatusCheck class CeleryAliveCheck(StatusCheck): def check(self): last_ping = options.get('sentry:last_worker_ping') or 0 if last_ping >= time() - 300: return [] return [ Problem( "Background workers haven't checked in recently. This can mean an issue with your configuration or a serious backlog in tasks.", url=absolute_uri(reverse('sentry-admin-queue')), ), ]
<commit_before>from __future__ import absolute_import from time import time from sentry import options from .base import StatusCheck, Problem class CeleryAliveCheck(StatusCheck): def check(self): last_ping = options.get('sentry:last_worker_ping') or 0 if last_ping >= time() - 300: return [] return [ Problem("Background workers haven't checked in recently. This can mean an issue with your configuration or a serious backlog in tasks."), ] <commit_msg>Add link to queue graphs for `CeleryAliveCheck` result.<commit_after>from __future__ import absolute_import from time import time from django.core.urlresolvers import reverse from sentry import options from sentry.utils.http import absolute_uri from .base import Problem, StatusCheck class CeleryAliveCheck(StatusCheck): def check(self): last_ping = options.get('sentry:last_worker_ping') or 0 if last_ping >= time() - 300: return [] return [ Problem( "Background workers haven't checked in recently. This can mean an issue with your configuration or a serious backlog in tasks.", url=absolute_uri(reverse('sentry-admin-queue')), ), ]
42cc93590bef8e97c76e79110d2b64906c34690d
config_template.py
config_template.py
chatbot_ubuntu = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_swisscom = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_ubuntu_seq2seq = { 'socket_address': '', 'socket_port': '' } ate = { 'path': '', 'python_env': '' } neuroate = { 'path': '', 'python_env': '' } ner = { 'path': '', 'python_env': '' } kpextract = { 'path': '', 'fetcher_path': '', 'python_env': '', 'api_emb_url':'' } neural_programmer = { 'socket_address': '', 'socket_port': '', 'mongo': False, 'mongo_address': '', 'mongo_port': '', 'mongo_db': '', 'mongo_feedback_coll': '', 'mongo_use_coll': '' } gsw_translator = { 'pbsmt_only_url': '', 'pbsmt_phono_url': '', 'pbsmt_ortho_url': '', 'pbsmt_cbnmt_url': '' } machine_translation_stdlangs = { 'base_url': '' } churn = { 'path' : '', 'python_env': '', 'e_host':'', 'e_port': }
chatbot_ubuntu = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_swisscom = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_ubuntu_seq2seq = { 'socket_address': '', 'socket_port': '' } chatbot_goaloriented = { 'socket_address': '127.0.0.1', 'socket_port': 8889 } ate = { 'path': '', 'python_env': '' } neuroate = { 'path': '', 'python_env': '' } ner = { 'path': '', 'python_env': '' } kpextract = { 'path': '', 'fetcher_path': '', 'python_env': '', 'api_emb_url':'' } neural_programmer = { 'socket_address': '', 'socket_port': '', 'mongo': False, 'mongo_address': '', 'mongo_port': '', 'mongo_db': '', 'mongo_feedback_coll': '', 'mongo_use_coll': '' } gsw_translator = { 'pbsmt_only_url': '', 'pbsmt_phono_url': '', 'pbsmt_ortho_url': '', 'pbsmt_cbnmt_url': '' } machine_translation_stdlangs = { 'base_url': '' } churn = { 'path' : '', 'python_env': '', 'e_host':'', 'e_port': '' }
Add ports and fix bug
Add ports and fix bug
Python
mit
nachoaguadoc/aimlx-demos,nachoaguadoc/aimlx-demos,nachoaguadoc/aimlx-demos
chatbot_ubuntu = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_swisscom = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_ubuntu_seq2seq = { 'socket_address': '', 'socket_port': '' } ate = { 'path': '', 'python_env': '' } neuroate = { 'path': '', 'python_env': '' } ner = { 'path': '', 'python_env': '' } kpextract = { 'path': '', 'fetcher_path': '', 'python_env': '', 'api_emb_url':'' } neural_programmer = { 'socket_address': '', 'socket_port': '', 'mongo': False, 'mongo_address': '', 'mongo_port': '', 'mongo_db': '', 'mongo_feedback_coll': '', 'mongo_use_coll': '' } gsw_translator = { 'pbsmt_only_url': '', 'pbsmt_phono_url': '', 'pbsmt_ortho_url': '', 'pbsmt_cbnmt_url': '' } machine_translation_stdlangs = { 'base_url': '' } churn = { 'path' : '', 'python_env': '', 'e_host':'', 'e_port': }Add ports and fix bug
chatbot_ubuntu = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_swisscom = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_ubuntu_seq2seq = { 'socket_address': '', 'socket_port': '' } chatbot_goaloriented = { 'socket_address': '127.0.0.1', 'socket_port': 8889 } ate = { 'path': '', 'python_env': '' } neuroate = { 'path': '', 'python_env': '' } ner = { 'path': '', 'python_env': '' } kpextract = { 'path': '', 'fetcher_path': '', 'python_env': '', 'api_emb_url':'' } neural_programmer = { 'socket_address': '', 'socket_port': '', 'mongo': False, 'mongo_address': '', 'mongo_port': '', 'mongo_db': '', 'mongo_feedback_coll': '', 'mongo_use_coll': '' } gsw_translator = { 'pbsmt_only_url': '', 'pbsmt_phono_url': '', 'pbsmt_ortho_url': '', 'pbsmt_cbnmt_url': '' } machine_translation_stdlangs = { 'base_url': '' } churn = { 'path' : '', 'python_env': '', 'e_host':'', 'e_port': '' }
<commit_before>chatbot_ubuntu = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_swisscom = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_ubuntu_seq2seq = { 'socket_address': '', 'socket_port': '' } ate = { 'path': '', 'python_env': '' } neuroate = { 'path': '', 'python_env': '' } ner = { 'path': '', 'python_env': '' } kpextract = { 'path': '', 'fetcher_path': '', 'python_env': '', 'api_emb_url':'' } neural_programmer = { 'socket_address': '', 'socket_port': '', 'mongo': False, 'mongo_address': '', 'mongo_port': '', 'mongo_db': '', 'mongo_feedback_coll': '', 'mongo_use_coll': '' } gsw_translator = { 'pbsmt_only_url': '', 'pbsmt_phono_url': '', 'pbsmt_ortho_url': '', 'pbsmt_cbnmt_url': '' } machine_translation_stdlangs = { 'base_url': '' } churn = { 'path' : '', 'python_env': '', 'e_host':'', 'e_port': }<commit_msg>Add ports and fix bug<commit_after>
chatbot_ubuntu = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_swisscom = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_ubuntu_seq2seq = { 'socket_address': '', 'socket_port': '' } chatbot_goaloriented = { 'socket_address': '127.0.0.1', 'socket_port': 8889 } ate = { 'path': '', 'python_env': '' } neuroate = { 'path': '', 'python_env': '' } ner = { 'path': '', 'python_env': '' } kpextract = { 'path': '', 'fetcher_path': '', 'python_env': '', 'api_emb_url':'' } neural_programmer = { 'socket_address': '', 'socket_port': '', 'mongo': False, 'mongo_address': '', 'mongo_port': '', 'mongo_db': '', 'mongo_feedback_coll': '', 'mongo_use_coll': '' } gsw_translator = { 'pbsmt_only_url': '', 'pbsmt_phono_url': '', 'pbsmt_ortho_url': '', 'pbsmt_cbnmt_url': '' } machine_translation_stdlangs = { 'base_url': '' } churn = { 'path' : '', 'python_env': '', 'e_host':'', 'e_port': '' }
chatbot_ubuntu = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_swisscom = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_ubuntu_seq2seq = { 'socket_address': '', 'socket_port': '' } ate = { 'path': '', 'python_env': '' } neuroate = { 'path': '', 'python_env': '' } ner = { 'path': '', 'python_env': '' } kpextract = { 'path': '', 'fetcher_path': '', 'python_env': '', 'api_emb_url':'' } neural_programmer = { 'socket_address': '', 'socket_port': '', 'mongo': False, 'mongo_address': '', 'mongo_port': '', 'mongo_db': '', 'mongo_feedback_coll': '', 'mongo_use_coll': '' } gsw_translator = { 'pbsmt_only_url': '', 'pbsmt_phono_url': '', 'pbsmt_ortho_url': '', 'pbsmt_cbnmt_url': '' } machine_translation_stdlangs = { 'base_url': '' } churn = { 'path' : '', 'python_env': '', 'e_host':'', 'e_port': }Add ports and fix bugchatbot_ubuntu = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_swisscom = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_ubuntu_seq2seq = { 'socket_address': '', 'socket_port': '' } chatbot_goaloriented = { 'socket_address': '127.0.0.1', 'socket_port': 8889 } ate = { 'path': '', 'python_env': '' } neuroate = { 'path': '', 'python_env': '' } ner = { 'path': '', 'python_env': '' } kpextract = { 'path': '', 'fetcher_path': '', 'python_env': '', 'api_emb_url':'' } neural_programmer = { 'socket_address': '', 'socket_port': '', 'mongo': False, 'mongo_address': '', 'mongo_port': '', 'mongo_db': '', 'mongo_feedback_coll': '', 'mongo_use_coll': '' } gsw_translator = { 'pbsmt_only_url': '', 'pbsmt_phono_url': '', 'pbsmt_ortho_url': '', 'pbsmt_cbnmt_url': '' } machine_translation_stdlangs = { 'base_url': '' } churn = { 'path' : '', 'python_env': '', 'e_host':'', 'e_port': '' }
<commit_before>chatbot_ubuntu = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_swisscom = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_ubuntu_seq2seq = { 'socket_address': '', 'socket_port': '' } ate = { 'path': '', 'python_env': '' } neuroate = { 'path': '', 'python_env': '' } ner = { 'path': '', 'python_env': '' } kpextract = { 'path': '', 'fetcher_path': '', 'python_env': '', 'api_emb_url':'' } neural_programmer = { 'socket_address': '', 'socket_port': '', 'mongo': False, 'mongo_address': '', 'mongo_port': '', 'mongo_db': '', 'mongo_feedback_coll': '', 'mongo_use_coll': '' } gsw_translator = { 'pbsmt_only_url': '', 'pbsmt_phono_url': '', 'pbsmt_ortho_url': '', 'pbsmt_cbnmt_url': '' } machine_translation_stdlangs = { 'base_url': '' } churn = { 'path' : '', 'python_env': '', 'e_host':'', 'e_port': }<commit_msg>Add ports and fix bug<commit_after>chatbot_ubuntu = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_swisscom = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_ubuntu_seq2seq = { 'socket_address': '', 'socket_port': '' } chatbot_goaloriented = { 'socket_address': '127.0.0.1', 'socket_port': 8889 } ate = { 'path': '', 'python_env': '' } neuroate = { 'path': '', 'python_env': '' } ner = { 'path': '', 'python_env': '' } kpextract = { 'path': '', 'fetcher_path': '', 'python_env': '', 'api_emb_url':'' } neural_programmer = { 'socket_address': '', 'socket_port': '', 'mongo': False, 'mongo_address': '', 'mongo_port': '', 'mongo_db': '', 'mongo_feedback_coll': '', 'mongo_use_coll': '' } gsw_translator = { 'pbsmt_only_url': '', 'pbsmt_phono_url': '', 'pbsmt_ortho_url': '', 'pbsmt_cbnmt_url': '' } machine_translation_stdlangs = { 'base_url': '' } churn = { 'path' : '', 'python_env': '', 'e_host':'', 'e_port': '' }
b00cc9aa45a455b187bec869e367422bb78785c1
luigi_td/targets/tableau.py
luigi_td/targets/tableau.py
from luigi_td.targets.result import ResultTarget import urllib import logging logger = logging.getLogger('luigi-interface') class TableauServerResultTarget(ResultTarget): # required server = None username = None password = None datasource = None # optional ssl = 'true' ssl_verify = 'true' version = None site = None project = None mode = 'replace' def get_result_url(self): reqs = {} for name in ['server', 'username', 'password', 'datasource']: if getattr(self, name) is None: raise TypeError('missing option "{0}" for {1}'.format(name, self)) reqs[name] = urllib.quote(getattr(self, name)) params = { 'ssl': self.ssl, 'ssl_verify': self.ssl_verify, 'version': self.version, 'site': self.site, 'project': self.project, 'mode': self.mode, } reqs['params'] = urllib.urlencode([(key, params[key]) for key in params if params[key] is not None]) return "tableau://{username}:{password}@{server}/{datasource}?{params}".format(**reqs) class TableauOnlineResultTarget(TableauServerResultTarget): server = 'online.tableausoftware.com' version = 'online'
from luigi_td.targets.result import ResultTarget import urllib import logging logger = logging.getLogger('luigi-interface') class TableauServerResultTarget(ResultTarget): # required server = None username = None password = None datasource = None # optional ssl = 'true' ssl_verify = 'true' server_version = None site = None project = None mode = 'replace' def get_result_url(self): reqs = {} for name in ['server', 'username', 'password', 'datasource']: if getattr(self, name) is None: raise TypeError('missing option "{0}" for {1}'.format(name, self)) reqs[name] = urllib.quote(getattr(self, name)) params = { 'ssl': self.ssl, 'ssl_verify': self.ssl_verify, 'server_version': self.server_version, 'site': self.site, 'project': self.project, 'mode': self.mode, } reqs['params'] = urllib.urlencode([(key, params[key]) for key in params if params[key] is not None]) return "tableau://{username}:{password}@{server}/{datasource}?{params}".format(**reqs) class TableauOnlineResultTarget(TableauServerResultTarget): server = 'online.tableausoftware.com' server_version = 'online'
Fix the option name for Tableau server version
Fix the option name for Tableau server version
Python
apache-2.0
treasure-data/luigi-td
from luigi_td.targets.result import ResultTarget import urllib import logging logger = logging.getLogger('luigi-interface') class TableauServerResultTarget(ResultTarget): # required server = None username = None password = None datasource = None # optional ssl = 'true' ssl_verify = 'true' version = None site = None project = None mode = 'replace' def get_result_url(self): reqs = {} for name in ['server', 'username', 'password', 'datasource']: if getattr(self, name) is None: raise TypeError('missing option "{0}" for {1}'.format(name, self)) reqs[name] = urllib.quote(getattr(self, name)) params = { 'ssl': self.ssl, 'ssl_verify': self.ssl_verify, 'version': self.version, 'site': self.site, 'project': self.project, 'mode': self.mode, } reqs['params'] = urllib.urlencode([(key, params[key]) for key in params if params[key] is not None]) return "tableau://{username}:{password}@{server}/{datasource}?{params}".format(**reqs) class TableauOnlineResultTarget(TableauServerResultTarget): server = 'online.tableausoftware.com' version = 'online' Fix the option name for Tableau server version
from luigi_td.targets.result import ResultTarget import urllib import logging logger = logging.getLogger('luigi-interface') class TableauServerResultTarget(ResultTarget): # required server = None username = None password = None datasource = None # optional ssl = 'true' ssl_verify = 'true' server_version = None site = None project = None mode = 'replace' def get_result_url(self): reqs = {} for name in ['server', 'username', 'password', 'datasource']: if getattr(self, name) is None: raise TypeError('missing option "{0}" for {1}'.format(name, self)) reqs[name] = urllib.quote(getattr(self, name)) params = { 'ssl': self.ssl, 'ssl_verify': self.ssl_verify, 'server_version': self.server_version, 'site': self.site, 'project': self.project, 'mode': self.mode, } reqs['params'] = urllib.urlencode([(key, params[key]) for key in params if params[key] is not None]) return "tableau://{username}:{password}@{server}/{datasource}?{params}".format(**reqs) class TableauOnlineResultTarget(TableauServerResultTarget): server = 'online.tableausoftware.com' server_version = 'online'
<commit_before>from luigi_td.targets.result import ResultTarget import urllib import logging logger = logging.getLogger('luigi-interface') class TableauServerResultTarget(ResultTarget): # required server = None username = None password = None datasource = None # optional ssl = 'true' ssl_verify = 'true' version = None site = None project = None mode = 'replace' def get_result_url(self): reqs = {} for name in ['server', 'username', 'password', 'datasource']: if getattr(self, name) is None: raise TypeError('missing option "{0}" for {1}'.format(name, self)) reqs[name] = urllib.quote(getattr(self, name)) params = { 'ssl': self.ssl, 'ssl_verify': self.ssl_verify, 'version': self.version, 'site': self.site, 'project': self.project, 'mode': self.mode, } reqs['params'] = urllib.urlencode([(key, params[key]) for key in params if params[key] is not None]) return "tableau://{username}:{password}@{server}/{datasource}?{params}".format(**reqs) class TableauOnlineResultTarget(TableauServerResultTarget): server = 'online.tableausoftware.com' version = 'online' <commit_msg>Fix the option name for Tableau server version<commit_after>
from luigi_td.targets.result import ResultTarget import urllib import logging logger = logging.getLogger('luigi-interface') class TableauServerResultTarget(ResultTarget): # required server = None username = None password = None datasource = None # optional ssl = 'true' ssl_verify = 'true' server_version = None site = None project = None mode = 'replace' def get_result_url(self): reqs = {} for name in ['server', 'username', 'password', 'datasource']: if getattr(self, name) is None: raise TypeError('missing option "{0}" for {1}'.format(name, self)) reqs[name] = urllib.quote(getattr(self, name)) params = { 'ssl': self.ssl, 'ssl_verify': self.ssl_verify, 'server_version': self.server_version, 'site': self.site, 'project': self.project, 'mode': self.mode, } reqs['params'] = urllib.urlencode([(key, params[key]) for key in params if params[key] is not None]) return "tableau://{username}:{password}@{server}/{datasource}?{params}".format(**reqs) class TableauOnlineResultTarget(TableauServerResultTarget): server = 'online.tableausoftware.com' server_version = 'online'
from luigi_td.targets.result import ResultTarget import urllib import logging logger = logging.getLogger('luigi-interface') class TableauServerResultTarget(ResultTarget): # required server = None username = None password = None datasource = None # optional ssl = 'true' ssl_verify = 'true' version = None site = None project = None mode = 'replace' def get_result_url(self): reqs = {} for name in ['server', 'username', 'password', 'datasource']: if getattr(self, name) is None: raise TypeError('missing option "{0}" for {1}'.format(name, self)) reqs[name] = urllib.quote(getattr(self, name)) params = { 'ssl': self.ssl, 'ssl_verify': self.ssl_verify, 'version': self.version, 'site': self.site, 'project': self.project, 'mode': self.mode, } reqs['params'] = urllib.urlencode([(key, params[key]) for key in params if params[key] is not None]) return "tableau://{username}:{password}@{server}/{datasource}?{params}".format(**reqs) class TableauOnlineResultTarget(TableauServerResultTarget): server = 'online.tableausoftware.com' version = 'online' Fix the option name for Tableau server versionfrom luigi_td.targets.result import ResultTarget import urllib import logging logger = logging.getLogger('luigi-interface') class TableauServerResultTarget(ResultTarget): # required server = None username = None password = None datasource = None # optional ssl = 'true' ssl_verify = 'true' server_version = None site = None project = None mode = 'replace' def get_result_url(self): reqs = {} for name in ['server', 'username', 'password', 'datasource']: if getattr(self, name) is None: raise TypeError('missing option "{0}" for {1}'.format(name, self)) reqs[name] = urllib.quote(getattr(self, name)) params = { 'ssl': self.ssl, 'ssl_verify': self.ssl_verify, 'server_version': self.server_version, 'site': self.site, 'project': self.project, 'mode': self.mode, } reqs['params'] = urllib.urlencode([(key, params[key]) for key in params if params[key] is not None]) return "tableau://{username}:{password}@{server}/{datasource}?{params}".format(**reqs) class TableauOnlineResultTarget(TableauServerResultTarget): server = 'online.tableausoftware.com' server_version = 'online'
<commit_before>from luigi_td.targets.result import ResultTarget import urllib import logging logger = logging.getLogger('luigi-interface') class TableauServerResultTarget(ResultTarget): # required server = None username = None password = None datasource = None # optional ssl = 'true' ssl_verify = 'true' version = None site = None project = None mode = 'replace' def get_result_url(self): reqs = {} for name in ['server', 'username', 'password', 'datasource']: if getattr(self, name) is None: raise TypeError('missing option "{0}" for {1}'.format(name, self)) reqs[name] = urllib.quote(getattr(self, name)) params = { 'ssl': self.ssl, 'ssl_verify': self.ssl_verify, 'version': self.version, 'site': self.site, 'project': self.project, 'mode': self.mode, } reqs['params'] = urllib.urlencode([(key, params[key]) for key in params if params[key] is not None]) return "tableau://{username}:{password}@{server}/{datasource}?{params}".format(**reqs) class TableauOnlineResultTarget(TableauServerResultTarget): server = 'online.tableausoftware.com' version = 'online' <commit_msg>Fix the option name for Tableau server version<commit_after>from luigi_td.targets.result import ResultTarget import urllib import logging logger = logging.getLogger('luigi-interface') class TableauServerResultTarget(ResultTarget): # required server = None username = None password = None datasource = None # optional ssl = 'true' ssl_verify = 'true' server_version = None site = None project = None mode = 'replace' def get_result_url(self): reqs = {} for name in ['server', 'username', 'password', 'datasource']: if getattr(self, name) is None: raise TypeError('missing option "{0}" for {1}'.format(name, self)) reqs[name] = urllib.quote(getattr(self, name)) params = { 'ssl': self.ssl, 'ssl_verify': self.ssl_verify, 'server_version': self.server_version, 'site': self.site, 'project': self.project, 'mode': self.mode, } reqs['params'] = urllib.urlencode([(key, params[key]) for key in params if params[key] is not None]) return "tableau://{username}:{password}@{server}/{datasource}?{params}".format(**reqs) class TableauOnlineResultTarget(TableauServerResultTarget): server = 'online.tableausoftware.com' server_version = 'online'
779b9223a0e57a00964fa73ce3e164ececfbf4cb
kolibri/deployment/default/settings/test.py
kolibri/deployment/default/settings/test.py
from __future__ import absolute_import, print_function, unicode_literals from .base import * # noqa KOLIBRI_SKIP_AUTO_DATABASE_MIGRATION = True
from __future__ import absolute_import, print_function, unicode_literals from .base import * # noqa KOLIBRI_SKIP_AUTO_DATABASE_MIGRATION = False
Use migrations because `kolibri start` was added to tox matrix
Use migrations because `kolibri start` was added to tox matrix
Python
mit
christianmemije/kolibri,lyw07/kolibri,benjaoming/kolibri,jonboiser/kolibri,benjaoming/kolibri,lyw07/kolibri,learningequality/kolibri,mrpau/kolibri,rtibbles/kolibri,lyw07/kolibri,DXCanas/kolibri,MingDai/kolibri,rtibbles/kolibri,MingDai/kolibri,learningequality/kolibri,MingDai/kolibri,rtibbles/kolibri,jonboiser/kolibri,jonboiser/kolibri,rtibbles/kolibri,indirectlylit/kolibri,MingDai/kolibri,indirectlylit/kolibri,mrpau/kolibri,christianmemije/kolibri,jonboiser/kolibri,lyw07/kolibri,indirectlylit/kolibri,christianmemije/kolibri,learningequality/kolibri,benjaoming/kolibri,learningequality/kolibri,mrpau/kolibri,benjaoming/kolibri,DXCanas/kolibri,indirectlylit/kolibri,christianmemije/kolibri,DXCanas/kolibri,DXCanas/kolibri,mrpau/kolibri
from __future__ import absolute_import, print_function, unicode_literals from .base import * # noqa KOLIBRI_SKIP_AUTO_DATABASE_MIGRATION = True Use migrations because `kolibri start` was added to tox matrix
from __future__ import absolute_import, print_function, unicode_literals from .base import * # noqa KOLIBRI_SKIP_AUTO_DATABASE_MIGRATION = False
<commit_before>from __future__ import absolute_import, print_function, unicode_literals from .base import * # noqa KOLIBRI_SKIP_AUTO_DATABASE_MIGRATION = True <commit_msg>Use migrations because `kolibri start` was added to tox matrix<commit_after>
from __future__ import absolute_import, print_function, unicode_literals from .base import * # noqa KOLIBRI_SKIP_AUTO_DATABASE_MIGRATION = False
from __future__ import absolute_import, print_function, unicode_literals from .base import * # noqa KOLIBRI_SKIP_AUTO_DATABASE_MIGRATION = True Use migrations because `kolibri start` was added to tox matrixfrom __future__ import absolute_import, print_function, unicode_literals from .base import * # noqa KOLIBRI_SKIP_AUTO_DATABASE_MIGRATION = False
<commit_before>from __future__ import absolute_import, print_function, unicode_literals from .base import * # noqa KOLIBRI_SKIP_AUTO_DATABASE_MIGRATION = True <commit_msg>Use migrations because `kolibri start` was added to tox matrix<commit_after>from __future__ import absolute_import, print_function, unicode_literals from .base import * # noqa KOLIBRI_SKIP_AUTO_DATABASE_MIGRATION = False
78c13173fadbdc3d261ab3690ffb9c37d8f8a72d
bootstrap.py
bootstrap.py
from __future__ import print_function from getpass import getpass import readline import sys import annotator from annotator.model import Consumer, User if __name__ == '__main__': r = raw_input("This program will perform initial setup of the annotation \n" "store, and create the required admin accounts. Proceed? [Y/n] ") if r and r[0] in ['n', 'N']: sys.exit(1) print("\nCreating SQLite database and ElasticSearch indices... ", end="") annotator.create_app() annotator.create_all() print("done.\n") username = raw_input("Admin username [admin]: ").strip() if not username: username = 'admin' email = '' while not email: email = raw_input("Admin email: ").strip() password = '' while not password: password = getpass("Admin password: ") ckey = raw_input("Primary consumer key [annotateit]: ").strip() if not ckey: ckey = 'annotateit' with annotator.app.test_request_context(): print("\nCreating admin user... ", end="") u = User(username, email, password) annotator.db.session.add(u) annotator.db.session.commit() print("done.") print("Creating primary consumer... ", end="") c = Consumer(ckey) c.user_id = u.id annotator.db.session.add(c) annotator.db.session.commit() print("done.\n") print("Primary consumer secret: %s" % c.secret)
from __future__ import print_function from getpass import getpass import readline import sys import annotator from annotator.model import Consumer, User if __name__ == '__main__': r = raw_input("This program will perform initial setup of the annotation \n" "store, and create the required admin accounts. Proceed? [Y/n] ") if r and r[0] in ['n', 'N']: sys.exit(1) print("\nCreating SQLite database and ElasticSearch indices... ", end="") app = annotator.create_app() annotator.create_all(app) print("done.\n") username = raw_input("Admin username [admin]: ").strip() if not username: username = 'admin' email = '' while not email: email = raw_input("Admin email: ").strip() password = '' while not password: password = getpass("Admin password: ") ckey = raw_input("Primary consumer key [annotateit]: ").strip() if not ckey: ckey = 'annotateit' with app.test_request_context(): db = app.extensions['sqlalchemy'].db print("\nCreating admin user... ", end="") u = User(username, email, password) db.session.add(u) db.session.commit() print("done.") print("Creating primary consumer... ", end="") c = Consumer(ckey) c.user_id = u.id db.session.add(c) db.session.commit() print("done.\n") print("Primary consumer secret: %s" % c.secret)
Update to reflect new create_app signature
Update to reflect new create_app signature
Python
mit
openannotation/annotator-store,nobita-isc/annotator-store,nobita-isc/annotator-store,ningyifan/annotator-store,nobita-isc/annotator-store,nobita-isc/annotator-store,happybelly/annotator-store
from __future__ import print_function from getpass import getpass import readline import sys import annotator from annotator.model import Consumer, User if __name__ == '__main__': r = raw_input("This program will perform initial setup of the annotation \n" "store, and create the required admin accounts. Proceed? [Y/n] ") if r and r[0] in ['n', 'N']: sys.exit(1) print("\nCreating SQLite database and ElasticSearch indices... ", end="") annotator.create_app() annotator.create_all() print("done.\n") username = raw_input("Admin username [admin]: ").strip() if not username: username = 'admin' email = '' while not email: email = raw_input("Admin email: ").strip() password = '' while not password: password = getpass("Admin password: ") ckey = raw_input("Primary consumer key [annotateit]: ").strip() if not ckey: ckey = 'annotateit' with annotator.app.test_request_context(): print("\nCreating admin user... ", end="") u = User(username, email, password) annotator.db.session.add(u) annotator.db.session.commit() print("done.") print("Creating primary consumer... ", end="") c = Consumer(ckey) c.user_id = u.id annotator.db.session.add(c) annotator.db.session.commit() print("done.\n") print("Primary consumer secret: %s" % c.secret) Update to reflect new create_app signature
from __future__ import print_function from getpass import getpass import readline import sys import annotator from annotator.model import Consumer, User if __name__ == '__main__': r = raw_input("This program will perform initial setup of the annotation \n" "store, and create the required admin accounts. Proceed? [Y/n] ") if r and r[0] in ['n', 'N']: sys.exit(1) print("\nCreating SQLite database and ElasticSearch indices... ", end="") app = annotator.create_app() annotator.create_all(app) print("done.\n") username = raw_input("Admin username [admin]: ").strip() if not username: username = 'admin' email = '' while not email: email = raw_input("Admin email: ").strip() password = '' while not password: password = getpass("Admin password: ") ckey = raw_input("Primary consumer key [annotateit]: ").strip() if not ckey: ckey = 'annotateit' with app.test_request_context(): db = app.extensions['sqlalchemy'].db print("\nCreating admin user... ", end="") u = User(username, email, password) db.session.add(u) db.session.commit() print("done.") print("Creating primary consumer... ", end="") c = Consumer(ckey) c.user_id = u.id db.session.add(c) db.session.commit() print("done.\n") print("Primary consumer secret: %s" % c.secret)
<commit_before>from __future__ import print_function from getpass import getpass import readline import sys import annotator from annotator.model import Consumer, User if __name__ == '__main__': r = raw_input("This program will perform initial setup of the annotation \n" "store, and create the required admin accounts. Proceed? [Y/n] ") if r and r[0] in ['n', 'N']: sys.exit(1) print("\nCreating SQLite database and ElasticSearch indices... ", end="") annotator.create_app() annotator.create_all() print("done.\n") username = raw_input("Admin username [admin]: ").strip() if not username: username = 'admin' email = '' while not email: email = raw_input("Admin email: ").strip() password = '' while not password: password = getpass("Admin password: ") ckey = raw_input("Primary consumer key [annotateit]: ").strip() if not ckey: ckey = 'annotateit' with annotator.app.test_request_context(): print("\nCreating admin user... ", end="") u = User(username, email, password) annotator.db.session.add(u) annotator.db.session.commit() print("done.") print("Creating primary consumer... ", end="") c = Consumer(ckey) c.user_id = u.id annotator.db.session.add(c) annotator.db.session.commit() print("done.\n") print("Primary consumer secret: %s" % c.secret) <commit_msg>Update to reflect new create_app signature<commit_after>
from __future__ import print_function from getpass import getpass import readline import sys import annotator from annotator.model import Consumer, User if __name__ == '__main__': r = raw_input("This program will perform initial setup of the annotation \n" "store, and create the required admin accounts. Proceed? [Y/n] ") if r and r[0] in ['n', 'N']: sys.exit(1) print("\nCreating SQLite database and ElasticSearch indices... ", end="") app = annotator.create_app() annotator.create_all(app) print("done.\n") username = raw_input("Admin username [admin]: ").strip() if not username: username = 'admin' email = '' while not email: email = raw_input("Admin email: ").strip() password = '' while not password: password = getpass("Admin password: ") ckey = raw_input("Primary consumer key [annotateit]: ").strip() if not ckey: ckey = 'annotateit' with app.test_request_context(): db = app.extensions['sqlalchemy'].db print("\nCreating admin user... ", end="") u = User(username, email, password) db.session.add(u) db.session.commit() print("done.") print("Creating primary consumer... ", end="") c = Consumer(ckey) c.user_id = u.id db.session.add(c) db.session.commit() print("done.\n") print("Primary consumer secret: %s" % c.secret)
from __future__ import print_function from getpass import getpass import readline import sys import annotator from annotator.model import Consumer, User if __name__ == '__main__': r = raw_input("This program will perform initial setup of the annotation \n" "store, and create the required admin accounts. Proceed? [Y/n] ") if r and r[0] in ['n', 'N']: sys.exit(1) print("\nCreating SQLite database and ElasticSearch indices... ", end="") annotator.create_app() annotator.create_all() print("done.\n") username = raw_input("Admin username [admin]: ").strip() if not username: username = 'admin' email = '' while not email: email = raw_input("Admin email: ").strip() password = '' while not password: password = getpass("Admin password: ") ckey = raw_input("Primary consumer key [annotateit]: ").strip() if not ckey: ckey = 'annotateit' with annotator.app.test_request_context(): print("\nCreating admin user... ", end="") u = User(username, email, password) annotator.db.session.add(u) annotator.db.session.commit() print("done.") print("Creating primary consumer... ", end="") c = Consumer(ckey) c.user_id = u.id annotator.db.session.add(c) annotator.db.session.commit() print("done.\n") print("Primary consumer secret: %s" % c.secret) Update to reflect new create_app signaturefrom __future__ import print_function from getpass import getpass import readline import sys import annotator from annotator.model import Consumer, User if __name__ == '__main__': r = raw_input("This program will perform initial setup of the annotation \n" "store, and create the required admin accounts. Proceed? [Y/n] ") if r and r[0] in ['n', 'N']: sys.exit(1) print("\nCreating SQLite database and ElasticSearch indices... ", end="") app = annotator.create_app() annotator.create_all(app) print("done.\n") username = raw_input("Admin username [admin]: ").strip() if not username: username = 'admin' email = '' while not email: email = raw_input("Admin email: ").strip() password = '' while not password: password = getpass("Admin password: ") ckey = raw_input("Primary consumer key [annotateit]: ").strip() if not ckey: ckey = 'annotateit' with app.test_request_context(): db = app.extensions['sqlalchemy'].db print("\nCreating admin user... ", end="") u = User(username, email, password) db.session.add(u) db.session.commit() print("done.") print("Creating primary consumer... ", end="") c = Consumer(ckey) c.user_id = u.id db.session.add(c) db.session.commit() print("done.\n") print("Primary consumer secret: %s" % c.secret)
<commit_before>from __future__ import print_function from getpass import getpass import readline import sys import annotator from annotator.model import Consumer, User if __name__ == '__main__': r = raw_input("This program will perform initial setup of the annotation \n" "store, and create the required admin accounts. Proceed? [Y/n] ") if r and r[0] in ['n', 'N']: sys.exit(1) print("\nCreating SQLite database and ElasticSearch indices... ", end="") annotator.create_app() annotator.create_all() print("done.\n") username = raw_input("Admin username [admin]: ").strip() if not username: username = 'admin' email = '' while not email: email = raw_input("Admin email: ").strip() password = '' while not password: password = getpass("Admin password: ") ckey = raw_input("Primary consumer key [annotateit]: ").strip() if not ckey: ckey = 'annotateit' with annotator.app.test_request_context(): print("\nCreating admin user... ", end="") u = User(username, email, password) annotator.db.session.add(u) annotator.db.session.commit() print("done.") print("Creating primary consumer... ", end="") c = Consumer(ckey) c.user_id = u.id annotator.db.session.add(c) annotator.db.session.commit() print("done.\n") print("Primary consumer secret: %s" % c.secret) <commit_msg>Update to reflect new create_app signature<commit_after>from __future__ import print_function from getpass import getpass import readline import sys import annotator from annotator.model import Consumer, User if __name__ == '__main__': r = raw_input("This program will perform initial setup of the annotation \n" "store, and create the required admin accounts. Proceed? [Y/n] ") if r and r[0] in ['n', 'N']: sys.exit(1) print("\nCreating SQLite database and ElasticSearch indices... ", end="") app = annotator.create_app() annotator.create_all(app) print("done.\n") username = raw_input("Admin username [admin]: ").strip() if not username: username = 'admin' email = '' while not email: email = raw_input("Admin email: ").strip() password = '' while not password: password = getpass("Admin password: ") ckey = raw_input("Primary consumer key [annotateit]: ").strip() if not ckey: ckey = 'annotateit' with app.test_request_context(): db = app.extensions['sqlalchemy'].db print("\nCreating admin user... ", end="") u = User(username, email, password) db.session.add(u) db.session.commit() print("done.") print("Creating primary consumer... ", end="") c = Consumer(ckey) c.user_id = u.id db.session.add(c) db.session.commit() print("done.\n") print("Primary consumer secret: %s" % c.secret)
bf790bb1ad59cca3034715e9e5c92e128bd1902e
apps/users/admin.py
apps/users/admin.py
from django.contrib import admin from users.models import UserBan class UserBanAdmin(admin.ModelAdmin): fields = ('user', 'by', 'reason', 'is_active') list_display = ('user', 'by', 'reason') list_filter = ('is_active',) raw_id_fields = ('user',) search_fields = ('user', 'reason') admin.site.register(UserBan, UserBanAdmin)
from django.contrib import admin from users.models import UserBan class UserBanAdmin(admin.ModelAdmin): fields = ('user', 'by', 'reason', 'is_active') list_display = ('user', 'by', 'reason') list_filter = ('is_active',) raw_id_fields = ('user',) search_fields = ('user__username', 'reason') admin.site.register(UserBan, UserBanAdmin)
Use explicit related-lookup syntax in ban search.
Use explicit related-lookup syntax in ban search.
Python
mpl-2.0
biswajitsahu/kuma,davehunt/kuma,SphinxKnight/kuma,escattone/kuma,yfdyh000/kuma,ronakkhunt/kuma,carnell69/kuma,tximikel/kuma,darkwing/kuma,YOTOV-LIMITED/kuma,SphinxKnight/kuma,safwanrahman/kuma,a2sheppy/kuma,safwanrahman/kuma,MenZil/kuma,tximikel/kuma,bluemini/kuma,SphinxKnight/kuma,whip112/Whip112,biswajitsahu/kuma,anaran/kuma,jezdez/kuma,openjck/kuma,hoosteeno/kuma,nhenezi/kuma,tximikel/kuma,whip112/Whip112,darkwing/kuma,darkwing/kuma,varunkamra/kuma,RanadeepPolavarapu/kuma,davehunt/kuma,safwanrahman/kuma,scrollback/kuma,a2sheppy/kuma,ollie314/kuma,carnell69/kuma,anaran/kuma,MenZil/kuma,openjck/kuma,hoosteeno/kuma,utkbansal/kuma,mastizada/kuma,robhudson/kuma,FrankBian/kuma,mastizada/kuma,yfdyh000/kuma,Elchi3/kuma,RanadeepPolavarapu/kuma,jgmize/kuma,nhenezi/kuma,davehunt/kuma,YOTOV-LIMITED/kuma,groovecoder/kuma,chirilo/kuma,mozilla/kuma,nhenezi/kuma,carnell69/kuma,biswajitsahu/kuma,biswajitsahu/kuma,ronakkhunt/kuma,jwhitlock/kuma,chirilo/kuma,scrollback/kuma,darkwing/kuma,cindyyu/kuma,RanadeepPolavarapu/kuma,bluemini/kuma,FrankBian/kuma,MenZil/kuma,YOTOV-LIMITED/kuma,jgmize/kuma,tximikel/kuma,davehunt/kuma,Elchi3/kuma,davidyezsetz/kuma,anaran/kuma,ronakkhunt/kuma,jwhitlock/kuma,safwanrahman/kuma,groovecoder/kuma,nhenezi/kuma,Elchi3/kuma,SphinxKnight/kuma,jwhitlock/kuma,jezdez/kuma,tximikel/kuma,MenZil/kuma,safwanrahman/kuma,tximikel/kuma,robhudson/kuma,mozilla/kuma,yfdyh000/kuma,RanadeepPolavarapu/kuma,YOTOV-LIMITED/kuma,scrollback/kuma,Elchi3/kuma,jwhitlock/kuma,jwhitlock/kuma,YOTOV-LIMITED/kuma,mozilla/kuma,scrollback/kuma,openjck/kuma,ollie314/kuma,jezdez/kuma,nhenezi/kuma,groovecoder/kuma,RanadeepPolavarapu/kuma,cindyyu/kuma,mozilla/kuma,jezdez/kuma,bluemini/kuma,carnell69/kuma,MenZil/kuma,openjck/kuma,chirilo/kuma,jgmize/kuma,davidyezsetz/kuma,yfdyh000/kuma,darkwing/kuma,SphinxKnight/kuma,varunkamra/kuma,utkbansal/kuma,a2sheppy/kuma,yfdyh000/kuma,RanadeepPolavarapu/kuma,anaran/kuma,escattone/kuma,mastizada/kuma,a2sheppy/kuma,whip112/Whip112,chirilo/kuma,ollie314/kuma,davehunt/kuma,ollie314/kuma,cindyyu/kuma,FrankBian/kuma,jgmize/kuma,hoosteeno/kuma,scrollback/kuma,hoosteeno/kuma,MenZil/kuma,escattone/kuma,whip112/Whip112,bluemini/kuma,varunkamra/kuma,surajssd/kuma,varunkamra/kuma,biswajitsahu/kuma,carnell69/kuma,anaran/kuma,utkbansal/kuma,FrankBian/kuma,utkbansal/kuma,surajssd/kuma,ronakkhunt/kuma,varunkamra/kuma,robhudson/kuma,openjck/kuma,biswajitsahu/kuma,surajssd/kuma,yfdyh000/kuma,robhudson/kuma,cindyyu/kuma,robhudson/kuma,jgmize/kuma,robhudson/kuma,jgmize/kuma,groovecoder/kuma,chirilo/kuma,davidyezsetz/kuma,surajssd/kuma,ollie314/kuma,darkwing/kuma,ollie314/kuma,groovecoder/kuma,surajssd/kuma,hoosteeno/kuma,Elchi3/kuma,hoosteeno/kuma,jezdez/kuma,FrankBian/kuma,surajssd/kuma,jezdez/kuma,carnell69/kuma,davehunt/kuma,safwanrahman/kuma,ronakkhunt/kuma,bluemini/kuma,a2sheppy/kuma,openjck/kuma,ronakkhunt/kuma,cindyyu/kuma,davidyezsetz/kuma,whip112/Whip112,SphinxKnight/kuma,davidyezsetz/kuma,anaran/kuma,groovecoder/kuma,varunkamra/kuma,utkbansal/kuma,whip112/Whip112,utkbansal/kuma,mastizada/kuma,cindyyu/kuma,bluemini/kuma,YOTOV-LIMITED/kuma,chirilo/kuma,mozilla/kuma
from django.contrib import admin from users.models import UserBan class UserBanAdmin(admin.ModelAdmin): fields = ('user', 'by', 'reason', 'is_active') list_display = ('user', 'by', 'reason') list_filter = ('is_active',) raw_id_fields = ('user',) search_fields = ('user', 'reason') admin.site.register(UserBan, UserBanAdmin) Use explicit related-lookup syntax in ban search.
from django.contrib import admin from users.models import UserBan class UserBanAdmin(admin.ModelAdmin): fields = ('user', 'by', 'reason', 'is_active') list_display = ('user', 'by', 'reason') list_filter = ('is_active',) raw_id_fields = ('user',) search_fields = ('user__username', 'reason') admin.site.register(UserBan, UserBanAdmin)
<commit_before>from django.contrib import admin from users.models import UserBan class UserBanAdmin(admin.ModelAdmin): fields = ('user', 'by', 'reason', 'is_active') list_display = ('user', 'by', 'reason') list_filter = ('is_active',) raw_id_fields = ('user',) search_fields = ('user', 'reason') admin.site.register(UserBan, UserBanAdmin) <commit_msg>Use explicit related-lookup syntax in ban search.<commit_after>
from django.contrib import admin from users.models import UserBan class UserBanAdmin(admin.ModelAdmin): fields = ('user', 'by', 'reason', 'is_active') list_display = ('user', 'by', 'reason') list_filter = ('is_active',) raw_id_fields = ('user',) search_fields = ('user__username', 'reason') admin.site.register(UserBan, UserBanAdmin)
from django.contrib import admin from users.models import UserBan class UserBanAdmin(admin.ModelAdmin): fields = ('user', 'by', 'reason', 'is_active') list_display = ('user', 'by', 'reason') list_filter = ('is_active',) raw_id_fields = ('user',) search_fields = ('user', 'reason') admin.site.register(UserBan, UserBanAdmin) Use explicit related-lookup syntax in ban search.from django.contrib import admin from users.models import UserBan class UserBanAdmin(admin.ModelAdmin): fields = ('user', 'by', 'reason', 'is_active') list_display = ('user', 'by', 'reason') list_filter = ('is_active',) raw_id_fields = ('user',) search_fields = ('user__username', 'reason') admin.site.register(UserBan, UserBanAdmin)
<commit_before>from django.contrib import admin from users.models import UserBan class UserBanAdmin(admin.ModelAdmin): fields = ('user', 'by', 'reason', 'is_active') list_display = ('user', 'by', 'reason') list_filter = ('is_active',) raw_id_fields = ('user',) search_fields = ('user', 'reason') admin.site.register(UserBan, UserBanAdmin) <commit_msg>Use explicit related-lookup syntax in ban search.<commit_after>from django.contrib import admin from users.models import UserBan class UserBanAdmin(admin.ModelAdmin): fields = ('user', 'by', 'reason', 'is_active') list_display = ('user', 'by', 'reason') list_filter = ('is_active',) raw_id_fields = ('user',) search_fields = ('user__username', 'reason') admin.site.register(UserBan, UserBanAdmin)
72a5f58d7c7fe18f5ce4c2e02cf8a26146777f27
social/apps/pyramid_app/__init__.py
social/apps/pyramid_app/__init__.py
def includeme(config): config.add_route('social.auth', '/login/{backend}') config.add_route('social.complete', '/complete/{backend}') config.add_route('social.disconnect', '/disconnect/{backend}') config.add_route('social.disconnect_association', '/disconnect/{backend}/{association_id}')
from social.strategies.utils import set_current_strategy_getter from social.apps.pyramid_app.utils import load_strategy def includeme(config): config.add_route('social.auth', '/login/{backend}') config.add_route('social.complete', '/complete/{backend}') config.add_route('social.disconnect', '/disconnect/{backend}') config.add_route('social.disconnect_association', '/disconnect/{backend}/{association_id}') set_current_strategy_getter(load_strategy)
Set current strategy on pyramid app
Set current strategy on pyramid app
Python
bsd-3-clause
SeanHayes/python-social-auth,SeanHayes/python-social-auth,JerzySpendel/python-social-auth,ariestiyansyah/python-social-auth,bjorand/python-social-auth,drxos/python-social-auth,tkajtoch/python-social-auth,ByteInternet/python-social-auth,VishvajitP/python-social-auth,lawrence34/python-social-auth,JerzySpendel/python-social-auth,bjorand/python-social-auth,DhiaEddineSaidi/python-social-auth,chandolia/python-social-auth,tobias47n9e/social-core,cjltsod/python-social-auth,S01780/python-social-auth,jeyraof/python-social-auth,san-mate/python-social-auth,Andygmb/python-social-auth,webjunkie/python-social-auth,bjorand/python-social-auth,python-social-auth/social-core,mathspace/python-social-auth,MSOpenTech/python-social-auth,alrusdi/python-social-auth,rsteca/python-social-auth,cmichal/python-social-auth,python-social-auth/social-app-django,MSOpenTech/python-social-auth,mrwags/python-social-auth,degs098/python-social-auth,mchdks/python-social-auth,wildtetris/python-social-auth,muhammad-ammar/python-social-auth,frankier/python-social-auth,contracode/python-social-auth,mathspace/python-social-auth,contracode/python-social-auth,S01780/python-social-auth,henocdz/python-social-auth,hsr-ba-fs15-dat/python-social-auth,cjltsod/python-social-auth,tkajtoch/python-social-auth,yprez/python-social-auth,webjunkie/python-social-auth,hsr-ba-fs15-dat/python-social-auth,lamby/python-social-auth,VishvajitP/python-social-auth,mark-adams/python-social-auth,ariestiyansyah/python-social-auth,ByteInternet/python-social-auth,rsalmaso/python-social-auth,clef/python-social-auth,firstjob/python-social-auth,clef/python-social-auth,fearlessspider/python-social-auth,firstjob/python-social-auth,JJediny/python-social-auth,henocdz/python-social-auth,firstjob/python-social-auth,barseghyanartur/python-social-auth,drxos/python-social-auth,msampathkumar/python-social-auth,iruga090/python-social-auth,joelstanner/python-social-auth,python-social-auth/social-app-cherrypy,garrett-schlesinger/python-social-auth,jameslittle/python-social-auth,iruga090/python-social-auth,contracode/python-social-auth,mathspace/python-social-auth,falcon1kr/python-social-auth,S01780/python-social-auth,duoduo369/python-social-auth,alrusdi/python-social-auth,ByteInternet/python-social-auth,robbiet480/python-social-auth,mark-adams/python-social-auth,ononeor12/python-social-auth,alrusdi/python-social-auth,jneves/python-social-auth,lneoe/python-social-auth,fearlessspider/python-social-auth,rsteca/python-social-auth,jeyraof/python-social-auth,python-social-auth/social-docs,chandolia/python-social-auth,ononeor12/python-social-auth,rsteca/python-social-auth,python-social-auth/social-app-django,muhammad-ammar/python-social-auth,mark-adams/python-social-auth,Andygmb/python-social-auth,python-social-auth/social-core,yprez/python-social-auth,tkajtoch/python-social-auth,daniula/python-social-auth,degs098/python-social-auth,mchdks/python-social-auth,jeyraof/python-social-auth,lneoe/python-social-auth,lamby/python-social-auth,michael-borisov/python-social-auth,tutumcloud/python-social-auth,nirmalvp/python-social-auth,JJediny/python-social-auth,nirmalvp/python-social-auth,noodle-learns-programming/python-social-auth,jneves/python-social-auth,nirmalvp/python-social-auth,san-mate/python-social-auth,msampathkumar/python-social-auth,degs098/python-social-auth,clef/python-social-auth,muhammad-ammar/python-social-auth,mrwags/python-social-auth,DhiaEddineSaidi/python-social-auth,frankier/python-social-auth,joelstanner/python-social-auth,barseghyanartur/python-social-auth,VishvajitP/python-social-auth,jameslittle/python-social-auth,joelstanner/python-social-auth,lawrence34/python-social-auth,JJediny/python-social-auth,msampathkumar/python-social-auth,barseghyanartur/python-social-auth,rsalmaso/python-social-auth,duoduo369/python-social-auth,cmichal/python-social-auth,python-social-auth/social-storage-sqlalchemy,mrwags/python-social-auth,henocdz/python-social-auth,drxos/python-social-auth,fearlessspider/python-social-auth,robbiet480/python-social-auth,ononeor12/python-social-auth,wildtetris/python-social-auth,lneoe/python-social-auth,wildtetris/python-social-auth,Andygmb/python-social-auth,noodle-learns-programming/python-social-auth,merutak/python-social-auth,robbiet480/python-social-auth,MSOpenTech/python-social-auth,JerzySpendel/python-social-auth,merutak/python-social-auth,webjunkie/python-social-auth,falcon1kr/python-social-auth,michael-borisov/python-social-auth,noodle-learns-programming/python-social-auth,tutumcloud/python-social-auth,michael-borisov/python-social-auth,jneves/python-social-auth,garrett-schlesinger/python-social-auth,lamby/python-social-auth,merutak/python-social-auth,daniula/python-social-auth,DhiaEddineSaidi/python-social-auth,iruga090/python-social-auth,hsr-ba-fs15-dat/python-social-auth,chandolia/python-social-auth,mchdks/python-social-auth,falcon1kr/python-social-auth,san-mate/python-social-auth,cmichal/python-social-auth,jameslittle/python-social-auth,ariestiyansyah/python-social-auth,yprez/python-social-auth,lawrence34/python-social-auth,python-social-auth/social-app-django,daniula/python-social-auth
def includeme(config): config.add_route('social.auth', '/login/{backend}') config.add_route('social.complete', '/complete/{backend}') config.add_route('social.disconnect', '/disconnect/{backend}') config.add_route('social.disconnect_association', '/disconnect/{backend}/{association_id}') Set current strategy on pyramid app
from social.strategies.utils import set_current_strategy_getter from social.apps.pyramid_app.utils import load_strategy def includeme(config): config.add_route('social.auth', '/login/{backend}') config.add_route('social.complete', '/complete/{backend}') config.add_route('social.disconnect', '/disconnect/{backend}') config.add_route('social.disconnect_association', '/disconnect/{backend}/{association_id}') set_current_strategy_getter(load_strategy)
<commit_before>def includeme(config): config.add_route('social.auth', '/login/{backend}') config.add_route('social.complete', '/complete/{backend}') config.add_route('social.disconnect', '/disconnect/{backend}') config.add_route('social.disconnect_association', '/disconnect/{backend}/{association_id}') <commit_msg>Set current strategy on pyramid app<commit_after>
from social.strategies.utils import set_current_strategy_getter from social.apps.pyramid_app.utils import load_strategy def includeme(config): config.add_route('social.auth', '/login/{backend}') config.add_route('social.complete', '/complete/{backend}') config.add_route('social.disconnect', '/disconnect/{backend}') config.add_route('social.disconnect_association', '/disconnect/{backend}/{association_id}') set_current_strategy_getter(load_strategy)
def includeme(config): config.add_route('social.auth', '/login/{backend}') config.add_route('social.complete', '/complete/{backend}') config.add_route('social.disconnect', '/disconnect/{backend}') config.add_route('social.disconnect_association', '/disconnect/{backend}/{association_id}') Set current strategy on pyramid appfrom social.strategies.utils import set_current_strategy_getter from social.apps.pyramid_app.utils import load_strategy def includeme(config): config.add_route('social.auth', '/login/{backend}') config.add_route('social.complete', '/complete/{backend}') config.add_route('social.disconnect', '/disconnect/{backend}') config.add_route('social.disconnect_association', '/disconnect/{backend}/{association_id}') set_current_strategy_getter(load_strategy)
<commit_before>def includeme(config): config.add_route('social.auth', '/login/{backend}') config.add_route('social.complete', '/complete/{backend}') config.add_route('social.disconnect', '/disconnect/{backend}') config.add_route('social.disconnect_association', '/disconnect/{backend}/{association_id}') <commit_msg>Set current strategy on pyramid app<commit_after>from social.strategies.utils import set_current_strategy_getter from social.apps.pyramid_app.utils import load_strategy def includeme(config): config.add_route('social.auth', '/login/{backend}') config.add_route('social.complete', '/complete/{backend}') config.add_route('social.disconnect', '/disconnect/{backend}') config.add_route('social.disconnect_association', '/disconnect/{backend}/{association_id}') set_current_strategy_getter(load_strategy)
c0a6a18363e3bdaab67c4abb15add441e7a975ca
glaciercmd/command_upload_file_to_vault.py
glaciercmd/command_upload_file_to_vault.py
import boto class CommandUploadFileToVault(object): def execute(self, args, config): glacier_connection = boto.connect_glacier(aws_access_key_id=config.get('configuration', 'aws_key'), aws_secret_access_key=config.get('configuration', 'aws_secret')) try: vault = glacier_connection.get_vault(args[5]) except: vault = None if vault is None: print "Vault named '{}' does not exist.".format(args[5]) else: archive_id = vault.upload_archive(args[2]) print "Upload archive id: {}".format(archive_id) def accept(self, args): return len(args) >= 6 and args[0] == 'upload' and args[1] == 'file' and args[3] == 'to' and args[4] == 'vault' def command_init(): return CommandUploadFileToVault()
import boto import time import os from boto.dynamodb2.table import Table from boto.dynamodb2.layer1 import DynamoDBConnection class CommandUploadFileToVault(object): def execute(self, args, config): glacier_connection = boto.connect_glacier(aws_access_key_id=config.get('configuration', 'aws_key'), aws_secret_access_key=config.get('configuration', 'aws_secret')) try: vault = glacier_connection.get_vault(args[5]) except: vault = None if vault is None: print "Vault named '{}' does not exist.".format(args[5]) else: archive_id = vault.upload_archive(args[2]) print "Upload archive id: {}".format(archive_id) dynamo_connection=DynamoDBConnection(aws_access_key_id=config.get('configuration', 'aws_key'), aws_secret_access_key=config.get('configuration', 'aws_secret')) archive_id_table = Table(config.get('configuration', 'dynamodb_table'), connection=dynamo_connection) archive_id_table.put_item(data={ 'Archive ID': archive_id, 'Filename': os.path.abspath(args[2]), 'Upload Timestamp': int(time.time()) }) def accept(self, args): return len(args) >= 6 and args[0] == 'upload' and args[1] == 'file' and args[3] == 'to' and args[4] == 'vault' def command_init(): return CommandUploadFileToVault()
Save archive ids to dynamodb
Save archive ids to dynamodb
Python
mit
carsonmcdonald/glacier-cmd
import boto class CommandUploadFileToVault(object): def execute(self, args, config): glacier_connection = boto.connect_glacier(aws_access_key_id=config.get('configuration', 'aws_key'), aws_secret_access_key=config.get('configuration', 'aws_secret')) try: vault = glacier_connection.get_vault(args[5]) except: vault = None if vault is None: print "Vault named '{}' does not exist.".format(args[5]) else: archive_id = vault.upload_archive(args[2]) print "Upload archive id: {}".format(archive_id) def accept(self, args): return len(args) >= 6 and args[0] == 'upload' and args[1] == 'file' and args[3] == 'to' and args[4] == 'vault' def command_init(): return CommandUploadFileToVault() Save archive ids to dynamodb
import boto import time import os from boto.dynamodb2.table import Table from boto.dynamodb2.layer1 import DynamoDBConnection class CommandUploadFileToVault(object): def execute(self, args, config): glacier_connection = boto.connect_glacier(aws_access_key_id=config.get('configuration', 'aws_key'), aws_secret_access_key=config.get('configuration', 'aws_secret')) try: vault = glacier_connection.get_vault(args[5]) except: vault = None if vault is None: print "Vault named '{}' does not exist.".format(args[5]) else: archive_id = vault.upload_archive(args[2]) print "Upload archive id: {}".format(archive_id) dynamo_connection=DynamoDBConnection(aws_access_key_id=config.get('configuration', 'aws_key'), aws_secret_access_key=config.get('configuration', 'aws_secret')) archive_id_table = Table(config.get('configuration', 'dynamodb_table'), connection=dynamo_connection) archive_id_table.put_item(data={ 'Archive ID': archive_id, 'Filename': os.path.abspath(args[2]), 'Upload Timestamp': int(time.time()) }) def accept(self, args): return len(args) >= 6 and args[0] == 'upload' and args[1] == 'file' and args[3] == 'to' and args[4] == 'vault' def command_init(): return CommandUploadFileToVault()
<commit_before>import boto class CommandUploadFileToVault(object): def execute(self, args, config): glacier_connection = boto.connect_glacier(aws_access_key_id=config.get('configuration', 'aws_key'), aws_secret_access_key=config.get('configuration', 'aws_secret')) try: vault = glacier_connection.get_vault(args[5]) except: vault = None if vault is None: print "Vault named '{}' does not exist.".format(args[5]) else: archive_id = vault.upload_archive(args[2]) print "Upload archive id: {}".format(archive_id) def accept(self, args): return len(args) >= 6 and args[0] == 'upload' and args[1] == 'file' and args[3] == 'to' and args[4] == 'vault' def command_init(): return CommandUploadFileToVault() <commit_msg>Save archive ids to dynamodb<commit_after>
import boto import time import os from boto.dynamodb2.table import Table from boto.dynamodb2.layer1 import DynamoDBConnection class CommandUploadFileToVault(object): def execute(self, args, config): glacier_connection = boto.connect_glacier(aws_access_key_id=config.get('configuration', 'aws_key'), aws_secret_access_key=config.get('configuration', 'aws_secret')) try: vault = glacier_connection.get_vault(args[5]) except: vault = None if vault is None: print "Vault named '{}' does not exist.".format(args[5]) else: archive_id = vault.upload_archive(args[2]) print "Upload archive id: {}".format(archive_id) dynamo_connection=DynamoDBConnection(aws_access_key_id=config.get('configuration', 'aws_key'), aws_secret_access_key=config.get('configuration', 'aws_secret')) archive_id_table = Table(config.get('configuration', 'dynamodb_table'), connection=dynamo_connection) archive_id_table.put_item(data={ 'Archive ID': archive_id, 'Filename': os.path.abspath(args[2]), 'Upload Timestamp': int(time.time()) }) def accept(self, args): return len(args) >= 6 and args[0] == 'upload' and args[1] == 'file' and args[3] == 'to' and args[4] == 'vault' def command_init(): return CommandUploadFileToVault()
import boto class CommandUploadFileToVault(object): def execute(self, args, config): glacier_connection = boto.connect_glacier(aws_access_key_id=config.get('configuration', 'aws_key'), aws_secret_access_key=config.get('configuration', 'aws_secret')) try: vault = glacier_connection.get_vault(args[5]) except: vault = None if vault is None: print "Vault named '{}' does not exist.".format(args[5]) else: archive_id = vault.upload_archive(args[2]) print "Upload archive id: {}".format(archive_id) def accept(self, args): return len(args) >= 6 and args[0] == 'upload' and args[1] == 'file' and args[3] == 'to' and args[4] == 'vault' def command_init(): return CommandUploadFileToVault() Save archive ids to dynamodbimport boto import time import os from boto.dynamodb2.table import Table from boto.dynamodb2.layer1 import DynamoDBConnection class CommandUploadFileToVault(object): def execute(self, args, config): glacier_connection = boto.connect_glacier(aws_access_key_id=config.get('configuration', 'aws_key'), aws_secret_access_key=config.get('configuration', 'aws_secret')) try: vault = glacier_connection.get_vault(args[5]) except: vault = None if vault is None: print "Vault named '{}' does not exist.".format(args[5]) else: archive_id = vault.upload_archive(args[2]) print "Upload archive id: {}".format(archive_id) dynamo_connection=DynamoDBConnection(aws_access_key_id=config.get('configuration', 'aws_key'), aws_secret_access_key=config.get('configuration', 'aws_secret')) archive_id_table = Table(config.get('configuration', 'dynamodb_table'), connection=dynamo_connection) archive_id_table.put_item(data={ 'Archive ID': archive_id, 'Filename': os.path.abspath(args[2]), 'Upload Timestamp': int(time.time()) }) def accept(self, args): return len(args) >= 6 and args[0] == 'upload' and args[1] == 'file' and args[3] == 'to' and args[4] == 'vault' def command_init(): return CommandUploadFileToVault()
<commit_before>import boto class CommandUploadFileToVault(object): def execute(self, args, config): glacier_connection = boto.connect_glacier(aws_access_key_id=config.get('configuration', 'aws_key'), aws_secret_access_key=config.get('configuration', 'aws_secret')) try: vault = glacier_connection.get_vault(args[5]) except: vault = None if vault is None: print "Vault named '{}' does not exist.".format(args[5]) else: archive_id = vault.upload_archive(args[2]) print "Upload archive id: {}".format(archive_id) def accept(self, args): return len(args) >= 6 and args[0] == 'upload' and args[1] == 'file' and args[3] == 'to' and args[4] == 'vault' def command_init(): return CommandUploadFileToVault() <commit_msg>Save archive ids to dynamodb<commit_after>import boto import time import os from boto.dynamodb2.table import Table from boto.dynamodb2.layer1 import DynamoDBConnection class CommandUploadFileToVault(object): def execute(self, args, config): glacier_connection = boto.connect_glacier(aws_access_key_id=config.get('configuration', 'aws_key'), aws_secret_access_key=config.get('configuration', 'aws_secret')) try: vault = glacier_connection.get_vault(args[5]) except: vault = None if vault is None: print "Vault named '{}' does not exist.".format(args[5]) else: archive_id = vault.upload_archive(args[2]) print "Upload archive id: {}".format(archive_id) dynamo_connection=DynamoDBConnection(aws_access_key_id=config.get('configuration', 'aws_key'), aws_secret_access_key=config.get('configuration', 'aws_secret')) archive_id_table = Table(config.get('configuration', 'dynamodb_table'), connection=dynamo_connection) archive_id_table.put_item(data={ 'Archive ID': archive_id, 'Filename': os.path.abspath(args[2]), 'Upload Timestamp': int(time.time()) }) def accept(self, args): return len(args) >= 6 and args[0] == 'upload' and args[1] == 'file' and args[3] == 'to' and args[4] == 'vault' def command_init(): return CommandUploadFileToVault()
f762c4e129db71ef7cfccba9b8e60582a3358617
octane_fuelclient/octaneclient/commands.py
octane_fuelclient/octaneclient/commands.py
from fuelclient.commands import base from fuelclient.commands import environment as env_commands from fuelclient.common import data_utils class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand): """Clone environment and translate settings to the given release.""" columns = env_commands.EnvShow.columns def get_parser(self, prog_name): parser = super(EnvClone, self).get_parser(prog_name) parser.add_argument('name', type=str, help='Name of the new environment.') parser.add_argument('release', type=int, help='ID of the release of the new environment.') return parser def take_action(self, parsed_args): new_env = self.client.connection.post_request( "clusters/{0}/upgrade/clone".format(parsed_args.id), { 'name': parsed_args.name, 'release_id': parsed_args.release, } ) new_env = data_utils.get_display_data_single(self.columns, new_env) return (self.columns, new_env)
from fuelclient.commands import base from fuelclient.commands import environment as env_commands from fuelclient.common import data_utils class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand): """Clone environment and translate settings to the given release.""" columns = env_commands.EnvShow.columns def get_parser(self, prog_name): parser = super(EnvClone, self).get_parser(prog_name) parser.add_argument('name', type=str, help='Name of the new environment.') parser.add_argument('release', type=int, help='ID of the release of the new environment.') return parser def take_action(self, parsed_args): # TODO(akscram): While the clone procedure is not a part of # fuelclient.objects.Environment the connection # colled directly. new_env = self.client._entity_wrapper.connection.post_request( "clusters/{0}/upgrade/clone".format(parsed_args.id), { 'name': parsed_args.name, 'release_id': parsed_args.release, } ) new_env = data_utils.get_display_data_single(self.columns, new_env) return (self.columns, new_env)
Call fuelclient directly passing over the object
Call fuelclient directly passing over the object
Python
apache-2.0
Mirantis/octane,stackforge/fuel-octane,Mirantis/octane,stackforge/fuel-octane
from fuelclient.commands import base from fuelclient.commands import environment as env_commands from fuelclient.common import data_utils class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand): """Clone environment and translate settings to the given release.""" columns = env_commands.EnvShow.columns def get_parser(self, prog_name): parser = super(EnvClone, self).get_parser(prog_name) parser.add_argument('name', type=str, help='Name of the new environment.') parser.add_argument('release', type=int, help='ID of the release of the new environment.') return parser def take_action(self, parsed_args): new_env = self.client.connection.post_request( "clusters/{0}/upgrade/clone".format(parsed_args.id), { 'name': parsed_args.name, 'release_id': parsed_args.release, } ) new_env = data_utils.get_display_data_single(self.columns, new_env) return (self.columns, new_env) Call fuelclient directly passing over the object
from fuelclient.commands import base from fuelclient.commands import environment as env_commands from fuelclient.common import data_utils class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand): """Clone environment and translate settings to the given release.""" columns = env_commands.EnvShow.columns def get_parser(self, prog_name): parser = super(EnvClone, self).get_parser(prog_name) parser.add_argument('name', type=str, help='Name of the new environment.') parser.add_argument('release', type=int, help='ID of the release of the new environment.') return parser def take_action(self, parsed_args): # TODO(akscram): While the clone procedure is not a part of # fuelclient.objects.Environment the connection # colled directly. new_env = self.client._entity_wrapper.connection.post_request( "clusters/{0}/upgrade/clone".format(parsed_args.id), { 'name': parsed_args.name, 'release_id': parsed_args.release, } ) new_env = data_utils.get_display_data_single(self.columns, new_env) return (self.columns, new_env)
<commit_before>from fuelclient.commands import base from fuelclient.commands import environment as env_commands from fuelclient.common import data_utils class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand): """Clone environment and translate settings to the given release.""" columns = env_commands.EnvShow.columns def get_parser(self, prog_name): parser = super(EnvClone, self).get_parser(prog_name) parser.add_argument('name', type=str, help='Name of the new environment.') parser.add_argument('release', type=int, help='ID of the release of the new environment.') return parser def take_action(self, parsed_args): new_env = self.client.connection.post_request( "clusters/{0}/upgrade/clone".format(parsed_args.id), { 'name': parsed_args.name, 'release_id': parsed_args.release, } ) new_env = data_utils.get_display_data_single(self.columns, new_env) return (self.columns, new_env) <commit_msg>Call fuelclient directly passing over the object<commit_after>
from fuelclient.commands import base from fuelclient.commands import environment as env_commands from fuelclient.common import data_utils class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand): """Clone environment and translate settings to the given release.""" columns = env_commands.EnvShow.columns def get_parser(self, prog_name): parser = super(EnvClone, self).get_parser(prog_name) parser.add_argument('name', type=str, help='Name of the new environment.') parser.add_argument('release', type=int, help='ID of the release of the new environment.') return parser def take_action(self, parsed_args): # TODO(akscram): While the clone procedure is not a part of # fuelclient.objects.Environment the connection # colled directly. new_env = self.client._entity_wrapper.connection.post_request( "clusters/{0}/upgrade/clone".format(parsed_args.id), { 'name': parsed_args.name, 'release_id': parsed_args.release, } ) new_env = data_utils.get_display_data_single(self.columns, new_env) return (self.columns, new_env)
from fuelclient.commands import base from fuelclient.commands import environment as env_commands from fuelclient.common import data_utils class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand): """Clone environment and translate settings to the given release.""" columns = env_commands.EnvShow.columns def get_parser(self, prog_name): parser = super(EnvClone, self).get_parser(prog_name) parser.add_argument('name', type=str, help='Name of the new environment.') parser.add_argument('release', type=int, help='ID of the release of the new environment.') return parser def take_action(self, parsed_args): new_env = self.client.connection.post_request( "clusters/{0}/upgrade/clone".format(parsed_args.id), { 'name': parsed_args.name, 'release_id': parsed_args.release, } ) new_env = data_utils.get_display_data_single(self.columns, new_env) return (self.columns, new_env) Call fuelclient directly passing over the objectfrom fuelclient.commands import base from fuelclient.commands import environment as env_commands from fuelclient.common import data_utils class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand): """Clone environment and translate settings to the given release.""" columns = env_commands.EnvShow.columns def get_parser(self, prog_name): parser = super(EnvClone, self).get_parser(prog_name) parser.add_argument('name', type=str, help='Name of the new environment.') parser.add_argument('release', type=int, help='ID of the release of the new environment.') return parser def take_action(self, parsed_args): # TODO(akscram): While the clone procedure is not a part of # fuelclient.objects.Environment the connection # colled directly. new_env = self.client._entity_wrapper.connection.post_request( "clusters/{0}/upgrade/clone".format(parsed_args.id), { 'name': parsed_args.name, 'release_id': parsed_args.release, } ) new_env = data_utils.get_display_data_single(self.columns, new_env) return (self.columns, new_env)
<commit_before>from fuelclient.commands import base from fuelclient.commands import environment as env_commands from fuelclient.common import data_utils class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand): """Clone environment and translate settings to the given release.""" columns = env_commands.EnvShow.columns def get_parser(self, prog_name): parser = super(EnvClone, self).get_parser(prog_name) parser.add_argument('name', type=str, help='Name of the new environment.') parser.add_argument('release', type=int, help='ID of the release of the new environment.') return parser def take_action(self, parsed_args): new_env = self.client.connection.post_request( "clusters/{0}/upgrade/clone".format(parsed_args.id), { 'name': parsed_args.name, 'release_id': parsed_args.release, } ) new_env = data_utils.get_display_data_single(self.columns, new_env) return (self.columns, new_env) <commit_msg>Call fuelclient directly passing over the object<commit_after>from fuelclient.commands import base from fuelclient.commands import environment as env_commands from fuelclient.common import data_utils class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand): """Clone environment and translate settings to the given release.""" columns = env_commands.EnvShow.columns def get_parser(self, prog_name): parser = super(EnvClone, self).get_parser(prog_name) parser.add_argument('name', type=str, help='Name of the new environment.') parser.add_argument('release', type=int, help='ID of the release of the new environment.') return parser def take_action(self, parsed_args): # TODO(akscram): While the clone procedure is not a part of # fuelclient.objects.Environment the connection # colled directly. new_env = self.client._entity_wrapper.connection.post_request( "clusters/{0}/upgrade/clone".format(parsed_args.id), { 'name': parsed_args.name, 'release_id': parsed_args.release, } ) new_env = data_utils.get_display_data_single(self.columns, new_env) return (self.columns, new_env)
bf9a3b78e2d0da66deee8e8f140ba161d601a4c6
assisstant/keyboard/config.py
assisstant/keyboard/config.py
from PyQt5.QtCore import Qt FREQ = [ 6.666666666666667, # 12.195121951219512, 5.882352941, 10, 7.575757575757576 ] # fifth freq # 8.620689655172415 # # TODO: Adjust colors COLOR = [Qt.green, Qt.green, Qt.green, Qt.green, Qt.black] TIME_FLASH_SEC = 2 TIME_REST_SEC = 4 ANIMATION_DURATION = 300 GRIDLAYOUT_MARGIN = 0 GRIDLAYOUT_SPACING = 100 # CHARS = ["ABCDQRST", # "EFGHUVWX", # "IJKLYZ.,", # "MNOP\"'?⏎", # "1234$@^!", # "5678~_|&", # "90-+()[]", # "*/^=<>{}"] CHARS = ["abcdqrst", "efghuvwx", "ijklyz.,", "mnop\"'?⏎", "1234$@^!", "5678~_|&", "90-+()[]", "*/^=<>{}"]
from PyQt5.QtCore import Qt FREQ = [ 6.666666666666667, # 12.195121951219512, 5.882352941, 10, 7.575757575757576 ] # fifth freq # 8.620689655172415 # # TODO: Adjust colors COLOR = [Qt.green, Qt.green, Qt.green, Qt.green, Qt.black] TIME_FLASH_SEC = 3 TIME_REST_SEC = 4 ANIMATION_DURATION = 300 GRIDLAYOUT_MARGIN = 0 GRIDLAYOUT_SPACING = 100 # CHARS = ["ABCDQRST", # "EFGHUVWX", # "IJKLYZ.,", # "MNOP\"'?⏎", # "1234$@^!", # "5678~_|&", # "90-+()[]", # "*/^=<>{}"] CHARS = ["abcdqrst", "efghuvwx", "ijklyz.,", "mnop\"'?⏎", "1234$@^!", "5678~_|&", "90-+()[]", "*/^=<>{}"]
Increase flashing time from 2 to 3 seconds
Increase flashing time from 2 to 3 seconds
Python
apache-2.0
brainbots/assistant
from PyQt5.QtCore import Qt FREQ = [ 6.666666666666667, # 12.195121951219512, 5.882352941, 10, 7.575757575757576 ] # fifth freq # 8.620689655172415 # # TODO: Adjust colors COLOR = [Qt.green, Qt.green, Qt.green, Qt.green, Qt.black] TIME_FLASH_SEC = 2 TIME_REST_SEC = 4 ANIMATION_DURATION = 300 GRIDLAYOUT_MARGIN = 0 GRIDLAYOUT_SPACING = 100 # CHARS = ["ABCDQRST", # "EFGHUVWX", # "IJKLYZ.,", # "MNOP\"'?⏎", # "1234$@^!", # "5678~_|&", # "90-+()[]", # "*/^=<>{}"] CHARS = ["abcdqrst", "efghuvwx", "ijklyz.,", "mnop\"'?⏎", "1234$@^!", "5678~_|&", "90-+()[]", "*/^=<>{}"] Increase flashing time from 2 to 3 seconds
from PyQt5.QtCore import Qt FREQ = [ 6.666666666666667, # 12.195121951219512, 5.882352941, 10, 7.575757575757576 ] # fifth freq # 8.620689655172415 # # TODO: Adjust colors COLOR = [Qt.green, Qt.green, Qt.green, Qt.green, Qt.black] TIME_FLASH_SEC = 3 TIME_REST_SEC = 4 ANIMATION_DURATION = 300 GRIDLAYOUT_MARGIN = 0 GRIDLAYOUT_SPACING = 100 # CHARS = ["ABCDQRST", # "EFGHUVWX", # "IJKLYZ.,", # "MNOP\"'?⏎", # "1234$@^!", # "5678~_|&", # "90-+()[]", # "*/^=<>{}"] CHARS = ["abcdqrst", "efghuvwx", "ijklyz.,", "mnop\"'?⏎", "1234$@^!", "5678~_|&", "90-+()[]", "*/^=<>{}"]
<commit_before>from PyQt5.QtCore import Qt FREQ = [ 6.666666666666667, # 12.195121951219512, 5.882352941, 10, 7.575757575757576 ] # fifth freq # 8.620689655172415 # # TODO: Adjust colors COLOR = [Qt.green, Qt.green, Qt.green, Qt.green, Qt.black] TIME_FLASH_SEC = 2 TIME_REST_SEC = 4 ANIMATION_DURATION = 300 GRIDLAYOUT_MARGIN = 0 GRIDLAYOUT_SPACING = 100 # CHARS = ["ABCDQRST", # "EFGHUVWX", # "IJKLYZ.,", # "MNOP\"'?⏎", # "1234$@^!", # "5678~_|&", # "90-+()[]", # "*/^=<>{}"] CHARS = ["abcdqrst", "efghuvwx", "ijklyz.,", "mnop\"'?⏎", "1234$@^!", "5678~_|&", "90-+()[]", "*/^=<>{}"] <commit_msg>Increase flashing time from 2 to 3 seconds<commit_after>
from PyQt5.QtCore import Qt FREQ = [ 6.666666666666667, # 12.195121951219512, 5.882352941, 10, 7.575757575757576 ] # fifth freq # 8.620689655172415 # # TODO: Adjust colors COLOR = [Qt.green, Qt.green, Qt.green, Qt.green, Qt.black] TIME_FLASH_SEC = 3 TIME_REST_SEC = 4 ANIMATION_DURATION = 300 GRIDLAYOUT_MARGIN = 0 GRIDLAYOUT_SPACING = 100 # CHARS = ["ABCDQRST", # "EFGHUVWX", # "IJKLYZ.,", # "MNOP\"'?⏎", # "1234$@^!", # "5678~_|&", # "90-+()[]", # "*/^=<>{}"] CHARS = ["abcdqrst", "efghuvwx", "ijklyz.,", "mnop\"'?⏎", "1234$@^!", "5678~_|&", "90-+()[]", "*/^=<>{}"]
from PyQt5.QtCore import Qt FREQ = [ 6.666666666666667, # 12.195121951219512, 5.882352941, 10, 7.575757575757576 ] # fifth freq # 8.620689655172415 # # TODO: Adjust colors COLOR = [Qt.green, Qt.green, Qt.green, Qt.green, Qt.black] TIME_FLASH_SEC = 2 TIME_REST_SEC = 4 ANIMATION_DURATION = 300 GRIDLAYOUT_MARGIN = 0 GRIDLAYOUT_SPACING = 100 # CHARS = ["ABCDQRST", # "EFGHUVWX", # "IJKLYZ.,", # "MNOP\"'?⏎", # "1234$@^!", # "5678~_|&", # "90-+()[]", # "*/^=<>{}"] CHARS = ["abcdqrst", "efghuvwx", "ijklyz.,", "mnop\"'?⏎", "1234$@^!", "5678~_|&", "90-+()[]", "*/^=<>{}"] Increase flashing time from 2 to 3 secondsfrom PyQt5.QtCore import Qt FREQ = [ 6.666666666666667, # 12.195121951219512, 5.882352941, 10, 7.575757575757576 ] # fifth freq # 8.620689655172415 # # TODO: Adjust colors COLOR = [Qt.green, Qt.green, Qt.green, Qt.green, Qt.black] TIME_FLASH_SEC = 3 TIME_REST_SEC = 4 ANIMATION_DURATION = 300 GRIDLAYOUT_MARGIN = 0 GRIDLAYOUT_SPACING = 100 # CHARS = ["ABCDQRST", # "EFGHUVWX", # "IJKLYZ.,", # "MNOP\"'?⏎", # "1234$@^!", # "5678~_|&", # "90-+()[]", # "*/^=<>{}"] CHARS = ["abcdqrst", "efghuvwx", "ijklyz.,", "mnop\"'?⏎", "1234$@^!", "5678~_|&", "90-+()[]", "*/^=<>{}"]
<commit_before>from PyQt5.QtCore import Qt FREQ = [ 6.666666666666667, # 12.195121951219512, 5.882352941, 10, 7.575757575757576 ] # fifth freq # 8.620689655172415 # # TODO: Adjust colors COLOR = [Qt.green, Qt.green, Qt.green, Qt.green, Qt.black] TIME_FLASH_SEC = 2 TIME_REST_SEC = 4 ANIMATION_DURATION = 300 GRIDLAYOUT_MARGIN = 0 GRIDLAYOUT_SPACING = 100 # CHARS = ["ABCDQRST", # "EFGHUVWX", # "IJKLYZ.,", # "MNOP\"'?⏎", # "1234$@^!", # "5678~_|&", # "90-+()[]", # "*/^=<>{}"] CHARS = ["abcdqrst", "efghuvwx", "ijklyz.,", "mnop\"'?⏎", "1234$@^!", "5678~_|&", "90-+()[]", "*/^=<>{}"] <commit_msg>Increase flashing time from 2 to 3 seconds<commit_after>from PyQt5.QtCore import Qt FREQ = [ 6.666666666666667, # 12.195121951219512, 5.882352941, 10, 7.575757575757576 ] # fifth freq # 8.620689655172415 # # TODO: Adjust colors COLOR = [Qt.green, Qt.green, Qt.green, Qt.green, Qt.black] TIME_FLASH_SEC = 3 TIME_REST_SEC = 4 ANIMATION_DURATION = 300 GRIDLAYOUT_MARGIN = 0 GRIDLAYOUT_SPACING = 100 # CHARS = ["ABCDQRST", # "EFGHUVWX", # "IJKLYZ.,", # "MNOP\"'?⏎", # "1234$@^!", # "5678~_|&", # "90-+()[]", # "*/^=<>{}"] CHARS = ["abcdqrst", "efghuvwx", "ijklyz.,", "mnop\"'?⏎", "1234$@^!", "5678~_|&", "90-+()[]", "*/^=<>{}"]
5cc071958aa63f46ec7f3708648f80a8424c661b
Lib/compositor/cmap.py
Lib/compositor/cmap.py
""" Utilities for handling the cmap table and character mapping in general. """ def extractCMAP(ttFont): cmap = {} cmapIDs = [(3, 10), (0, 3), (3, 1)] for i in range(len(cmapIDs)): if ttFont["cmap"].getcmap(*cmapIDs[i]): cmap = ttFont["cmap"].getcmap(*cmapIDs[i]).cmap break if not cmap: from compositor.error import CompositorError raise CompositorError("Found neither CMAP (3, 10), (0, 3), nor (3, 1) in font.") return cmap def reverseCMAP(cmap): reversed = {} for value, name in cmap.items(): if name not in reversed: reversed[name] = [] reversed[name].append(value) return reversed
""" Utilities for handling the cmap table and character mapping in general. """ def extractCMAP(ttFont): for platformID, encodingID in [(3, 10), (0, 3), (3, 1)]: cmapSubtable = ttFont["cmap"].getcmap(platformID, encodingID) if cmapSubtable is not None: return cmapSubtable.cmap from compositor.error import CompositorError raise CompositorError("Found neither CMAP (3, 10), (0, 3), nor (3, 1) in font.") def reverseCMAP(cmap): reversed = {} for value, name in cmap.items(): if name not in reversed: reversed[name] = [] reversed[name].append(value) return reversed
Make the code more compact
Make the code more compact
Python
mit
typesupply/compositor,anthrotype/compositor,anthrotype/compositor,typesupply/compositor
""" Utilities for handling the cmap table and character mapping in general. """ def extractCMAP(ttFont): cmap = {} cmapIDs = [(3, 10), (0, 3), (3, 1)] for i in range(len(cmapIDs)): if ttFont["cmap"].getcmap(*cmapIDs[i]): cmap = ttFont["cmap"].getcmap(*cmapIDs[i]).cmap break if not cmap: from compositor.error import CompositorError raise CompositorError("Found neither CMAP (3, 10), (0, 3), nor (3, 1) in font.") return cmap def reverseCMAP(cmap): reversed = {} for value, name in cmap.items(): if name not in reversed: reversed[name] = [] reversed[name].append(value) return reversed Make the code more compact
""" Utilities for handling the cmap table and character mapping in general. """ def extractCMAP(ttFont): for platformID, encodingID in [(3, 10), (0, 3), (3, 1)]: cmapSubtable = ttFont["cmap"].getcmap(platformID, encodingID) if cmapSubtable is not None: return cmapSubtable.cmap from compositor.error import CompositorError raise CompositorError("Found neither CMAP (3, 10), (0, 3), nor (3, 1) in font.") def reverseCMAP(cmap): reversed = {} for value, name in cmap.items(): if name not in reversed: reversed[name] = [] reversed[name].append(value) return reversed
<commit_before>""" Utilities for handling the cmap table and character mapping in general. """ def extractCMAP(ttFont): cmap = {} cmapIDs = [(3, 10), (0, 3), (3, 1)] for i in range(len(cmapIDs)): if ttFont["cmap"].getcmap(*cmapIDs[i]): cmap = ttFont["cmap"].getcmap(*cmapIDs[i]).cmap break if not cmap: from compositor.error import CompositorError raise CompositorError("Found neither CMAP (3, 10), (0, 3), nor (3, 1) in font.") return cmap def reverseCMAP(cmap): reversed = {} for value, name in cmap.items(): if name not in reversed: reversed[name] = [] reversed[name].append(value) return reversed <commit_msg>Make the code more compact<commit_after>
""" Utilities for handling the cmap table and character mapping in general. """ def extractCMAP(ttFont): for platformID, encodingID in [(3, 10), (0, 3), (3, 1)]: cmapSubtable = ttFont["cmap"].getcmap(platformID, encodingID) if cmapSubtable is not None: return cmapSubtable.cmap from compositor.error import CompositorError raise CompositorError("Found neither CMAP (3, 10), (0, 3), nor (3, 1) in font.") def reverseCMAP(cmap): reversed = {} for value, name in cmap.items(): if name not in reversed: reversed[name] = [] reversed[name].append(value) return reversed
""" Utilities for handling the cmap table and character mapping in general. """ def extractCMAP(ttFont): cmap = {} cmapIDs = [(3, 10), (0, 3), (3, 1)] for i in range(len(cmapIDs)): if ttFont["cmap"].getcmap(*cmapIDs[i]): cmap = ttFont["cmap"].getcmap(*cmapIDs[i]).cmap break if not cmap: from compositor.error import CompositorError raise CompositorError("Found neither CMAP (3, 10), (0, 3), nor (3, 1) in font.") return cmap def reverseCMAP(cmap): reversed = {} for value, name in cmap.items(): if name not in reversed: reversed[name] = [] reversed[name].append(value) return reversed Make the code more compact""" Utilities for handling the cmap table and character mapping in general. """ def extractCMAP(ttFont): for platformID, encodingID in [(3, 10), (0, 3), (3, 1)]: cmapSubtable = ttFont["cmap"].getcmap(platformID, encodingID) if cmapSubtable is not None: return cmapSubtable.cmap from compositor.error import CompositorError raise CompositorError("Found neither CMAP (3, 10), (0, 3), nor (3, 1) in font.") def reverseCMAP(cmap): reversed = {} for value, name in cmap.items(): if name not in reversed: reversed[name] = [] reversed[name].append(value) return reversed
<commit_before>""" Utilities for handling the cmap table and character mapping in general. """ def extractCMAP(ttFont): cmap = {} cmapIDs = [(3, 10), (0, 3), (3, 1)] for i in range(len(cmapIDs)): if ttFont["cmap"].getcmap(*cmapIDs[i]): cmap = ttFont["cmap"].getcmap(*cmapIDs[i]).cmap break if not cmap: from compositor.error import CompositorError raise CompositorError("Found neither CMAP (3, 10), (0, 3), nor (3, 1) in font.") return cmap def reverseCMAP(cmap): reversed = {} for value, name in cmap.items(): if name not in reversed: reversed[name] = [] reversed[name].append(value) return reversed <commit_msg>Make the code more compact<commit_after>""" Utilities for handling the cmap table and character mapping in general. """ def extractCMAP(ttFont): for platformID, encodingID in [(3, 10), (0, 3), (3, 1)]: cmapSubtable = ttFont["cmap"].getcmap(platformID, encodingID) if cmapSubtable is not None: return cmapSubtable.cmap from compositor.error import CompositorError raise CompositorError("Found neither CMAP (3, 10), (0, 3), nor (3, 1) in font.") def reverseCMAP(cmap): reversed = {} for value, name in cmap.items(): if name not in reversed: reversed[name] = [] reversed[name].append(value) return reversed
3cb52b94d2b5b3376a5dd965a976c398cd835e6d
docs/examples/schema4.py
docs/examples/schema4.py
from pydantic import BaseModel class Person(BaseModel): name: str age: int class Config: schema_extra = { "examples": [ { "name": "John Doe", "age": 25, } ] } print(Person.schema()) # {'title': 'Person', # 'type': 'object', # 'properties': {'name': {'title': 'Name', 'type': 'string'}, # 'age': {'title': 'Age', 'type': 'integer'}}, # 'required': ['name', 'age'], # 'examples': [{'name': 'John Doe', 'age': 25}]} print(Person.schema_json(indent=2))
from pydantic import BaseModel class Person(BaseModel): name: str age: int class Config: schema_extra = { 'examples': [ { 'name': 'John Doe', 'age': 25, } ] } print(Person.schema()) # {'title': 'Person', # 'type': 'object', # 'properties': {'name': {'title': 'Name', 'type': 'string'}, # 'age': {'title': 'Age', 'type': 'integer'}}, # 'required': ['name', 'age'], # 'examples': [{'name': 'John Doe', 'age': 25}]} print(Person.schema_json(indent=2))
Fix double quotes to single quotes
Fix double quotes to single quotes
Python
mit
samuelcolvin/pydantic,samuelcolvin/pydantic
from pydantic import BaseModel class Person(BaseModel): name: str age: int class Config: schema_extra = { "examples": [ { "name": "John Doe", "age": 25, } ] } print(Person.schema()) # {'title': 'Person', # 'type': 'object', # 'properties': {'name': {'title': 'Name', 'type': 'string'}, # 'age': {'title': 'Age', 'type': 'integer'}}, # 'required': ['name', 'age'], # 'examples': [{'name': 'John Doe', 'age': 25}]} print(Person.schema_json(indent=2)) Fix double quotes to single quotes
from pydantic import BaseModel class Person(BaseModel): name: str age: int class Config: schema_extra = { 'examples': [ { 'name': 'John Doe', 'age': 25, } ] } print(Person.schema()) # {'title': 'Person', # 'type': 'object', # 'properties': {'name': {'title': 'Name', 'type': 'string'}, # 'age': {'title': 'Age', 'type': 'integer'}}, # 'required': ['name', 'age'], # 'examples': [{'name': 'John Doe', 'age': 25}]} print(Person.schema_json(indent=2))
<commit_before>from pydantic import BaseModel class Person(BaseModel): name: str age: int class Config: schema_extra = { "examples": [ { "name": "John Doe", "age": 25, } ] } print(Person.schema()) # {'title': 'Person', # 'type': 'object', # 'properties': {'name': {'title': 'Name', 'type': 'string'}, # 'age': {'title': 'Age', 'type': 'integer'}}, # 'required': ['name', 'age'], # 'examples': [{'name': 'John Doe', 'age': 25}]} print(Person.schema_json(indent=2)) <commit_msg>Fix double quotes to single quotes<commit_after>
from pydantic import BaseModel class Person(BaseModel): name: str age: int class Config: schema_extra = { 'examples': [ { 'name': 'John Doe', 'age': 25, } ] } print(Person.schema()) # {'title': 'Person', # 'type': 'object', # 'properties': {'name': {'title': 'Name', 'type': 'string'}, # 'age': {'title': 'Age', 'type': 'integer'}}, # 'required': ['name', 'age'], # 'examples': [{'name': 'John Doe', 'age': 25}]} print(Person.schema_json(indent=2))
from pydantic import BaseModel class Person(BaseModel): name: str age: int class Config: schema_extra = { "examples": [ { "name": "John Doe", "age": 25, } ] } print(Person.schema()) # {'title': 'Person', # 'type': 'object', # 'properties': {'name': {'title': 'Name', 'type': 'string'}, # 'age': {'title': 'Age', 'type': 'integer'}}, # 'required': ['name', 'age'], # 'examples': [{'name': 'John Doe', 'age': 25}]} print(Person.schema_json(indent=2)) Fix double quotes to single quotesfrom pydantic import BaseModel class Person(BaseModel): name: str age: int class Config: schema_extra = { 'examples': [ { 'name': 'John Doe', 'age': 25, } ] } print(Person.schema()) # {'title': 'Person', # 'type': 'object', # 'properties': {'name': {'title': 'Name', 'type': 'string'}, # 'age': {'title': 'Age', 'type': 'integer'}}, # 'required': ['name', 'age'], # 'examples': [{'name': 'John Doe', 'age': 25}]} print(Person.schema_json(indent=2))
<commit_before>from pydantic import BaseModel class Person(BaseModel): name: str age: int class Config: schema_extra = { "examples": [ { "name": "John Doe", "age": 25, } ] } print(Person.schema()) # {'title': 'Person', # 'type': 'object', # 'properties': {'name': {'title': 'Name', 'type': 'string'}, # 'age': {'title': 'Age', 'type': 'integer'}}, # 'required': ['name', 'age'], # 'examples': [{'name': 'John Doe', 'age': 25}]} print(Person.schema_json(indent=2)) <commit_msg>Fix double quotes to single quotes<commit_after>from pydantic import BaseModel class Person(BaseModel): name: str age: int class Config: schema_extra = { 'examples': [ { 'name': 'John Doe', 'age': 25, } ] } print(Person.schema()) # {'title': 'Person', # 'type': 'object', # 'properties': {'name': {'title': 'Name', 'type': 'string'}, # 'age': {'title': 'Age', 'type': 'integer'}}, # 'required': ['name', 'age'], # 'examples': [{'name': 'John Doe', 'age': 25}]} print(Person.schema_json(indent=2))
25b5f88d5105ed1b9a2e39b8bea7238709238fd0
shakyo/consolekit/__init__.py
shakyo/consolekit/__init__.py
import curses from .character import Character from .console import Console from .line import Line from .misc import ESCAPE_CHARS, DELETE_CHARS, BACKSPACE_CHARS, \ is_printable_char, ctrl, unctrl def turn_on_console(asciize=False, spaces_per_tab=4, background_rgb=(0, 0, 0)): Line._ASCIIZE = asciize Line._SPACES_PER_TAB = spaces_per_tab window = curses.initscr() curses.noecho() curses.cbreak() curses.start_color() curses.use_default_colors() return Console(window, background_rgb=background_rgb) def turn_off_console(): curses.nocbreak() curses.echo() curses.endwin()
import curses from .character import Character from .console import Console from .line import Line from .misc import ESCAPE_CHARS, DELETE_CHARS, BACKSPACE_CHARS, \ is_printable_char, ctrl, unctrl def turn_on_console(asciize=False, spaces_per_tab=4, background_rgb=(0, 0, 0)): Line._ASCIIZE = asciize Line._SPACES_PER_TAB = spaces_per_tab window = curses.initscr() curses.noecho() curses.cbreak() curses.start_color() curses.use_default_colors() return Console(window, background_rgb=background_rgb) def turn_off_console(): curses.nocbreak() curses.echo() curses.endwin()
Remove an extra blank line
Remove an extra blank line
Python
unlicense
raviqqe/shakyo
import curses from .character import Character from .console import Console from .line import Line from .misc import ESCAPE_CHARS, DELETE_CHARS, BACKSPACE_CHARS, \ is_printable_char, ctrl, unctrl def turn_on_console(asciize=False, spaces_per_tab=4, background_rgb=(0, 0, 0)): Line._ASCIIZE = asciize Line._SPACES_PER_TAB = spaces_per_tab window = curses.initscr() curses.noecho() curses.cbreak() curses.start_color() curses.use_default_colors() return Console(window, background_rgb=background_rgb) def turn_off_console(): curses.nocbreak() curses.echo() curses.endwin() Remove an extra blank line
import curses from .character import Character from .console import Console from .line import Line from .misc import ESCAPE_CHARS, DELETE_CHARS, BACKSPACE_CHARS, \ is_printable_char, ctrl, unctrl def turn_on_console(asciize=False, spaces_per_tab=4, background_rgb=(0, 0, 0)): Line._ASCIIZE = asciize Line._SPACES_PER_TAB = spaces_per_tab window = curses.initscr() curses.noecho() curses.cbreak() curses.start_color() curses.use_default_colors() return Console(window, background_rgb=background_rgb) def turn_off_console(): curses.nocbreak() curses.echo() curses.endwin()
<commit_before>import curses from .character import Character from .console import Console from .line import Line from .misc import ESCAPE_CHARS, DELETE_CHARS, BACKSPACE_CHARS, \ is_printable_char, ctrl, unctrl def turn_on_console(asciize=False, spaces_per_tab=4, background_rgb=(0, 0, 0)): Line._ASCIIZE = asciize Line._SPACES_PER_TAB = spaces_per_tab window = curses.initscr() curses.noecho() curses.cbreak() curses.start_color() curses.use_default_colors() return Console(window, background_rgb=background_rgb) def turn_off_console(): curses.nocbreak() curses.echo() curses.endwin() <commit_msg>Remove an extra blank line<commit_after>
import curses from .character import Character from .console import Console from .line import Line from .misc import ESCAPE_CHARS, DELETE_CHARS, BACKSPACE_CHARS, \ is_printable_char, ctrl, unctrl def turn_on_console(asciize=False, spaces_per_tab=4, background_rgb=(0, 0, 0)): Line._ASCIIZE = asciize Line._SPACES_PER_TAB = spaces_per_tab window = curses.initscr() curses.noecho() curses.cbreak() curses.start_color() curses.use_default_colors() return Console(window, background_rgb=background_rgb) def turn_off_console(): curses.nocbreak() curses.echo() curses.endwin()
import curses from .character import Character from .console import Console from .line import Line from .misc import ESCAPE_CHARS, DELETE_CHARS, BACKSPACE_CHARS, \ is_printable_char, ctrl, unctrl def turn_on_console(asciize=False, spaces_per_tab=4, background_rgb=(0, 0, 0)): Line._ASCIIZE = asciize Line._SPACES_PER_TAB = spaces_per_tab window = curses.initscr() curses.noecho() curses.cbreak() curses.start_color() curses.use_default_colors() return Console(window, background_rgb=background_rgb) def turn_off_console(): curses.nocbreak() curses.echo() curses.endwin() Remove an extra blank lineimport curses from .character import Character from .console import Console from .line import Line from .misc import ESCAPE_CHARS, DELETE_CHARS, BACKSPACE_CHARS, \ is_printable_char, ctrl, unctrl def turn_on_console(asciize=False, spaces_per_tab=4, background_rgb=(0, 0, 0)): Line._ASCIIZE = asciize Line._SPACES_PER_TAB = spaces_per_tab window = curses.initscr() curses.noecho() curses.cbreak() curses.start_color() curses.use_default_colors() return Console(window, background_rgb=background_rgb) def turn_off_console(): curses.nocbreak() curses.echo() curses.endwin()
<commit_before>import curses from .character import Character from .console import Console from .line import Line from .misc import ESCAPE_CHARS, DELETE_CHARS, BACKSPACE_CHARS, \ is_printable_char, ctrl, unctrl def turn_on_console(asciize=False, spaces_per_tab=4, background_rgb=(0, 0, 0)): Line._ASCIIZE = asciize Line._SPACES_PER_TAB = spaces_per_tab window = curses.initscr() curses.noecho() curses.cbreak() curses.start_color() curses.use_default_colors() return Console(window, background_rgb=background_rgb) def turn_off_console(): curses.nocbreak() curses.echo() curses.endwin() <commit_msg>Remove an extra blank line<commit_after>import curses from .character import Character from .console import Console from .line import Line from .misc import ESCAPE_CHARS, DELETE_CHARS, BACKSPACE_CHARS, \ is_printable_char, ctrl, unctrl def turn_on_console(asciize=False, spaces_per_tab=4, background_rgb=(0, 0, 0)): Line._ASCIIZE = asciize Line._SPACES_PER_TAB = spaces_per_tab window = curses.initscr() curses.noecho() curses.cbreak() curses.start_color() curses.use_default_colors() return Console(window, background_rgb=background_rgb) def turn_off_console(): curses.nocbreak() curses.echo() curses.endwin()
6cd9b0c731839a75cd8e8bd2ab1e5d2f2687c96a
shirka/responders/__init__.py
shirka/responders/__init__.py
# vim: set fileencoding=utf-8 : class Responder(object): def support(message): pass def generate(message): pass def on_start(self, consumer): return False def support(self, request): return request.content[0:len(self.name())] == self.name() class Response(object): def __init__(self, content): self.content = content self.tags = [] self.command = "" def __str__(self): return self.content class StreamResponse(Response): def __init__(self, content): self.is_completed = False self.content = content def stop(self): self.is_completed = True def handle(self, request, consumer): self.is_completed = True def __str__(self): return "<StreamResponse>" from rageface import RagefaceResponder from flowdock import FlowdockWhoisResponder from math import MathResponder from wat import WatResponder from xkcd import XkcdResponder from bigbro import BigbroResponder from ascii import AsciiResponder from ninegag import NineGagResponder from link import LinkResponder from reminder import ReminderResponder from status import StatusResponder from help import HelpResponder from remote import RemoteResponder from monitor import MonitorResponder from process import ProcessResponder from so import SoResponder from jira_responder import JiraResponder from graphite import GraphiteResponder
# vim: set fileencoding=utf-8 : class Responder(object): def support(message): pass def generate(message): pass def on_start(self, consumer): return False def support(self, request): return request.content[0:len(self.name())] == self.name() class Response(object): def __init__(self, content): self.content = content self.tags = [] self.command = "" def __str__(self): return self.content class StreamResponse(Response): def __init__(self, content): self.is_completed = False self.content = content def stop(self): self.is_completed = True def handle(self, request, consumer): self.is_completed = True def __str__(self): return "<StreamResponse>" from rageface import RagefaceResponder from flowdock import FlowdockWhoisResponder from math import MathResponder from wat import WatResponder from xkcd import XkcdResponder from bigbro import BigbroResponder from ascii import AsciiResponder from ninegag import NineGagResponder from link import LinkResponder from reminder import ReminderResponder from status import StatusResponder from help import HelpResponder from remote import RemoteResponder from monitor import MonitorResponder from process import ProcessResponder from so import SoResponder from jira_responder import JiraResponder
Remove import for graphite responder
Remove import for graphite responder
Python
mit
rande/python-shirka,rande/python-shirka
# vim: set fileencoding=utf-8 : class Responder(object): def support(message): pass def generate(message): pass def on_start(self, consumer): return False def support(self, request): return request.content[0:len(self.name())] == self.name() class Response(object): def __init__(self, content): self.content = content self.tags = [] self.command = "" def __str__(self): return self.content class StreamResponse(Response): def __init__(self, content): self.is_completed = False self.content = content def stop(self): self.is_completed = True def handle(self, request, consumer): self.is_completed = True def __str__(self): return "<StreamResponse>" from rageface import RagefaceResponder from flowdock import FlowdockWhoisResponder from math import MathResponder from wat import WatResponder from xkcd import XkcdResponder from bigbro import BigbroResponder from ascii import AsciiResponder from ninegag import NineGagResponder from link import LinkResponder from reminder import ReminderResponder from status import StatusResponder from help import HelpResponder from remote import RemoteResponder from monitor import MonitorResponder from process import ProcessResponder from so import SoResponder from jira_responder import JiraResponder from graphite import GraphiteResponder Remove import for graphite responder
# vim: set fileencoding=utf-8 : class Responder(object): def support(message): pass def generate(message): pass def on_start(self, consumer): return False def support(self, request): return request.content[0:len(self.name())] == self.name() class Response(object): def __init__(self, content): self.content = content self.tags = [] self.command = "" def __str__(self): return self.content class StreamResponse(Response): def __init__(self, content): self.is_completed = False self.content = content def stop(self): self.is_completed = True def handle(self, request, consumer): self.is_completed = True def __str__(self): return "<StreamResponse>" from rageface import RagefaceResponder from flowdock import FlowdockWhoisResponder from math import MathResponder from wat import WatResponder from xkcd import XkcdResponder from bigbro import BigbroResponder from ascii import AsciiResponder from ninegag import NineGagResponder from link import LinkResponder from reminder import ReminderResponder from status import StatusResponder from help import HelpResponder from remote import RemoteResponder from monitor import MonitorResponder from process import ProcessResponder from so import SoResponder from jira_responder import JiraResponder
<commit_before># vim: set fileencoding=utf-8 : class Responder(object): def support(message): pass def generate(message): pass def on_start(self, consumer): return False def support(self, request): return request.content[0:len(self.name())] == self.name() class Response(object): def __init__(self, content): self.content = content self.tags = [] self.command = "" def __str__(self): return self.content class StreamResponse(Response): def __init__(self, content): self.is_completed = False self.content = content def stop(self): self.is_completed = True def handle(self, request, consumer): self.is_completed = True def __str__(self): return "<StreamResponse>" from rageface import RagefaceResponder from flowdock import FlowdockWhoisResponder from math import MathResponder from wat import WatResponder from xkcd import XkcdResponder from bigbro import BigbroResponder from ascii import AsciiResponder from ninegag import NineGagResponder from link import LinkResponder from reminder import ReminderResponder from status import StatusResponder from help import HelpResponder from remote import RemoteResponder from monitor import MonitorResponder from process import ProcessResponder from so import SoResponder from jira_responder import JiraResponder from graphite import GraphiteResponder <commit_msg>Remove import for graphite responder<commit_after>
# vim: set fileencoding=utf-8 : class Responder(object): def support(message): pass def generate(message): pass def on_start(self, consumer): return False def support(self, request): return request.content[0:len(self.name())] == self.name() class Response(object): def __init__(self, content): self.content = content self.tags = [] self.command = "" def __str__(self): return self.content class StreamResponse(Response): def __init__(self, content): self.is_completed = False self.content = content def stop(self): self.is_completed = True def handle(self, request, consumer): self.is_completed = True def __str__(self): return "<StreamResponse>" from rageface import RagefaceResponder from flowdock import FlowdockWhoisResponder from math import MathResponder from wat import WatResponder from xkcd import XkcdResponder from bigbro import BigbroResponder from ascii import AsciiResponder from ninegag import NineGagResponder from link import LinkResponder from reminder import ReminderResponder from status import StatusResponder from help import HelpResponder from remote import RemoteResponder from monitor import MonitorResponder from process import ProcessResponder from so import SoResponder from jira_responder import JiraResponder
# vim: set fileencoding=utf-8 : class Responder(object): def support(message): pass def generate(message): pass def on_start(self, consumer): return False def support(self, request): return request.content[0:len(self.name())] == self.name() class Response(object): def __init__(self, content): self.content = content self.tags = [] self.command = "" def __str__(self): return self.content class StreamResponse(Response): def __init__(self, content): self.is_completed = False self.content = content def stop(self): self.is_completed = True def handle(self, request, consumer): self.is_completed = True def __str__(self): return "<StreamResponse>" from rageface import RagefaceResponder from flowdock import FlowdockWhoisResponder from math import MathResponder from wat import WatResponder from xkcd import XkcdResponder from bigbro import BigbroResponder from ascii import AsciiResponder from ninegag import NineGagResponder from link import LinkResponder from reminder import ReminderResponder from status import StatusResponder from help import HelpResponder from remote import RemoteResponder from monitor import MonitorResponder from process import ProcessResponder from so import SoResponder from jira_responder import JiraResponder from graphite import GraphiteResponder Remove import for graphite responder# vim: set fileencoding=utf-8 : class Responder(object): def support(message): pass def generate(message): pass def on_start(self, consumer): return False def support(self, request): return request.content[0:len(self.name())] == self.name() class Response(object): def __init__(self, content): self.content = content self.tags = [] self.command = "" def __str__(self): return self.content class StreamResponse(Response): def __init__(self, content): self.is_completed = False self.content = content def stop(self): self.is_completed = True def handle(self, request, consumer): self.is_completed = True def __str__(self): return "<StreamResponse>" from rageface import RagefaceResponder from flowdock import FlowdockWhoisResponder from math import MathResponder from wat import WatResponder from xkcd import XkcdResponder from bigbro import BigbroResponder from ascii import AsciiResponder from ninegag import NineGagResponder from link import LinkResponder from reminder import ReminderResponder from status import StatusResponder from help import HelpResponder from remote import RemoteResponder from monitor import MonitorResponder from process import ProcessResponder from so import SoResponder from jira_responder import JiraResponder
<commit_before># vim: set fileencoding=utf-8 : class Responder(object): def support(message): pass def generate(message): pass def on_start(self, consumer): return False def support(self, request): return request.content[0:len(self.name())] == self.name() class Response(object): def __init__(self, content): self.content = content self.tags = [] self.command = "" def __str__(self): return self.content class StreamResponse(Response): def __init__(self, content): self.is_completed = False self.content = content def stop(self): self.is_completed = True def handle(self, request, consumer): self.is_completed = True def __str__(self): return "<StreamResponse>" from rageface import RagefaceResponder from flowdock import FlowdockWhoisResponder from math import MathResponder from wat import WatResponder from xkcd import XkcdResponder from bigbro import BigbroResponder from ascii import AsciiResponder from ninegag import NineGagResponder from link import LinkResponder from reminder import ReminderResponder from status import StatusResponder from help import HelpResponder from remote import RemoteResponder from monitor import MonitorResponder from process import ProcessResponder from so import SoResponder from jira_responder import JiraResponder from graphite import GraphiteResponder <commit_msg>Remove import for graphite responder<commit_after># vim: set fileencoding=utf-8 : class Responder(object): def support(message): pass def generate(message): pass def on_start(self, consumer): return False def support(self, request): return request.content[0:len(self.name())] == self.name() class Response(object): def __init__(self, content): self.content = content self.tags = [] self.command = "" def __str__(self): return self.content class StreamResponse(Response): def __init__(self, content): self.is_completed = False self.content = content def stop(self): self.is_completed = True def handle(self, request, consumer): self.is_completed = True def __str__(self): return "<StreamResponse>" from rageface import RagefaceResponder from flowdock import FlowdockWhoisResponder from math import MathResponder from wat import WatResponder from xkcd import XkcdResponder from bigbro import BigbroResponder from ascii import AsciiResponder from ninegag import NineGagResponder from link import LinkResponder from reminder import ReminderResponder from status import StatusResponder from help import HelpResponder from remote import RemoteResponder from monitor import MonitorResponder from process import ProcessResponder from so import SoResponder from jira_responder import JiraResponder
9b79f940806dbcd7a7326c955b2bc3bbd47892ea
test_results/plot_all.py
test_results/plot_all.py
import glob import csv import numpy as np import matplotlib.pyplot as plt for file in glob.glob("*.csv"): data = np.genfromtxt(file, delimiter = ',', names = True) plt.figure() num_plots = len(data.dtype.names) count = 1 for col_name in data.dtype.names: plt.subplot(num_plots, 1, count) plt.plot(data[col_name], label=col_name) plt.legend() count += 1 plt.show()
import glob import csv import numpy as np import matplotlib.pyplot as plt for file in glob.glob("*.csv"): data = np.genfromtxt(file, delimiter = ',', names = True) plt.figure() plt.suptitle(file) num_plots = len(data.dtype.names) count = 1 for col_name in data.dtype.names: plt.subplot(num_plots, 1, count) plt.plot(data[col_name], label=col_name) plt.legend() count += 1 mng = plt.get_current_fig_manager() if plt.get_backend() == 'TkAgg': mng.window.state('zoomed') elif plt.get_backend() == 'wxAgg': mng.frame.Maximize(True) elif plt.get_backend() == 'QT4Agg': mng.window.showMaximized() plt.show()
Add test name to plot as title, maximize plot window
Add test name to plot as title, maximize plot window
Python
agpl-3.0
BrewPi/firmware,BrewPi/firmware,glibersat/firmware,BrewPi/firmware,etk29321/firmware,BrewPi/firmware,BrewPi/firmware,BrewPi/firmware,glibersat/firmware,etk29321/firmware,etk29321/firmware,etk29321/firmware,glibersat/firmware,glibersat/firmware,BrewPi/firmware,glibersat/firmware,etk29321/firmware,glibersat/firmware,glibersat/firmware,BrewPi/firmware,etk29321/firmware
import glob import csv import numpy as np import matplotlib.pyplot as plt for file in glob.glob("*.csv"): data = np.genfromtxt(file, delimiter = ',', names = True) plt.figure() num_plots = len(data.dtype.names) count = 1 for col_name in data.dtype.names: plt.subplot(num_plots, 1, count) plt.plot(data[col_name], label=col_name) plt.legend() count += 1 plt.show() Add test name to plot as title, maximize plot window
import glob import csv import numpy as np import matplotlib.pyplot as plt for file in glob.glob("*.csv"): data = np.genfromtxt(file, delimiter = ',', names = True) plt.figure() plt.suptitle(file) num_plots = len(data.dtype.names) count = 1 for col_name in data.dtype.names: plt.subplot(num_plots, 1, count) plt.plot(data[col_name], label=col_name) plt.legend() count += 1 mng = plt.get_current_fig_manager() if plt.get_backend() == 'TkAgg': mng.window.state('zoomed') elif plt.get_backend() == 'wxAgg': mng.frame.Maximize(True) elif plt.get_backend() == 'QT4Agg': mng.window.showMaximized() plt.show()
<commit_before>import glob import csv import numpy as np import matplotlib.pyplot as plt for file in glob.glob("*.csv"): data = np.genfromtxt(file, delimiter = ',', names = True) plt.figure() num_plots = len(data.dtype.names) count = 1 for col_name in data.dtype.names: plt.subplot(num_plots, 1, count) plt.plot(data[col_name], label=col_name) plt.legend() count += 1 plt.show() <commit_msg>Add test name to plot as title, maximize plot window<commit_after>
import glob import csv import numpy as np import matplotlib.pyplot as plt for file in glob.glob("*.csv"): data = np.genfromtxt(file, delimiter = ',', names = True) plt.figure() plt.suptitle(file) num_plots = len(data.dtype.names) count = 1 for col_name in data.dtype.names: plt.subplot(num_plots, 1, count) plt.plot(data[col_name], label=col_name) plt.legend() count += 1 mng = plt.get_current_fig_manager() if plt.get_backend() == 'TkAgg': mng.window.state('zoomed') elif plt.get_backend() == 'wxAgg': mng.frame.Maximize(True) elif plt.get_backend() == 'QT4Agg': mng.window.showMaximized() plt.show()
import glob import csv import numpy as np import matplotlib.pyplot as plt for file in glob.glob("*.csv"): data = np.genfromtxt(file, delimiter = ',', names = True) plt.figure() num_plots = len(data.dtype.names) count = 1 for col_name in data.dtype.names: plt.subplot(num_plots, 1, count) plt.plot(data[col_name], label=col_name) plt.legend() count += 1 plt.show() Add test name to plot as title, maximize plot windowimport glob import csv import numpy as np import matplotlib.pyplot as plt for file in glob.glob("*.csv"): data = np.genfromtxt(file, delimiter = ',', names = True) plt.figure() plt.suptitle(file) num_plots = len(data.dtype.names) count = 1 for col_name in data.dtype.names: plt.subplot(num_plots, 1, count) plt.plot(data[col_name], label=col_name) plt.legend() count += 1 mng = plt.get_current_fig_manager() if plt.get_backend() == 'TkAgg': mng.window.state('zoomed') elif plt.get_backend() == 'wxAgg': mng.frame.Maximize(True) elif plt.get_backend() == 'QT4Agg': mng.window.showMaximized() plt.show()
<commit_before>import glob import csv import numpy as np import matplotlib.pyplot as plt for file in glob.glob("*.csv"): data = np.genfromtxt(file, delimiter = ',', names = True) plt.figure() num_plots = len(data.dtype.names) count = 1 for col_name in data.dtype.names: plt.subplot(num_plots, 1, count) plt.plot(data[col_name], label=col_name) plt.legend() count += 1 plt.show() <commit_msg>Add test name to plot as title, maximize plot window<commit_after>import glob import csv import numpy as np import matplotlib.pyplot as plt for file in glob.glob("*.csv"): data = np.genfromtxt(file, delimiter = ',', names = True) plt.figure() plt.suptitle(file) num_plots = len(data.dtype.names) count = 1 for col_name in data.dtype.names: plt.subplot(num_plots, 1, count) plt.plot(data[col_name], label=col_name) plt.legend() count += 1 mng = plt.get_current_fig_manager() if plt.get_backend() == 'TkAgg': mng.window.state('zoomed') elif plt.get_backend() == 'wxAgg': mng.frame.Maximize(True) elif plt.get_backend() == 'QT4Agg': mng.window.showMaximized() plt.show()
e5c436dfc39f38007c1cf8ee5e42a2e33e71740c
tests/test_base_utils.py
tests/test_base_utils.py
import attr import pytest from eli5.base_utils import attrs def test_attrs_with_default(): @attrs class WithDefault(object): def __init__(self, x, y=1): self.x = x self.y = y x_attr, y_attr = attr.fields(WithDefault) assert x_attr.name == 'x' assert y_attr.name == 'y' assert x_attr.default is attr.NOTHING assert y_attr.default == 1 assert WithDefault(1) == WithDefault(1) assert WithDefault(1, 1) != WithDefault(1, 2) def test_attrs_without_default(): @attrs class WithoutDefault(object): def __init__(self, x): self.x = x x_attr, = attr.fields(WithoutDefault) assert x_attr.name == 'x' assert x_attr.default is attr.NOTHING assert WithoutDefault(1) == WithoutDefault(1) assert WithoutDefault(1) != WithoutDefault(2) def test_attrs_with_repr(): @attrs class WithRepr(object): def __init__(self, x): self.x = x def __repr__(self): return 'foo' assert hash(WithRepr(1)) == hash(WithRepr(1)) assert repr(WithRepr(2)) == 'foo' def test_bad_init(): @attrs class BadInit(object): def __init__(self, x): self._x = x with pytest.raises(AttributeError): BadInit(1)
import attr import pytest from eli5.base_utils import attrs def test_attrs_with_default(): @attrs class WithDefault(object): def __init__(self, x, y=1): self.x = x self.y = y x_attr, y_attr = attr.fields(WithDefault) assert x_attr.name == 'x' assert y_attr.name == 'y' assert x_attr.default is attr.NOTHING assert y_attr.default == 1 assert WithDefault(1) == WithDefault(1) assert WithDefault(1, 1) != WithDefault(1, 2) def test_attrs_without_default(): @attrs class WithoutDefault(object): def __init__(self, x): self.x = x x_attr, = attr.fields(WithoutDefault) assert x_attr.name == 'x' assert x_attr.default is attr.NOTHING assert WithoutDefault(1) == WithoutDefault(1) assert WithoutDefault(1) != WithoutDefault(2) def test_attrs_with_repr(): @attrs class WithRepr(object): def __init__(self, x): self.x = x def __repr__(self): return 'foo' # assert hash(WithRepr(1)) == hash(WithRepr(1)) assert repr(WithRepr(2)) == 'foo' def test_bad_init(): @attrs class BadInit(object): def __init__(self, x): self._x = x with pytest.raises(AttributeError): BadInit(1)
Comment out failing check. See GH-199.
Comment out failing check. See GH-199.
Python
mit
TeamHG-Memex/eli5,TeamHG-Memex/eli5,TeamHG-Memex/eli5
import attr import pytest from eli5.base_utils import attrs def test_attrs_with_default(): @attrs class WithDefault(object): def __init__(self, x, y=1): self.x = x self.y = y x_attr, y_attr = attr.fields(WithDefault) assert x_attr.name == 'x' assert y_attr.name == 'y' assert x_attr.default is attr.NOTHING assert y_attr.default == 1 assert WithDefault(1) == WithDefault(1) assert WithDefault(1, 1) != WithDefault(1, 2) def test_attrs_without_default(): @attrs class WithoutDefault(object): def __init__(self, x): self.x = x x_attr, = attr.fields(WithoutDefault) assert x_attr.name == 'x' assert x_attr.default is attr.NOTHING assert WithoutDefault(1) == WithoutDefault(1) assert WithoutDefault(1) != WithoutDefault(2) def test_attrs_with_repr(): @attrs class WithRepr(object): def __init__(self, x): self.x = x def __repr__(self): return 'foo' assert hash(WithRepr(1)) == hash(WithRepr(1)) assert repr(WithRepr(2)) == 'foo' def test_bad_init(): @attrs class BadInit(object): def __init__(self, x): self._x = x with pytest.raises(AttributeError): BadInit(1) Comment out failing check. See GH-199.
import attr import pytest from eli5.base_utils import attrs def test_attrs_with_default(): @attrs class WithDefault(object): def __init__(self, x, y=1): self.x = x self.y = y x_attr, y_attr = attr.fields(WithDefault) assert x_attr.name == 'x' assert y_attr.name == 'y' assert x_attr.default is attr.NOTHING assert y_attr.default == 1 assert WithDefault(1) == WithDefault(1) assert WithDefault(1, 1) != WithDefault(1, 2) def test_attrs_without_default(): @attrs class WithoutDefault(object): def __init__(self, x): self.x = x x_attr, = attr.fields(WithoutDefault) assert x_attr.name == 'x' assert x_attr.default is attr.NOTHING assert WithoutDefault(1) == WithoutDefault(1) assert WithoutDefault(1) != WithoutDefault(2) def test_attrs_with_repr(): @attrs class WithRepr(object): def __init__(self, x): self.x = x def __repr__(self): return 'foo' # assert hash(WithRepr(1)) == hash(WithRepr(1)) assert repr(WithRepr(2)) == 'foo' def test_bad_init(): @attrs class BadInit(object): def __init__(self, x): self._x = x with pytest.raises(AttributeError): BadInit(1)
<commit_before>import attr import pytest from eli5.base_utils import attrs def test_attrs_with_default(): @attrs class WithDefault(object): def __init__(self, x, y=1): self.x = x self.y = y x_attr, y_attr = attr.fields(WithDefault) assert x_attr.name == 'x' assert y_attr.name == 'y' assert x_attr.default is attr.NOTHING assert y_attr.default == 1 assert WithDefault(1) == WithDefault(1) assert WithDefault(1, 1) != WithDefault(1, 2) def test_attrs_without_default(): @attrs class WithoutDefault(object): def __init__(self, x): self.x = x x_attr, = attr.fields(WithoutDefault) assert x_attr.name == 'x' assert x_attr.default is attr.NOTHING assert WithoutDefault(1) == WithoutDefault(1) assert WithoutDefault(1) != WithoutDefault(2) def test_attrs_with_repr(): @attrs class WithRepr(object): def __init__(self, x): self.x = x def __repr__(self): return 'foo' assert hash(WithRepr(1)) == hash(WithRepr(1)) assert repr(WithRepr(2)) == 'foo' def test_bad_init(): @attrs class BadInit(object): def __init__(self, x): self._x = x with pytest.raises(AttributeError): BadInit(1) <commit_msg>Comment out failing check. See GH-199.<commit_after>
import attr import pytest from eli5.base_utils import attrs def test_attrs_with_default(): @attrs class WithDefault(object): def __init__(self, x, y=1): self.x = x self.y = y x_attr, y_attr = attr.fields(WithDefault) assert x_attr.name == 'x' assert y_attr.name == 'y' assert x_attr.default is attr.NOTHING assert y_attr.default == 1 assert WithDefault(1) == WithDefault(1) assert WithDefault(1, 1) != WithDefault(1, 2) def test_attrs_without_default(): @attrs class WithoutDefault(object): def __init__(self, x): self.x = x x_attr, = attr.fields(WithoutDefault) assert x_attr.name == 'x' assert x_attr.default is attr.NOTHING assert WithoutDefault(1) == WithoutDefault(1) assert WithoutDefault(1) != WithoutDefault(2) def test_attrs_with_repr(): @attrs class WithRepr(object): def __init__(self, x): self.x = x def __repr__(self): return 'foo' # assert hash(WithRepr(1)) == hash(WithRepr(1)) assert repr(WithRepr(2)) == 'foo' def test_bad_init(): @attrs class BadInit(object): def __init__(self, x): self._x = x with pytest.raises(AttributeError): BadInit(1)
import attr import pytest from eli5.base_utils import attrs def test_attrs_with_default(): @attrs class WithDefault(object): def __init__(self, x, y=1): self.x = x self.y = y x_attr, y_attr = attr.fields(WithDefault) assert x_attr.name == 'x' assert y_attr.name == 'y' assert x_attr.default is attr.NOTHING assert y_attr.default == 1 assert WithDefault(1) == WithDefault(1) assert WithDefault(1, 1) != WithDefault(1, 2) def test_attrs_without_default(): @attrs class WithoutDefault(object): def __init__(self, x): self.x = x x_attr, = attr.fields(WithoutDefault) assert x_attr.name == 'x' assert x_attr.default is attr.NOTHING assert WithoutDefault(1) == WithoutDefault(1) assert WithoutDefault(1) != WithoutDefault(2) def test_attrs_with_repr(): @attrs class WithRepr(object): def __init__(self, x): self.x = x def __repr__(self): return 'foo' assert hash(WithRepr(1)) == hash(WithRepr(1)) assert repr(WithRepr(2)) == 'foo' def test_bad_init(): @attrs class BadInit(object): def __init__(self, x): self._x = x with pytest.raises(AttributeError): BadInit(1) Comment out failing check. See GH-199.import attr import pytest from eli5.base_utils import attrs def test_attrs_with_default(): @attrs class WithDefault(object): def __init__(self, x, y=1): self.x = x self.y = y x_attr, y_attr = attr.fields(WithDefault) assert x_attr.name == 'x' assert y_attr.name == 'y' assert x_attr.default is attr.NOTHING assert y_attr.default == 1 assert WithDefault(1) == WithDefault(1) assert WithDefault(1, 1) != WithDefault(1, 2) def test_attrs_without_default(): @attrs class WithoutDefault(object): def __init__(self, x): self.x = x x_attr, = attr.fields(WithoutDefault) assert x_attr.name == 'x' assert x_attr.default is attr.NOTHING assert WithoutDefault(1) == WithoutDefault(1) assert WithoutDefault(1) != WithoutDefault(2) def test_attrs_with_repr(): @attrs class WithRepr(object): def __init__(self, x): self.x = x def __repr__(self): return 'foo' # assert hash(WithRepr(1)) == hash(WithRepr(1)) assert repr(WithRepr(2)) == 'foo' def test_bad_init(): @attrs class BadInit(object): def __init__(self, x): self._x = x with pytest.raises(AttributeError): BadInit(1)
<commit_before>import attr import pytest from eli5.base_utils import attrs def test_attrs_with_default(): @attrs class WithDefault(object): def __init__(self, x, y=1): self.x = x self.y = y x_attr, y_attr = attr.fields(WithDefault) assert x_attr.name == 'x' assert y_attr.name == 'y' assert x_attr.default is attr.NOTHING assert y_attr.default == 1 assert WithDefault(1) == WithDefault(1) assert WithDefault(1, 1) != WithDefault(1, 2) def test_attrs_without_default(): @attrs class WithoutDefault(object): def __init__(self, x): self.x = x x_attr, = attr.fields(WithoutDefault) assert x_attr.name == 'x' assert x_attr.default is attr.NOTHING assert WithoutDefault(1) == WithoutDefault(1) assert WithoutDefault(1) != WithoutDefault(2) def test_attrs_with_repr(): @attrs class WithRepr(object): def __init__(self, x): self.x = x def __repr__(self): return 'foo' assert hash(WithRepr(1)) == hash(WithRepr(1)) assert repr(WithRepr(2)) == 'foo' def test_bad_init(): @attrs class BadInit(object): def __init__(self, x): self._x = x with pytest.raises(AttributeError): BadInit(1) <commit_msg>Comment out failing check. See GH-199.<commit_after>import attr import pytest from eli5.base_utils import attrs def test_attrs_with_default(): @attrs class WithDefault(object): def __init__(self, x, y=1): self.x = x self.y = y x_attr, y_attr = attr.fields(WithDefault) assert x_attr.name == 'x' assert y_attr.name == 'y' assert x_attr.default is attr.NOTHING assert y_attr.default == 1 assert WithDefault(1) == WithDefault(1) assert WithDefault(1, 1) != WithDefault(1, 2) def test_attrs_without_default(): @attrs class WithoutDefault(object): def __init__(self, x): self.x = x x_attr, = attr.fields(WithoutDefault) assert x_attr.name == 'x' assert x_attr.default is attr.NOTHING assert WithoutDefault(1) == WithoutDefault(1) assert WithoutDefault(1) != WithoutDefault(2) def test_attrs_with_repr(): @attrs class WithRepr(object): def __init__(self, x): self.x = x def __repr__(self): return 'foo' # assert hash(WithRepr(1)) == hash(WithRepr(1)) assert repr(WithRepr(2)) == 'foo' def test_bad_init(): @attrs class BadInit(object): def __init__(self, x): self._x = x with pytest.raises(AttributeError): BadInit(1)
601b35c2ad07d7927c9473c6cbf500d1fec3e307
tests/test_invariants.py
tests/test_invariants.py
from collections import deque from hypothesis import given from hypothesis.strategies import (frozensets, integers, lists, one_of, sets, tuples) from tests.hypothesis2 import examples from tests.hypothesis2.strategies import deques, optionals from tests.test_entities import (DataClassWithDeque, DataClassWithFrozenSet, DataClassWithList, DataClassWithOptional, DataClassWithSet, DataClassWithTuple) conss_to_strategies = [(DataClassWithList, lists, list), (DataClassWithSet, sets, set), (DataClassWithTuple, tuples, tuple), (DataClassWithFrozenSet, frozensets, frozenset), (DataClassWithDeque, deques, deque), (DataClassWithOptional, optionals, lambda x: x)] example_input = [1] @given(one_of(*[strategy_fn(integers()).map(cons) for cons, strategy_fn, _ in conss_to_strategies])) @examples(*[cons(f(example_input)) for cons, _, f in conss_to_strategies]) def test_generic_encode_and_decode_are_inverses(dc): assert dc.from_json(dc.to_json()) == dc
from collections import deque from hypothesis import given from hypothesis.strategies import (frozensets, integers, lists, one_of, sets, tuples) from tests.hypothesis2 import examples from tests.hypothesis2.strategies import deques, optionals from tests.test_entities import (DataClassWithDeque, DataClassWithFrozenSet, DataClassWithList, DataClassWithOptional, DataClassWithSet, DataClassWithTuple) dcconss_strategies_conss = [(DataClassWithList, lists, list), (DataClassWithSet, sets, set), (DataClassWithTuple, tuples, tuple), (DataClassWithFrozenSet, frozensets, frozenset), (DataClassWithDeque, deques, deque), (DataClassWithOptional, optionals, lambda x: x)] example_input = [1] @given(one_of(*[strategy_fn(integers()).map(dccons) for dccons, strategy_fn, _ in dcconss_strategies_conss])) @examples(*[dccons(cons(example_input)) for dccons, _, cons in dcconss_strategies_conss]) def test_generic_encode_and_decode_are_inverses(dc): assert dc.from_json(dc.to_json()) == dc
Rename encode/decode parameterization in test
Rename encode/decode parameterization in test
Python
mit
lidatong/dataclasses-json,lidatong/dataclasses-json
from collections import deque from hypothesis import given from hypothesis.strategies import (frozensets, integers, lists, one_of, sets, tuples) from tests.hypothesis2 import examples from tests.hypothesis2.strategies import deques, optionals from tests.test_entities import (DataClassWithDeque, DataClassWithFrozenSet, DataClassWithList, DataClassWithOptional, DataClassWithSet, DataClassWithTuple) conss_to_strategies = [(DataClassWithList, lists, list), (DataClassWithSet, sets, set), (DataClassWithTuple, tuples, tuple), (DataClassWithFrozenSet, frozensets, frozenset), (DataClassWithDeque, deques, deque), (DataClassWithOptional, optionals, lambda x: x)] example_input = [1] @given(one_of(*[strategy_fn(integers()).map(cons) for cons, strategy_fn, _ in conss_to_strategies])) @examples(*[cons(f(example_input)) for cons, _, f in conss_to_strategies]) def test_generic_encode_and_decode_are_inverses(dc): assert dc.from_json(dc.to_json()) == dc Rename encode/decode parameterization in test
from collections import deque from hypothesis import given from hypothesis.strategies import (frozensets, integers, lists, one_of, sets, tuples) from tests.hypothesis2 import examples from tests.hypothesis2.strategies import deques, optionals from tests.test_entities import (DataClassWithDeque, DataClassWithFrozenSet, DataClassWithList, DataClassWithOptional, DataClassWithSet, DataClassWithTuple) dcconss_strategies_conss = [(DataClassWithList, lists, list), (DataClassWithSet, sets, set), (DataClassWithTuple, tuples, tuple), (DataClassWithFrozenSet, frozensets, frozenset), (DataClassWithDeque, deques, deque), (DataClassWithOptional, optionals, lambda x: x)] example_input = [1] @given(one_of(*[strategy_fn(integers()).map(dccons) for dccons, strategy_fn, _ in dcconss_strategies_conss])) @examples(*[dccons(cons(example_input)) for dccons, _, cons in dcconss_strategies_conss]) def test_generic_encode_and_decode_are_inverses(dc): assert dc.from_json(dc.to_json()) == dc
<commit_before>from collections import deque from hypothesis import given from hypothesis.strategies import (frozensets, integers, lists, one_of, sets, tuples) from tests.hypothesis2 import examples from tests.hypothesis2.strategies import deques, optionals from tests.test_entities import (DataClassWithDeque, DataClassWithFrozenSet, DataClassWithList, DataClassWithOptional, DataClassWithSet, DataClassWithTuple) conss_to_strategies = [(DataClassWithList, lists, list), (DataClassWithSet, sets, set), (DataClassWithTuple, tuples, tuple), (DataClassWithFrozenSet, frozensets, frozenset), (DataClassWithDeque, deques, deque), (DataClassWithOptional, optionals, lambda x: x)] example_input = [1] @given(one_of(*[strategy_fn(integers()).map(cons) for cons, strategy_fn, _ in conss_to_strategies])) @examples(*[cons(f(example_input)) for cons, _, f in conss_to_strategies]) def test_generic_encode_and_decode_are_inverses(dc): assert dc.from_json(dc.to_json()) == dc <commit_msg>Rename encode/decode parameterization in test<commit_after>
from collections import deque from hypothesis import given from hypothesis.strategies import (frozensets, integers, lists, one_of, sets, tuples) from tests.hypothesis2 import examples from tests.hypothesis2.strategies import deques, optionals from tests.test_entities import (DataClassWithDeque, DataClassWithFrozenSet, DataClassWithList, DataClassWithOptional, DataClassWithSet, DataClassWithTuple) dcconss_strategies_conss = [(DataClassWithList, lists, list), (DataClassWithSet, sets, set), (DataClassWithTuple, tuples, tuple), (DataClassWithFrozenSet, frozensets, frozenset), (DataClassWithDeque, deques, deque), (DataClassWithOptional, optionals, lambda x: x)] example_input = [1] @given(one_of(*[strategy_fn(integers()).map(dccons) for dccons, strategy_fn, _ in dcconss_strategies_conss])) @examples(*[dccons(cons(example_input)) for dccons, _, cons in dcconss_strategies_conss]) def test_generic_encode_and_decode_are_inverses(dc): assert dc.from_json(dc.to_json()) == dc
from collections import deque from hypothesis import given from hypothesis.strategies import (frozensets, integers, lists, one_of, sets, tuples) from tests.hypothesis2 import examples from tests.hypothesis2.strategies import deques, optionals from tests.test_entities import (DataClassWithDeque, DataClassWithFrozenSet, DataClassWithList, DataClassWithOptional, DataClassWithSet, DataClassWithTuple) conss_to_strategies = [(DataClassWithList, lists, list), (DataClassWithSet, sets, set), (DataClassWithTuple, tuples, tuple), (DataClassWithFrozenSet, frozensets, frozenset), (DataClassWithDeque, deques, deque), (DataClassWithOptional, optionals, lambda x: x)] example_input = [1] @given(one_of(*[strategy_fn(integers()).map(cons) for cons, strategy_fn, _ in conss_to_strategies])) @examples(*[cons(f(example_input)) for cons, _, f in conss_to_strategies]) def test_generic_encode_and_decode_are_inverses(dc): assert dc.from_json(dc.to_json()) == dc Rename encode/decode parameterization in testfrom collections import deque from hypothesis import given from hypothesis.strategies import (frozensets, integers, lists, one_of, sets, tuples) from tests.hypothesis2 import examples from tests.hypothesis2.strategies import deques, optionals from tests.test_entities import (DataClassWithDeque, DataClassWithFrozenSet, DataClassWithList, DataClassWithOptional, DataClassWithSet, DataClassWithTuple) dcconss_strategies_conss = [(DataClassWithList, lists, list), (DataClassWithSet, sets, set), (DataClassWithTuple, tuples, tuple), (DataClassWithFrozenSet, frozensets, frozenset), (DataClassWithDeque, deques, deque), (DataClassWithOptional, optionals, lambda x: x)] example_input = [1] @given(one_of(*[strategy_fn(integers()).map(dccons) for dccons, strategy_fn, _ in dcconss_strategies_conss])) @examples(*[dccons(cons(example_input)) for dccons, _, cons in dcconss_strategies_conss]) def test_generic_encode_and_decode_are_inverses(dc): assert dc.from_json(dc.to_json()) == dc
<commit_before>from collections import deque from hypothesis import given from hypothesis.strategies import (frozensets, integers, lists, one_of, sets, tuples) from tests.hypothesis2 import examples from tests.hypothesis2.strategies import deques, optionals from tests.test_entities import (DataClassWithDeque, DataClassWithFrozenSet, DataClassWithList, DataClassWithOptional, DataClassWithSet, DataClassWithTuple) conss_to_strategies = [(DataClassWithList, lists, list), (DataClassWithSet, sets, set), (DataClassWithTuple, tuples, tuple), (DataClassWithFrozenSet, frozensets, frozenset), (DataClassWithDeque, deques, deque), (DataClassWithOptional, optionals, lambda x: x)] example_input = [1] @given(one_of(*[strategy_fn(integers()).map(cons) for cons, strategy_fn, _ in conss_to_strategies])) @examples(*[cons(f(example_input)) for cons, _, f in conss_to_strategies]) def test_generic_encode_and_decode_are_inverses(dc): assert dc.from_json(dc.to_json()) == dc <commit_msg>Rename encode/decode parameterization in test<commit_after>from collections import deque from hypothesis import given from hypothesis.strategies import (frozensets, integers, lists, one_of, sets, tuples) from tests.hypothesis2 import examples from tests.hypothesis2.strategies import deques, optionals from tests.test_entities import (DataClassWithDeque, DataClassWithFrozenSet, DataClassWithList, DataClassWithOptional, DataClassWithSet, DataClassWithTuple) dcconss_strategies_conss = [(DataClassWithList, lists, list), (DataClassWithSet, sets, set), (DataClassWithTuple, tuples, tuple), (DataClassWithFrozenSet, frozensets, frozenset), (DataClassWithDeque, deques, deque), (DataClassWithOptional, optionals, lambda x: x)] example_input = [1] @given(one_of(*[strategy_fn(integers()).map(dccons) for dccons, strategy_fn, _ in dcconss_strategies_conss])) @examples(*[dccons(cons(example_input)) for dccons, _, cons in dcconss_strategies_conss]) def test_generic_encode_and_decode_are_inverses(dc): assert dc.from_json(dc.to_json()) == dc
cd8407831091d169677d278d3ad9b5b92600b30a
generator/generator.py
generator/generator.py
""" Main class for doing the work. """ from helper import Helper from renderer import Renderer class Generator(object): @classmethod def generate_statements(cls, class_list_def): """ :type class_list_def: str """ class_def_list = Helper.parse_definition_string(class_list_def) member_def_statement = Renderer.gen_all_members(class_def_list) constructor_statement = Renderer.gen_constructor_statement(class_def_list) result = member_def_statement + constructor_statement cls.copy_to_clipboard(result) return result @classmethod def copy_to_clipboard(cls, result): """ If the dependent clipboard support is available, copy the result to the system clipboard. :param result: :return: """ try: from pyperclip.pyperclip import copy copy(result) except ImportError, Exception: pass
""" Main class for doing the work. """ from helper import Helper from renderer import Renderer class Generator(object): @classmethod def generate_statements(cls, class_list_def): """ :type class_list_def: str """ class_def_list = Helper.parse_definition_string(class_list_def) member_def_statement = Renderer.gen_all_members(class_def_list) constructor_statement = Renderer.gen_constructor_statement(class_def_list) result = member_def_statement + constructor_statement cls.copy_to_clipboard(result) return result @classmethod def copy_to_clipboard(cls, result): """ If the dependent clipboard support is available, copy the result to the system clipboard. :param result: :return: """ try: from pyperclip.pyperclip import copy copy(result) except Exception: pass
Fix exception handling syntax error
Fix exception handling syntax error
Python
apache-2.0
HappyRay/php-di-generator
""" Main class for doing the work. """ from helper import Helper from renderer import Renderer class Generator(object): @classmethod def generate_statements(cls, class_list_def): """ :type class_list_def: str """ class_def_list = Helper.parse_definition_string(class_list_def) member_def_statement = Renderer.gen_all_members(class_def_list) constructor_statement = Renderer.gen_constructor_statement(class_def_list) result = member_def_statement + constructor_statement cls.copy_to_clipboard(result) return result @classmethod def copy_to_clipboard(cls, result): """ If the dependent clipboard support is available, copy the result to the system clipboard. :param result: :return: """ try: from pyperclip.pyperclip import copy copy(result) except ImportError, Exception: pass Fix exception handling syntax error
""" Main class for doing the work. """ from helper import Helper from renderer import Renderer class Generator(object): @classmethod def generate_statements(cls, class_list_def): """ :type class_list_def: str """ class_def_list = Helper.parse_definition_string(class_list_def) member_def_statement = Renderer.gen_all_members(class_def_list) constructor_statement = Renderer.gen_constructor_statement(class_def_list) result = member_def_statement + constructor_statement cls.copy_to_clipboard(result) return result @classmethod def copy_to_clipboard(cls, result): """ If the dependent clipboard support is available, copy the result to the system clipboard. :param result: :return: """ try: from pyperclip.pyperclip import copy copy(result) except Exception: pass
<commit_before>""" Main class for doing the work. """ from helper import Helper from renderer import Renderer class Generator(object): @classmethod def generate_statements(cls, class_list_def): """ :type class_list_def: str """ class_def_list = Helper.parse_definition_string(class_list_def) member_def_statement = Renderer.gen_all_members(class_def_list) constructor_statement = Renderer.gen_constructor_statement(class_def_list) result = member_def_statement + constructor_statement cls.copy_to_clipboard(result) return result @classmethod def copy_to_clipboard(cls, result): """ If the dependent clipboard support is available, copy the result to the system clipboard. :param result: :return: """ try: from pyperclip.pyperclip import copy copy(result) except ImportError, Exception: pass <commit_msg>Fix exception handling syntax error<commit_after>
""" Main class for doing the work. """ from helper import Helper from renderer import Renderer class Generator(object): @classmethod def generate_statements(cls, class_list_def): """ :type class_list_def: str """ class_def_list = Helper.parse_definition_string(class_list_def) member_def_statement = Renderer.gen_all_members(class_def_list) constructor_statement = Renderer.gen_constructor_statement(class_def_list) result = member_def_statement + constructor_statement cls.copy_to_clipboard(result) return result @classmethod def copy_to_clipboard(cls, result): """ If the dependent clipboard support is available, copy the result to the system clipboard. :param result: :return: """ try: from pyperclip.pyperclip import copy copy(result) except Exception: pass
""" Main class for doing the work. """ from helper import Helper from renderer import Renderer class Generator(object): @classmethod def generate_statements(cls, class_list_def): """ :type class_list_def: str """ class_def_list = Helper.parse_definition_string(class_list_def) member_def_statement = Renderer.gen_all_members(class_def_list) constructor_statement = Renderer.gen_constructor_statement(class_def_list) result = member_def_statement + constructor_statement cls.copy_to_clipboard(result) return result @classmethod def copy_to_clipboard(cls, result): """ If the dependent clipboard support is available, copy the result to the system clipboard. :param result: :return: """ try: from pyperclip.pyperclip import copy copy(result) except ImportError, Exception: pass Fix exception handling syntax error""" Main class for doing the work. """ from helper import Helper from renderer import Renderer class Generator(object): @classmethod def generate_statements(cls, class_list_def): """ :type class_list_def: str """ class_def_list = Helper.parse_definition_string(class_list_def) member_def_statement = Renderer.gen_all_members(class_def_list) constructor_statement = Renderer.gen_constructor_statement(class_def_list) result = member_def_statement + constructor_statement cls.copy_to_clipboard(result) return result @classmethod def copy_to_clipboard(cls, result): """ If the dependent clipboard support is available, copy the result to the system clipboard. :param result: :return: """ try: from pyperclip.pyperclip import copy copy(result) except Exception: pass
<commit_before>""" Main class for doing the work. """ from helper import Helper from renderer import Renderer class Generator(object): @classmethod def generate_statements(cls, class_list_def): """ :type class_list_def: str """ class_def_list = Helper.parse_definition_string(class_list_def) member_def_statement = Renderer.gen_all_members(class_def_list) constructor_statement = Renderer.gen_constructor_statement(class_def_list) result = member_def_statement + constructor_statement cls.copy_to_clipboard(result) return result @classmethod def copy_to_clipboard(cls, result): """ If the dependent clipboard support is available, copy the result to the system clipboard. :param result: :return: """ try: from pyperclip.pyperclip import copy copy(result) except ImportError, Exception: pass <commit_msg>Fix exception handling syntax error<commit_after>""" Main class for doing the work. """ from helper import Helper from renderer import Renderer class Generator(object): @classmethod def generate_statements(cls, class_list_def): """ :type class_list_def: str """ class_def_list = Helper.parse_definition_string(class_list_def) member_def_statement = Renderer.gen_all_members(class_def_list) constructor_statement = Renderer.gen_constructor_statement(class_def_list) result = member_def_statement + constructor_statement cls.copy_to_clipboard(result) return result @classmethod def copy_to_clipboard(cls, result): """ If the dependent clipboard support is available, copy the result to the system clipboard. :param result: :return: """ try: from pyperclip.pyperclip import copy copy(result) except Exception: pass
cbb59747af48ae60473f27b6de976a08a741ab54
tests/test_test_utils.py
tests/test_test_utils.py
""" Tests for our testing utilities. """ from itertools import product from unittest import TestCase from zipline.utils.test_utils import parameter_space class TestParameterSpace(TestCase): x_args = [1, 2] y_args = [3, 4] @classmethod def setUpClass(cls): cls.xy_invocations = [] @classmethod def tearDownClass(cls): # This is the only actual test here. assert cls.xy_invocations == list(product(cls.x_args, cls.y_args)) @parameter_space(x=x_args, y=y_args) def test_xy(self, x, y): self.xy_invocations.append((x, y)) def test_nothing(self): # Ensure that there's at least one "real" test in the class, or else # our {setUp,tearDown}Class won't be called if, for example, # `parameter_space` returns None. pass
""" Tests for our testing utilities. """ from itertools import product from unittest import TestCase from zipline.utils.test_utils import parameter_space class TestParameterSpace(TestCase): x_args = [1, 2] y_args = [3, 4] @classmethod def setUpClass(cls): cls.xy_invocations = [] cls.yx_invocations = [] @classmethod def tearDownClass(cls): # This is the only actual test here. assert cls.xy_invocations == list(product(cls.x_args, cls.y_args)) assert cls.yx_invocations == list(product(cls.y_args, cls.x_args)) @parameter_space(x=x_args, y=y_args) def test_xy(self, x, y): self.xy_invocations.append((x, y)) @parameter_space(x=x_args, y=y_args) def test_yx(self, y, x): # Ensure that product is called with args in the order that they appear # in the function's parameter list. self.yx_invocations.append((y, x)) def test_nothing(self): # Ensure that there's at least one "real" test in the class, or else # our {setUp,tearDown}Class won't be called if, for example, # `parameter_space` returns None. pass
Add test for parameter_space ordering.
TEST: Add test for parameter_space ordering.
Python
apache-2.0
magne-max/zipline-ja,florentchandelier/zipline,Scapogo/zipline,florentchandelier/zipline,bartosh/zipline,wilsonkichoi/zipline,bartosh/zipline,alphaBenj/zipline,wilsonkichoi/zipline,humdings/zipline,humdings/zipline,umuzungu/zipline,alphaBenj/zipline,enigmampc/catalyst,enigmampc/catalyst,magne-max/zipline-ja,quantopian/zipline,Scapogo/zipline,umuzungu/zipline,quantopian/zipline
""" Tests for our testing utilities. """ from itertools import product from unittest import TestCase from zipline.utils.test_utils import parameter_space class TestParameterSpace(TestCase): x_args = [1, 2] y_args = [3, 4] @classmethod def setUpClass(cls): cls.xy_invocations = [] @classmethod def tearDownClass(cls): # This is the only actual test here. assert cls.xy_invocations == list(product(cls.x_args, cls.y_args)) @parameter_space(x=x_args, y=y_args) def test_xy(self, x, y): self.xy_invocations.append((x, y)) def test_nothing(self): # Ensure that there's at least one "real" test in the class, or else # our {setUp,tearDown}Class won't be called if, for example, # `parameter_space` returns None. pass TEST: Add test for parameter_space ordering.
""" Tests for our testing utilities. """ from itertools import product from unittest import TestCase from zipline.utils.test_utils import parameter_space class TestParameterSpace(TestCase): x_args = [1, 2] y_args = [3, 4] @classmethod def setUpClass(cls): cls.xy_invocations = [] cls.yx_invocations = [] @classmethod def tearDownClass(cls): # This is the only actual test here. assert cls.xy_invocations == list(product(cls.x_args, cls.y_args)) assert cls.yx_invocations == list(product(cls.y_args, cls.x_args)) @parameter_space(x=x_args, y=y_args) def test_xy(self, x, y): self.xy_invocations.append((x, y)) @parameter_space(x=x_args, y=y_args) def test_yx(self, y, x): # Ensure that product is called with args in the order that they appear # in the function's parameter list. self.yx_invocations.append((y, x)) def test_nothing(self): # Ensure that there's at least one "real" test in the class, or else # our {setUp,tearDown}Class won't be called if, for example, # `parameter_space` returns None. pass
<commit_before>""" Tests for our testing utilities. """ from itertools import product from unittest import TestCase from zipline.utils.test_utils import parameter_space class TestParameterSpace(TestCase): x_args = [1, 2] y_args = [3, 4] @classmethod def setUpClass(cls): cls.xy_invocations = [] @classmethod def tearDownClass(cls): # This is the only actual test here. assert cls.xy_invocations == list(product(cls.x_args, cls.y_args)) @parameter_space(x=x_args, y=y_args) def test_xy(self, x, y): self.xy_invocations.append((x, y)) def test_nothing(self): # Ensure that there's at least one "real" test in the class, or else # our {setUp,tearDown}Class won't be called if, for example, # `parameter_space` returns None. pass <commit_msg>TEST: Add test for parameter_space ordering.<commit_after>
""" Tests for our testing utilities. """ from itertools import product from unittest import TestCase from zipline.utils.test_utils import parameter_space class TestParameterSpace(TestCase): x_args = [1, 2] y_args = [3, 4] @classmethod def setUpClass(cls): cls.xy_invocations = [] cls.yx_invocations = [] @classmethod def tearDownClass(cls): # This is the only actual test here. assert cls.xy_invocations == list(product(cls.x_args, cls.y_args)) assert cls.yx_invocations == list(product(cls.y_args, cls.x_args)) @parameter_space(x=x_args, y=y_args) def test_xy(self, x, y): self.xy_invocations.append((x, y)) @parameter_space(x=x_args, y=y_args) def test_yx(self, y, x): # Ensure that product is called with args in the order that they appear # in the function's parameter list. self.yx_invocations.append((y, x)) def test_nothing(self): # Ensure that there's at least one "real" test in the class, or else # our {setUp,tearDown}Class won't be called if, for example, # `parameter_space` returns None. pass
""" Tests for our testing utilities. """ from itertools import product from unittest import TestCase from zipline.utils.test_utils import parameter_space class TestParameterSpace(TestCase): x_args = [1, 2] y_args = [3, 4] @classmethod def setUpClass(cls): cls.xy_invocations = [] @classmethod def tearDownClass(cls): # This is the only actual test here. assert cls.xy_invocations == list(product(cls.x_args, cls.y_args)) @parameter_space(x=x_args, y=y_args) def test_xy(self, x, y): self.xy_invocations.append((x, y)) def test_nothing(self): # Ensure that there's at least one "real" test in the class, or else # our {setUp,tearDown}Class won't be called if, for example, # `parameter_space` returns None. pass TEST: Add test for parameter_space ordering.""" Tests for our testing utilities. """ from itertools import product from unittest import TestCase from zipline.utils.test_utils import parameter_space class TestParameterSpace(TestCase): x_args = [1, 2] y_args = [3, 4] @classmethod def setUpClass(cls): cls.xy_invocations = [] cls.yx_invocations = [] @classmethod def tearDownClass(cls): # This is the only actual test here. assert cls.xy_invocations == list(product(cls.x_args, cls.y_args)) assert cls.yx_invocations == list(product(cls.y_args, cls.x_args)) @parameter_space(x=x_args, y=y_args) def test_xy(self, x, y): self.xy_invocations.append((x, y)) @parameter_space(x=x_args, y=y_args) def test_yx(self, y, x): # Ensure that product is called with args in the order that they appear # in the function's parameter list. self.yx_invocations.append((y, x)) def test_nothing(self): # Ensure that there's at least one "real" test in the class, or else # our {setUp,tearDown}Class won't be called if, for example, # `parameter_space` returns None. pass
<commit_before>""" Tests for our testing utilities. """ from itertools import product from unittest import TestCase from zipline.utils.test_utils import parameter_space class TestParameterSpace(TestCase): x_args = [1, 2] y_args = [3, 4] @classmethod def setUpClass(cls): cls.xy_invocations = [] @classmethod def tearDownClass(cls): # This is the only actual test here. assert cls.xy_invocations == list(product(cls.x_args, cls.y_args)) @parameter_space(x=x_args, y=y_args) def test_xy(self, x, y): self.xy_invocations.append((x, y)) def test_nothing(self): # Ensure that there's at least one "real" test in the class, or else # our {setUp,tearDown}Class won't be called if, for example, # `parameter_space` returns None. pass <commit_msg>TEST: Add test for parameter_space ordering.<commit_after>""" Tests for our testing utilities. """ from itertools import product from unittest import TestCase from zipline.utils.test_utils import parameter_space class TestParameterSpace(TestCase): x_args = [1, 2] y_args = [3, 4] @classmethod def setUpClass(cls): cls.xy_invocations = [] cls.yx_invocations = [] @classmethod def tearDownClass(cls): # This is the only actual test here. assert cls.xy_invocations == list(product(cls.x_args, cls.y_args)) assert cls.yx_invocations == list(product(cls.y_args, cls.x_args)) @parameter_space(x=x_args, y=y_args) def test_xy(self, x, y): self.xy_invocations.append((x, y)) @parameter_space(x=x_args, y=y_args) def test_yx(self, y, x): # Ensure that product is called with args in the order that they appear # in the function's parameter list. self.yx_invocations.append((y, x)) def test_nothing(self): # Ensure that there's at least one "real" test in the class, or else # our {setUp,tearDown}Class won't be called if, for example, # `parameter_space` returns None. pass
ce7d3e1da44d9f33474684db674f3a7660587320
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 formatted_title.startswith('A '): formatted_title = formatted_title.replace('A ', '', 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('-', '') formatted_title = formatted_title.replace(':', '') 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 formatted_title.startswith('A '): formatted_title = formatted_title.replace('A ', '', 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('-', '') formatted_title = formatted_title.replace(':', '') formatted_title = formatted_title.replace(',', '') formatted_title = formatted_title.replace('.', '') formatted_title = formatted_title.replace('&', 'and') 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)
Add character replacements for RT search
Add character replacements for RT search
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 formatted_title.startswith('A '): formatted_title = formatted_title.replace('A ', '', 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('-', '') formatted_title = formatted_title.replace(':', '') 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) Add character replacements for RT search
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 formatted_title.startswith('A '): formatted_title = formatted_title.replace('A ', '', 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('-', '') formatted_title = formatted_title.replace(':', '') formatted_title = formatted_title.replace(',', '') formatted_title = formatted_title.replace('.', '') formatted_title = formatted_title.replace('&', 'and') 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 formatted_title.startswith('A '): formatted_title = formatted_title.replace('A ', '', 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('-', '') formatted_title = formatted_title.replace(':', '') 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>Add character replacements for RT search<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 formatted_title.startswith('A '): formatted_title = formatted_title.replace('A ', '', 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('-', '') formatted_title = formatted_title.replace(':', '') formatted_title = formatted_title.replace(',', '') formatted_title = formatted_title.replace('.', '') formatted_title = formatted_title.replace('&', 'and') 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 formatted_title.startswith('A '): formatted_title = formatted_title.replace('A ', '', 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('-', '') formatted_title = formatted_title.replace(':', '') 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) Add character replacements for RT searchimport 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 formatted_title.startswith('A '): formatted_title = formatted_title.replace('A ', '', 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('-', '') formatted_title = formatted_title.replace(':', '') formatted_title = formatted_title.replace(',', '') formatted_title = formatted_title.replace('.', '') formatted_title = formatted_title.replace('&', 'and') 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 formatted_title.startswith('A '): formatted_title = formatted_title.replace('A ', '', 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('-', '') formatted_title = formatted_title.replace(':', '') 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>Add character replacements for RT search<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 formatted_title.startswith('A '): formatted_title = formatted_title.replace('A ', '', 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('-', '') formatted_title = formatted_title.replace(':', '') formatted_title = formatted_title.replace(',', '') formatted_title = formatted_title.replace('.', '') formatted_title = formatted_title.replace('&', 'and') 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)
494b628ab57c38335368a1b7a2734c7abafc5277
buildcert.py
buildcert.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime from subprocess import call from ca import app, db from ca.models import Request for request in Request.query.filter(Request.generation_date == None).all(): # noqa prompt = "Do you want to generate a certificate for {}, {} ?" print(prompt.format(request.id, request.email)) print("Type y to continue") confirm = input('>') if confirm in ['Y', 'y']: print('generating certificate') call([app.config['COMMAND_BUILD'], request.id, request.email]) call([app.config['COMMAND_MAIL'], request.id, request.email]) request.generation_date = datetime.date.today() db.session.commit() print() else: print('skipping generation \n')
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime from subprocess import call from ca import app, db from ca.models import Request from flask import Flask, render_template from flask_mail import Mail, Message def mail_certificate(id, email): msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email]) msg.body = render_template('mail.txt') with app.open_resource("/etc/openvpn/client/freifunk_{}.tgz".format(id)) as fp: msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read()) mail.send(msg) for request in Request.query.filter(Request.generation_date == None).all(): # noqa prompt = "Do you want to generate a certificate for {}, {} ?" print(prompt.format(request.id, request.email)) print("Type y to continue") confirm = input('>') if confirm in ['Y', 'y']: print('generating certificate') call([app.config['COMMAND_BUILD'], request.id, request.email]) #call([app.config['COMMAND_MAIL'], request.id, request.email]) mail_certificate(request.id, request.email) request.generation_date = datetime.date.today() db.session.commit() print() else: print('skipping generation \n')
Add mail_certificate which sends email with flask-mail
Add mail_certificate which sends email with flask-mail Replace COMMAND_MAIL. Send certs from /etc/openvpn/client/ Use template /templates/mail.txt
Python
mit
freifunk-berlin/ca.berlin.freifunk.net,freifunk-berlin/ca.berlin.freifunk.net,freifunk-berlin/ca.berlin.freifunk.net
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime from subprocess import call from ca import app, db from ca.models import Request for request in Request.query.filter(Request.generation_date == None).all(): # noqa prompt = "Do you want to generate a certificate for {}, {} ?" print(prompt.format(request.id, request.email)) print("Type y to continue") confirm = input('>') if confirm in ['Y', 'y']: print('generating certificate') call([app.config['COMMAND_BUILD'], request.id, request.email]) call([app.config['COMMAND_MAIL'], request.id, request.email]) request.generation_date = datetime.date.today() db.session.commit() print() else: print('skipping generation \n') Add mail_certificate which sends email with flask-mail Replace COMMAND_MAIL. Send certs from /etc/openvpn/client/ Use template /templates/mail.txt
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime from subprocess import call from ca import app, db from ca.models import Request from flask import Flask, render_template from flask_mail import Mail, Message def mail_certificate(id, email): msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email]) msg.body = render_template('mail.txt') with app.open_resource("/etc/openvpn/client/freifunk_{}.tgz".format(id)) as fp: msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read()) mail.send(msg) for request in Request.query.filter(Request.generation_date == None).all(): # noqa prompt = "Do you want to generate a certificate for {}, {} ?" print(prompt.format(request.id, request.email)) print("Type y to continue") confirm = input('>') if confirm in ['Y', 'y']: print('generating certificate') call([app.config['COMMAND_BUILD'], request.id, request.email]) #call([app.config['COMMAND_MAIL'], request.id, request.email]) mail_certificate(request.id, request.email) request.generation_date = datetime.date.today() db.session.commit() print() else: print('skipping generation \n')
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime from subprocess import call from ca import app, db from ca.models import Request for request in Request.query.filter(Request.generation_date == None).all(): # noqa prompt = "Do you want to generate a certificate for {}, {} ?" print(prompt.format(request.id, request.email)) print("Type y to continue") confirm = input('>') if confirm in ['Y', 'y']: print('generating certificate') call([app.config['COMMAND_BUILD'], request.id, request.email]) call([app.config['COMMAND_MAIL'], request.id, request.email]) request.generation_date = datetime.date.today() db.session.commit() print() else: print('skipping generation \n') <commit_msg>Add mail_certificate which sends email with flask-mail Replace COMMAND_MAIL. Send certs from /etc/openvpn/client/ Use template /templates/mail.txt<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime from subprocess import call from ca import app, db from ca.models import Request from flask import Flask, render_template from flask_mail import Mail, Message def mail_certificate(id, email): msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email]) msg.body = render_template('mail.txt') with app.open_resource("/etc/openvpn/client/freifunk_{}.tgz".format(id)) as fp: msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read()) mail.send(msg) for request in Request.query.filter(Request.generation_date == None).all(): # noqa prompt = "Do you want to generate a certificate for {}, {} ?" print(prompt.format(request.id, request.email)) print("Type y to continue") confirm = input('>') if confirm in ['Y', 'y']: print('generating certificate') call([app.config['COMMAND_BUILD'], request.id, request.email]) #call([app.config['COMMAND_MAIL'], request.id, request.email]) mail_certificate(request.id, request.email) request.generation_date = datetime.date.today() db.session.commit() print() else: print('skipping generation \n')
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime from subprocess import call from ca import app, db from ca.models import Request for request in Request.query.filter(Request.generation_date == None).all(): # noqa prompt = "Do you want to generate a certificate for {}, {} ?" print(prompt.format(request.id, request.email)) print("Type y to continue") confirm = input('>') if confirm in ['Y', 'y']: print('generating certificate') call([app.config['COMMAND_BUILD'], request.id, request.email]) call([app.config['COMMAND_MAIL'], request.id, request.email]) request.generation_date = datetime.date.today() db.session.commit() print() else: print('skipping generation \n') Add mail_certificate which sends email with flask-mail Replace COMMAND_MAIL. Send certs from /etc/openvpn/client/ Use template /templates/mail.txt#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime from subprocess import call from ca import app, db from ca.models import Request from flask import Flask, render_template from flask_mail import Mail, Message def mail_certificate(id, email): msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email]) msg.body = render_template('mail.txt') with app.open_resource("/etc/openvpn/client/freifunk_{}.tgz".format(id)) as fp: msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read()) mail.send(msg) for request in Request.query.filter(Request.generation_date == None).all(): # noqa prompt = "Do you want to generate a certificate for {}, {} ?" print(prompt.format(request.id, request.email)) print("Type y to continue") confirm = input('>') if confirm in ['Y', 'y']: print('generating certificate') call([app.config['COMMAND_BUILD'], request.id, request.email]) #call([app.config['COMMAND_MAIL'], request.id, request.email]) mail_certificate(request.id, request.email) request.generation_date = datetime.date.today() db.session.commit() print() else: print('skipping generation \n')
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime from subprocess import call from ca import app, db from ca.models import Request for request in Request.query.filter(Request.generation_date == None).all(): # noqa prompt = "Do you want to generate a certificate for {}, {} ?" print(prompt.format(request.id, request.email)) print("Type y to continue") confirm = input('>') if confirm in ['Y', 'y']: print('generating certificate') call([app.config['COMMAND_BUILD'], request.id, request.email]) call([app.config['COMMAND_MAIL'], request.id, request.email]) request.generation_date = datetime.date.today() db.session.commit() print() else: print('skipping generation \n') <commit_msg>Add mail_certificate which sends email with flask-mail Replace COMMAND_MAIL. Send certs from /etc/openvpn/client/ Use template /templates/mail.txt<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime from subprocess import call from ca import app, db from ca.models import Request from flask import Flask, render_template from flask_mail import Mail, Message def mail_certificate(id, email): msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email]) msg.body = render_template('mail.txt') with app.open_resource("/etc/openvpn/client/freifunk_{}.tgz".format(id)) as fp: msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read()) mail.send(msg) for request in Request.query.filter(Request.generation_date == None).all(): # noqa prompt = "Do you want to generate a certificate for {}, {} ?" print(prompt.format(request.id, request.email)) print("Type y to continue") confirm = input('>') if confirm in ['Y', 'y']: print('generating certificate') call([app.config['COMMAND_BUILD'], request.id, request.email]) #call([app.config['COMMAND_MAIL'], request.id, request.email]) mail_certificate(request.id, request.email) request.generation_date = datetime.date.today() db.session.commit() print() else: print('skipping generation \n')
b4f4226d153e993888f6e7429dcc9aca480e680e
owners_client.py
owners_client.py
# Copyright (c) 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class OwnersClient(object): """Interact with OWNERS files in a repository. This class allows you to interact with OWNERS files in a repository both the Gerrit Code-Owners plugin REST API, and the owners database implemented by Depot Tools in owners.py: - List all the owners for a change. - Check if a change has been approved. - Check if the OWNERS configuration in a change is valid. All code should use this class to interact with OWNERS files instead of the owners database in owners.py """ def __init__(self, host): self._host = host def ListOwnersForFile(self, project, branch, path): """List all owners for a file.""" raise Exception('Not implemented') def IsChangeApproved(self, change_number): """Check if the latest patch set for a change has been approved.""" raise Exception('Not implemented') def IsOwnerConfigurationValid(self, change_number, patch): """Check if the owners configuration in a change is valid.""" raise Exception('Not implemented')
# Copyright (c) 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import owners class OwnersClient(object): """Interact with OWNERS files in a repository. This class allows you to interact with OWNERS files in a repository both the Gerrit Code-Owners plugin REST API, and the owners database implemented by Depot Tools in owners.py: - List all the owners for a change. - Check if a change has been approved. - Check if the OWNERS configuration in a change is valid. All code should use this class to interact with OWNERS files instead of the owners database in owners.py """ def __init__(self, host): self._host = host def ListOwnersForFile(self, project, branch, path): """List all owners for a file.""" raise Exception('Not implemented') def IsChangeApproved(self, change_id): """Check if the latest patch set for a change has been approved.""" raise Exception('Not implemented') def IsOwnerConfigurationValid(self, change_id, patch): """Check if the owners configuration in a change is valid.""" raise Exception('Not implemented') class DepotToolsClient(OwnersClient): """Implement OwnersClient using owners.py Database.""" def __init__(self, host, root): super(DepotToolsClient, self).__init__(host) self._root = root self._db = owners.Database(root, open, os.path) def ListOwnersForFile(self, _project, _branch, path): return sorted(self._db.all_possible_owners([arg], None))
Implement ListOwnersForFile for Depot Tools
[owners] Implement ListOwnersForFile for Depot Tools Add DepotToolsClient to implement the OwnersClient API for Depot Tools, and implement the ListOwnersForFile method. Change-Id: I933a262898439d879c919d695aa62d7702b4c9a4 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/2530509 Auto-Submit: Edward Lesmes <d05609f027dc667cc37492b1dc1bdea5d60fa82a@chromium.org> Reviewed-by: Anthony Polito <05bb588aa9020353543fee7ac4e6e0a3d0d6f6ed@google.com> Commit-Queue: Edward Lesmes <d05609f027dc667cc37492b1dc1bdea5d60fa82a@chromium.org>
Python
bsd-3-clause
CoherentLabs/depot_tools,CoherentLabs/depot_tools
# Copyright (c) 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class OwnersClient(object): """Interact with OWNERS files in a repository. This class allows you to interact with OWNERS files in a repository both the Gerrit Code-Owners plugin REST API, and the owners database implemented by Depot Tools in owners.py: - List all the owners for a change. - Check if a change has been approved. - Check if the OWNERS configuration in a change is valid. All code should use this class to interact with OWNERS files instead of the owners database in owners.py """ def __init__(self, host): self._host = host def ListOwnersForFile(self, project, branch, path): """List all owners for a file.""" raise Exception('Not implemented') def IsChangeApproved(self, change_number): """Check if the latest patch set for a change has been approved.""" raise Exception('Not implemented') def IsOwnerConfigurationValid(self, change_number, patch): """Check if the owners configuration in a change is valid.""" raise Exception('Not implemented') [owners] Implement ListOwnersForFile for Depot Tools Add DepotToolsClient to implement the OwnersClient API for Depot Tools, and implement the ListOwnersForFile method. Change-Id: I933a262898439d879c919d695aa62d7702b4c9a4 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/2530509 Auto-Submit: Edward Lesmes <d05609f027dc667cc37492b1dc1bdea5d60fa82a@chromium.org> Reviewed-by: Anthony Polito <05bb588aa9020353543fee7ac4e6e0a3d0d6f6ed@google.com> Commit-Queue: Edward Lesmes <d05609f027dc667cc37492b1dc1bdea5d60fa82a@chromium.org>
# Copyright (c) 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import owners class OwnersClient(object): """Interact with OWNERS files in a repository. This class allows you to interact with OWNERS files in a repository both the Gerrit Code-Owners plugin REST API, and the owners database implemented by Depot Tools in owners.py: - List all the owners for a change. - Check if a change has been approved. - Check if the OWNERS configuration in a change is valid. All code should use this class to interact with OWNERS files instead of the owners database in owners.py """ def __init__(self, host): self._host = host def ListOwnersForFile(self, project, branch, path): """List all owners for a file.""" raise Exception('Not implemented') def IsChangeApproved(self, change_id): """Check if the latest patch set for a change has been approved.""" raise Exception('Not implemented') def IsOwnerConfigurationValid(self, change_id, patch): """Check if the owners configuration in a change is valid.""" raise Exception('Not implemented') class DepotToolsClient(OwnersClient): """Implement OwnersClient using owners.py Database.""" def __init__(self, host, root): super(DepotToolsClient, self).__init__(host) self._root = root self._db = owners.Database(root, open, os.path) def ListOwnersForFile(self, _project, _branch, path): return sorted(self._db.all_possible_owners([arg], None))
<commit_before># Copyright (c) 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class OwnersClient(object): """Interact with OWNERS files in a repository. This class allows you to interact with OWNERS files in a repository both the Gerrit Code-Owners plugin REST API, and the owners database implemented by Depot Tools in owners.py: - List all the owners for a change. - Check if a change has been approved. - Check if the OWNERS configuration in a change is valid. All code should use this class to interact with OWNERS files instead of the owners database in owners.py """ def __init__(self, host): self._host = host def ListOwnersForFile(self, project, branch, path): """List all owners for a file.""" raise Exception('Not implemented') def IsChangeApproved(self, change_number): """Check if the latest patch set for a change has been approved.""" raise Exception('Not implemented') def IsOwnerConfigurationValid(self, change_number, patch): """Check if the owners configuration in a change is valid.""" raise Exception('Not implemented') <commit_msg>[owners] Implement ListOwnersForFile for Depot Tools Add DepotToolsClient to implement the OwnersClient API for Depot Tools, and implement the ListOwnersForFile method. Change-Id: I933a262898439d879c919d695aa62d7702b4c9a4 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/2530509 Auto-Submit: Edward Lesmes <d05609f027dc667cc37492b1dc1bdea5d60fa82a@chromium.org> Reviewed-by: Anthony Polito <05bb588aa9020353543fee7ac4e6e0a3d0d6f6ed@google.com> Commit-Queue: Edward Lesmes <d05609f027dc667cc37492b1dc1bdea5d60fa82a@chromium.org><commit_after>
# Copyright (c) 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import owners class OwnersClient(object): """Interact with OWNERS files in a repository. This class allows you to interact with OWNERS files in a repository both the Gerrit Code-Owners plugin REST API, and the owners database implemented by Depot Tools in owners.py: - List all the owners for a change. - Check if a change has been approved. - Check if the OWNERS configuration in a change is valid. All code should use this class to interact with OWNERS files instead of the owners database in owners.py """ def __init__(self, host): self._host = host def ListOwnersForFile(self, project, branch, path): """List all owners for a file.""" raise Exception('Not implemented') def IsChangeApproved(self, change_id): """Check if the latest patch set for a change has been approved.""" raise Exception('Not implemented') def IsOwnerConfigurationValid(self, change_id, patch): """Check if the owners configuration in a change is valid.""" raise Exception('Not implemented') class DepotToolsClient(OwnersClient): """Implement OwnersClient using owners.py Database.""" def __init__(self, host, root): super(DepotToolsClient, self).__init__(host) self._root = root self._db = owners.Database(root, open, os.path) def ListOwnersForFile(self, _project, _branch, path): return sorted(self._db.all_possible_owners([arg], None))
# Copyright (c) 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class OwnersClient(object): """Interact with OWNERS files in a repository. This class allows you to interact with OWNERS files in a repository both the Gerrit Code-Owners plugin REST API, and the owners database implemented by Depot Tools in owners.py: - List all the owners for a change. - Check if a change has been approved. - Check if the OWNERS configuration in a change is valid. All code should use this class to interact with OWNERS files instead of the owners database in owners.py """ def __init__(self, host): self._host = host def ListOwnersForFile(self, project, branch, path): """List all owners for a file.""" raise Exception('Not implemented') def IsChangeApproved(self, change_number): """Check if the latest patch set for a change has been approved.""" raise Exception('Not implemented') def IsOwnerConfigurationValid(self, change_number, patch): """Check if the owners configuration in a change is valid.""" raise Exception('Not implemented') [owners] Implement ListOwnersForFile for Depot Tools Add DepotToolsClient to implement the OwnersClient API for Depot Tools, and implement the ListOwnersForFile method. Change-Id: I933a262898439d879c919d695aa62d7702b4c9a4 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/2530509 Auto-Submit: Edward Lesmes <d05609f027dc667cc37492b1dc1bdea5d60fa82a@chromium.org> Reviewed-by: Anthony Polito <05bb588aa9020353543fee7ac4e6e0a3d0d6f6ed@google.com> Commit-Queue: Edward Lesmes <d05609f027dc667cc37492b1dc1bdea5d60fa82a@chromium.org># Copyright (c) 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import owners class OwnersClient(object): """Interact with OWNERS files in a repository. This class allows you to interact with OWNERS files in a repository both the Gerrit Code-Owners plugin REST API, and the owners database implemented by Depot Tools in owners.py: - List all the owners for a change. - Check if a change has been approved. - Check if the OWNERS configuration in a change is valid. All code should use this class to interact with OWNERS files instead of the owners database in owners.py """ def __init__(self, host): self._host = host def ListOwnersForFile(self, project, branch, path): """List all owners for a file.""" raise Exception('Not implemented') def IsChangeApproved(self, change_id): """Check if the latest patch set for a change has been approved.""" raise Exception('Not implemented') def IsOwnerConfigurationValid(self, change_id, patch): """Check if the owners configuration in a change is valid.""" raise Exception('Not implemented') class DepotToolsClient(OwnersClient): """Implement OwnersClient using owners.py Database.""" def __init__(self, host, root): super(DepotToolsClient, self).__init__(host) self._root = root self._db = owners.Database(root, open, os.path) def ListOwnersForFile(self, _project, _branch, path): return sorted(self._db.all_possible_owners([arg], None))
<commit_before># Copyright (c) 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class OwnersClient(object): """Interact with OWNERS files in a repository. This class allows you to interact with OWNERS files in a repository both the Gerrit Code-Owners plugin REST API, and the owners database implemented by Depot Tools in owners.py: - List all the owners for a change. - Check if a change has been approved. - Check if the OWNERS configuration in a change is valid. All code should use this class to interact with OWNERS files instead of the owners database in owners.py """ def __init__(self, host): self._host = host def ListOwnersForFile(self, project, branch, path): """List all owners for a file.""" raise Exception('Not implemented') def IsChangeApproved(self, change_number): """Check if the latest patch set for a change has been approved.""" raise Exception('Not implemented') def IsOwnerConfigurationValid(self, change_number, patch): """Check if the owners configuration in a change is valid.""" raise Exception('Not implemented') <commit_msg>[owners] Implement ListOwnersForFile for Depot Tools Add DepotToolsClient to implement the OwnersClient API for Depot Tools, and implement the ListOwnersForFile method. Change-Id: I933a262898439d879c919d695aa62d7702b4c9a4 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/2530509 Auto-Submit: Edward Lesmes <d05609f027dc667cc37492b1dc1bdea5d60fa82a@chromium.org> Reviewed-by: Anthony Polito <05bb588aa9020353543fee7ac4e6e0a3d0d6f6ed@google.com> Commit-Queue: Edward Lesmes <d05609f027dc667cc37492b1dc1bdea5d60fa82a@chromium.org><commit_after># Copyright (c) 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import owners class OwnersClient(object): """Interact with OWNERS files in a repository. This class allows you to interact with OWNERS files in a repository both the Gerrit Code-Owners plugin REST API, and the owners database implemented by Depot Tools in owners.py: - List all the owners for a change. - Check if a change has been approved. - Check if the OWNERS configuration in a change is valid. All code should use this class to interact with OWNERS files instead of the owners database in owners.py """ def __init__(self, host): self._host = host def ListOwnersForFile(self, project, branch, path): """List all owners for a file.""" raise Exception('Not implemented') def IsChangeApproved(self, change_id): """Check if the latest patch set for a change has been approved.""" raise Exception('Not implemented') def IsOwnerConfigurationValid(self, change_id, patch): """Check if the owners configuration in a change is valid.""" raise Exception('Not implemented') class DepotToolsClient(OwnersClient): """Implement OwnersClient using owners.py Database.""" def __init__(self, host, root): super(DepotToolsClient, self).__init__(host) self._root = root self._db = owners.Database(root, open, os.path) def ListOwnersForFile(self, _project, _branch, path): return sorted(self._db.all_possible_owners([arg], None))
98988373899da3541f084e4c893628f028200d8c
PunchCard.py
PunchCard.py
import fileinput weekHours = 0.0 dayHours = 0.0 def calcWorkTime(timeIn, timeOut): inSplit = timeIn.split(':') outSplit = timeOut.split(':') hourIn = int(inSplit[0]) minuteIn = int(inSplit[1]) hourOut = int(outSplit[0]) minuteOut = int(outSplit[1]) if hourIn > hourOut: newHour = (hourOut + 24) - hourIn else: newHour = hourOut - hourIn newMinutes = minuteOut - minuteIn if newMinutes < 0: newHour -= 1 newMinutes += 60 global dayHours dayHours += float(newHour) + (float(newMinutes)/60) def calculateDay(dayEntry): day = dayEntry.pop(0)[0] index = 0 while(index < len(dayEntry)): calcWorkTime(dayEntry[index], dayEntry[index+1]) index += 2 print day + ': ' + str(dayHours) lines=[] for line in fileinput.input(): lines.append(line) print lines.pop(0) for line in lines: calculateDay(line.split(',')) weekHours += dayHours dayHours = 0 print '\nTotal hours for the week: ' + str(weekHours)
import fileinput weekHours = 0.0 dayHours = 0.0 def calcWorkTime(timeIn, timeOut): inSplit = timeIn.split(':') outSplit = timeOut.split(':') hourIn = float(inSplit[0]) minuteIn = float(inSplit[1]) hourOut = float(outSplit[0]) minuteOut = float(outSplit[1]) if hourIn > hourOut: newHour = (hourOut + 12) - hourIn else: newHour = hourOut - hourIn newMinutes = minuteOut - minuteIn if newMinutes < 0: newHour -= 1 newMinutes += 60 global dayHours dayHours += newHour + (newMinutes / 60) def calculateDay(dayEntry): day = dayEntry.pop(0)[0] index = 0 while(index < len(dayEntry)): calcWorkTime(dayEntry[index], dayEntry[index+1]) index += 2 print day + ': ' + str(dayHours) lines=[] for line in fileinput.input(): lines.append(line) print lines.pop(0) for line in lines: calculateDay(line.split(',')) weekHours += dayHours dayHours = 0.0 print '\nTotal hours for the week: ' + str(weekHours)
Fix type casts and incorrect numbers
Fix type casts and incorrect numbers Replaced int casts to float casts to eliminate need for recasting to float. Was resetting dayHours to 0 when it should have been 0.0 and if hourIn was bigger than hourOut it was adding 24 when it should have been adding 12.
Python
mit
NLSteveO/PunchCard,NLSteveO/PunchCard
import fileinput weekHours = 0.0 dayHours = 0.0 def calcWorkTime(timeIn, timeOut): inSplit = timeIn.split(':') outSplit = timeOut.split(':') hourIn = int(inSplit[0]) minuteIn = int(inSplit[1]) hourOut = int(outSplit[0]) minuteOut = int(outSplit[1]) if hourIn > hourOut: newHour = (hourOut + 24) - hourIn else: newHour = hourOut - hourIn newMinutes = minuteOut - minuteIn if newMinutes < 0: newHour -= 1 newMinutes += 60 global dayHours dayHours += float(newHour) + (float(newMinutes)/60) def calculateDay(dayEntry): day = dayEntry.pop(0)[0] index = 0 while(index < len(dayEntry)): calcWorkTime(dayEntry[index], dayEntry[index+1]) index += 2 print day + ': ' + str(dayHours) lines=[] for line in fileinput.input(): lines.append(line) print lines.pop(0) for line in lines: calculateDay(line.split(',')) weekHours += dayHours dayHours = 0 print '\nTotal hours for the week: ' + str(weekHours) Fix type casts and incorrect numbers Replaced int casts to float casts to eliminate need for recasting to float. Was resetting dayHours to 0 when it should have been 0.0 and if hourIn was bigger than hourOut it was adding 24 when it should have been adding 12.
import fileinput weekHours = 0.0 dayHours = 0.0 def calcWorkTime(timeIn, timeOut): inSplit = timeIn.split(':') outSplit = timeOut.split(':') hourIn = float(inSplit[0]) minuteIn = float(inSplit[1]) hourOut = float(outSplit[0]) minuteOut = float(outSplit[1]) if hourIn > hourOut: newHour = (hourOut + 12) - hourIn else: newHour = hourOut - hourIn newMinutes = minuteOut - minuteIn if newMinutes < 0: newHour -= 1 newMinutes += 60 global dayHours dayHours += newHour + (newMinutes / 60) def calculateDay(dayEntry): day = dayEntry.pop(0)[0] index = 0 while(index < len(dayEntry)): calcWorkTime(dayEntry[index], dayEntry[index+1]) index += 2 print day + ': ' + str(dayHours) lines=[] for line in fileinput.input(): lines.append(line) print lines.pop(0) for line in lines: calculateDay(line.split(',')) weekHours += dayHours dayHours = 0.0 print '\nTotal hours for the week: ' + str(weekHours)
<commit_before>import fileinput weekHours = 0.0 dayHours = 0.0 def calcWorkTime(timeIn, timeOut): inSplit = timeIn.split(':') outSplit = timeOut.split(':') hourIn = int(inSplit[0]) minuteIn = int(inSplit[1]) hourOut = int(outSplit[0]) minuteOut = int(outSplit[1]) if hourIn > hourOut: newHour = (hourOut + 24) - hourIn else: newHour = hourOut - hourIn newMinutes = minuteOut - minuteIn if newMinutes < 0: newHour -= 1 newMinutes += 60 global dayHours dayHours += float(newHour) + (float(newMinutes)/60) def calculateDay(dayEntry): day = dayEntry.pop(0)[0] index = 0 while(index < len(dayEntry)): calcWorkTime(dayEntry[index], dayEntry[index+1]) index += 2 print day + ': ' + str(dayHours) lines=[] for line in fileinput.input(): lines.append(line) print lines.pop(0) for line in lines: calculateDay(line.split(',')) weekHours += dayHours dayHours = 0 print '\nTotal hours for the week: ' + str(weekHours) <commit_msg>Fix type casts and incorrect numbers Replaced int casts to float casts to eliminate need for recasting to float. Was resetting dayHours to 0 when it should have been 0.0 and if hourIn was bigger than hourOut it was adding 24 when it should have been adding 12.<commit_after>
import fileinput weekHours = 0.0 dayHours = 0.0 def calcWorkTime(timeIn, timeOut): inSplit = timeIn.split(':') outSplit = timeOut.split(':') hourIn = float(inSplit[0]) minuteIn = float(inSplit[1]) hourOut = float(outSplit[0]) minuteOut = float(outSplit[1]) if hourIn > hourOut: newHour = (hourOut + 12) - hourIn else: newHour = hourOut - hourIn newMinutes = minuteOut - minuteIn if newMinutes < 0: newHour -= 1 newMinutes += 60 global dayHours dayHours += newHour + (newMinutes / 60) def calculateDay(dayEntry): day = dayEntry.pop(0)[0] index = 0 while(index < len(dayEntry)): calcWorkTime(dayEntry[index], dayEntry[index+1]) index += 2 print day + ': ' + str(dayHours) lines=[] for line in fileinput.input(): lines.append(line) print lines.pop(0) for line in lines: calculateDay(line.split(',')) weekHours += dayHours dayHours = 0.0 print '\nTotal hours for the week: ' + str(weekHours)
import fileinput weekHours = 0.0 dayHours = 0.0 def calcWorkTime(timeIn, timeOut): inSplit = timeIn.split(':') outSplit = timeOut.split(':') hourIn = int(inSplit[0]) minuteIn = int(inSplit[1]) hourOut = int(outSplit[0]) minuteOut = int(outSplit[1]) if hourIn > hourOut: newHour = (hourOut + 24) - hourIn else: newHour = hourOut - hourIn newMinutes = minuteOut - minuteIn if newMinutes < 0: newHour -= 1 newMinutes += 60 global dayHours dayHours += float(newHour) + (float(newMinutes)/60) def calculateDay(dayEntry): day = dayEntry.pop(0)[0] index = 0 while(index < len(dayEntry)): calcWorkTime(dayEntry[index], dayEntry[index+1]) index += 2 print day + ': ' + str(dayHours) lines=[] for line in fileinput.input(): lines.append(line) print lines.pop(0) for line in lines: calculateDay(line.split(',')) weekHours += dayHours dayHours = 0 print '\nTotal hours for the week: ' + str(weekHours) Fix type casts and incorrect numbers Replaced int casts to float casts to eliminate need for recasting to float. Was resetting dayHours to 0 when it should have been 0.0 and if hourIn was bigger than hourOut it was adding 24 when it should have been adding 12.import fileinput weekHours = 0.0 dayHours = 0.0 def calcWorkTime(timeIn, timeOut): inSplit = timeIn.split(':') outSplit = timeOut.split(':') hourIn = float(inSplit[0]) minuteIn = float(inSplit[1]) hourOut = float(outSplit[0]) minuteOut = float(outSplit[1]) if hourIn > hourOut: newHour = (hourOut + 12) - hourIn else: newHour = hourOut - hourIn newMinutes = minuteOut - minuteIn if newMinutes < 0: newHour -= 1 newMinutes += 60 global dayHours dayHours += newHour + (newMinutes / 60) def calculateDay(dayEntry): day = dayEntry.pop(0)[0] index = 0 while(index < len(dayEntry)): calcWorkTime(dayEntry[index], dayEntry[index+1]) index += 2 print day + ': ' + str(dayHours) lines=[] for line in fileinput.input(): lines.append(line) print lines.pop(0) for line in lines: calculateDay(line.split(',')) weekHours += dayHours dayHours = 0.0 print '\nTotal hours for the week: ' + str(weekHours)
<commit_before>import fileinput weekHours = 0.0 dayHours = 0.0 def calcWorkTime(timeIn, timeOut): inSplit = timeIn.split(':') outSplit = timeOut.split(':') hourIn = int(inSplit[0]) minuteIn = int(inSplit[1]) hourOut = int(outSplit[0]) minuteOut = int(outSplit[1]) if hourIn > hourOut: newHour = (hourOut + 24) - hourIn else: newHour = hourOut - hourIn newMinutes = minuteOut - minuteIn if newMinutes < 0: newHour -= 1 newMinutes += 60 global dayHours dayHours += float(newHour) + (float(newMinutes)/60) def calculateDay(dayEntry): day = dayEntry.pop(0)[0] index = 0 while(index < len(dayEntry)): calcWorkTime(dayEntry[index], dayEntry[index+1]) index += 2 print day + ': ' + str(dayHours) lines=[] for line in fileinput.input(): lines.append(line) print lines.pop(0) for line in lines: calculateDay(line.split(',')) weekHours += dayHours dayHours = 0 print '\nTotal hours for the week: ' + str(weekHours) <commit_msg>Fix type casts and incorrect numbers Replaced int casts to float casts to eliminate need for recasting to float. Was resetting dayHours to 0 when it should have been 0.0 and if hourIn was bigger than hourOut it was adding 24 when it should have been adding 12.<commit_after>import fileinput weekHours = 0.0 dayHours = 0.0 def calcWorkTime(timeIn, timeOut): inSplit = timeIn.split(':') outSplit = timeOut.split(':') hourIn = float(inSplit[0]) minuteIn = float(inSplit[1]) hourOut = float(outSplit[0]) minuteOut = float(outSplit[1]) if hourIn > hourOut: newHour = (hourOut + 12) - hourIn else: newHour = hourOut - hourIn newMinutes = minuteOut - minuteIn if newMinutes < 0: newHour -= 1 newMinutes += 60 global dayHours dayHours += newHour + (newMinutes / 60) def calculateDay(dayEntry): day = dayEntry.pop(0)[0] index = 0 while(index < len(dayEntry)): calcWorkTime(dayEntry[index], dayEntry[index+1]) index += 2 print day + ': ' + str(dayHours) lines=[] for line in fileinput.input(): lines.append(line) print lines.pop(0) for line in lines: calculateDay(line.split(',')) weekHours += dayHours dayHours = 0.0 print '\nTotal hours for the week: ' + str(weekHours)
70245be1a4fbb22d20459383136887f0a9cc2ad4
passwd_change.py
passwd_change.py
#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 4: keys_file = _args[1] target_file = _args[2] result_file = _args[3] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or line.split(':')[3] != '12': r.write(line) except Exception as e: print(str(e)) sys.exit() else: print('./passwd_change.py keys_file.txt passwd_file result_file')
#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 4: keys_file = _args[1] target_file = _args[2] result_file = _args[3] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() log = open('deletel.log', 'w') with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or line.split(':')[3] != '12': r.write(line) else: log.write(line) log.close() except Exception as e: print(str(e)) sys.exit() else: print('./passwd_change.py keys_file.txt passwd_file result_file')
Add log file for deleted lines.
Add log file for deleted lines.
Python
mit
maxsocl/oldmailer
#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 4: keys_file = _args[1] target_file = _args[2] result_file = _args[3] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or line.split(':')[3] != '12': r.write(line) except Exception as e: print(str(e)) sys.exit() else: print('./passwd_change.py keys_file.txt passwd_file result_file') Add log file for deleted lines.
#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 4: keys_file = _args[1] target_file = _args[2] result_file = _args[3] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() log = open('deletel.log', 'w') with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or line.split(':')[3] != '12': r.write(line) else: log.write(line) log.close() except Exception as e: print(str(e)) sys.exit() else: print('./passwd_change.py keys_file.txt passwd_file result_file')
<commit_before>#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 4: keys_file = _args[1] target_file = _args[2] result_file = _args[3] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or line.split(':')[3] != '12': r.write(line) except Exception as e: print(str(e)) sys.exit() else: print('./passwd_change.py keys_file.txt passwd_file result_file') <commit_msg>Add log file for deleted lines.<commit_after>
#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 4: keys_file = _args[1] target_file = _args[2] result_file = _args[3] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() log = open('deletel.log', 'w') with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or line.split(':')[3] != '12': r.write(line) else: log.write(line) log.close() except Exception as e: print(str(e)) sys.exit() else: print('./passwd_change.py keys_file.txt passwd_file result_file')
#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 4: keys_file = _args[1] target_file = _args[2] result_file = _args[3] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or line.split(':')[3] != '12': r.write(line) except Exception as e: print(str(e)) sys.exit() else: print('./passwd_change.py keys_file.txt passwd_file result_file') Add log file for deleted lines.#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 4: keys_file = _args[1] target_file = _args[2] result_file = _args[3] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() log = open('deletel.log', 'w') with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or line.split(':')[3] != '12': r.write(line) else: log.write(line) log.close() except Exception as e: print(str(e)) sys.exit() else: print('./passwd_change.py keys_file.txt passwd_file result_file')
<commit_before>#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 4: keys_file = _args[1] target_file = _args[2] result_file = _args[3] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or line.split(':')[3] != '12': r.write(line) except Exception as e: print(str(e)) sys.exit() else: print('./passwd_change.py keys_file.txt passwd_file result_file') <commit_msg>Add log file for deleted lines.<commit_after>#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 4: keys_file = _args[1] target_file = _args[2] result_file = _args[3] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() log = open('deletel.log', 'w') with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or line.split(':')[3] != '12': r.write(line) else: log.write(line) log.close() except Exception as e: print(str(e)) sys.exit() else: print('./passwd_change.py keys_file.txt passwd_file result_file')
68a40f909294c5e2ad6c6bce9f6b7a970d133d21
conanfile.py
conanfile.py
from conans import ConanFile from conans.tools import download, unzip import os VERSION = "0.0.2" class IWYUCTargetCmakeConan(ConanFile): name = "iwyu-target-cmake" version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION) generators = "cmake" requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard", "tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util", "tooling-cmake-util/master@smspillaz/tooling-cmake-util", "cmake-unit/master@smspillaz/cmake-unit") url = "http://github.com/polysquare/iwyu-target-cmake" license = "MIT" def source(self): zip_name = "iwyu-target-cmake.zip" download("https://github.com/polysquare/" "iwyu-target-cmake/archive/{version}.zip" "".format(version="v" + VERSION), zip_name) unzip(zip_name) os.unlink(zip_name) def package(self): self.copy(pattern="*.cmake", dst="cmake/iwyu-target-cmake", src="iwyu-target-cmake-" + VERSION, keep_path=True)
from conans import ConanFile from conans.tools import download, unzip import os VERSION = "0.0.2" class IWYUCTargetCmakeConan(ConanFile): name = "iwyu-target-cmake" version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION) generators = "cmake" requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard", "tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util", "tooling-cmake-util/master@smspillaz/tooling-cmake-util", "cmake-unit/master@smspillaz/cmake-unit") url = "http://github.com/polysquare/iwyu-target-cmake" license = "MIT" def source(self): zip_name = "iwyu-target-cmake.zip" download("https://github.com/polysquare/" "iwyu-target-cmake/archive/{version}.zip" "".format(version="v" + VERSION), zip_name) unzip(zip_name) os.unlink(zip_name) def package(self): self.copy(pattern="Find*.cmake", dst="", src="iwyu-target-cmake-" + VERSION, keep_path=True) self.copy(pattern="*.cmake", dst="cmake/iwyu-target-cmake", src="iwyu-target-cmake-" + VERSION, keep_path=True)
Copy find modules to root of module path
conan: Copy find modules to root of module path
Python
mit
polysquare/iwyu-target-cmake,polysquare/include-what-you-use-target-cmake
from conans import ConanFile from conans.tools import download, unzip import os VERSION = "0.0.2" class IWYUCTargetCmakeConan(ConanFile): name = "iwyu-target-cmake" version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION) generators = "cmake" requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard", "tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util", "tooling-cmake-util/master@smspillaz/tooling-cmake-util", "cmake-unit/master@smspillaz/cmake-unit") url = "http://github.com/polysquare/iwyu-target-cmake" license = "MIT" def source(self): zip_name = "iwyu-target-cmake.zip" download("https://github.com/polysquare/" "iwyu-target-cmake/archive/{version}.zip" "".format(version="v" + VERSION), zip_name) unzip(zip_name) os.unlink(zip_name) def package(self): self.copy(pattern="*.cmake", dst="cmake/iwyu-target-cmake", src="iwyu-target-cmake-" + VERSION, keep_path=True) conan: Copy find modules to root of module path
from conans import ConanFile from conans.tools import download, unzip import os VERSION = "0.0.2" class IWYUCTargetCmakeConan(ConanFile): name = "iwyu-target-cmake" version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION) generators = "cmake" requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard", "tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util", "tooling-cmake-util/master@smspillaz/tooling-cmake-util", "cmake-unit/master@smspillaz/cmake-unit") url = "http://github.com/polysquare/iwyu-target-cmake" license = "MIT" def source(self): zip_name = "iwyu-target-cmake.zip" download("https://github.com/polysquare/" "iwyu-target-cmake/archive/{version}.zip" "".format(version="v" + VERSION), zip_name) unzip(zip_name) os.unlink(zip_name) def package(self): self.copy(pattern="Find*.cmake", dst="", src="iwyu-target-cmake-" + VERSION, keep_path=True) self.copy(pattern="*.cmake", dst="cmake/iwyu-target-cmake", src="iwyu-target-cmake-" + VERSION, keep_path=True)
<commit_before>from conans import ConanFile from conans.tools import download, unzip import os VERSION = "0.0.2" class IWYUCTargetCmakeConan(ConanFile): name = "iwyu-target-cmake" version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION) generators = "cmake" requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard", "tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util", "tooling-cmake-util/master@smspillaz/tooling-cmake-util", "cmake-unit/master@smspillaz/cmake-unit") url = "http://github.com/polysquare/iwyu-target-cmake" license = "MIT" def source(self): zip_name = "iwyu-target-cmake.zip" download("https://github.com/polysquare/" "iwyu-target-cmake/archive/{version}.zip" "".format(version="v" + VERSION), zip_name) unzip(zip_name) os.unlink(zip_name) def package(self): self.copy(pattern="*.cmake", dst="cmake/iwyu-target-cmake", src="iwyu-target-cmake-" + VERSION, keep_path=True) <commit_msg>conan: Copy find modules to root of module path<commit_after>
from conans import ConanFile from conans.tools import download, unzip import os VERSION = "0.0.2" class IWYUCTargetCmakeConan(ConanFile): name = "iwyu-target-cmake" version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION) generators = "cmake" requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard", "tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util", "tooling-cmake-util/master@smspillaz/tooling-cmake-util", "cmake-unit/master@smspillaz/cmake-unit") url = "http://github.com/polysquare/iwyu-target-cmake" license = "MIT" def source(self): zip_name = "iwyu-target-cmake.zip" download("https://github.com/polysquare/" "iwyu-target-cmake/archive/{version}.zip" "".format(version="v" + VERSION), zip_name) unzip(zip_name) os.unlink(zip_name) def package(self): self.copy(pattern="Find*.cmake", dst="", src="iwyu-target-cmake-" + VERSION, keep_path=True) self.copy(pattern="*.cmake", dst="cmake/iwyu-target-cmake", src="iwyu-target-cmake-" + VERSION, keep_path=True)
from conans import ConanFile from conans.tools import download, unzip import os VERSION = "0.0.2" class IWYUCTargetCmakeConan(ConanFile): name = "iwyu-target-cmake" version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION) generators = "cmake" requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard", "tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util", "tooling-cmake-util/master@smspillaz/tooling-cmake-util", "cmake-unit/master@smspillaz/cmake-unit") url = "http://github.com/polysquare/iwyu-target-cmake" license = "MIT" def source(self): zip_name = "iwyu-target-cmake.zip" download("https://github.com/polysquare/" "iwyu-target-cmake/archive/{version}.zip" "".format(version="v" + VERSION), zip_name) unzip(zip_name) os.unlink(zip_name) def package(self): self.copy(pattern="*.cmake", dst="cmake/iwyu-target-cmake", src="iwyu-target-cmake-" + VERSION, keep_path=True) conan: Copy find modules to root of module pathfrom conans import ConanFile from conans.tools import download, unzip import os VERSION = "0.0.2" class IWYUCTargetCmakeConan(ConanFile): name = "iwyu-target-cmake" version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION) generators = "cmake" requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard", "tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util", "tooling-cmake-util/master@smspillaz/tooling-cmake-util", "cmake-unit/master@smspillaz/cmake-unit") url = "http://github.com/polysquare/iwyu-target-cmake" license = "MIT" def source(self): zip_name = "iwyu-target-cmake.zip" download("https://github.com/polysquare/" "iwyu-target-cmake/archive/{version}.zip" "".format(version="v" + VERSION), zip_name) unzip(zip_name) os.unlink(zip_name) def package(self): self.copy(pattern="Find*.cmake", dst="", src="iwyu-target-cmake-" + VERSION, keep_path=True) self.copy(pattern="*.cmake", dst="cmake/iwyu-target-cmake", src="iwyu-target-cmake-" + VERSION, keep_path=True)
<commit_before>from conans import ConanFile from conans.tools import download, unzip import os VERSION = "0.0.2" class IWYUCTargetCmakeConan(ConanFile): name = "iwyu-target-cmake" version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION) generators = "cmake" requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard", "tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util", "tooling-cmake-util/master@smspillaz/tooling-cmake-util", "cmake-unit/master@smspillaz/cmake-unit") url = "http://github.com/polysquare/iwyu-target-cmake" license = "MIT" def source(self): zip_name = "iwyu-target-cmake.zip" download("https://github.com/polysquare/" "iwyu-target-cmake/archive/{version}.zip" "".format(version="v" + VERSION), zip_name) unzip(zip_name) os.unlink(zip_name) def package(self): self.copy(pattern="*.cmake", dst="cmake/iwyu-target-cmake", src="iwyu-target-cmake-" + VERSION, keep_path=True) <commit_msg>conan: Copy find modules to root of module path<commit_after>from conans import ConanFile from conans.tools import download, unzip import os VERSION = "0.0.2" class IWYUCTargetCmakeConan(ConanFile): name = "iwyu-target-cmake" version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION) generators = "cmake" requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard", "tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util", "tooling-cmake-util/master@smspillaz/tooling-cmake-util", "cmake-unit/master@smspillaz/cmake-unit") url = "http://github.com/polysquare/iwyu-target-cmake" license = "MIT" def source(self): zip_name = "iwyu-target-cmake.zip" download("https://github.com/polysquare/" "iwyu-target-cmake/archive/{version}.zip" "".format(version="v" + VERSION), zip_name) unzip(zip_name) os.unlink(zip_name) def package(self): self.copy(pattern="Find*.cmake", dst="", src="iwyu-target-cmake-" + VERSION, keep_path=True) self.copy(pattern="*.cmake", dst="cmake/iwyu-target-cmake", src="iwyu-target-cmake-" + VERSION, keep_path=True)
52aeb0d37aa903c0189416bbafc2a75ea41f3201
slave/skia_slave_scripts/do_skps_capture.py
slave/skia_slave_scripts/do_skps_capture.py
#!/usr/bin/env python # Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Run the webpages_playback automation script.""" import os import sys from build_step import BuildStep from utils import shell_utils class SKPsCapture(BuildStep): """BuildStep that captures the buildbot SKPs.""" def __init__(self, timeout=10800, **kwargs): super(SKPsCapture, self).__init__(timeout=timeout, **kwargs) def _Run(self): webpages_playback_cmd = [ 'python', os.path.join(os.path.dirname(os.path.realpath(__file__)), 'webpages_playback.py'), '--page_sets', self._args['page_sets'], '--skia_tools', self._args['skia_tools'], '--browser_executable', self._args['browser_executable'], '--non-interactive' ] if not self._is_try: webpages_playback_cmd.append('--upload_to_gs') shell_utils.Bash(webpages_playback_cmd) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(SKPsCapture))
#!/usr/bin/env python # Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Run the webpages_playback automation script.""" import os import sys from build_step import BuildStep from utils import shell_utils class SKPsCapture(BuildStep): """BuildStep that captures the buildbot SKPs.""" def __init__(self, timeout=10800, **kwargs): super(SKPsCapture, self).__init__(timeout=timeout, **kwargs) def _Run(self): webpages_playback_cmd = [ 'python', os.path.join(os.path.dirname(os.path.realpath(__file__)), 'webpages_playback.py'), '--page_sets', self._args['page_sets'], '--skia_tools', self._args['skia_tools'], '--browser_executable', self._args['browser_executable'], '--non-interactive' ] if not self._is_try: webpages_playback_cmd.append('--upload_to_gs') shell_utils.Bash(webpages_playback_cmd) # Clean up any leftover browser instances. This can happen if there are # telemetry crashes, processes are not always cleaned up appropriately by # the webpagereplay and telemetry frameworks. cleanup_cmd = [ 'pkill', '-9', '-f', self._args['browser_executable'] ] shell_utils.Bash(cleanup_cmd) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(SKPsCapture))
Clean up any left over browser processes in the RecreateSKPs buildstep.
Clean up any left over browser processes in the RecreateSKPs buildstep. BUG=skia:2055 R=borenet@google.com Review URL: https://codereview.chromium.org/140003003
Python
bsd-3-clause
google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot
#!/usr/bin/env python # Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Run the webpages_playback automation script.""" import os import sys from build_step import BuildStep from utils import shell_utils class SKPsCapture(BuildStep): """BuildStep that captures the buildbot SKPs.""" def __init__(self, timeout=10800, **kwargs): super(SKPsCapture, self).__init__(timeout=timeout, **kwargs) def _Run(self): webpages_playback_cmd = [ 'python', os.path.join(os.path.dirname(os.path.realpath(__file__)), 'webpages_playback.py'), '--page_sets', self._args['page_sets'], '--skia_tools', self._args['skia_tools'], '--browser_executable', self._args['browser_executable'], '--non-interactive' ] if not self._is_try: webpages_playback_cmd.append('--upload_to_gs') shell_utils.Bash(webpages_playback_cmd) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(SKPsCapture)) Clean up any left over browser processes in the RecreateSKPs buildstep. BUG=skia:2055 R=borenet@google.com Review URL: https://codereview.chromium.org/140003003
#!/usr/bin/env python # Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Run the webpages_playback automation script.""" import os import sys from build_step import BuildStep from utils import shell_utils class SKPsCapture(BuildStep): """BuildStep that captures the buildbot SKPs.""" def __init__(self, timeout=10800, **kwargs): super(SKPsCapture, self).__init__(timeout=timeout, **kwargs) def _Run(self): webpages_playback_cmd = [ 'python', os.path.join(os.path.dirname(os.path.realpath(__file__)), 'webpages_playback.py'), '--page_sets', self._args['page_sets'], '--skia_tools', self._args['skia_tools'], '--browser_executable', self._args['browser_executable'], '--non-interactive' ] if not self._is_try: webpages_playback_cmd.append('--upload_to_gs') shell_utils.Bash(webpages_playback_cmd) # Clean up any leftover browser instances. This can happen if there are # telemetry crashes, processes are not always cleaned up appropriately by # the webpagereplay and telemetry frameworks. cleanup_cmd = [ 'pkill', '-9', '-f', self._args['browser_executable'] ] shell_utils.Bash(cleanup_cmd) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(SKPsCapture))
<commit_before>#!/usr/bin/env python # Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Run the webpages_playback automation script.""" import os import sys from build_step import BuildStep from utils import shell_utils class SKPsCapture(BuildStep): """BuildStep that captures the buildbot SKPs.""" def __init__(self, timeout=10800, **kwargs): super(SKPsCapture, self).__init__(timeout=timeout, **kwargs) def _Run(self): webpages_playback_cmd = [ 'python', os.path.join(os.path.dirname(os.path.realpath(__file__)), 'webpages_playback.py'), '--page_sets', self._args['page_sets'], '--skia_tools', self._args['skia_tools'], '--browser_executable', self._args['browser_executable'], '--non-interactive' ] if not self._is_try: webpages_playback_cmd.append('--upload_to_gs') shell_utils.Bash(webpages_playback_cmd) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(SKPsCapture)) <commit_msg>Clean up any left over browser processes in the RecreateSKPs buildstep. BUG=skia:2055 R=borenet@google.com Review URL: https://codereview.chromium.org/140003003<commit_after>
#!/usr/bin/env python # Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Run the webpages_playback automation script.""" import os import sys from build_step import BuildStep from utils import shell_utils class SKPsCapture(BuildStep): """BuildStep that captures the buildbot SKPs.""" def __init__(self, timeout=10800, **kwargs): super(SKPsCapture, self).__init__(timeout=timeout, **kwargs) def _Run(self): webpages_playback_cmd = [ 'python', os.path.join(os.path.dirname(os.path.realpath(__file__)), 'webpages_playback.py'), '--page_sets', self._args['page_sets'], '--skia_tools', self._args['skia_tools'], '--browser_executable', self._args['browser_executable'], '--non-interactive' ] if not self._is_try: webpages_playback_cmd.append('--upload_to_gs') shell_utils.Bash(webpages_playback_cmd) # Clean up any leftover browser instances. This can happen if there are # telemetry crashes, processes are not always cleaned up appropriately by # the webpagereplay and telemetry frameworks. cleanup_cmd = [ 'pkill', '-9', '-f', self._args['browser_executable'] ] shell_utils.Bash(cleanup_cmd) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(SKPsCapture))
#!/usr/bin/env python # Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Run the webpages_playback automation script.""" import os import sys from build_step import BuildStep from utils import shell_utils class SKPsCapture(BuildStep): """BuildStep that captures the buildbot SKPs.""" def __init__(self, timeout=10800, **kwargs): super(SKPsCapture, self).__init__(timeout=timeout, **kwargs) def _Run(self): webpages_playback_cmd = [ 'python', os.path.join(os.path.dirname(os.path.realpath(__file__)), 'webpages_playback.py'), '--page_sets', self._args['page_sets'], '--skia_tools', self._args['skia_tools'], '--browser_executable', self._args['browser_executable'], '--non-interactive' ] if not self._is_try: webpages_playback_cmd.append('--upload_to_gs') shell_utils.Bash(webpages_playback_cmd) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(SKPsCapture)) Clean up any left over browser processes in the RecreateSKPs buildstep. BUG=skia:2055 R=borenet@google.com Review URL: https://codereview.chromium.org/140003003#!/usr/bin/env python # Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Run the webpages_playback automation script.""" import os import sys from build_step import BuildStep from utils import shell_utils class SKPsCapture(BuildStep): """BuildStep that captures the buildbot SKPs.""" def __init__(self, timeout=10800, **kwargs): super(SKPsCapture, self).__init__(timeout=timeout, **kwargs) def _Run(self): webpages_playback_cmd = [ 'python', os.path.join(os.path.dirname(os.path.realpath(__file__)), 'webpages_playback.py'), '--page_sets', self._args['page_sets'], '--skia_tools', self._args['skia_tools'], '--browser_executable', self._args['browser_executable'], '--non-interactive' ] if not self._is_try: webpages_playback_cmd.append('--upload_to_gs') shell_utils.Bash(webpages_playback_cmd) # Clean up any leftover browser instances. This can happen if there are # telemetry crashes, processes are not always cleaned up appropriately by # the webpagereplay and telemetry frameworks. cleanup_cmd = [ 'pkill', '-9', '-f', self._args['browser_executable'] ] shell_utils.Bash(cleanup_cmd) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(SKPsCapture))
<commit_before>#!/usr/bin/env python # Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Run the webpages_playback automation script.""" import os import sys from build_step import BuildStep from utils import shell_utils class SKPsCapture(BuildStep): """BuildStep that captures the buildbot SKPs.""" def __init__(self, timeout=10800, **kwargs): super(SKPsCapture, self).__init__(timeout=timeout, **kwargs) def _Run(self): webpages_playback_cmd = [ 'python', os.path.join(os.path.dirname(os.path.realpath(__file__)), 'webpages_playback.py'), '--page_sets', self._args['page_sets'], '--skia_tools', self._args['skia_tools'], '--browser_executable', self._args['browser_executable'], '--non-interactive' ] if not self._is_try: webpages_playback_cmd.append('--upload_to_gs') shell_utils.Bash(webpages_playback_cmd) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(SKPsCapture)) <commit_msg>Clean up any left over browser processes in the RecreateSKPs buildstep. BUG=skia:2055 R=borenet@google.com Review URL: https://codereview.chromium.org/140003003<commit_after>#!/usr/bin/env python # Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Run the webpages_playback automation script.""" import os import sys from build_step import BuildStep from utils import shell_utils class SKPsCapture(BuildStep): """BuildStep that captures the buildbot SKPs.""" def __init__(self, timeout=10800, **kwargs): super(SKPsCapture, self).__init__(timeout=timeout, **kwargs) def _Run(self): webpages_playback_cmd = [ 'python', os.path.join(os.path.dirname(os.path.realpath(__file__)), 'webpages_playback.py'), '--page_sets', self._args['page_sets'], '--skia_tools', self._args['skia_tools'], '--browser_executable', self._args['browser_executable'], '--non-interactive' ] if not self._is_try: webpages_playback_cmd.append('--upload_to_gs') shell_utils.Bash(webpages_playback_cmd) # Clean up any leftover browser instances. This can happen if there are # telemetry crashes, processes are not always cleaned up appropriately by # the webpagereplay and telemetry frameworks. cleanup_cmd = [ 'pkill', '-9', '-f', self._args['browser_executable'] ] shell_utils.Bash(cleanup_cmd) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(SKPsCapture))
957b623ee36aaae7696cdfcbe33bafcd5cd8a42d
ai_genome.py
ai_genome.py
class GenomeException(Exception): pass class Genome(object): def __init__(self, name): defaults = { "name": name, "use_openings_book": True, # Search params "max_depth": 6, "max_depth_boost": 0, "mmpdl": 9, "narrowing": 0, "chokes": [(4,2)], "filter2": False, # Utility function "capture_score_base": 300, "take_score_base": 100, "threat_score_base": 20, "captures_scale": [0, 1, 1, 1, 1, 1], "length_factor": 27, "move_factor": 30, "blindness": 0, "sub": True, } super(Genome, self).__setattr__("__dict__", defaults) def __setattr__(self, attr_name, val): if not hasattr(self, attr_name): raise GenomeException("Cannot set attribute %s" % attr_name) super(Genome, self).__setattr__(attr_name, val) def key(self): return self.name
class GenomeException(Exception): pass class Genome(object): def __init__(self, name): defaults = { "name": name, "use_openings_book": True, # Search params "max_depth": 6, "max_depth_boost": 0, "mmpdl": 9, "narrowing": 0, "chokes": [(4,5)], "filter2": True, # Utility function "capture_score_base": 300, "take_score_base": 100, "threat_score_base": 20, "captures_scale": [0, 1, 1, 1, 1, 1], "length_factor": 27, "move_factor": 30, "blindness": 0, "sub": True, } super(Genome, self).__setattr__("__dict__", defaults) def __setattr__(self, attr_name, val): if not hasattr(self, attr_name): raise GenomeException("Cannot set attribute %s" % attr_name) super(Genome, self).__setattr__(attr_name, val) def key(self): return self.name
Change a couple of defaults
Change a couple of defaults
Python
mit
cropleyb/pentai,cropleyb/pentai,cropleyb/pentai
class GenomeException(Exception): pass class Genome(object): def __init__(self, name): defaults = { "name": name, "use_openings_book": True, # Search params "max_depth": 6, "max_depth_boost": 0, "mmpdl": 9, "narrowing": 0, "chokes": [(4,2)], "filter2": False, # Utility function "capture_score_base": 300, "take_score_base": 100, "threat_score_base": 20, "captures_scale": [0, 1, 1, 1, 1, 1], "length_factor": 27, "move_factor": 30, "blindness": 0, "sub": True, } super(Genome, self).__setattr__("__dict__", defaults) def __setattr__(self, attr_name, val): if not hasattr(self, attr_name): raise GenomeException("Cannot set attribute %s" % attr_name) super(Genome, self).__setattr__(attr_name, val) def key(self): return self.name Change a couple of defaults
class GenomeException(Exception): pass class Genome(object): def __init__(self, name): defaults = { "name": name, "use_openings_book": True, # Search params "max_depth": 6, "max_depth_boost": 0, "mmpdl": 9, "narrowing": 0, "chokes": [(4,5)], "filter2": True, # Utility function "capture_score_base": 300, "take_score_base": 100, "threat_score_base": 20, "captures_scale": [0, 1, 1, 1, 1, 1], "length_factor": 27, "move_factor": 30, "blindness": 0, "sub": True, } super(Genome, self).__setattr__("__dict__", defaults) def __setattr__(self, attr_name, val): if not hasattr(self, attr_name): raise GenomeException("Cannot set attribute %s" % attr_name) super(Genome, self).__setattr__(attr_name, val) def key(self): return self.name
<commit_before> class GenomeException(Exception): pass class Genome(object): def __init__(self, name): defaults = { "name": name, "use_openings_book": True, # Search params "max_depth": 6, "max_depth_boost": 0, "mmpdl": 9, "narrowing": 0, "chokes": [(4,2)], "filter2": False, # Utility function "capture_score_base": 300, "take_score_base": 100, "threat_score_base": 20, "captures_scale": [0, 1, 1, 1, 1, 1], "length_factor": 27, "move_factor": 30, "blindness": 0, "sub": True, } super(Genome, self).__setattr__("__dict__", defaults) def __setattr__(self, attr_name, val): if not hasattr(self, attr_name): raise GenomeException("Cannot set attribute %s" % attr_name) super(Genome, self).__setattr__(attr_name, val) def key(self): return self.name <commit_msg>Change a couple of defaults<commit_after>
class GenomeException(Exception): pass class Genome(object): def __init__(self, name): defaults = { "name": name, "use_openings_book": True, # Search params "max_depth": 6, "max_depth_boost": 0, "mmpdl": 9, "narrowing": 0, "chokes": [(4,5)], "filter2": True, # Utility function "capture_score_base": 300, "take_score_base": 100, "threat_score_base": 20, "captures_scale": [0, 1, 1, 1, 1, 1], "length_factor": 27, "move_factor": 30, "blindness": 0, "sub": True, } super(Genome, self).__setattr__("__dict__", defaults) def __setattr__(self, attr_name, val): if not hasattr(self, attr_name): raise GenomeException("Cannot set attribute %s" % attr_name) super(Genome, self).__setattr__(attr_name, val) def key(self): return self.name
class GenomeException(Exception): pass class Genome(object): def __init__(self, name): defaults = { "name": name, "use_openings_book": True, # Search params "max_depth": 6, "max_depth_boost": 0, "mmpdl": 9, "narrowing": 0, "chokes": [(4,2)], "filter2": False, # Utility function "capture_score_base": 300, "take_score_base": 100, "threat_score_base": 20, "captures_scale": [0, 1, 1, 1, 1, 1], "length_factor": 27, "move_factor": 30, "blindness": 0, "sub": True, } super(Genome, self).__setattr__("__dict__", defaults) def __setattr__(self, attr_name, val): if not hasattr(self, attr_name): raise GenomeException("Cannot set attribute %s" % attr_name) super(Genome, self).__setattr__(attr_name, val) def key(self): return self.name Change a couple of defaults class GenomeException(Exception): pass class Genome(object): def __init__(self, name): defaults = { "name": name, "use_openings_book": True, # Search params "max_depth": 6, "max_depth_boost": 0, "mmpdl": 9, "narrowing": 0, "chokes": [(4,5)], "filter2": True, # Utility function "capture_score_base": 300, "take_score_base": 100, "threat_score_base": 20, "captures_scale": [0, 1, 1, 1, 1, 1], "length_factor": 27, "move_factor": 30, "blindness": 0, "sub": True, } super(Genome, self).__setattr__("__dict__", defaults) def __setattr__(self, attr_name, val): if not hasattr(self, attr_name): raise GenomeException("Cannot set attribute %s" % attr_name) super(Genome, self).__setattr__(attr_name, val) def key(self): return self.name
<commit_before> class GenomeException(Exception): pass class Genome(object): def __init__(self, name): defaults = { "name": name, "use_openings_book": True, # Search params "max_depth": 6, "max_depth_boost": 0, "mmpdl": 9, "narrowing": 0, "chokes": [(4,2)], "filter2": False, # Utility function "capture_score_base": 300, "take_score_base": 100, "threat_score_base": 20, "captures_scale": [0, 1, 1, 1, 1, 1], "length_factor": 27, "move_factor": 30, "blindness": 0, "sub": True, } super(Genome, self).__setattr__("__dict__", defaults) def __setattr__(self, attr_name, val): if not hasattr(self, attr_name): raise GenomeException("Cannot set attribute %s" % attr_name) super(Genome, self).__setattr__(attr_name, val) def key(self): return self.name <commit_msg>Change a couple of defaults<commit_after> class GenomeException(Exception): pass class Genome(object): def __init__(self, name): defaults = { "name": name, "use_openings_book": True, # Search params "max_depth": 6, "max_depth_boost": 0, "mmpdl": 9, "narrowing": 0, "chokes": [(4,5)], "filter2": True, # Utility function "capture_score_base": 300, "take_score_base": 100, "threat_score_base": 20, "captures_scale": [0, 1, 1, 1, 1, 1], "length_factor": 27, "move_factor": 30, "blindness": 0, "sub": True, } super(Genome, self).__setattr__("__dict__", defaults) def __setattr__(self, attr_name, val): if not hasattr(self, attr_name): raise GenomeException("Cannot set attribute %s" % attr_name) super(Genome, self).__setattr__(attr_name, val) def key(self): return self.name
5adc4a0637b31de518b30bbc662c3d50bc523a5a
airtravel.py
airtravel.py
"""Model for aircraft flights""" class Flight: def __init__(self, number): if not number[:4].isalpha(): raise ValueError("No airline code in '{}'".format(number)) if not number[:4].isupper(): raise ValueError("Invalid airline code'{}'".format(number)) if not (number[4:].isdigit() and int(number[4:]) <= 999999): raise ValueError("Invalid route number '{}'".format(number)) self._number = number def number(self): return self._number def airline(self): return self._number[:4] class Aircraft: def __init__(self, registration, model, num_rows, num_seats_per_row): self._registration = registration self._model = model self._num_rows = num_rows self._num_seats_per_row = num_seats_per_row def registration(self): return self._registration def model(self): return self._model
"""Model for aircraft flights""" class Flight: def __init__(self, number): if not number[:4].isalpha(): raise ValueError("No airline code in '{}'".format(number)) if not number[:4].isupper(): raise ValueError("Invalid airline code'{}'".format(number)) if not (number[4:].isdigit() and int(number[4:]) <= 999999): raise ValueError("Invalid route number '{}'".format(number)) self._number = number def number(self): return self._number def airline(self): return self._number[:4] class Aircraft: def __init__(self, registration, model, num_rows, num_seats_per_row): self._registration = registration self._model = model self._num_rows = num_rows self._num_seats_per_row = num_seats_per_row def registration(self): return self._registration def model(self): return self._model def seating_plan(self): return (range(1, self._num_rows + 1), "ABCDEFGHJKLMNOP"[:self._num_seats_per_row])
Add seating plan to aircraft
Add seating plan to aircraft
Python
mit
kentoj/python-fundamentals
"""Model for aircraft flights""" class Flight: def __init__(self, number): if not number[:4].isalpha(): raise ValueError("No airline code in '{}'".format(number)) if not number[:4].isupper(): raise ValueError("Invalid airline code'{}'".format(number)) if not (number[4:].isdigit() and int(number[4:]) <= 999999): raise ValueError("Invalid route number '{}'".format(number)) self._number = number def number(self): return self._number def airline(self): return self._number[:4] class Aircraft: def __init__(self, registration, model, num_rows, num_seats_per_row): self._registration = registration self._model = model self._num_rows = num_rows self._num_seats_per_row = num_seats_per_row def registration(self): return self._registration def model(self): return self._model Add seating plan to aircraft
"""Model for aircraft flights""" class Flight: def __init__(self, number): if not number[:4].isalpha(): raise ValueError("No airline code in '{}'".format(number)) if not number[:4].isupper(): raise ValueError("Invalid airline code'{}'".format(number)) if not (number[4:].isdigit() and int(number[4:]) <= 999999): raise ValueError("Invalid route number '{}'".format(number)) self._number = number def number(self): return self._number def airline(self): return self._number[:4] class Aircraft: def __init__(self, registration, model, num_rows, num_seats_per_row): self._registration = registration self._model = model self._num_rows = num_rows self._num_seats_per_row = num_seats_per_row def registration(self): return self._registration def model(self): return self._model def seating_plan(self): return (range(1, self._num_rows + 1), "ABCDEFGHJKLMNOP"[:self._num_seats_per_row])
<commit_before>"""Model for aircraft flights""" class Flight: def __init__(self, number): if not number[:4].isalpha(): raise ValueError("No airline code in '{}'".format(number)) if not number[:4].isupper(): raise ValueError("Invalid airline code'{}'".format(number)) if not (number[4:].isdigit() and int(number[4:]) <= 999999): raise ValueError("Invalid route number '{}'".format(number)) self._number = number def number(self): return self._number def airline(self): return self._number[:4] class Aircraft: def __init__(self, registration, model, num_rows, num_seats_per_row): self._registration = registration self._model = model self._num_rows = num_rows self._num_seats_per_row = num_seats_per_row def registration(self): return self._registration def model(self): return self._model <commit_msg>Add seating plan to aircraft<commit_after>
"""Model for aircraft flights""" class Flight: def __init__(self, number): if not number[:4].isalpha(): raise ValueError("No airline code in '{}'".format(number)) if not number[:4].isupper(): raise ValueError("Invalid airline code'{}'".format(number)) if not (number[4:].isdigit() and int(number[4:]) <= 999999): raise ValueError("Invalid route number '{}'".format(number)) self._number = number def number(self): return self._number def airline(self): return self._number[:4] class Aircraft: def __init__(self, registration, model, num_rows, num_seats_per_row): self._registration = registration self._model = model self._num_rows = num_rows self._num_seats_per_row = num_seats_per_row def registration(self): return self._registration def model(self): return self._model def seating_plan(self): return (range(1, self._num_rows + 1), "ABCDEFGHJKLMNOP"[:self._num_seats_per_row])
"""Model for aircraft flights""" class Flight: def __init__(self, number): if not number[:4].isalpha(): raise ValueError("No airline code in '{}'".format(number)) if not number[:4].isupper(): raise ValueError("Invalid airline code'{}'".format(number)) if not (number[4:].isdigit() and int(number[4:]) <= 999999): raise ValueError("Invalid route number '{}'".format(number)) self._number = number def number(self): return self._number def airline(self): return self._number[:4] class Aircraft: def __init__(self, registration, model, num_rows, num_seats_per_row): self._registration = registration self._model = model self._num_rows = num_rows self._num_seats_per_row = num_seats_per_row def registration(self): return self._registration def model(self): return self._model Add seating plan to aircraft"""Model for aircraft flights""" class Flight: def __init__(self, number): if not number[:4].isalpha(): raise ValueError("No airline code in '{}'".format(number)) if not number[:4].isupper(): raise ValueError("Invalid airline code'{}'".format(number)) if not (number[4:].isdigit() and int(number[4:]) <= 999999): raise ValueError("Invalid route number '{}'".format(number)) self._number = number def number(self): return self._number def airline(self): return self._number[:4] class Aircraft: def __init__(self, registration, model, num_rows, num_seats_per_row): self._registration = registration self._model = model self._num_rows = num_rows self._num_seats_per_row = num_seats_per_row def registration(self): return self._registration def model(self): return self._model def seating_plan(self): return (range(1, self._num_rows + 1), "ABCDEFGHJKLMNOP"[:self._num_seats_per_row])
<commit_before>"""Model for aircraft flights""" class Flight: def __init__(self, number): if not number[:4].isalpha(): raise ValueError("No airline code in '{}'".format(number)) if not number[:4].isupper(): raise ValueError("Invalid airline code'{}'".format(number)) if not (number[4:].isdigit() and int(number[4:]) <= 999999): raise ValueError("Invalid route number '{}'".format(number)) self._number = number def number(self): return self._number def airline(self): return self._number[:4] class Aircraft: def __init__(self, registration, model, num_rows, num_seats_per_row): self._registration = registration self._model = model self._num_rows = num_rows self._num_seats_per_row = num_seats_per_row def registration(self): return self._registration def model(self): return self._model <commit_msg>Add seating plan to aircraft<commit_after>"""Model for aircraft flights""" class Flight: def __init__(self, number): if not number[:4].isalpha(): raise ValueError("No airline code in '{}'".format(number)) if not number[:4].isupper(): raise ValueError("Invalid airline code'{}'".format(number)) if not (number[4:].isdigit() and int(number[4:]) <= 999999): raise ValueError("Invalid route number '{}'".format(number)) self._number = number def number(self): return self._number def airline(self): return self._number[:4] class Aircraft: def __init__(self, registration, model, num_rows, num_seats_per_row): self._registration = registration self._model = model self._num_rows = num_rows self._num_seats_per_row = num_seats_per_row def registration(self): return self._registration def model(self): return self._model def seating_plan(self): return (range(1, self._num_rows + 1), "ABCDEFGHJKLMNOP"[:self._num_seats_per_row])
36f59422fdf9d7dc76c31b096c3b7f909762109a
Lib/compiler/syntax.py
Lib/compiler/syntax.py
"""Check for errs in the AST. The Python parser does not catch all syntax errors. Others, like assignments with invalid targets, are caught in the code generation phase. The compiler package catches some errors in the transformer module. But it seems clearer to write checkers that use the AST to detect errors. """ from compiler import ast, walk def check(tree, multi=None): v = SyntaxErrorChecker(multi) walk(tree, v) return v.errors class SyntaxErrorChecker: """A visitor to find syntax errors in the AST.""" def __init__(self, multi=None): """Create new visitor object. If optional argument multi is not None, then print messages for each error rather than raising a SyntaxError for the first. """ self.multi = multi self.errors = 0 def error(self, node, msg): self.errors = self.errors + 1 if self.multi is not None: print "%s:%s: %s" % (node.filename, node.lineno, msg) else: raise SyntaxError, "%s (%s:%s)" % (msg, node.filename, node.lineno) def visitAssign(self, node): # the transformer module handles many of these for target in node.nodes: pass ## if isinstance(target, ast.AssList): ## if target.lineno is None: ## target.lineno = node.lineno ## self.error(target, "can't assign to list comprehension")
"""Check for errs in the AST. The Python parser does not catch all syntax errors. Others, like assignments with invalid targets, are caught in the code generation phase. The compiler package catches some errors in the transformer module. But it seems clearer to write checkers that use the AST to detect errors. """ from compiler import ast, walk def check(tree, multi=None): v = SyntaxErrorChecker(multi) walk(tree, v) return v.errors class SyntaxErrorChecker: """A visitor to find syntax errors in the AST.""" def __init__(self, multi=None): """Create new visitor object. If optional argument multi is not None, then print messages for each error rather than raising a SyntaxError for the first. """ self.multi = multi self.errors = 0 def error(self, node, msg): self.errors = self.errors + 1 if self.multi is not None: print "%s:%s: %s" % (node.filename, node.lineno, msg) else: raise SyntaxError, "%s (%s:%s)" % (msg, node.filename, node.lineno) def visitAssign(self, node): # the transformer module handles many of these pass ## for target in node.nodes: ## if isinstance(target, ast.AssList): ## if target.lineno is None: ## target.lineno = node.lineno ## self.error(target, "can't assign to list comprehension")
Stop looping to do nothing, just pass.
Stop looping to do nothing, just pass.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
"""Check for errs in the AST. The Python parser does not catch all syntax errors. Others, like assignments with invalid targets, are caught in the code generation phase. The compiler package catches some errors in the transformer module. But it seems clearer to write checkers that use the AST to detect errors. """ from compiler import ast, walk def check(tree, multi=None): v = SyntaxErrorChecker(multi) walk(tree, v) return v.errors class SyntaxErrorChecker: """A visitor to find syntax errors in the AST.""" def __init__(self, multi=None): """Create new visitor object. If optional argument multi is not None, then print messages for each error rather than raising a SyntaxError for the first. """ self.multi = multi self.errors = 0 def error(self, node, msg): self.errors = self.errors + 1 if self.multi is not None: print "%s:%s: %s" % (node.filename, node.lineno, msg) else: raise SyntaxError, "%s (%s:%s)" % (msg, node.filename, node.lineno) def visitAssign(self, node): # the transformer module handles many of these for target in node.nodes: pass ## if isinstance(target, ast.AssList): ## if target.lineno is None: ## target.lineno = node.lineno ## self.error(target, "can't assign to list comprehension") Stop looping to do nothing, just pass.
"""Check for errs in the AST. The Python parser does not catch all syntax errors. Others, like assignments with invalid targets, are caught in the code generation phase. The compiler package catches some errors in the transformer module. But it seems clearer to write checkers that use the AST to detect errors. """ from compiler import ast, walk def check(tree, multi=None): v = SyntaxErrorChecker(multi) walk(tree, v) return v.errors class SyntaxErrorChecker: """A visitor to find syntax errors in the AST.""" def __init__(self, multi=None): """Create new visitor object. If optional argument multi is not None, then print messages for each error rather than raising a SyntaxError for the first. """ self.multi = multi self.errors = 0 def error(self, node, msg): self.errors = self.errors + 1 if self.multi is not None: print "%s:%s: %s" % (node.filename, node.lineno, msg) else: raise SyntaxError, "%s (%s:%s)" % (msg, node.filename, node.lineno) def visitAssign(self, node): # the transformer module handles many of these pass ## for target in node.nodes: ## if isinstance(target, ast.AssList): ## if target.lineno is None: ## target.lineno = node.lineno ## self.error(target, "can't assign to list comprehension")
<commit_before>"""Check for errs in the AST. The Python parser does not catch all syntax errors. Others, like assignments with invalid targets, are caught in the code generation phase. The compiler package catches some errors in the transformer module. But it seems clearer to write checkers that use the AST to detect errors. """ from compiler import ast, walk def check(tree, multi=None): v = SyntaxErrorChecker(multi) walk(tree, v) return v.errors class SyntaxErrorChecker: """A visitor to find syntax errors in the AST.""" def __init__(self, multi=None): """Create new visitor object. If optional argument multi is not None, then print messages for each error rather than raising a SyntaxError for the first. """ self.multi = multi self.errors = 0 def error(self, node, msg): self.errors = self.errors + 1 if self.multi is not None: print "%s:%s: %s" % (node.filename, node.lineno, msg) else: raise SyntaxError, "%s (%s:%s)" % (msg, node.filename, node.lineno) def visitAssign(self, node): # the transformer module handles many of these for target in node.nodes: pass ## if isinstance(target, ast.AssList): ## if target.lineno is None: ## target.lineno = node.lineno ## self.error(target, "can't assign to list comprehension") <commit_msg>Stop looping to do nothing, just pass.<commit_after>
"""Check for errs in the AST. The Python parser does not catch all syntax errors. Others, like assignments with invalid targets, are caught in the code generation phase. The compiler package catches some errors in the transformer module. But it seems clearer to write checkers that use the AST to detect errors. """ from compiler import ast, walk def check(tree, multi=None): v = SyntaxErrorChecker(multi) walk(tree, v) return v.errors class SyntaxErrorChecker: """A visitor to find syntax errors in the AST.""" def __init__(self, multi=None): """Create new visitor object. If optional argument multi is not None, then print messages for each error rather than raising a SyntaxError for the first. """ self.multi = multi self.errors = 0 def error(self, node, msg): self.errors = self.errors + 1 if self.multi is not None: print "%s:%s: %s" % (node.filename, node.lineno, msg) else: raise SyntaxError, "%s (%s:%s)" % (msg, node.filename, node.lineno) def visitAssign(self, node): # the transformer module handles many of these pass ## for target in node.nodes: ## if isinstance(target, ast.AssList): ## if target.lineno is None: ## target.lineno = node.lineno ## self.error(target, "can't assign to list comprehension")
"""Check for errs in the AST. The Python parser does not catch all syntax errors. Others, like assignments with invalid targets, are caught in the code generation phase. The compiler package catches some errors in the transformer module. But it seems clearer to write checkers that use the AST to detect errors. """ from compiler import ast, walk def check(tree, multi=None): v = SyntaxErrorChecker(multi) walk(tree, v) return v.errors class SyntaxErrorChecker: """A visitor to find syntax errors in the AST.""" def __init__(self, multi=None): """Create new visitor object. If optional argument multi is not None, then print messages for each error rather than raising a SyntaxError for the first. """ self.multi = multi self.errors = 0 def error(self, node, msg): self.errors = self.errors + 1 if self.multi is not None: print "%s:%s: %s" % (node.filename, node.lineno, msg) else: raise SyntaxError, "%s (%s:%s)" % (msg, node.filename, node.lineno) def visitAssign(self, node): # the transformer module handles many of these for target in node.nodes: pass ## if isinstance(target, ast.AssList): ## if target.lineno is None: ## target.lineno = node.lineno ## self.error(target, "can't assign to list comprehension") Stop looping to do nothing, just pass."""Check for errs in the AST. The Python parser does not catch all syntax errors. Others, like assignments with invalid targets, are caught in the code generation phase. The compiler package catches some errors in the transformer module. But it seems clearer to write checkers that use the AST to detect errors. """ from compiler import ast, walk def check(tree, multi=None): v = SyntaxErrorChecker(multi) walk(tree, v) return v.errors class SyntaxErrorChecker: """A visitor to find syntax errors in the AST.""" def __init__(self, multi=None): """Create new visitor object. If optional argument multi is not None, then print messages for each error rather than raising a SyntaxError for the first. """ self.multi = multi self.errors = 0 def error(self, node, msg): self.errors = self.errors + 1 if self.multi is not None: print "%s:%s: %s" % (node.filename, node.lineno, msg) else: raise SyntaxError, "%s (%s:%s)" % (msg, node.filename, node.lineno) def visitAssign(self, node): # the transformer module handles many of these pass ## for target in node.nodes: ## if isinstance(target, ast.AssList): ## if target.lineno is None: ## target.lineno = node.lineno ## self.error(target, "can't assign to list comprehension")
<commit_before>"""Check for errs in the AST. The Python parser does not catch all syntax errors. Others, like assignments with invalid targets, are caught in the code generation phase. The compiler package catches some errors in the transformer module. But it seems clearer to write checkers that use the AST to detect errors. """ from compiler import ast, walk def check(tree, multi=None): v = SyntaxErrorChecker(multi) walk(tree, v) return v.errors class SyntaxErrorChecker: """A visitor to find syntax errors in the AST.""" def __init__(self, multi=None): """Create new visitor object. If optional argument multi is not None, then print messages for each error rather than raising a SyntaxError for the first. """ self.multi = multi self.errors = 0 def error(self, node, msg): self.errors = self.errors + 1 if self.multi is not None: print "%s:%s: %s" % (node.filename, node.lineno, msg) else: raise SyntaxError, "%s (%s:%s)" % (msg, node.filename, node.lineno) def visitAssign(self, node): # the transformer module handles many of these for target in node.nodes: pass ## if isinstance(target, ast.AssList): ## if target.lineno is None: ## target.lineno = node.lineno ## self.error(target, "can't assign to list comprehension") <commit_msg>Stop looping to do nothing, just pass.<commit_after>"""Check for errs in the AST. The Python parser does not catch all syntax errors. Others, like assignments with invalid targets, are caught in the code generation phase. The compiler package catches some errors in the transformer module. But it seems clearer to write checkers that use the AST to detect errors. """ from compiler import ast, walk def check(tree, multi=None): v = SyntaxErrorChecker(multi) walk(tree, v) return v.errors class SyntaxErrorChecker: """A visitor to find syntax errors in the AST.""" def __init__(self, multi=None): """Create new visitor object. If optional argument multi is not None, then print messages for each error rather than raising a SyntaxError for the first. """ self.multi = multi self.errors = 0 def error(self, node, msg): self.errors = self.errors + 1 if self.multi is not None: print "%s:%s: %s" % (node.filename, node.lineno, msg) else: raise SyntaxError, "%s (%s:%s)" % (msg, node.filename, node.lineno) def visitAssign(self, node): # the transformer module handles many of these pass ## for target in node.nodes: ## if isinstance(target, ast.AssList): ## if target.lineno is None: ## target.lineno = node.lineno ## self.error(target, "can't assign to list comprehension")
6d6e83734d0cb034f8fc198df94bc64cf412d8d6
ceam/framework/components.py
ceam/framework/components.py
from importlib import import_module import json def read_component_configuration(path): if path.endswith('.json'): with open(path) as f: config = json.load(f) return apply_defaults(config) else: raise ValueError("Unknown components configuration type: {}".format(path)) def apply_defaults(config): base_components = config['components'] if 'comparisons' in config: comparisons = {c['name']:c for c in config['comparisons']} for comparison in comparisons.values(): comparison['components'] = base_components + comparison['components'] else: comparisons = {'base': {'name': 'base', 'components': base_components}} return comparisons def load(component_list): components = [] for component in component_list: if isinstance(component, str) or isinstance(component, list): if isinstance(component, list): component, args, kwargs = component call = True elif component.endswith('()'): component = component[:-2] args = () kwargs = {} call = True else: call = False module_path, _, component_name = component.rpartition('.') component = getattr(import_module(module_path), component_name) if call: component = component(*args, **kwargs) if isinstance(component, type): component = component() components.append(component) return components
from importlib import import_module from collections import Iterable import json def read_component_configuration(path): if path.endswith('.json'): with open(path) as f: config = json.load(f) return apply_defaults(config) else: raise ValueError("Unknown components configuration type: {}".format(path)) def apply_defaults(config): base_components = config['components'] if 'comparisons' in config: comparisons = {c['name']:c for c in config['comparisons']} for comparison in comparisons.values(): comparison['components'] = base_components + comparison['components'] else: comparisons = {'base': {'name': 'base', 'components': base_components}} return comparisons def load(component_list): components = [] for component in component_list: if isinstance(component, str) or isinstance(component, list): if isinstance(component, list): component, args, kwargs = component call = True elif component.endswith('()'): component = component[:-2] args = () kwargs = {} call = True else: call = False module_path, _, component_name = component.rpartition('.') component = getattr(import_module(module_path), component_name) if call: component = component(*args, **kwargs) if isinstance(component, type): component = component() if isinstance(component, Iterable): components.extend(component) else: components.append(component) return components
Add support for component initialization that returns lists
Add support for component initialization that returns lists
Python
bsd-3-clause
ihmeuw/vivarium
from importlib import import_module import json def read_component_configuration(path): if path.endswith('.json'): with open(path) as f: config = json.load(f) return apply_defaults(config) else: raise ValueError("Unknown components configuration type: {}".format(path)) def apply_defaults(config): base_components = config['components'] if 'comparisons' in config: comparisons = {c['name']:c for c in config['comparisons']} for comparison in comparisons.values(): comparison['components'] = base_components + comparison['components'] else: comparisons = {'base': {'name': 'base', 'components': base_components}} return comparisons def load(component_list): components = [] for component in component_list: if isinstance(component, str) or isinstance(component, list): if isinstance(component, list): component, args, kwargs = component call = True elif component.endswith('()'): component = component[:-2] args = () kwargs = {} call = True else: call = False module_path, _, component_name = component.rpartition('.') component = getattr(import_module(module_path), component_name) if call: component = component(*args, **kwargs) if isinstance(component, type): component = component() components.append(component) return components Add support for component initialization that returns lists
from importlib import import_module from collections import Iterable import json def read_component_configuration(path): if path.endswith('.json'): with open(path) as f: config = json.load(f) return apply_defaults(config) else: raise ValueError("Unknown components configuration type: {}".format(path)) def apply_defaults(config): base_components = config['components'] if 'comparisons' in config: comparisons = {c['name']:c for c in config['comparisons']} for comparison in comparisons.values(): comparison['components'] = base_components + comparison['components'] else: comparisons = {'base': {'name': 'base', 'components': base_components}} return comparisons def load(component_list): components = [] for component in component_list: if isinstance(component, str) or isinstance(component, list): if isinstance(component, list): component, args, kwargs = component call = True elif component.endswith('()'): component = component[:-2] args = () kwargs = {} call = True else: call = False module_path, _, component_name = component.rpartition('.') component = getattr(import_module(module_path), component_name) if call: component = component(*args, **kwargs) if isinstance(component, type): component = component() if isinstance(component, Iterable): components.extend(component) else: components.append(component) return components
<commit_before>from importlib import import_module import json def read_component_configuration(path): if path.endswith('.json'): with open(path) as f: config = json.load(f) return apply_defaults(config) else: raise ValueError("Unknown components configuration type: {}".format(path)) def apply_defaults(config): base_components = config['components'] if 'comparisons' in config: comparisons = {c['name']:c for c in config['comparisons']} for comparison in comparisons.values(): comparison['components'] = base_components + comparison['components'] else: comparisons = {'base': {'name': 'base', 'components': base_components}} return comparisons def load(component_list): components = [] for component in component_list: if isinstance(component, str) or isinstance(component, list): if isinstance(component, list): component, args, kwargs = component call = True elif component.endswith('()'): component = component[:-2] args = () kwargs = {} call = True else: call = False module_path, _, component_name = component.rpartition('.') component = getattr(import_module(module_path), component_name) if call: component = component(*args, **kwargs) if isinstance(component, type): component = component() components.append(component) return components <commit_msg>Add support for component initialization that returns lists<commit_after>
from importlib import import_module from collections import Iterable import json def read_component_configuration(path): if path.endswith('.json'): with open(path) as f: config = json.load(f) return apply_defaults(config) else: raise ValueError("Unknown components configuration type: {}".format(path)) def apply_defaults(config): base_components = config['components'] if 'comparisons' in config: comparisons = {c['name']:c for c in config['comparisons']} for comparison in comparisons.values(): comparison['components'] = base_components + comparison['components'] else: comparisons = {'base': {'name': 'base', 'components': base_components}} return comparisons def load(component_list): components = [] for component in component_list: if isinstance(component, str) or isinstance(component, list): if isinstance(component, list): component, args, kwargs = component call = True elif component.endswith('()'): component = component[:-2] args = () kwargs = {} call = True else: call = False module_path, _, component_name = component.rpartition('.') component = getattr(import_module(module_path), component_name) if call: component = component(*args, **kwargs) if isinstance(component, type): component = component() if isinstance(component, Iterable): components.extend(component) else: components.append(component) return components
from importlib import import_module import json def read_component_configuration(path): if path.endswith('.json'): with open(path) as f: config = json.load(f) return apply_defaults(config) else: raise ValueError("Unknown components configuration type: {}".format(path)) def apply_defaults(config): base_components = config['components'] if 'comparisons' in config: comparisons = {c['name']:c for c in config['comparisons']} for comparison in comparisons.values(): comparison['components'] = base_components + comparison['components'] else: comparisons = {'base': {'name': 'base', 'components': base_components}} return comparisons def load(component_list): components = [] for component in component_list: if isinstance(component, str) or isinstance(component, list): if isinstance(component, list): component, args, kwargs = component call = True elif component.endswith('()'): component = component[:-2] args = () kwargs = {} call = True else: call = False module_path, _, component_name = component.rpartition('.') component = getattr(import_module(module_path), component_name) if call: component = component(*args, **kwargs) if isinstance(component, type): component = component() components.append(component) return components Add support for component initialization that returns listsfrom importlib import import_module from collections import Iterable import json def read_component_configuration(path): if path.endswith('.json'): with open(path) as f: config = json.load(f) return apply_defaults(config) else: raise ValueError("Unknown components configuration type: {}".format(path)) def apply_defaults(config): base_components = config['components'] if 'comparisons' in config: comparisons = {c['name']:c for c in config['comparisons']} for comparison in comparisons.values(): comparison['components'] = base_components + comparison['components'] else: comparisons = {'base': {'name': 'base', 'components': base_components}} return comparisons def load(component_list): components = [] for component in component_list: if isinstance(component, str) or isinstance(component, list): if isinstance(component, list): component, args, kwargs = component call = True elif component.endswith('()'): component = component[:-2] args = () kwargs = {} call = True else: call = False module_path, _, component_name = component.rpartition('.') component = getattr(import_module(module_path), component_name) if call: component = component(*args, **kwargs) if isinstance(component, type): component = component() if isinstance(component, Iterable): components.extend(component) else: components.append(component) return components
<commit_before>from importlib import import_module import json def read_component_configuration(path): if path.endswith('.json'): with open(path) as f: config = json.load(f) return apply_defaults(config) else: raise ValueError("Unknown components configuration type: {}".format(path)) def apply_defaults(config): base_components = config['components'] if 'comparisons' in config: comparisons = {c['name']:c for c in config['comparisons']} for comparison in comparisons.values(): comparison['components'] = base_components + comparison['components'] else: comparisons = {'base': {'name': 'base', 'components': base_components}} return comparisons def load(component_list): components = [] for component in component_list: if isinstance(component, str) or isinstance(component, list): if isinstance(component, list): component, args, kwargs = component call = True elif component.endswith('()'): component = component[:-2] args = () kwargs = {} call = True else: call = False module_path, _, component_name = component.rpartition('.') component = getattr(import_module(module_path), component_name) if call: component = component(*args, **kwargs) if isinstance(component, type): component = component() components.append(component) return components <commit_msg>Add support for component initialization that returns lists<commit_after>from importlib import import_module from collections import Iterable import json def read_component_configuration(path): if path.endswith('.json'): with open(path) as f: config = json.load(f) return apply_defaults(config) else: raise ValueError("Unknown components configuration type: {}".format(path)) def apply_defaults(config): base_components = config['components'] if 'comparisons' in config: comparisons = {c['name']:c for c in config['comparisons']} for comparison in comparisons.values(): comparison['components'] = base_components + comparison['components'] else: comparisons = {'base': {'name': 'base', 'components': base_components}} return comparisons def load(component_list): components = [] for component in component_list: if isinstance(component, str) or isinstance(component, list): if isinstance(component, list): component, args, kwargs = component call = True elif component.endswith('()'): component = component[:-2] args = () kwargs = {} call = True else: call = False module_path, _, component_name = component.rpartition('.') component = getattr(import_module(module_path), component_name) if call: component = component(*args, **kwargs) if isinstance(component, type): component = component() if isinstance(component, Iterable): components.extend(component) else: components.append(component) return components
80f046bc851916de05ba90e4dc88b78043961061
inventory.py
inventory.py
from flask import Flask, render_template, url_for, redirect from flask import session, escape, request from peewee import * #from datetime import date app = Flask(__name__) # http://docs.peewee-orm.com/en/latest/peewee/quickstart.html database = SqliteDatabase('developmentData.db') class Device(Model): idNumber = IntField() serialNumber = CharField() typeCategory = CharField() description = TextField() issues = TextField() photo = CharField() quality = CharField() @app.route('/') def index(): # http://flask.pocoo.org/snippets/15/ if 'username' in session: return render_template('inventory.html', inventoryData="", deviceLogData="") return redirect(url_for('login')); @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) return render_template('login.html') if __name__ == '__main__': db.connect() app.run()
from flask import Flask, render_template, url_for, redirect from flask import session, escape, request from peewee import * #from datetime import date app = Flask(__name__) # http://docs.peewee-orm.com/en/latest/peewee/quickstart.html database = SqliteDatabase('developmentData.db') class Device(Model): idNumber = IntField() serialNumber = CharField() typeCategory = CharField() description = TextField() issues = TextField() photo = CharField() quality = CharField() @app.route('/') def index(): # http://flask.pocoo.org/snippets/15/ #if 'username' in session: return render_template('inventory.html', inventoryData="", deviceLogData="") #return redirect(url_for('login')); #@app.route('/login', methods=['GET', 'POST']) #def login(): # if request.method == 'POST': # session['username'] = request.form['username'] # return redirect(url_for('index')) # return render_template('login.html') if __name__ == '__main__': db.connect() app.run()
Comment out login system for debugging
Comment out login system for debugging
Python
mit
lcdi/Inventory,lcdi/Inventory,lcdi/Inventory,lcdi/Inventory
from flask import Flask, render_template, url_for, redirect from flask import session, escape, request from peewee import * #from datetime import date app = Flask(__name__) # http://docs.peewee-orm.com/en/latest/peewee/quickstart.html database = SqliteDatabase('developmentData.db') class Device(Model): idNumber = IntField() serialNumber = CharField() typeCategory = CharField() description = TextField() issues = TextField() photo = CharField() quality = CharField() @app.route('/') def index(): # http://flask.pocoo.org/snippets/15/ if 'username' in session: return render_template('inventory.html', inventoryData="", deviceLogData="") return redirect(url_for('login')); @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) return render_template('login.html') if __name__ == '__main__': db.connect() app.run() Comment out login system for debugging
from flask import Flask, render_template, url_for, redirect from flask import session, escape, request from peewee import * #from datetime import date app = Flask(__name__) # http://docs.peewee-orm.com/en/latest/peewee/quickstart.html database = SqliteDatabase('developmentData.db') class Device(Model): idNumber = IntField() serialNumber = CharField() typeCategory = CharField() description = TextField() issues = TextField() photo = CharField() quality = CharField() @app.route('/') def index(): # http://flask.pocoo.org/snippets/15/ #if 'username' in session: return render_template('inventory.html', inventoryData="", deviceLogData="") #return redirect(url_for('login')); #@app.route('/login', methods=['GET', 'POST']) #def login(): # if request.method == 'POST': # session['username'] = request.form['username'] # return redirect(url_for('index')) # return render_template('login.html') if __name__ == '__main__': db.connect() app.run()
<commit_before>from flask import Flask, render_template, url_for, redirect from flask import session, escape, request from peewee import * #from datetime import date app = Flask(__name__) # http://docs.peewee-orm.com/en/latest/peewee/quickstart.html database = SqliteDatabase('developmentData.db') class Device(Model): idNumber = IntField() serialNumber = CharField() typeCategory = CharField() description = TextField() issues = TextField() photo = CharField() quality = CharField() @app.route('/') def index(): # http://flask.pocoo.org/snippets/15/ if 'username' in session: return render_template('inventory.html', inventoryData="", deviceLogData="") return redirect(url_for('login')); @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) return render_template('login.html') if __name__ == '__main__': db.connect() app.run() <commit_msg>Comment out login system for debugging<commit_after>
from flask import Flask, render_template, url_for, redirect from flask import session, escape, request from peewee import * #from datetime import date app = Flask(__name__) # http://docs.peewee-orm.com/en/latest/peewee/quickstart.html database = SqliteDatabase('developmentData.db') class Device(Model): idNumber = IntField() serialNumber = CharField() typeCategory = CharField() description = TextField() issues = TextField() photo = CharField() quality = CharField() @app.route('/') def index(): # http://flask.pocoo.org/snippets/15/ #if 'username' in session: return render_template('inventory.html', inventoryData="", deviceLogData="") #return redirect(url_for('login')); #@app.route('/login', methods=['GET', 'POST']) #def login(): # if request.method == 'POST': # session['username'] = request.form['username'] # return redirect(url_for('index')) # return render_template('login.html') if __name__ == '__main__': db.connect() app.run()
from flask import Flask, render_template, url_for, redirect from flask import session, escape, request from peewee import * #from datetime import date app = Flask(__name__) # http://docs.peewee-orm.com/en/latest/peewee/quickstart.html database = SqliteDatabase('developmentData.db') class Device(Model): idNumber = IntField() serialNumber = CharField() typeCategory = CharField() description = TextField() issues = TextField() photo = CharField() quality = CharField() @app.route('/') def index(): # http://flask.pocoo.org/snippets/15/ if 'username' in session: return render_template('inventory.html', inventoryData="", deviceLogData="") return redirect(url_for('login')); @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) return render_template('login.html') if __name__ == '__main__': db.connect() app.run() Comment out login system for debuggingfrom flask import Flask, render_template, url_for, redirect from flask import session, escape, request from peewee import * #from datetime import date app = Flask(__name__) # http://docs.peewee-orm.com/en/latest/peewee/quickstart.html database = SqliteDatabase('developmentData.db') class Device(Model): idNumber = IntField() serialNumber = CharField() typeCategory = CharField() description = TextField() issues = TextField() photo = CharField() quality = CharField() @app.route('/') def index(): # http://flask.pocoo.org/snippets/15/ #if 'username' in session: return render_template('inventory.html', inventoryData="", deviceLogData="") #return redirect(url_for('login')); #@app.route('/login', methods=['GET', 'POST']) #def login(): # if request.method == 'POST': # session['username'] = request.form['username'] # return redirect(url_for('index')) # return render_template('login.html') if __name__ == '__main__': db.connect() app.run()
<commit_before>from flask import Flask, render_template, url_for, redirect from flask import session, escape, request from peewee import * #from datetime import date app = Flask(__name__) # http://docs.peewee-orm.com/en/latest/peewee/quickstart.html database = SqliteDatabase('developmentData.db') class Device(Model): idNumber = IntField() serialNumber = CharField() typeCategory = CharField() description = TextField() issues = TextField() photo = CharField() quality = CharField() @app.route('/') def index(): # http://flask.pocoo.org/snippets/15/ if 'username' in session: return render_template('inventory.html', inventoryData="", deviceLogData="") return redirect(url_for('login')); @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect(url_for('index')) return render_template('login.html') if __name__ == '__main__': db.connect() app.run() <commit_msg>Comment out login system for debugging<commit_after>from flask import Flask, render_template, url_for, redirect from flask import session, escape, request from peewee import * #from datetime import date app = Flask(__name__) # http://docs.peewee-orm.com/en/latest/peewee/quickstart.html database = SqliteDatabase('developmentData.db') class Device(Model): idNumber = IntField() serialNumber = CharField() typeCategory = CharField() description = TextField() issues = TextField() photo = CharField() quality = CharField() @app.route('/') def index(): # http://flask.pocoo.org/snippets/15/ #if 'username' in session: return render_template('inventory.html', inventoryData="", deviceLogData="") #return redirect(url_for('login')); #@app.route('/login', methods=['GET', 'POST']) #def login(): # if request.method == 'POST': # session['username'] = request.form['username'] # return redirect(url_for('index')) # return render_template('login.html') if __name__ == '__main__': db.connect() app.run()
cf822ee4994915cf178c6e603e3cc8726cf7fb82
api/locations/views.py
api/locations/views.py
# -*- coding: utf-8 -*- # Copyright 2016 Steven Oud. All rights reserved. # Use of this source code is governed by a MIT-style license that can be found # in the LICENSE file. from flask import jsonify, Blueprint, abort, request from .models import Location from api.tokens.models import Token from api.auth import requires_auth from api import db, socketio locations = Blueprint('locations', __name__) @locations.route('/') def all(): """Get all locations""" locations = Location.query.all() locations = [location.serialize() for location in locations] return jsonify(data=locations) @locations.route('/<int:location_id>') def status(location_id): """Get a location""" location = Location.query.get(location_id) if location: return jsonify(data=location.serialize()) abort(404, 'Location {} not found.'.format(location_id)) @locations.route('/toggle', methods=['PUT']) @requires_auth def update(): """Toggle the status of a location""" hash = request.headers.get('authorization') location = Location.query \ .join(Location.token) \ .filter_by(hash=hash) \ .first() location.occupied = not location.occupied db.session.commit() socketio.emit('location', {'occupied': location.occupied}, broadcast=True, namespace='/ws') return jsonify(), 204
# -*- coding: utf-8 -*- # Copyright 2016 Steven Oud. All rights reserved. # Use of this source code is governed by a MIT-style license that can be found # in the LICENSE file. from flask import jsonify, Blueprint, abort, request from .models import Location from api.tokens.models import Token from api.auth import requires_auth from api import db, socketio locations = Blueprint('locations', __name__) @locations.route('/') def all(): """Get all locations""" locations = Location.query.all() locations = [location.serialize() for location in locations] return jsonify(data=locations) @locations.route('/<int:location_id>') def status(location_id): """Get a location""" location = Location.query.get(location_id) if location: return jsonify(data=location.serialize()) abort(404, 'Location {} not found.'.format(location_id)) @locations.route('/toggle', methods=['PUT']) @requires_auth def update(): """Toggle the status of a location""" hash = request.headers.get('authorization') location = Location.query \ .join(Location.token) \ .filter_by(hash=hash) \ .first() location.occupied = not location.occupied db.session.commit() socketio.emit('location', location.serialize(), broadcast=True, namespace='/ws') return jsonify(), 204
Send whole location object over websocket
Send whole location object over websocket
Python
mit
Proj-P/project-p-api,Proj-P/project-p-api
# -*- coding: utf-8 -*- # Copyright 2016 Steven Oud. All rights reserved. # Use of this source code is governed by a MIT-style license that can be found # in the LICENSE file. from flask import jsonify, Blueprint, abort, request from .models import Location from api.tokens.models import Token from api.auth import requires_auth from api import db, socketio locations = Blueprint('locations', __name__) @locations.route('/') def all(): """Get all locations""" locations = Location.query.all() locations = [location.serialize() for location in locations] return jsonify(data=locations) @locations.route('/<int:location_id>') def status(location_id): """Get a location""" location = Location.query.get(location_id) if location: return jsonify(data=location.serialize()) abort(404, 'Location {} not found.'.format(location_id)) @locations.route('/toggle', methods=['PUT']) @requires_auth def update(): """Toggle the status of a location""" hash = request.headers.get('authorization') location = Location.query \ .join(Location.token) \ .filter_by(hash=hash) \ .first() location.occupied = not location.occupied db.session.commit() socketio.emit('location', {'occupied': location.occupied}, broadcast=True, namespace='/ws') return jsonify(), 204 Send whole location object over websocket
# -*- coding: utf-8 -*- # Copyright 2016 Steven Oud. All rights reserved. # Use of this source code is governed by a MIT-style license that can be found # in the LICENSE file. from flask import jsonify, Blueprint, abort, request from .models import Location from api.tokens.models import Token from api.auth import requires_auth from api import db, socketio locations = Blueprint('locations', __name__) @locations.route('/') def all(): """Get all locations""" locations = Location.query.all() locations = [location.serialize() for location in locations] return jsonify(data=locations) @locations.route('/<int:location_id>') def status(location_id): """Get a location""" location = Location.query.get(location_id) if location: return jsonify(data=location.serialize()) abort(404, 'Location {} not found.'.format(location_id)) @locations.route('/toggle', methods=['PUT']) @requires_auth def update(): """Toggle the status of a location""" hash = request.headers.get('authorization') location = Location.query \ .join(Location.token) \ .filter_by(hash=hash) \ .first() location.occupied = not location.occupied db.session.commit() socketio.emit('location', location.serialize(), broadcast=True, namespace='/ws') return jsonify(), 204
<commit_before># -*- coding: utf-8 -*- # Copyright 2016 Steven Oud. All rights reserved. # Use of this source code is governed by a MIT-style license that can be found # in the LICENSE file. from flask import jsonify, Blueprint, abort, request from .models import Location from api.tokens.models import Token from api.auth import requires_auth from api import db, socketio locations = Blueprint('locations', __name__) @locations.route('/') def all(): """Get all locations""" locations = Location.query.all() locations = [location.serialize() for location in locations] return jsonify(data=locations) @locations.route('/<int:location_id>') def status(location_id): """Get a location""" location = Location.query.get(location_id) if location: return jsonify(data=location.serialize()) abort(404, 'Location {} not found.'.format(location_id)) @locations.route('/toggle', methods=['PUT']) @requires_auth def update(): """Toggle the status of a location""" hash = request.headers.get('authorization') location = Location.query \ .join(Location.token) \ .filter_by(hash=hash) \ .first() location.occupied = not location.occupied db.session.commit() socketio.emit('location', {'occupied': location.occupied}, broadcast=True, namespace='/ws') return jsonify(), 204 <commit_msg>Send whole location object over websocket<commit_after>
# -*- coding: utf-8 -*- # Copyright 2016 Steven Oud. All rights reserved. # Use of this source code is governed by a MIT-style license that can be found # in the LICENSE file. from flask import jsonify, Blueprint, abort, request from .models import Location from api.tokens.models import Token from api.auth import requires_auth from api import db, socketio locations = Blueprint('locations', __name__) @locations.route('/') def all(): """Get all locations""" locations = Location.query.all() locations = [location.serialize() for location in locations] return jsonify(data=locations) @locations.route('/<int:location_id>') def status(location_id): """Get a location""" location = Location.query.get(location_id) if location: return jsonify(data=location.serialize()) abort(404, 'Location {} not found.'.format(location_id)) @locations.route('/toggle', methods=['PUT']) @requires_auth def update(): """Toggle the status of a location""" hash = request.headers.get('authorization') location = Location.query \ .join(Location.token) \ .filter_by(hash=hash) \ .first() location.occupied = not location.occupied db.session.commit() socketio.emit('location', location.serialize(), broadcast=True, namespace='/ws') return jsonify(), 204
# -*- coding: utf-8 -*- # Copyright 2016 Steven Oud. All rights reserved. # Use of this source code is governed by a MIT-style license that can be found # in the LICENSE file. from flask import jsonify, Blueprint, abort, request from .models import Location from api.tokens.models import Token from api.auth import requires_auth from api import db, socketio locations = Blueprint('locations', __name__) @locations.route('/') def all(): """Get all locations""" locations = Location.query.all() locations = [location.serialize() for location in locations] return jsonify(data=locations) @locations.route('/<int:location_id>') def status(location_id): """Get a location""" location = Location.query.get(location_id) if location: return jsonify(data=location.serialize()) abort(404, 'Location {} not found.'.format(location_id)) @locations.route('/toggle', methods=['PUT']) @requires_auth def update(): """Toggle the status of a location""" hash = request.headers.get('authorization') location = Location.query \ .join(Location.token) \ .filter_by(hash=hash) \ .first() location.occupied = not location.occupied db.session.commit() socketio.emit('location', {'occupied': location.occupied}, broadcast=True, namespace='/ws') return jsonify(), 204 Send whole location object over websocket# -*- coding: utf-8 -*- # Copyright 2016 Steven Oud. All rights reserved. # Use of this source code is governed by a MIT-style license that can be found # in the LICENSE file. from flask import jsonify, Blueprint, abort, request from .models import Location from api.tokens.models import Token from api.auth import requires_auth from api import db, socketio locations = Blueprint('locations', __name__) @locations.route('/') def all(): """Get all locations""" locations = Location.query.all() locations = [location.serialize() for location in locations] return jsonify(data=locations) @locations.route('/<int:location_id>') def status(location_id): """Get a location""" location = Location.query.get(location_id) if location: return jsonify(data=location.serialize()) abort(404, 'Location {} not found.'.format(location_id)) @locations.route('/toggle', methods=['PUT']) @requires_auth def update(): """Toggle the status of a location""" hash = request.headers.get('authorization') location = Location.query \ .join(Location.token) \ .filter_by(hash=hash) \ .first() location.occupied = not location.occupied db.session.commit() socketio.emit('location', location.serialize(), broadcast=True, namespace='/ws') return jsonify(), 204
<commit_before># -*- coding: utf-8 -*- # Copyright 2016 Steven Oud. All rights reserved. # Use of this source code is governed by a MIT-style license that can be found # in the LICENSE file. from flask import jsonify, Blueprint, abort, request from .models import Location from api.tokens.models import Token from api.auth import requires_auth from api import db, socketio locations = Blueprint('locations', __name__) @locations.route('/') def all(): """Get all locations""" locations = Location.query.all() locations = [location.serialize() for location in locations] return jsonify(data=locations) @locations.route('/<int:location_id>') def status(location_id): """Get a location""" location = Location.query.get(location_id) if location: return jsonify(data=location.serialize()) abort(404, 'Location {} not found.'.format(location_id)) @locations.route('/toggle', methods=['PUT']) @requires_auth def update(): """Toggle the status of a location""" hash = request.headers.get('authorization') location = Location.query \ .join(Location.token) \ .filter_by(hash=hash) \ .first() location.occupied = not location.occupied db.session.commit() socketio.emit('location', {'occupied': location.occupied}, broadcast=True, namespace='/ws') return jsonify(), 204 <commit_msg>Send whole location object over websocket<commit_after># -*- coding: utf-8 -*- # Copyright 2016 Steven Oud. All rights reserved. # Use of this source code is governed by a MIT-style license that can be found # in the LICENSE file. from flask import jsonify, Blueprint, abort, request from .models import Location from api.tokens.models import Token from api.auth import requires_auth from api import db, socketio locations = Blueprint('locations', __name__) @locations.route('/') def all(): """Get all locations""" locations = Location.query.all() locations = [location.serialize() for location in locations] return jsonify(data=locations) @locations.route('/<int:location_id>') def status(location_id): """Get a location""" location = Location.query.get(location_id) if location: return jsonify(data=location.serialize()) abort(404, 'Location {} not found.'.format(location_id)) @locations.route('/toggle', methods=['PUT']) @requires_auth def update(): """Toggle the status of a location""" hash = request.headers.get('authorization') location = Location.query \ .join(Location.token) \ .filter_by(hash=hash) \ .first() location.occupied = not location.occupied db.session.commit() socketio.emit('location', location.serialize(), broadcast=True, namespace='/ws') return jsonify(), 204
836fd354037a6aca6898b41a9d62ada31f1ee6ba
rasterio/tool.py
rasterio/tool.py
import code import collections import logging import sys try: import matplotlib.pyplot as plt except ImportError: plt = None import numpy import rasterio logger = logging.getLogger('rasterio') Stats = collections.namedtuple('Stats', ['min', 'max', 'mean']) # Collect dictionary of functions for use in the interpreter in main() funcs = locals() def show(source, cmap='gray'): """Show a raster using matplotlib. The raster may be either an ndarray or a (dataset, bidx) tuple. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source if plt is not None: plt.imshow(arr, cmap=cmap) plt.show() else: raise ImportError("matplotlib could not be imported") def stats(source): """Return a tuple with raster min, max, and mean. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source return Stats(numpy.min(arr), numpy.max(arr), numpy.mean(arr)) def main(banner, dataset): """ Main entry point for use with IPython interpreter """ import IPython locals = dict(funcs, src=dataset, np=numpy, rio=rasterio, plt=plt) IPython.start_ipython(argv=[], user_ns=locals) return 0
import code import collections import logging import sys try: import matplotlib.pyplot as plt except ImportError: plt = None import numpy import rasterio logger = logging.getLogger('rasterio') Stats = collections.namedtuple('Stats', ['min', 'max', 'mean']) # Collect dictionary of functions for use in the interpreter in main() funcs = locals() def show(source, cmap='gray'): """Show a raster using matplotlib. The raster may be either an ndarray or a (dataset, bidx) tuple. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source if plt is not None: plt.imshow(arr, cmap=cmap) plt.show() else: raise ImportError("matplotlib could not be imported") def stats(source): """Return a tuple with raster min, max, and mean. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source return Stats(numpy.min(arr), numpy.max(arr), numpy.mean(arr)) def main(banner, dataset): """ Main entry point for use with IPython interpreter """ import IPython locals = dict(funcs, src=dataset, np=numpy, rio=rasterio, plt=plt) IPython.InteractiveShell.banner1 = banner IPython.start_ipython(argv=[], user_ns=locals) return 0
Print the banner in IPython
Print the banner in IPython
Python
bsd-3-clause
clembou/rasterio,brendan-ward/rasterio,kapadia/rasterio,clembou/rasterio,njwilson23/rasterio,perrygeo/rasterio,brendan-ward/rasterio,perrygeo/rasterio,youngpm/rasterio,johanvdw/rasterio,clembou/rasterio,kapadia/rasterio,njwilson23/rasterio,perrygeo/rasterio,youngpm/rasterio,brendan-ward/rasterio,njwilson23/rasterio,johanvdw/rasterio,kapadia/rasterio,johanvdw/rasterio,youngpm/rasterio
import code import collections import logging import sys try: import matplotlib.pyplot as plt except ImportError: plt = None import numpy import rasterio logger = logging.getLogger('rasterio') Stats = collections.namedtuple('Stats', ['min', 'max', 'mean']) # Collect dictionary of functions for use in the interpreter in main() funcs = locals() def show(source, cmap='gray'): """Show a raster using matplotlib. The raster may be either an ndarray or a (dataset, bidx) tuple. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source if plt is not None: plt.imshow(arr, cmap=cmap) plt.show() else: raise ImportError("matplotlib could not be imported") def stats(source): """Return a tuple with raster min, max, and mean. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source return Stats(numpy.min(arr), numpy.max(arr), numpy.mean(arr)) def main(banner, dataset): """ Main entry point for use with IPython interpreter """ import IPython locals = dict(funcs, src=dataset, np=numpy, rio=rasterio, plt=plt) IPython.start_ipython(argv=[], user_ns=locals) return 0 Print the banner in IPython
import code import collections import logging import sys try: import matplotlib.pyplot as plt except ImportError: plt = None import numpy import rasterio logger = logging.getLogger('rasterio') Stats = collections.namedtuple('Stats', ['min', 'max', 'mean']) # Collect dictionary of functions for use in the interpreter in main() funcs = locals() def show(source, cmap='gray'): """Show a raster using matplotlib. The raster may be either an ndarray or a (dataset, bidx) tuple. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source if plt is not None: plt.imshow(arr, cmap=cmap) plt.show() else: raise ImportError("matplotlib could not be imported") def stats(source): """Return a tuple with raster min, max, and mean. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source return Stats(numpy.min(arr), numpy.max(arr), numpy.mean(arr)) def main(banner, dataset): """ Main entry point for use with IPython interpreter """ import IPython locals = dict(funcs, src=dataset, np=numpy, rio=rasterio, plt=plt) IPython.InteractiveShell.banner1 = banner IPython.start_ipython(argv=[], user_ns=locals) return 0
<commit_before> import code import collections import logging import sys try: import matplotlib.pyplot as plt except ImportError: plt = None import numpy import rasterio logger = logging.getLogger('rasterio') Stats = collections.namedtuple('Stats', ['min', 'max', 'mean']) # Collect dictionary of functions for use in the interpreter in main() funcs = locals() def show(source, cmap='gray'): """Show a raster using matplotlib. The raster may be either an ndarray or a (dataset, bidx) tuple. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source if plt is not None: plt.imshow(arr, cmap=cmap) plt.show() else: raise ImportError("matplotlib could not be imported") def stats(source): """Return a tuple with raster min, max, and mean. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source return Stats(numpy.min(arr), numpy.max(arr), numpy.mean(arr)) def main(banner, dataset): """ Main entry point for use with IPython interpreter """ import IPython locals = dict(funcs, src=dataset, np=numpy, rio=rasterio, plt=plt) IPython.start_ipython(argv=[], user_ns=locals) return 0 <commit_msg>Print the banner in IPython<commit_after>
import code import collections import logging import sys try: import matplotlib.pyplot as plt except ImportError: plt = None import numpy import rasterio logger = logging.getLogger('rasterio') Stats = collections.namedtuple('Stats', ['min', 'max', 'mean']) # Collect dictionary of functions for use in the interpreter in main() funcs = locals() def show(source, cmap='gray'): """Show a raster using matplotlib. The raster may be either an ndarray or a (dataset, bidx) tuple. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source if plt is not None: plt.imshow(arr, cmap=cmap) plt.show() else: raise ImportError("matplotlib could not be imported") def stats(source): """Return a tuple with raster min, max, and mean. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source return Stats(numpy.min(arr), numpy.max(arr), numpy.mean(arr)) def main(banner, dataset): """ Main entry point for use with IPython interpreter """ import IPython locals = dict(funcs, src=dataset, np=numpy, rio=rasterio, plt=plt) IPython.InteractiveShell.banner1 = banner IPython.start_ipython(argv=[], user_ns=locals) return 0
import code import collections import logging import sys try: import matplotlib.pyplot as plt except ImportError: plt = None import numpy import rasterio logger = logging.getLogger('rasterio') Stats = collections.namedtuple('Stats', ['min', 'max', 'mean']) # Collect dictionary of functions for use in the interpreter in main() funcs = locals() def show(source, cmap='gray'): """Show a raster using matplotlib. The raster may be either an ndarray or a (dataset, bidx) tuple. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source if plt is not None: plt.imshow(arr, cmap=cmap) plt.show() else: raise ImportError("matplotlib could not be imported") def stats(source): """Return a tuple with raster min, max, and mean. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source return Stats(numpy.min(arr), numpy.max(arr), numpy.mean(arr)) def main(banner, dataset): """ Main entry point for use with IPython interpreter """ import IPython locals = dict(funcs, src=dataset, np=numpy, rio=rasterio, plt=plt) IPython.start_ipython(argv=[], user_ns=locals) return 0 Print the banner in IPython import code import collections import logging import sys try: import matplotlib.pyplot as plt except ImportError: plt = None import numpy import rasterio logger = logging.getLogger('rasterio') Stats = collections.namedtuple('Stats', ['min', 'max', 'mean']) # Collect dictionary of functions for use in the interpreter in main() funcs = locals() def show(source, cmap='gray'): """Show a raster using matplotlib. The raster may be either an ndarray or a (dataset, bidx) tuple. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source if plt is not None: plt.imshow(arr, cmap=cmap) plt.show() else: raise ImportError("matplotlib could not be imported") def stats(source): """Return a tuple with raster min, max, and mean. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source return Stats(numpy.min(arr), numpy.max(arr), numpy.mean(arr)) def main(banner, dataset): """ Main entry point for use with IPython interpreter """ import IPython locals = dict(funcs, src=dataset, np=numpy, rio=rasterio, plt=plt) IPython.InteractiveShell.banner1 = banner IPython.start_ipython(argv=[], user_ns=locals) return 0
<commit_before> import code import collections import logging import sys try: import matplotlib.pyplot as plt except ImportError: plt = None import numpy import rasterio logger = logging.getLogger('rasterio') Stats = collections.namedtuple('Stats', ['min', 'max', 'mean']) # Collect dictionary of functions for use in the interpreter in main() funcs = locals() def show(source, cmap='gray'): """Show a raster using matplotlib. The raster may be either an ndarray or a (dataset, bidx) tuple. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source if plt is not None: plt.imshow(arr, cmap=cmap) plt.show() else: raise ImportError("matplotlib could not be imported") def stats(source): """Return a tuple with raster min, max, and mean. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source return Stats(numpy.min(arr), numpy.max(arr), numpy.mean(arr)) def main(banner, dataset): """ Main entry point for use with IPython interpreter """ import IPython locals = dict(funcs, src=dataset, np=numpy, rio=rasterio, plt=plt) IPython.start_ipython(argv=[], user_ns=locals) return 0 <commit_msg>Print the banner in IPython<commit_after> import code import collections import logging import sys try: import matplotlib.pyplot as plt except ImportError: plt = None import numpy import rasterio logger = logging.getLogger('rasterio') Stats = collections.namedtuple('Stats', ['min', 'max', 'mean']) # Collect dictionary of functions for use in the interpreter in main() funcs = locals() def show(source, cmap='gray'): """Show a raster using matplotlib. The raster may be either an ndarray or a (dataset, bidx) tuple. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source if plt is not None: plt.imshow(arr, cmap=cmap) plt.show() else: raise ImportError("matplotlib could not be imported") def stats(source): """Return a tuple with raster min, max, and mean. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source return Stats(numpy.min(arr), numpy.max(arr), numpy.mean(arr)) def main(banner, dataset): """ Main entry point for use with IPython interpreter """ import IPython locals = dict(funcs, src=dataset, np=numpy, rio=rasterio, plt=plt) IPython.InteractiveShell.banner1 = banner IPython.start_ipython(argv=[], user_ns=locals) return 0
c4803aca65f05d30285c6b7cad0571cd4baa599b
generator/test/runner.py
generator/test/runner.py
#!/usr/bin/env python3 """ Main entry point to run all tests """ import sys from pathlib import Path from unittest import TestLoader, TestSuite, TextTestRunner PATH = Path(__file__).absolute() sys.path.append(PATH.parents[1].joinpath('rpc_spec/InterfaceParser').as_posix()) sys.path.append(PATH.parents[1].as_posix()) try: from test_enums import TestEnumsProducer from test_functions import TestFunctionsProducer from test_structs import TestStructsProducer from test_code_format_and_quality import CodeFormatAndQuality except ImportError as message: print('{}. probably you did not initialize submodule'.format(message)) sys.exit(1) def main(): """ Main entry point to run all tests """ suite = TestSuite() suite.addTests(TestLoader().loadTestsFromTestCase(TestFunctionsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestEnumsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestStructsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(CodeFormatAndQuality)) ret = not runner.run(suite).wasSuccessful() sys.exit(ret) if __name__ == '__main__': main()
#!/usr/bin/env python3 """ Main entry point to run all tests """ import sys from pathlib import Path from unittest import TestLoader, TestSuite, TextTestRunner PATH = Path(__file__).absolute() sys.path.append(PATH.parents[1].joinpath('rpc_spec/InterfaceParser').as_posix()) sys.path.append(PATH.parents[1].as_posix()) try: from test_enums import TestEnumsProducer from test_functions import TestFunctionsProducer from test_structs import TestStructsProducer from test_code_format_and_quality import CodeFormatAndQuality except ImportError as message: print('{}. probably you did not initialize submodule'.format(message)) sys.exit(1) def main(): """ Main entry point to run all tests """ suite = TestSuite() suite.addTests(TestLoader().loadTestsFromTestCase(TestFunctionsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestEnumsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestStructsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(CodeFormatAndQuality)) runner = TextTestRunner(verbosity=2) ret = not runner.run(suite).wasSuccessful() sys.exit(ret) if __name__ == '__main__': main()
Add a line that was removed by mistake
Add a line that was removed by mistake
Python
bsd-3-clause
smartdevicelink/sdl_android
#!/usr/bin/env python3 """ Main entry point to run all tests """ import sys from pathlib import Path from unittest import TestLoader, TestSuite, TextTestRunner PATH = Path(__file__).absolute() sys.path.append(PATH.parents[1].joinpath('rpc_spec/InterfaceParser').as_posix()) sys.path.append(PATH.parents[1].as_posix()) try: from test_enums import TestEnumsProducer from test_functions import TestFunctionsProducer from test_structs import TestStructsProducer from test_code_format_and_quality import CodeFormatAndQuality except ImportError as message: print('{}. probably you did not initialize submodule'.format(message)) sys.exit(1) def main(): """ Main entry point to run all tests """ suite = TestSuite() suite.addTests(TestLoader().loadTestsFromTestCase(TestFunctionsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestEnumsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestStructsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(CodeFormatAndQuality)) ret = not runner.run(suite).wasSuccessful() sys.exit(ret) if __name__ == '__main__': main() Add a line that was removed by mistake
#!/usr/bin/env python3 """ Main entry point to run all tests """ import sys from pathlib import Path from unittest import TestLoader, TestSuite, TextTestRunner PATH = Path(__file__).absolute() sys.path.append(PATH.parents[1].joinpath('rpc_spec/InterfaceParser').as_posix()) sys.path.append(PATH.parents[1].as_posix()) try: from test_enums import TestEnumsProducer from test_functions import TestFunctionsProducer from test_structs import TestStructsProducer from test_code_format_and_quality import CodeFormatAndQuality except ImportError as message: print('{}. probably you did not initialize submodule'.format(message)) sys.exit(1) def main(): """ Main entry point to run all tests """ suite = TestSuite() suite.addTests(TestLoader().loadTestsFromTestCase(TestFunctionsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestEnumsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestStructsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(CodeFormatAndQuality)) runner = TextTestRunner(verbosity=2) ret = not runner.run(suite).wasSuccessful() sys.exit(ret) if __name__ == '__main__': main()
<commit_before>#!/usr/bin/env python3 """ Main entry point to run all tests """ import sys from pathlib import Path from unittest import TestLoader, TestSuite, TextTestRunner PATH = Path(__file__).absolute() sys.path.append(PATH.parents[1].joinpath('rpc_spec/InterfaceParser').as_posix()) sys.path.append(PATH.parents[1].as_posix()) try: from test_enums import TestEnumsProducer from test_functions import TestFunctionsProducer from test_structs import TestStructsProducer from test_code_format_and_quality import CodeFormatAndQuality except ImportError as message: print('{}. probably you did not initialize submodule'.format(message)) sys.exit(1) def main(): """ Main entry point to run all tests """ suite = TestSuite() suite.addTests(TestLoader().loadTestsFromTestCase(TestFunctionsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestEnumsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestStructsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(CodeFormatAndQuality)) ret = not runner.run(suite).wasSuccessful() sys.exit(ret) if __name__ == '__main__': main() <commit_msg>Add a line that was removed by mistake<commit_after>
#!/usr/bin/env python3 """ Main entry point to run all tests """ import sys from pathlib import Path from unittest import TestLoader, TestSuite, TextTestRunner PATH = Path(__file__).absolute() sys.path.append(PATH.parents[1].joinpath('rpc_spec/InterfaceParser').as_posix()) sys.path.append(PATH.parents[1].as_posix()) try: from test_enums import TestEnumsProducer from test_functions import TestFunctionsProducer from test_structs import TestStructsProducer from test_code_format_and_quality import CodeFormatAndQuality except ImportError as message: print('{}. probably you did not initialize submodule'.format(message)) sys.exit(1) def main(): """ Main entry point to run all tests """ suite = TestSuite() suite.addTests(TestLoader().loadTestsFromTestCase(TestFunctionsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestEnumsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestStructsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(CodeFormatAndQuality)) runner = TextTestRunner(verbosity=2) ret = not runner.run(suite).wasSuccessful() sys.exit(ret) if __name__ == '__main__': main()
#!/usr/bin/env python3 """ Main entry point to run all tests """ import sys from pathlib import Path from unittest import TestLoader, TestSuite, TextTestRunner PATH = Path(__file__).absolute() sys.path.append(PATH.parents[1].joinpath('rpc_spec/InterfaceParser').as_posix()) sys.path.append(PATH.parents[1].as_posix()) try: from test_enums import TestEnumsProducer from test_functions import TestFunctionsProducer from test_structs import TestStructsProducer from test_code_format_and_quality import CodeFormatAndQuality except ImportError as message: print('{}. probably you did not initialize submodule'.format(message)) sys.exit(1) def main(): """ Main entry point to run all tests """ suite = TestSuite() suite.addTests(TestLoader().loadTestsFromTestCase(TestFunctionsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestEnumsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestStructsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(CodeFormatAndQuality)) ret = not runner.run(suite).wasSuccessful() sys.exit(ret) if __name__ == '__main__': main() Add a line that was removed by mistake#!/usr/bin/env python3 """ Main entry point to run all tests """ import sys from pathlib import Path from unittest import TestLoader, TestSuite, TextTestRunner PATH = Path(__file__).absolute() sys.path.append(PATH.parents[1].joinpath('rpc_spec/InterfaceParser').as_posix()) sys.path.append(PATH.parents[1].as_posix()) try: from test_enums import TestEnumsProducer from test_functions import TestFunctionsProducer from test_structs import TestStructsProducer from test_code_format_and_quality import CodeFormatAndQuality except ImportError as message: print('{}. probably you did not initialize submodule'.format(message)) sys.exit(1) def main(): """ Main entry point to run all tests """ suite = TestSuite() suite.addTests(TestLoader().loadTestsFromTestCase(TestFunctionsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestEnumsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestStructsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(CodeFormatAndQuality)) runner = TextTestRunner(verbosity=2) ret = not runner.run(suite).wasSuccessful() sys.exit(ret) if __name__ == '__main__': main()
<commit_before>#!/usr/bin/env python3 """ Main entry point to run all tests """ import sys from pathlib import Path from unittest import TestLoader, TestSuite, TextTestRunner PATH = Path(__file__).absolute() sys.path.append(PATH.parents[1].joinpath('rpc_spec/InterfaceParser').as_posix()) sys.path.append(PATH.parents[1].as_posix()) try: from test_enums import TestEnumsProducer from test_functions import TestFunctionsProducer from test_structs import TestStructsProducer from test_code_format_and_quality import CodeFormatAndQuality except ImportError as message: print('{}. probably you did not initialize submodule'.format(message)) sys.exit(1) def main(): """ Main entry point to run all tests """ suite = TestSuite() suite.addTests(TestLoader().loadTestsFromTestCase(TestFunctionsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestEnumsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestStructsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(CodeFormatAndQuality)) ret = not runner.run(suite).wasSuccessful() sys.exit(ret) if __name__ == '__main__': main() <commit_msg>Add a line that was removed by mistake<commit_after>#!/usr/bin/env python3 """ Main entry point to run all tests """ import sys from pathlib import Path from unittest import TestLoader, TestSuite, TextTestRunner PATH = Path(__file__).absolute() sys.path.append(PATH.parents[1].joinpath('rpc_spec/InterfaceParser').as_posix()) sys.path.append(PATH.parents[1].as_posix()) try: from test_enums import TestEnumsProducer from test_functions import TestFunctionsProducer from test_structs import TestStructsProducer from test_code_format_and_quality import CodeFormatAndQuality except ImportError as message: print('{}. probably you did not initialize submodule'.format(message)) sys.exit(1) def main(): """ Main entry point to run all tests """ suite = TestSuite() suite.addTests(TestLoader().loadTestsFromTestCase(TestFunctionsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestEnumsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(TestStructsProducer)) suite.addTests(TestLoader().loadTestsFromTestCase(CodeFormatAndQuality)) runner = TextTestRunner(verbosity=2) ret = not runner.run(suite).wasSuccessful() sys.exit(ret) if __name__ == '__main__': main()
5a6b19f956dfde65a1d8316fd4bebe4697846e45
connman_dispatcher/detect.py
connman_dispatcher/detect.py
import glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] def property_changed(_, message): if message.get_member() == "PropertyChanged": _, state = message.get_args_list() if state == 'online' and not detector.is_online: logger.info('network state change: online' ) detector.emit('up') detector.is_online = True elif state == 'idle': logger.info('network state change: offline' ) detector.emit('down') detector.is_online = False detector = EventEmitter() detector.is_online = is_online() DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() bus.add_match_string_non_blocking("interface='net.connman.Manager'") bus.add_message_filter(property_changed) manager = dbus.Interface(bus.get_object('net.connman', "/"), 'net.connman.Manager') def is_online(): properties = manager.GetProperties() if properties['State'] == 'online': return True return False def run(): mainloop = glib.MainLoop() mainloop.run() detector.run = run detector.is_online = is_online
import glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] def property_changed(_, message): if message.get_member() == "PropertyChanged": _, state = message.get_args_list() if state == 'online' and detector.state == 'offline': logger.info('network state change: online' ) detector.emit('up') detector.state = 'online' elif state == 'idle': logger.info('network state change: offline' ) detector.emit('down') detector.state = 'online' detector = EventEmitter() DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() bus.add_match_string_non_blocking("interface='net.connman.Manager'") bus.add_message_filter(property_changed) manager = dbus.Interface(bus.get_object('net.connman', "/"), 'net.connman.Manager') def is_online(): properties = manager.GetProperties() if properties['State'] == 'online': return True return False def run(): mainloop = glib.MainLoop() mainloop.run() detector.run = run detector.is_online = is_online detector.state = 'online' if is_online() else 'offline'
Use .state instead of .is_online to keep internal state
Use .state instead of .is_online to keep internal state
Python
isc
a-sk/connman-dispatcher
import glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] def property_changed(_, message): if message.get_member() == "PropertyChanged": _, state = message.get_args_list() if state == 'online' and not detector.is_online: logger.info('network state change: online' ) detector.emit('up') detector.is_online = True elif state == 'idle': logger.info('network state change: offline' ) detector.emit('down') detector.is_online = False detector = EventEmitter() detector.is_online = is_online() DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() bus.add_match_string_non_blocking("interface='net.connman.Manager'") bus.add_message_filter(property_changed) manager = dbus.Interface(bus.get_object('net.connman', "/"), 'net.connman.Manager') def is_online(): properties = manager.GetProperties() if properties['State'] == 'online': return True return False def run(): mainloop = glib.MainLoop() mainloop.run() detector.run = run detector.is_online = is_online Use .state instead of .is_online to keep internal state
import glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] def property_changed(_, message): if message.get_member() == "PropertyChanged": _, state = message.get_args_list() if state == 'online' and detector.state == 'offline': logger.info('network state change: online' ) detector.emit('up') detector.state = 'online' elif state == 'idle': logger.info('network state change: offline' ) detector.emit('down') detector.state = 'online' detector = EventEmitter() DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() bus.add_match_string_non_blocking("interface='net.connman.Manager'") bus.add_message_filter(property_changed) manager = dbus.Interface(bus.get_object('net.connman', "/"), 'net.connman.Manager') def is_online(): properties = manager.GetProperties() if properties['State'] == 'online': return True return False def run(): mainloop = glib.MainLoop() mainloop.run() detector.run = run detector.is_online = is_online detector.state = 'online' if is_online() else 'offline'
<commit_before>import glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] def property_changed(_, message): if message.get_member() == "PropertyChanged": _, state = message.get_args_list() if state == 'online' and not detector.is_online: logger.info('network state change: online' ) detector.emit('up') detector.is_online = True elif state == 'idle': logger.info('network state change: offline' ) detector.emit('down') detector.is_online = False detector = EventEmitter() detector.is_online = is_online() DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() bus.add_match_string_non_blocking("interface='net.connman.Manager'") bus.add_message_filter(property_changed) manager = dbus.Interface(bus.get_object('net.connman', "/"), 'net.connman.Manager') def is_online(): properties = manager.GetProperties() if properties['State'] == 'online': return True return False def run(): mainloop = glib.MainLoop() mainloop.run() detector.run = run detector.is_online = is_online <commit_msg>Use .state instead of .is_online to keep internal state<commit_after>
import glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] def property_changed(_, message): if message.get_member() == "PropertyChanged": _, state = message.get_args_list() if state == 'online' and detector.state == 'offline': logger.info('network state change: online' ) detector.emit('up') detector.state = 'online' elif state == 'idle': logger.info('network state change: offline' ) detector.emit('down') detector.state = 'online' detector = EventEmitter() DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() bus.add_match_string_non_blocking("interface='net.connman.Manager'") bus.add_message_filter(property_changed) manager = dbus.Interface(bus.get_object('net.connman', "/"), 'net.connman.Manager') def is_online(): properties = manager.GetProperties() if properties['State'] == 'online': return True return False def run(): mainloop = glib.MainLoop() mainloop.run() detector.run = run detector.is_online = is_online detector.state = 'online' if is_online() else 'offline'
import glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] def property_changed(_, message): if message.get_member() == "PropertyChanged": _, state = message.get_args_list() if state == 'online' and not detector.is_online: logger.info('network state change: online' ) detector.emit('up') detector.is_online = True elif state == 'idle': logger.info('network state change: offline' ) detector.emit('down') detector.is_online = False detector = EventEmitter() detector.is_online = is_online() DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() bus.add_match_string_non_blocking("interface='net.connman.Manager'") bus.add_message_filter(property_changed) manager = dbus.Interface(bus.get_object('net.connman', "/"), 'net.connman.Manager') def is_online(): properties = manager.GetProperties() if properties['State'] == 'online': return True return False def run(): mainloop = glib.MainLoop() mainloop.run() detector.run = run detector.is_online = is_online Use .state instead of .is_online to keep internal stateimport glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] def property_changed(_, message): if message.get_member() == "PropertyChanged": _, state = message.get_args_list() if state == 'online' and detector.state == 'offline': logger.info('network state change: online' ) detector.emit('up') detector.state = 'online' elif state == 'idle': logger.info('network state change: offline' ) detector.emit('down') detector.state = 'online' detector = EventEmitter() DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() bus.add_match_string_non_blocking("interface='net.connman.Manager'") bus.add_message_filter(property_changed) manager = dbus.Interface(bus.get_object('net.connman', "/"), 'net.connman.Manager') def is_online(): properties = manager.GetProperties() if properties['State'] == 'online': return True return False def run(): mainloop = glib.MainLoop() mainloop.run() detector.run = run detector.is_online = is_online detector.state = 'online' if is_online() else 'offline'
<commit_before>import glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] def property_changed(_, message): if message.get_member() == "PropertyChanged": _, state = message.get_args_list() if state == 'online' and not detector.is_online: logger.info('network state change: online' ) detector.emit('up') detector.is_online = True elif state == 'idle': logger.info('network state change: offline' ) detector.emit('down') detector.is_online = False detector = EventEmitter() detector.is_online = is_online() DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() bus.add_match_string_non_blocking("interface='net.connman.Manager'") bus.add_message_filter(property_changed) manager = dbus.Interface(bus.get_object('net.connman', "/"), 'net.connman.Manager') def is_online(): properties = manager.GetProperties() if properties['State'] == 'online': return True return False def run(): mainloop = glib.MainLoop() mainloop.run() detector.run = run detector.is_online = is_online <commit_msg>Use .state instead of .is_online to keep internal state<commit_after>import glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] def property_changed(_, message): if message.get_member() == "PropertyChanged": _, state = message.get_args_list() if state == 'online' and detector.state == 'offline': logger.info('network state change: online' ) detector.emit('up') detector.state = 'online' elif state == 'idle': logger.info('network state change: offline' ) detector.emit('down') detector.state = 'online' detector = EventEmitter() DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() bus.add_match_string_non_blocking("interface='net.connman.Manager'") bus.add_message_filter(property_changed) manager = dbus.Interface(bus.get_object('net.connman', "/"), 'net.connman.Manager') def is_online(): properties = manager.GetProperties() if properties['State'] == 'online': return True return False def run(): mainloop = glib.MainLoop() mainloop.run() detector.run = run detector.is_online = is_online detector.state = 'online' if is_online() else 'offline'
cc92850fd6ebe5adc4064df1956377bb4f9aa30c
pyslicer/url_resources.py
pyslicer/url_resources.py
#!/usr/bin/env python # -*- coding: utf-8 -*- class URLResources(object): PROJECT = "/project/" FIELD = "/field/" INDEX = "/index/" QUERY_COUNT_ENTITY = "/query/count/entity/" QUERY_COUNT_ENTITY_TOTAL = "/query/count/entity/total/" QUERY_COUNT_EVENT = "/query/count/event/" QUERY_AGGREGATION = "/query/aggregation/" QUERY_TOP_VALUES = "/query/top_values/" QUERY_EXISTS_ENTITY = "/query/exists/entity/" QUERY_SAVED = "/query/saved/" QUERY_DATA_EXTRACTION_RESULT = "/query/data_extraction/result/" QUERY_DATA_EXTRACTION_SCORE = "/query/data_extraction/score/"
#!/usr/bin/env python # -*- coding: utf-8 -*- class URLResources(object): PROJECT = "/project/" FIELD = "/field/" INDEX = "/index/" QUERY_COUNT_ENTITY = "/query/count/entity/" QUERY_COUNT_ENTITY_TOTAL = "/query/count/entity/total/" QUERY_COUNT_EVENT = "/query/count/event/" QUERY_AGGREGATION = "/query/aggregation/" QUERY_TOP_VALUES = "/query/top_values/" QUERY_EXISTS_ENTITY = "/query/exists/entity/" QUERY_SAVED = "/query/saved/" QUERY_DATA_EXTRACTION_RESULT = "/data_extraction/result/" QUERY_DATA_EXTRACTION_SCORE = "/data_extraction/score/"
Correct endpoint for result and score
Correct endpoint for result and score
Python
mit
SlicingDice/slicingdice-python
#!/usr/bin/env python # -*- coding: utf-8 -*- class URLResources(object): PROJECT = "/project/" FIELD = "/field/" INDEX = "/index/" QUERY_COUNT_ENTITY = "/query/count/entity/" QUERY_COUNT_ENTITY_TOTAL = "/query/count/entity/total/" QUERY_COUNT_EVENT = "/query/count/event/" QUERY_AGGREGATION = "/query/aggregation/" QUERY_TOP_VALUES = "/query/top_values/" QUERY_EXISTS_ENTITY = "/query/exists/entity/" QUERY_SAVED = "/query/saved/" QUERY_DATA_EXTRACTION_RESULT = "/query/data_extraction/result/" QUERY_DATA_EXTRACTION_SCORE = "/query/data_extraction/score/" Correct endpoint for result and score
#!/usr/bin/env python # -*- coding: utf-8 -*- class URLResources(object): PROJECT = "/project/" FIELD = "/field/" INDEX = "/index/" QUERY_COUNT_ENTITY = "/query/count/entity/" QUERY_COUNT_ENTITY_TOTAL = "/query/count/entity/total/" QUERY_COUNT_EVENT = "/query/count/event/" QUERY_AGGREGATION = "/query/aggregation/" QUERY_TOP_VALUES = "/query/top_values/" QUERY_EXISTS_ENTITY = "/query/exists/entity/" QUERY_SAVED = "/query/saved/" QUERY_DATA_EXTRACTION_RESULT = "/data_extraction/result/" QUERY_DATA_EXTRACTION_SCORE = "/data_extraction/score/"
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- class URLResources(object): PROJECT = "/project/" FIELD = "/field/" INDEX = "/index/" QUERY_COUNT_ENTITY = "/query/count/entity/" QUERY_COUNT_ENTITY_TOTAL = "/query/count/entity/total/" QUERY_COUNT_EVENT = "/query/count/event/" QUERY_AGGREGATION = "/query/aggregation/" QUERY_TOP_VALUES = "/query/top_values/" QUERY_EXISTS_ENTITY = "/query/exists/entity/" QUERY_SAVED = "/query/saved/" QUERY_DATA_EXTRACTION_RESULT = "/query/data_extraction/result/" QUERY_DATA_EXTRACTION_SCORE = "/query/data_extraction/score/" <commit_msg>Correct endpoint for result and score<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- class URLResources(object): PROJECT = "/project/" FIELD = "/field/" INDEX = "/index/" QUERY_COUNT_ENTITY = "/query/count/entity/" QUERY_COUNT_ENTITY_TOTAL = "/query/count/entity/total/" QUERY_COUNT_EVENT = "/query/count/event/" QUERY_AGGREGATION = "/query/aggregation/" QUERY_TOP_VALUES = "/query/top_values/" QUERY_EXISTS_ENTITY = "/query/exists/entity/" QUERY_SAVED = "/query/saved/" QUERY_DATA_EXTRACTION_RESULT = "/data_extraction/result/" QUERY_DATA_EXTRACTION_SCORE = "/data_extraction/score/"
#!/usr/bin/env python # -*- coding: utf-8 -*- class URLResources(object): PROJECT = "/project/" FIELD = "/field/" INDEX = "/index/" QUERY_COUNT_ENTITY = "/query/count/entity/" QUERY_COUNT_ENTITY_TOTAL = "/query/count/entity/total/" QUERY_COUNT_EVENT = "/query/count/event/" QUERY_AGGREGATION = "/query/aggregation/" QUERY_TOP_VALUES = "/query/top_values/" QUERY_EXISTS_ENTITY = "/query/exists/entity/" QUERY_SAVED = "/query/saved/" QUERY_DATA_EXTRACTION_RESULT = "/query/data_extraction/result/" QUERY_DATA_EXTRACTION_SCORE = "/query/data_extraction/score/" Correct endpoint for result and score#!/usr/bin/env python # -*- coding: utf-8 -*- class URLResources(object): PROJECT = "/project/" FIELD = "/field/" INDEX = "/index/" QUERY_COUNT_ENTITY = "/query/count/entity/" QUERY_COUNT_ENTITY_TOTAL = "/query/count/entity/total/" QUERY_COUNT_EVENT = "/query/count/event/" QUERY_AGGREGATION = "/query/aggregation/" QUERY_TOP_VALUES = "/query/top_values/" QUERY_EXISTS_ENTITY = "/query/exists/entity/" QUERY_SAVED = "/query/saved/" QUERY_DATA_EXTRACTION_RESULT = "/data_extraction/result/" QUERY_DATA_EXTRACTION_SCORE = "/data_extraction/score/"
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- class URLResources(object): PROJECT = "/project/" FIELD = "/field/" INDEX = "/index/" QUERY_COUNT_ENTITY = "/query/count/entity/" QUERY_COUNT_ENTITY_TOTAL = "/query/count/entity/total/" QUERY_COUNT_EVENT = "/query/count/event/" QUERY_AGGREGATION = "/query/aggregation/" QUERY_TOP_VALUES = "/query/top_values/" QUERY_EXISTS_ENTITY = "/query/exists/entity/" QUERY_SAVED = "/query/saved/" QUERY_DATA_EXTRACTION_RESULT = "/query/data_extraction/result/" QUERY_DATA_EXTRACTION_SCORE = "/query/data_extraction/score/" <commit_msg>Correct endpoint for result and score<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- class URLResources(object): PROJECT = "/project/" FIELD = "/field/" INDEX = "/index/" QUERY_COUNT_ENTITY = "/query/count/entity/" QUERY_COUNT_ENTITY_TOTAL = "/query/count/entity/total/" QUERY_COUNT_EVENT = "/query/count/event/" QUERY_AGGREGATION = "/query/aggregation/" QUERY_TOP_VALUES = "/query/top_values/" QUERY_EXISTS_ENTITY = "/query/exists/entity/" QUERY_SAVED = "/query/saved/" QUERY_DATA_EXTRACTION_RESULT = "/data_extraction/result/" QUERY_DATA_EXTRACTION_SCORE = "/data_extraction/score/"
df6cba06091132065dcbc571fa48a84cb5b11775
project_fish/whats_fresh/tests/test_image_model.py
project_fish/whats_fresh/tests/test_image_model.py
from django.test import TestCase from django.conf import settings from phonenumber_field.modelfields import PhoneNumberField from whats_fresh.models import * from django.contrib.gis.db import models import os import time import sys import datetime class ImageTestCase(TestCase): def setUp(self): self.expected_fields = { 'image': models.ImageField, 'caption': models.TextField, 'created': models.DateTimeField, 'modified': models.DateTimeField, u'id': models.AutoField } def test_fields_exist(self): model = models.get_model('whats_fresh', 'Image') for field, field_type in self.expected_fields.items(): self.assertEqual( field_type, type(model._meta.get_field_by_name(field)[0])) def test_no_additional_fields(self): fields = Image._meta.get_all_field_names() self.assertTrue(sorted(fields) == sorted(self.expected_fields.keys())) def test_created_modified_fields(self): self.assertTrue(Image._meta.get_field('modified').auto_now) self.assertTrue(Image._meta.get_field('created').auto_now_add)
from django.test import TestCase from django.conf import settings from phonenumber_field.modelfields import PhoneNumberField from whats_fresh.models import * from django.contrib.gis.db import models import os import time import sys import datetime class ImageTestCase(TestCase): def setUp(self): self.expected_fields = { 'image': models.ImageField, 'caption': models.TextField, 'created': models.DateTimeField, 'modified': models.DateTimeField, 'id': models.AutoField } def test_fields_exist(self): model = models.get_model('whats_fresh', 'Image') for field, field_type in self.expected_fields.items(): self.assertEqual( field_type, type(model._meta.get_field_by_name(field)[0])) def test_no_additional_fields(self): fields = Image._meta.get_all_field_names() self.assertTrue(sorted(fields) == sorted(self.expected_fields.keys())) def test_created_modified_fields(self): self.assertTrue(Image._meta.get_field('modified').auto_now) self.assertTrue(Image._meta.get_field('created').auto_now_add)
Change id field unicode string to ascii string
Change id field unicode string to ascii string
Python
apache-2.0
osu-cass/whats-fresh-api,osu-cass/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,iCHAIT/whats-fresh-api,iCHAIT/whats-fresh-api
from django.test import TestCase from django.conf import settings from phonenumber_field.modelfields import PhoneNumberField from whats_fresh.models import * from django.contrib.gis.db import models import os import time import sys import datetime class ImageTestCase(TestCase): def setUp(self): self.expected_fields = { 'image': models.ImageField, 'caption': models.TextField, 'created': models.DateTimeField, 'modified': models.DateTimeField, u'id': models.AutoField } def test_fields_exist(self): model = models.get_model('whats_fresh', 'Image') for field, field_type in self.expected_fields.items(): self.assertEqual( field_type, type(model._meta.get_field_by_name(field)[0])) def test_no_additional_fields(self): fields = Image._meta.get_all_field_names() self.assertTrue(sorted(fields) == sorted(self.expected_fields.keys())) def test_created_modified_fields(self): self.assertTrue(Image._meta.get_field('modified').auto_now) self.assertTrue(Image._meta.get_field('created').auto_now_add) Change id field unicode string to ascii string
from django.test import TestCase from django.conf import settings from phonenumber_field.modelfields import PhoneNumberField from whats_fresh.models import * from django.contrib.gis.db import models import os import time import sys import datetime class ImageTestCase(TestCase): def setUp(self): self.expected_fields = { 'image': models.ImageField, 'caption': models.TextField, 'created': models.DateTimeField, 'modified': models.DateTimeField, 'id': models.AutoField } def test_fields_exist(self): model = models.get_model('whats_fresh', 'Image') for field, field_type in self.expected_fields.items(): self.assertEqual( field_type, type(model._meta.get_field_by_name(field)[0])) def test_no_additional_fields(self): fields = Image._meta.get_all_field_names() self.assertTrue(sorted(fields) == sorted(self.expected_fields.keys())) def test_created_modified_fields(self): self.assertTrue(Image._meta.get_field('modified').auto_now) self.assertTrue(Image._meta.get_field('created').auto_now_add)
<commit_before>from django.test import TestCase from django.conf import settings from phonenumber_field.modelfields import PhoneNumberField from whats_fresh.models import * from django.contrib.gis.db import models import os import time import sys import datetime class ImageTestCase(TestCase): def setUp(self): self.expected_fields = { 'image': models.ImageField, 'caption': models.TextField, 'created': models.DateTimeField, 'modified': models.DateTimeField, u'id': models.AutoField } def test_fields_exist(self): model = models.get_model('whats_fresh', 'Image') for field, field_type in self.expected_fields.items(): self.assertEqual( field_type, type(model._meta.get_field_by_name(field)[0])) def test_no_additional_fields(self): fields = Image._meta.get_all_field_names() self.assertTrue(sorted(fields) == sorted(self.expected_fields.keys())) def test_created_modified_fields(self): self.assertTrue(Image._meta.get_field('modified').auto_now) self.assertTrue(Image._meta.get_field('created').auto_now_add) <commit_msg>Change id field unicode string to ascii string<commit_after>
from django.test import TestCase from django.conf import settings from phonenumber_field.modelfields import PhoneNumberField from whats_fresh.models import * from django.contrib.gis.db import models import os import time import sys import datetime class ImageTestCase(TestCase): def setUp(self): self.expected_fields = { 'image': models.ImageField, 'caption': models.TextField, 'created': models.DateTimeField, 'modified': models.DateTimeField, 'id': models.AutoField } def test_fields_exist(self): model = models.get_model('whats_fresh', 'Image') for field, field_type in self.expected_fields.items(): self.assertEqual( field_type, type(model._meta.get_field_by_name(field)[0])) def test_no_additional_fields(self): fields = Image._meta.get_all_field_names() self.assertTrue(sorted(fields) == sorted(self.expected_fields.keys())) def test_created_modified_fields(self): self.assertTrue(Image._meta.get_field('modified').auto_now) self.assertTrue(Image._meta.get_field('created').auto_now_add)
from django.test import TestCase from django.conf import settings from phonenumber_field.modelfields import PhoneNumberField from whats_fresh.models import * from django.contrib.gis.db import models import os import time import sys import datetime class ImageTestCase(TestCase): def setUp(self): self.expected_fields = { 'image': models.ImageField, 'caption': models.TextField, 'created': models.DateTimeField, 'modified': models.DateTimeField, u'id': models.AutoField } def test_fields_exist(self): model = models.get_model('whats_fresh', 'Image') for field, field_type in self.expected_fields.items(): self.assertEqual( field_type, type(model._meta.get_field_by_name(field)[0])) def test_no_additional_fields(self): fields = Image._meta.get_all_field_names() self.assertTrue(sorted(fields) == sorted(self.expected_fields.keys())) def test_created_modified_fields(self): self.assertTrue(Image._meta.get_field('modified').auto_now) self.assertTrue(Image._meta.get_field('created').auto_now_add) Change id field unicode string to ascii stringfrom django.test import TestCase from django.conf import settings from phonenumber_field.modelfields import PhoneNumberField from whats_fresh.models import * from django.contrib.gis.db import models import os import time import sys import datetime class ImageTestCase(TestCase): def setUp(self): self.expected_fields = { 'image': models.ImageField, 'caption': models.TextField, 'created': models.DateTimeField, 'modified': models.DateTimeField, 'id': models.AutoField } def test_fields_exist(self): model = models.get_model('whats_fresh', 'Image') for field, field_type in self.expected_fields.items(): self.assertEqual( field_type, type(model._meta.get_field_by_name(field)[0])) def test_no_additional_fields(self): fields = Image._meta.get_all_field_names() self.assertTrue(sorted(fields) == sorted(self.expected_fields.keys())) def test_created_modified_fields(self): self.assertTrue(Image._meta.get_field('modified').auto_now) self.assertTrue(Image._meta.get_field('created').auto_now_add)
<commit_before>from django.test import TestCase from django.conf import settings from phonenumber_field.modelfields import PhoneNumberField from whats_fresh.models import * from django.contrib.gis.db import models import os import time import sys import datetime class ImageTestCase(TestCase): def setUp(self): self.expected_fields = { 'image': models.ImageField, 'caption': models.TextField, 'created': models.DateTimeField, 'modified': models.DateTimeField, u'id': models.AutoField } def test_fields_exist(self): model = models.get_model('whats_fresh', 'Image') for field, field_type in self.expected_fields.items(): self.assertEqual( field_type, type(model._meta.get_field_by_name(field)[0])) def test_no_additional_fields(self): fields = Image._meta.get_all_field_names() self.assertTrue(sorted(fields) == sorted(self.expected_fields.keys())) def test_created_modified_fields(self): self.assertTrue(Image._meta.get_field('modified').auto_now) self.assertTrue(Image._meta.get_field('created').auto_now_add) <commit_msg>Change id field unicode string to ascii string<commit_after>from django.test import TestCase from django.conf import settings from phonenumber_field.modelfields import PhoneNumberField from whats_fresh.models import * from django.contrib.gis.db import models import os import time import sys import datetime class ImageTestCase(TestCase): def setUp(self): self.expected_fields = { 'image': models.ImageField, 'caption': models.TextField, 'created': models.DateTimeField, 'modified': models.DateTimeField, 'id': models.AutoField } def test_fields_exist(self): model = models.get_model('whats_fresh', 'Image') for field, field_type in self.expected_fields.items(): self.assertEqual( field_type, type(model._meta.get_field_by_name(field)[0])) def test_no_additional_fields(self): fields = Image._meta.get_all_field_names() self.assertTrue(sorted(fields) == sorted(self.expected_fields.keys())) def test_created_modified_fields(self): self.assertTrue(Image._meta.get_field('modified').auto_now) self.assertTrue(Image._meta.get_field('created').auto_now_add)
7b9ba8634c0a02cb4c82313d9bef3197640c3187
pyqtgraph/graphicsItems/tests/test_PlotDataItem.py
pyqtgraph/graphicsItems/tests/test_PlotDataItem.py
import numpy as np import pyqtgraph as pg pg.mkQApp() def test_fft(): f = 20. x = np.linspace(0, 1, 1000) y = np.sin(2 * np.pi * f * x) pd = pg.PlotDataItem(x, y) pd.setFftMode(True) x, y = pd.getData() assert abs(x[np.argmax(y)] - f) < 0.03 x = np.linspace(0, 1, 1001) y = np.sin(2 * np.pi * f * x) pd.setData(x, y) x, y = pd.getData() assert abs(x[np.argmax(y)]- f) < 0.03 pd.setLogMode(True, False) x, y = pd.getData() assert abs(x[np.argmax(y)] - np.log10(f)) < 0.01
import numpy as np import pyqtgraph as pg pg.mkQApp() def test_fft(): f = 20. x = np.linspace(0, 1, 1000) y = np.sin(2 * np.pi * f * x) pd = pg.PlotDataItem(x, y) pd.setFftMode(True) x, y = pd.getData() assert abs(x[np.argmax(y)] - f) < 0.03 x = np.linspace(0, 1, 1001) y = np.sin(2 * np.pi * f * x) pd.setData(x, y) x, y = pd.getData() assert abs(x[np.argmax(y)]- f) < 0.03 pd.setLogMode(True, False) x, y = pd.getData() assert abs(x[np.argmax(y)] - np.log10(f)) < 0.01 def test_setData(): pdi = pg.PlotDataItem() #test empty data pdi.setData([]) #test y data y = list(np.random.normal(size=100)) pdi.setData(y) assert len(pdi.xData) == 100 assert len(pdi.yData) == 100 #test x, y data y += list(np.random.normal(size=50)) x = np.linspace(5, 10, 150) pdi.setData(x, y) assert len(pdi.xData) == 150 assert len(pdi.yData) == 150 #test dict of x, y list y += list(np.random.normal(size=50)) x = list(np.linspace(5, 10, 200)) pdi.setData({'x': x, 'y': y}) assert len(pdi.xData) == 200 assert len(pdi.yData) == 200
Add test_setData() for PlotDataItem class
Add test_setData() for PlotDataItem class
Python
mit
campagnola/acq4,pbmanis/acq4,meganbkratz/acq4,acq4/acq4,meganbkratz/acq4,acq4/acq4,pbmanis/acq4,acq4/acq4,pbmanis/acq4,meganbkratz/acq4,acq4/acq4,meganbkratz/acq4,campagnola/acq4,campagnola/acq4,pbmanis/acq4,campagnola/acq4
import numpy as np import pyqtgraph as pg pg.mkQApp() def test_fft(): f = 20. x = np.linspace(0, 1, 1000) y = np.sin(2 * np.pi * f * x) pd = pg.PlotDataItem(x, y) pd.setFftMode(True) x, y = pd.getData() assert abs(x[np.argmax(y)] - f) < 0.03 x = np.linspace(0, 1, 1001) y = np.sin(2 * np.pi * f * x) pd.setData(x, y) x, y = pd.getData() assert abs(x[np.argmax(y)]- f) < 0.03 pd.setLogMode(True, False) x, y = pd.getData() assert abs(x[np.argmax(y)] - np.log10(f)) < 0.01 Add test_setData() for PlotDataItem class
import numpy as np import pyqtgraph as pg pg.mkQApp() def test_fft(): f = 20. x = np.linspace(0, 1, 1000) y = np.sin(2 * np.pi * f * x) pd = pg.PlotDataItem(x, y) pd.setFftMode(True) x, y = pd.getData() assert abs(x[np.argmax(y)] - f) < 0.03 x = np.linspace(0, 1, 1001) y = np.sin(2 * np.pi * f * x) pd.setData(x, y) x, y = pd.getData() assert abs(x[np.argmax(y)]- f) < 0.03 pd.setLogMode(True, False) x, y = pd.getData() assert abs(x[np.argmax(y)] - np.log10(f)) < 0.01 def test_setData(): pdi = pg.PlotDataItem() #test empty data pdi.setData([]) #test y data y = list(np.random.normal(size=100)) pdi.setData(y) assert len(pdi.xData) == 100 assert len(pdi.yData) == 100 #test x, y data y += list(np.random.normal(size=50)) x = np.linspace(5, 10, 150) pdi.setData(x, y) assert len(pdi.xData) == 150 assert len(pdi.yData) == 150 #test dict of x, y list y += list(np.random.normal(size=50)) x = list(np.linspace(5, 10, 200)) pdi.setData({'x': x, 'y': y}) assert len(pdi.xData) == 200 assert len(pdi.yData) == 200
<commit_before>import numpy as np import pyqtgraph as pg pg.mkQApp() def test_fft(): f = 20. x = np.linspace(0, 1, 1000) y = np.sin(2 * np.pi * f * x) pd = pg.PlotDataItem(x, y) pd.setFftMode(True) x, y = pd.getData() assert abs(x[np.argmax(y)] - f) < 0.03 x = np.linspace(0, 1, 1001) y = np.sin(2 * np.pi * f * x) pd.setData(x, y) x, y = pd.getData() assert abs(x[np.argmax(y)]- f) < 0.03 pd.setLogMode(True, False) x, y = pd.getData() assert abs(x[np.argmax(y)] - np.log10(f)) < 0.01 <commit_msg>Add test_setData() for PlotDataItem class<commit_after>
import numpy as np import pyqtgraph as pg pg.mkQApp() def test_fft(): f = 20. x = np.linspace(0, 1, 1000) y = np.sin(2 * np.pi * f * x) pd = pg.PlotDataItem(x, y) pd.setFftMode(True) x, y = pd.getData() assert abs(x[np.argmax(y)] - f) < 0.03 x = np.linspace(0, 1, 1001) y = np.sin(2 * np.pi * f * x) pd.setData(x, y) x, y = pd.getData() assert abs(x[np.argmax(y)]- f) < 0.03 pd.setLogMode(True, False) x, y = pd.getData() assert abs(x[np.argmax(y)] - np.log10(f)) < 0.01 def test_setData(): pdi = pg.PlotDataItem() #test empty data pdi.setData([]) #test y data y = list(np.random.normal(size=100)) pdi.setData(y) assert len(pdi.xData) == 100 assert len(pdi.yData) == 100 #test x, y data y += list(np.random.normal(size=50)) x = np.linspace(5, 10, 150) pdi.setData(x, y) assert len(pdi.xData) == 150 assert len(pdi.yData) == 150 #test dict of x, y list y += list(np.random.normal(size=50)) x = list(np.linspace(5, 10, 200)) pdi.setData({'x': x, 'y': y}) assert len(pdi.xData) == 200 assert len(pdi.yData) == 200
import numpy as np import pyqtgraph as pg pg.mkQApp() def test_fft(): f = 20. x = np.linspace(0, 1, 1000) y = np.sin(2 * np.pi * f * x) pd = pg.PlotDataItem(x, y) pd.setFftMode(True) x, y = pd.getData() assert abs(x[np.argmax(y)] - f) < 0.03 x = np.linspace(0, 1, 1001) y = np.sin(2 * np.pi * f * x) pd.setData(x, y) x, y = pd.getData() assert abs(x[np.argmax(y)]- f) < 0.03 pd.setLogMode(True, False) x, y = pd.getData() assert abs(x[np.argmax(y)] - np.log10(f)) < 0.01 Add test_setData() for PlotDataItem classimport numpy as np import pyqtgraph as pg pg.mkQApp() def test_fft(): f = 20. x = np.linspace(0, 1, 1000) y = np.sin(2 * np.pi * f * x) pd = pg.PlotDataItem(x, y) pd.setFftMode(True) x, y = pd.getData() assert abs(x[np.argmax(y)] - f) < 0.03 x = np.linspace(0, 1, 1001) y = np.sin(2 * np.pi * f * x) pd.setData(x, y) x, y = pd.getData() assert abs(x[np.argmax(y)]- f) < 0.03 pd.setLogMode(True, False) x, y = pd.getData() assert abs(x[np.argmax(y)] - np.log10(f)) < 0.01 def test_setData(): pdi = pg.PlotDataItem() #test empty data pdi.setData([]) #test y data y = list(np.random.normal(size=100)) pdi.setData(y) assert len(pdi.xData) == 100 assert len(pdi.yData) == 100 #test x, y data y += list(np.random.normal(size=50)) x = np.linspace(5, 10, 150) pdi.setData(x, y) assert len(pdi.xData) == 150 assert len(pdi.yData) == 150 #test dict of x, y list y += list(np.random.normal(size=50)) x = list(np.linspace(5, 10, 200)) pdi.setData({'x': x, 'y': y}) assert len(pdi.xData) == 200 assert len(pdi.yData) == 200
<commit_before>import numpy as np import pyqtgraph as pg pg.mkQApp() def test_fft(): f = 20. x = np.linspace(0, 1, 1000) y = np.sin(2 * np.pi * f * x) pd = pg.PlotDataItem(x, y) pd.setFftMode(True) x, y = pd.getData() assert abs(x[np.argmax(y)] - f) < 0.03 x = np.linspace(0, 1, 1001) y = np.sin(2 * np.pi * f * x) pd.setData(x, y) x, y = pd.getData() assert abs(x[np.argmax(y)]- f) < 0.03 pd.setLogMode(True, False) x, y = pd.getData() assert abs(x[np.argmax(y)] - np.log10(f)) < 0.01 <commit_msg>Add test_setData() for PlotDataItem class<commit_after>import numpy as np import pyqtgraph as pg pg.mkQApp() def test_fft(): f = 20. x = np.linspace(0, 1, 1000) y = np.sin(2 * np.pi * f * x) pd = pg.PlotDataItem(x, y) pd.setFftMode(True) x, y = pd.getData() assert abs(x[np.argmax(y)] - f) < 0.03 x = np.linspace(0, 1, 1001) y = np.sin(2 * np.pi * f * x) pd.setData(x, y) x, y = pd.getData() assert abs(x[np.argmax(y)]- f) < 0.03 pd.setLogMode(True, False) x, y = pd.getData() assert abs(x[np.argmax(y)] - np.log10(f)) < 0.01 def test_setData(): pdi = pg.PlotDataItem() #test empty data pdi.setData([]) #test y data y = list(np.random.normal(size=100)) pdi.setData(y) assert len(pdi.xData) == 100 assert len(pdi.yData) == 100 #test x, y data y += list(np.random.normal(size=50)) x = np.linspace(5, 10, 150) pdi.setData(x, y) assert len(pdi.xData) == 150 assert len(pdi.yData) == 150 #test dict of x, y list y += list(np.random.normal(size=50)) x = list(np.linspace(5, 10, 200)) pdi.setData({'x': x, 'y': y}) assert len(pdi.xData) == 200 assert len(pdi.yData) == 200
1973c68a623557380b07b9a09e4bc194e546655e
buildings.py
buildings.py
"""Game buildings.""" from attr import attrs, attrib, Factory from objects import ObjectWithHP, TYPE_BUILDING from mobiles import mobile_types @attrs class GameBuilding(ObjectWithHP): """A building in the game.""" # Mobiles this building produces: provides = attrib(default=Factory(list)) # Things which have to be built before this building can be constructed: depends = attrib(default=Factory(list)) def __attrs_post_init__(self): self.type_flag = TYPE_BUILDING town_hall = GameBuilding( 'Town Hall', pop_time=5*60, provides=[mobile_types['Labourer']], max_hp=100 ) _buildings = [ town_hall ] building_types = {x.name: x for x in _buildings}
"""Game buildings.""" from attr import attrs, attrib, Factory from objects import ObjectWithHP, TYPE_BUILDING from mobiles import mobile_types @attrs class GameBuilding(ObjectWithHP): """A building in the game.""" # Mobiles this building produces: provides = attrib(default=Factory(list)) # Things which have to be built before this building can be constructed: depends = attrib(default=Factory(list)) def __attrs_post_init__(self): self.type_flag = TYPE_BUILDING town_hall = GameBuilding( 'Town Hall', pop_time=2*60, provides=[mobile_types['Labourer']], max_hp=100 ) _buildings = [ town_hall ] building_types = {x.name: x for x in _buildings}
Set Town Hall pop time to 2 minutes instead of 5.
Set Town Hall pop time to 2 minutes instead of 5.
Python
mpl-2.0
chrisnorman7/pyrts,chrisnorman7/pyrts,chrisnorman7/pyrts
"""Game buildings.""" from attr import attrs, attrib, Factory from objects import ObjectWithHP, TYPE_BUILDING from mobiles import mobile_types @attrs class GameBuilding(ObjectWithHP): """A building in the game.""" # Mobiles this building produces: provides = attrib(default=Factory(list)) # Things which have to be built before this building can be constructed: depends = attrib(default=Factory(list)) def __attrs_post_init__(self): self.type_flag = TYPE_BUILDING town_hall = GameBuilding( 'Town Hall', pop_time=5*60, provides=[mobile_types['Labourer']], max_hp=100 ) _buildings = [ town_hall ] building_types = {x.name: x for x in _buildings} Set Town Hall pop time to 2 minutes instead of 5.
"""Game buildings.""" from attr import attrs, attrib, Factory from objects import ObjectWithHP, TYPE_BUILDING from mobiles import mobile_types @attrs class GameBuilding(ObjectWithHP): """A building in the game.""" # Mobiles this building produces: provides = attrib(default=Factory(list)) # Things which have to be built before this building can be constructed: depends = attrib(default=Factory(list)) def __attrs_post_init__(self): self.type_flag = TYPE_BUILDING town_hall = GameBuilding( 'Town Hall', pop_time=2*60, provides=[mobile_types['Labourer']], max_hp=100 ) _buildings = [ town_hall ] building_types = {x.name: x for x in _buildings}
<commit_before>"""Game buildings.""" from attr import attrs, attrib, Factory from objects import ObjectWithHP, TYPE_BUILDING from mobiles import mobile_types @attrs class GameBuilding(ObjectWithHP): """A building in the game.""" # Mobiles this building produces: provides = attrib(default=Factory(list)) # Things which have to be built before this building can be constructed: depends = attrib(default=Factory(list)) def __attrs_post_init__(self): self.type_flag = TYPE_BUILDING town_hall = GameBuilding( 'Town Hall', pop_time=5*60, provides=[mobile_types['Labourer']], max_hp=100 ) _buildings = [ town_hall ] building_types = {x.name: x for x in _buildings} <commit_msg>Set Town Hall pop time to 2 minutes instead of 5.<commit_after>
"""Game buildings.""" from attr import attrs, attrib, Factory from objects import ObjectWithHP, TYPE_BUILDING from mobiles import mobile_types @attrs class GameBuilding(ObjectWithHP): """A building in the game.""" # Mobiles this building produces: provides = attrib(default=Factory(list)) # Things which have to be built before this building can be constructed: depends = attrib(default=Factory(list)) def __attrs_post_init__(self): self.type_flag = TYPE_BUILDING town_hall = GameBuilding( 'Town Hall', pop_time=2*60, provides=[mobile_types['Labourer']], max_hp=100 ) _buildings = [ town_hall ] building_types = {x.name: x for x in _buildings}
"""Game buildings.""" from attr import attrs, attrib, Factory from objects import ObjectWithHP, TYPE_BUILDING from mobiles import mobile_types @attrs class GameBuilding(ObjectWithHP): """A building in the game.""" # Mobiles this building produces: provides = attrib(default=Factory(list)) # Things which have to be built before this building can be constructed: depends = attrib(default=Factory(list)) def __attrs_post_init__(self): self.type_flag = TYPE_BUILDING town_hall = GameBuilding( 'Town Hall', pop_time=5*60, provides=[mobile_types['Labourer']], max_hp=100 ) _buildings = [ town_hall ] building_types = {x.name: x for x in _buildings} Set Town Hall pop time to 2 minutes instead of 5."""Game buildings.""" from attr import attrs, attrib, Factory from objects import ObjectWithHP, TYPE_BUILDING from mobiles import mobile_types @attrs class GameBuilding(ObjectWithHP): """A building in the game.""" # Mobiles this building produces: provides = attrib(default=Factory(list)) # Things which have to be built before this building can be constructed: depends = attrib(default=Factory(list)) def __attrs_post_init__(self): self.type_flag = TYPE_BUILDING town_hall = GameBuilding( 'Town Hall', pop_time=2*60, provides=[mobile_types['Labourer']], max_hp=100 ) _buildings = [ town_hall ] building_types = {x.name: x for x in _buildings}
<commit_before>"""Game buildings.""" from attr import attrs, attrib, Factory from objects import ObjectWithHP, TYPE_BUILDING from mobiles import mobile_types @attrs class GameBuilding(ObjectWithHP): """A building in the game.""" # Mobiles this building produces: provides = attrib(default=Factory(list)) # Things which have to be built before this building can be constructed: depends = attrib(default=Factory(list)) def __attrs_post_init__(self): self.type_flag = TYPE_BUILDING town_hall = GameBuilding( 'Town Hall', pop_time=5*60, provides=[mobile_types['Labourer']], max_hp=100 ) _buildings = [ town_hall ] building_types = {x.name: x for x in _buildings} <commit_msg>Set Town Hall pop time to 2 minutes instead of 5.<commit_after>"""Game buildings.""" from attr import attrs, attrib, Factory from objects import ObjectWithHP, TYPE_BUILDING from mobiles import mobile_types @attrs class GameBuilding(ObjectWithHP): """A building in the game.""" # Mobiles this building produces: provides = attrib(default=Factory(list)) # Things which have to be built before this building can be constructed: depends = attrib(default=Factory(list)) def __attrs_post_init__(self): self.type_flag = TYPE_BUILDING town_hall = GameBuilding( 'Town Hall', pop_time=2*60, provides=[mobile_types['Labourer']], max_hp=100 ) _buildings = [ town_hall ] building_types = {x.name: x for x in _buildings}
5e7d73215d17aa52b6aae4dbb1d8e369d785b31d
api/base/exceptions.py
api/base/exceptions.py
from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, str): value = [value] errors.extend([{'source': {'pointer': '/data/attributes/' + key}, 'detail': reason} for reason in value]) elif isinstance(message, (list, tuple)): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """Raised when client passes an invalid filter in the querystring.""" default_detail = 'Querystring contains an invalid filter.'
from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, str): value = [value] errors.extend([{'source': {'pointer': '/data/attributes/' + key}, 'detail': reason} for reason in value]) else: if isinstance(message, str): message = [message] errors.extend([{'detail': error} for error in message]) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """Raised when client passes an invalid filter in the querystring.""" default_detail = 'Querystring contains an invalid filter.'
Use list comprehensions to format all errors where message is not a dict
Use list comprehensions to format all errors where message is not a dict
Python
apache-2.0
SSJohns/osf.io,haoyuchen1992/osf.io,felliott/osf.io,danielneis/osf.io,icereval/osf.io,samchrisinger/osf.io,sloria/osf.io,ZobairAlijan/osf.io,mluke93/osf.io,alexschiller/osf.io,ticklemepierce/osf.io,GageGaskins/osf.io,acshi/osf.io,CenterForOpenScience/osf.io,HalcyonChimera/osf.io,doublebits/osf.io,njantrania/osf.io,kch8qx/osf.io,mattclark/osf.io,hmoco/osf.io,caseyrollins/osf.io,cosenal/osf.io,leb2dg/osf.io,samchrisinger/osf.io,monikagrabowska/osf.io,kwierman/osf.io,icereval/osf.io,sloria/osf.io,samanehsan/osf.io,haoyuchen1992/osf.io,DanielSBrown/osf.io,rdhyee/osf.io,monikagrabowska/osf.io,aaxelb/osf.io,danielneis/osf.io,chennan47/osf.io,HalcyonChimera/osf.io,arpitar/osf.io,brandonPurvis/osf.io,doublebits/osf.io,mattclark/osf.io,erinspace/osf.io,adlius/osf.io,brandonPurvis/osf.io,CenterForOpenScience/osf.io,abought/osf.io,TomHeatwole/osf.io,jnayak1/osf.io,SSJohns/osf.io,RomanZWang/osf.io,asanfilippo7/osf.io,haoyuchen1992/osf.io,danielneis/osf.io,samchrisinger/osf.io,billyhunt/osf.io,billyhunt/osf.io,adlius/osf.io,mfraezz/osf.io,Nesiehr/osf.io,chrisseto/osf.io,Nesiehr/osf.io,cslzchen/osf.io,asanfilippo7/osf.io,doublebits/osf.io,SSJohns/osf.io,DanielSBrown/osf.io,emetsger/osf.io,CenterForOpenScience/osf.io,mluo613/osf.io,GageGaskins/osf.io,zamattiac/osf.io,crcresearch/osf.io,alexschiller/osf.io,sloria/osf.io,chrisseto/osf.io,abought/osf.io,kwierman/osf.io,alexschiller/osf.io,crcresearch/osf.io,saradbowman/osf.io,aaxelb/osf.io,njantrania/osf.io,billyhunt/osf.io,GageGaskins/osf.io,KAsante95/osf.io,RomanZWang/osf.io,brandonPurvis/osf.io,hmoco/osf.io,KAsante95/osf.io,RomanZWang/osf.io,HalcyonChimera/osf.io,brandonPurvis/osf.io,acshi/osf.io,leb2dg/osf.io,brianjgeiger/osf.io,Johnetordoff/osf.io,ZobairAlijan/osf.io,SSJohns/osf.io,Johnetordoff/osf.io,GageGaskins/osf.io,samanehsan/osf.io,Johnetordoff/osf.io,brianjgeiger/osf.io,cwisecarver/osf.io,erinspace/osf.io,njantrania/osf.io,kch8qx/osf.io,haoyuchen1992/osf.io,zachjanicki/osf.io,billyhunt/osf.io,samanehsan/osf.io,Ghalko/osf.io,felliott/osf.io,zamattiac/osf.io,TomHeatwole/osf.io,ZobairAlijan/osf.io,icereval/osf.io,cosenal/osf.io,mluo613/osf.io,kwierman/osf.io,billyhunt/osf.io,ticklemepierce/osf.io,baylee-d/osf.io,amyshi188/osf.io,brandonPurvis/osf.io,wearpants/osf.io,Nesiehr/osf.io,arpitar/osf.io,chennan47/osf.io,laurenrevere/osf.io,KAsante95/osf.io,zachjanicki/osf.io,petermalcolm/osf.io,TomBaxter/osf.io,kch8qx/osf.io,wearpants/osf.io,mfraezz/osf.io,samchrisinger/osf.io,Ghalko/osf.io,arpitar/osf.io,petermalcolm/osf.io,amyshi188/osf.io,caseyrygt/osf.io,KAsante95/osf.io,mluo613/osf.io,aaxelb/osf.io,monikagrabowska/osf.io,felliott/osf.io,HalcyonChimera/osf.io,cosenal/osf.io,zamattiac/osf.io,baylee-d/osf.io,caneruguz/osf.io,monikagrabowska/osf.io,ticklemepierce/osf.io,alexschiller/osf.io,KAsante95/osf.io,aaxelb/osf.io,kwierman/osf.io,hmoco/osf.io,cslzchen/osf.io,caneruguz/osf.io,abought/osf.io,acshi/osf.io,RomanZWang/osf.io,asanfilippo7/osf.io,njantrania/osf.io,TomHeatwole/osf.io,amyshi188/osf.io,binoculars/osf.io,pattisdr/osf.io,chennan47/osf.io,leb2dg/osf.io,alexschiller/osf.io,wearpants/osf.io,leb2dg/osf.io,acshi/osf.io,mluke93/osf.io,caseyrollins/osf.io,ZobairAlijan/osf.io,pattisdr/osf.io,chrisseto/osf.io,erinspace/osf.io,TomBaxter/osf.io,mluke93/osf.io,wearpants/osf.io,binoculars/osf.io,zachjanicki/osf.io,arpitar/osf.io,Ghalko/osf.io,asanfilippo7/osf.io,pattisdr/osf.io,kch8qx/osf.io,petermalcolm/osf.io,cwisecarver/osf.io,monikagrabowska/osf.io,saradbowman/osf.io,samanehsan/osf.io,danielneis/osf.io,TomHeatwole/osf.io,TomBaxter/osf.io,jnayak1/osf.io,rdhyee/osf.io,felliott/osf.io,crcresearch/osf.io,ticklemepierce/osf.io,acshi/osf.io,cslzchen/osf.io,cslzchen/osf.io,caseyrygt/osf.io,caseyrollins/osf.io,jnayak1/osf.io,abought/osf.io,binoculars/osf.io,mluke93/osf.io,zamattiac/osf.io,mluo613/osf.io,doublebits/osf.io,rdhyee/osf.io,rdhyee/osf.io,caseyrygt/osf.io,Nesiehr/osf.io,doublebits/osf.io,cwisecarver/osf.io,zachjanicki/osf.io,kch8qx/osf.io,DanielSBrown/osf.io,RomanZWang/osf.io,baylee-d/osf.io,mluo613/osf.io,adlius/osf.io,mfraezz/osf.io,jnayak1/osf.io,mattclark/osf.io,emetsger/osf.io,emetsger/osf.io,brianjgeiger/osf.io,amyshi188/osf.io,petermalcolm/osf.io,adlius/osf.io,mfraezz/osf.io,hmoco/osf.io,chrisseto/osf.io,caneruguz/osf.io,GageGaskins/osf.io,Ghalko/osf.io,cosenal/osf.io,laurenrevere/osf.io,laurenrevere/osf.io,caneruguz/osf.io,brianjgeiger/osf.io,caseyrygt/osf.io,emetsger/osf.io,Johnetordoff/osf.io,DanielSBrown/osf.io,cwisecarver/osf.io,CenterForOpenScience/osf.io
from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, str): value = [value] errors.extend([{'source': {'pointer': '/data/attributes/' + key}, 'detail': reason} for reason in value]) elif isinstance(message, (list, tuple)): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """Raised when client passes an invalid filter in the querystring.""" default_detail = 'Querystring contains an invalid filter.' Use list comprehensions to format all errors where message is not a dict
from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, str): value = [value] errors.extend([{'source': {'pointer': '/data/attributes/' + key}, 'detail': reason} for reason in value]) else: if isinstance(message, str): message = [message] errors.extend([{'detail': error} for error in message]) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """Raised when client passes an invalid filter in the querystring.""" default_detail = 'Querystring contains an invalid filter.'
<commit_before> from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, str): value = [value] errors.extend([{'source': {'pointer': '/data/attributes/' + key}, 'detail': reason} for reason in value]) elif isinstance(message, (list, tuple)): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """Raised when client passes an invalid filter in the querystring.""" default_detail = 'Querystring contains an invalid filter.' <commit_msg>Use list comprehensions to format all errors where message is not a dict<commit_after>
from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, str): value = [value] errors.extend([{'source': {'pointer': '/data/attributes/' + key}, 'detail': reason} for reason in value]) else: if isinstance(message, str): message = [message] errors.extend([{'detail': error} for error in message]) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """Raised when client passes an invalid filter in the querystring.""" default_detail = 'Querystring contains an invalid filter.'
from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, str): value = [value] errors.extend([{'source': {'pointer': '/data/attributes/' + key}, 'detail': reason} for reason in value]) elif isinstance(message, (list, tuple)): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """Raised when client passes an invalid filter in the querystring.""" default_detail = 'Querystring contains an invalid filter.' Use list comprehensions to format all errors where message is not a dict from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, str): value = [value] errors.extend([{'source': {'pointer': '/data/attributes/' + key}, 'detail': reason} for reason in value]) else: if isinstance(message, str): message = [message] errors.extend([{'detail': error} for error in message]) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """Raised when client passes an invalid filter in the querystring.""" default_detail = 'Querystring contains an invalid filter.'
<commit_before> from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, str): value = [value] errors.extend([{'source': {'pointer': '/data/attributes/' + key}, 'detail': reason} for reason in value]) elif isinstance(message, (list, tuple)): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """Raised when client passes an invalid filter in the querystring.""" default_detail = 'Querystring contains an invalid filter.' <commit_msg>Use list comprehensions to format all errors where message is not a dict<commit_after> from rest_framework import status from rest_framework.exceptions import APIException, ParseError def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, str): value = [value] errors.extend([{'source': {'pointer': '/data/attributes/' + key}, 'detail': reason} for reason in value]) else: if isinstance(message, str): message = [message] errors.extend([{'detail': error} for error in message]) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """Raised when client passes an invalid filter in the querystring.""" default_detail = 'Querystring contains an invalid filter.'
53aecfed27a01ea3ae44f87e9223260c735c82c6
apps/reviews/models.py
apps/reviews/models.py
import itertools from django.db import models import amo from translations.fields import TranslatedField from translations.models import Translation class Review(amo.ModelBase): version = models.ForeignKey('versions.Version') user = models.ForeignKey('users.UserProfile') reply_to = models.ForeignKey('self', null=True, unique=True, db_column='reply_to') rating = models.PositiveSmallIntegerField(null=True) title = TranslatedField() body = TranslatedField() editorreview = models.BooleanField(default=False) flag = models.BooleanField(default=False) sandbox = models.BooleanField(default=False) class Meta: db_table = 'reviews' def fetch_translations(self, ids, lang): if not ids: return [] rv = {} ts = Translation.objects.filter(id__in=ids) # If a translation exists for the current language, use it. Otherwise, # make do with whatever is available. (Reviewers only write reviews in # their language). for id, translations in itertools.groupby(ts, lambda t: t.id): locales = dict((t.locale, t) for t in translations) if lang in locales: rv[id] = locales[lang] else: rv[id] = locales.itervalues().next() return rv.values()
import itertools from django.db import models import amo from translations.fields import TranslatedField from translations.models import Translation class Review(amo.ModelBase): version = models.ForeignKey('versions.Version') user = models.ForeignKey('users.UserProfile') reply_to = models.ForeignKey('self', null=True, unique=True, db_column='reply_to') rating = models.PositiveSmallIntegerField(null=True) title = TranslatedField() body = TranslatedField() ip_address = models.CharField(max_length=255, default='0.0.0.0') editorreview = models.BooleanField(default=False) flag = models.BooleanField(default=False) sandbox = models.BooleanField(default=False) class Meta: db_table = 'reviews' def fetch_translations(self, ids, lang): if not ids: return [] rv = {} ts = Translation.objects.filter(id__in=ids) # If a translation exists for the current language, use it. Otherwise, # make do with whatever is available. (Reviewers only write reviews in # their language). for id, translations in itertools.groupby(ts, lambda t: t.id): locales = dict((t.locale, t) for t in translations) if lang in locales: rv[id] = locales[lang] else: rv[id] = locales.itervalues().next() return rv.values()
Update reviews model for new added field in 5.5
Update reviews model for new added field in 5.5
Python
bsd-3-clause
Prashant-Surya/addons-server,andymckay/zamboni,elysium001/zamboni,eviljeff/zamboni,eviljeff/zamboni,lavish205/olympia,psiinon/addons-server,mozilla/olympia,andymckay/olympia,wagnerand/addons-server,tsl143/zamboni,kumar303/olympia,andymckay/addons-server,jbalogh/zamboni,wagnerand/zamboni,crdoconnor/olympia,Revanth47/addons-server,mdaif/olympia,mozilla/olympia,Jobava/zamboni,harry-7/addons-server,magopian/olympia,ddurst/zamboni,Prashant-Surya/addons-server,Witia1/olympia,muffinresearch/addons-server,andymckay/addons-server,harry-7/addons-server,koehlermichael/olympia,Hitechverma/zamboni,mozilla/olympia,jpetto/olympia,mudithkr/zamboni,andymckay/olympia,muffinresearch/addons-server,bqbn/addons-server,harikishen/addons-server,beni55/olympia,mstriemer/olympia,muffinresearch/addons-server,yfdyh000/olympia,aviarypl/mozilla-l10n-addons-server,spasovski/zamboni,eviljeff/olympia,kumar303/addons-server,wagnerand/olympia,aviarypl/mozilla-l10n-addons-server,shahbaz17/zamboni,mdaif/olympia,luckylavish/zamboni,wagnerand/zamboni,harikishen/addons-server,tsl143/addons-server,Joergen/olympia,Revanth47/addons-server,mozilla/zamboni,harikishen/addons-server,mozilla/addons-server,ngokevin/zamboni,muffinresearch/olympia,SuriyaaKudoIsc/olympia,Revanth47/addons-server,ddurst/zamboni,beni55/olympia,ingenioustechie/zamboni,andymckay/olympia,diox/olympia,johancz/olympia,eviljeff/olympia,jpetto/olympia,kumar303/addons-server,diox/zamboni,johancz/olympia,lavish205/olympia,luckylavish/zamboni,ddurst/zamboni,mstriemer/zamboni,Witia1/olympia,Hitechverma/zamboni,diox/olympia,mstriemer/olympia,jasonthomas/zamboni,eviljeff/olympia,shahbaz17/zamboni,diox/olympia,mudithkr/zamboni,kumar303/olympia,jamesthechamp/zamboni,luckylavish/zamboni,tsl143/addons-server,eviljeff/olympia,koehlermichael/olympia,kumar303/addons-server,bqbn/addons-server,kumar303/olympia,washort/zamboni,mozilla/addons-server,beni55/olympia,elysium001/zamboni,kumar303/olympia,aviarypl/mozilla-l10n-addons-server,wagnerand/olympia,Joergen/olympia,elysium001/zamboni,harikishen/addons-server,Jobava/zamboni,andymckay/addons-server,ddurst/zamboni,crdoconnor/olympia,magopian/olympia,beni55/olympia,jasonthomas/zamboni,ingenioustechie/zamboni,aviarypl/mozilla-l10n-addons-server,Prashant-Surya/addons-server,kmaglione/olympia,Joergen/zamboni,eviljeff/zamboni,muffinresearch/addons-server,koehlermichael/olympia,Nolski/olympia,mozilla/zamboni,kumar303/addons-server,ingenioustechie/zamboni,jamesthechamp/zamboni,andymckay/addons-server,Hitechverma/zamboni,wagnerand/zamboni,crdoconnor/olympia,Witia1/olympia,mstriemer/addons-server,Prashant-Surya/addons-server,jasonthomas/zamboni,mstriemer/addons-server,johancz/olympia,koehlermichael/olympia,shahbaz17/zamboni,diox/zamboni,ayushagrawal288/zamboni,atiqueahmedziad/addons-server,jpetto/olympia,atiqueahmedziad/addons-server,Joergen/zamboni,yfdyh000/olympia,SuriyaaKudoIsc/olympia,atiqueahmedziad/addons-server,tsl143/zamboni,andymckay/zamboni,mrrrgn/olympia,crdoconnor/olympia,elysium001/zamboni,diox/zamboni,Nolski/olympia,luckylavish/zamboni,mstriemer/zamboni,tsl143/zamboni,robhudson/zamboni,Joergen/zamboni,clouserw/zamboni,bqbn/addons-server,ngokevin/zamboni,bqbn/addons-server,spasovski/zamboni,atiqueahmedziad/addons-server,mdaif/olympia,clouserw/zamboni,mrrrgn/olympia,wagnerand/zamboni,anaran/olympia,mstriemer/addons-server,clouserw/zamboni,mozilla/addons-server,mstriemer/zamboni,wagnerand/addons-server,yfdyh000/olympia,andymckay/olympia,Joergen/zamboni,mrrrgn/olympia,jamesthechamp/zamboni,ingenioustechie/zamboni,lavish205/olympia,muffinresearch/addons-server,SuriyaaKudoIsc/olympia,spasovski/zamboni,muffinresearch/olympia,psiinon/addons-server,mozilla/zamboni,kumar303/zamboni,beni55/olympia,mrrrgn/olympia,Revanth47/addons-server,kumar303/zamboni,Nolski/olympia,Joergen/zamboni,muffinresearch/olympia,kumar303/zamboni,Joergen/olympia,Joergen/zamboni,jbalogh/zamboni,mstriemer/olympia,robhudson/zamboni,mudithkr/zamboni,tsl143/zamboni,kmaglione/olympia,mozilla/zamboni,yfdyh000/olympia,Joergen/olympia,mdaif/olympia,tsl143/addons-server,diox/zamboni,Nolski/olympia,anaran/olympia,kumar303/zamboni,mozilla/addons-server,eviljeff/zamboni,wagnerand/addons-server,johancz/olympia,yfdyh000/olympia,wagnerand/olympia,Witia1/olympia,lavish205/olympia,mstriemer/zamboni,jasonthomas/zamboni,magopian/olympia,kmaglione/olympia,crdoconnor/olympia,washort/zamboni,ayushagrawal288/zamboni,harry-7/addons-server,Witia1/olympia,jbalogh/zamboni,wagnerand/olympia,jbalogh/zamboni,robhudson/zamboni,muffinresearch/olympia,johancz/olympia,shahbaz17/zamboni,SuriyaaKudoIsc/olympia,spasovski/zamboni,Jobava/zamboni,anaran/olympia,kmaglione/olympia,washort/zamboni,muffinresearch/olympia,robhudson/zamboni,psiinon/addons-server,jamesthechamp/zamboni,Hitechverma/zamboni,mstriemer/olympia,anaran/olympia,wagnerand/addons-server,ngokevin/zamboni,Jobava/zamboni,magopian/olympia,ayushagrawal288/zamboni,mrrrgn/olympia,clouserw/zamboni,Joergen/olympia,koehlermichael/olympia,mdaif/olympia,washort/zamboni,andymckay/zamboni,mstriemer/addons-server,ayushagrawal288/zamboni,kmaglione/olympia,Nolski/olympia,magopian/olympia,tsl143/addons-server,mozilla/olympia,mudithkr/zamboni,diox/olympia,jpetto/olympia,psiinon/addons-server,harry-7/addons-server
import itertools from django.db import models import amo from translations.fields import TranslatedField from translations.models import Translation class Review(amo.ModelBase): version = models.ForeignKey('versions.Version') user = models.ForeignKey('users.UserProfile') reply_to = models.ForeignKey('self', null=True, unique=True, db_column='reply_to') rating = models.PositiveSmallIntegerField(null=True) title = TranslatedField() body = TranslatedField() editorreview = models.BooleanField(default=False) flag = models.BooleanField(default=False) sandbox = models.BooleanField(default=False) class Meta: db_table = 'reviews' def fetch_translations(self, ids, lang): if not ids: return [] rv = {} ts = Translation.objects.filter(id__in=ids) # If a translation exists for the current language, use it. Otherwise, # make do with whatever is available. (Reviewers only write reviews in # their language). for id, translations in itertools.groupby(ts, lambda t: t.id): locales = dict((t.locale, t) for t in translations) if lang in locales: rv[id] = locales[lang] else: rv[id] = locales.itervalues().next() return rv.values() Update reviews model for new added field in 5.5
import itertools from django.db import models import amo from translations.fields import TranslatedField from translations.models import Translation class Review(amo.ModelBase): version = models.ForeignKey('versions.Version') user = models.ForeignKey('users.UserProfile') reply_to = models.ForeignKey('self', null=True, unique=True, db_column='reply_to') rating = models.PositiveSmallIntegerField(null=True) title = TranslatedField() body = TranslatedField() ip_address = models.CharField(max_length=255, default='0.0.0.0') editorreview = models.BooleanField(default=False) flag = models.BooleanField(default=False) sandbox = models.BooleanField(default=False) class Meta: db_table = 'reviews' def fetch_translations(self, ids, lang): if not ids: return [] rv = {} ts = Translation.objects.filter(id__in=ids) # If a translation exists for the current language, use it. Otherwise, # make do with whatever is available. (Reviewers only write reviews in # their language). for id, translations in itertools.groupby(ts, lambda t: t.id): locales = dict((t.locale, t) for t in translations) if lang in locales: rv[id] = locales[lang] else: rv[id] = locales.itervalues().next() return rv.values()
<commit_before>import itertools from django.db import models import amo from translations.fields import TranslatedField from translations.models import Translation class Review(amo.ModelBase): version = models.ForeignKey('versions.Version') user = models.ForeignKey('users.UserProfile') reply_to = models.ForeignKey('self', null=True, unique=True, db_column='reply_to') rating = models.PositiveSmallIntegerField(null=True) title = TranslatedField() body = TranslatedField() editorreview = models.BooleanField(default=False) flag = models.BooleanField(default=False) sandbox = models.BooleanField(default=False) class Meta: db_table = 'reviews' def fetch_translations(self, ids, lang): if not ids: return [] rv = {} ts = Translation.objects.filter(id__in=ids) # If a translation exists for the current language, use it. Otherwise, # make do with whatever is available. (Reviewers only write reviews in # their language). for id, translations in itertools.groupby(ts, lambda t: t.id): locales = dict((t.locale, t) for t in translations) if lang in locales: rv[id] = locales[lang] else: rv[id] = locales.itervalues().next() return rv.values() <commit_msg>Update reviews model for new added field in 5.5<commit_after>
import itertools from django.db import models import amo from translations.fields import TranslatedField from translations.models import Translation class Review(amo.ModelBase): version = models.ForeignKey('versions.Version') user = models.ForeignKey('users.UserProfile') reply_to = models.ForeignKey('self', null=True, unique=True, db_column='reply_to') rating = models.PositiveSmallIntegerField(null=True) title = TranslatedField() body = TranslatedField() ip_address = models.CharField(max_length=255, default='0.0.0.0') editorreview = models.BooleanField(default=False) flag = models.BooleanField(default=False) sandbox = models.BooleanField(default=False) class Meta: db_table = 'reviews' def fetch_translations(self, ids, lang): if not ids: return [] rv = {} ts = Translation.objects.filter(id__in=ids) # If a translation exists for the current language, use it. Otherwise, # make do with whatever is available. (Reviewers only write reviews in # their language). for id, translations in itertools.groupby(ts, lambda t: t.id): locales = dict((t.locale, t) for t in translations) if lang in locales: rv[id] = locales[lang] else: rv[id] = locales.itervalues().next() return rv.values()
import itertools from django.db import models import amo from translations.fields import TranslatedField from translations.models import Translation class Review(amo.ModelBase): version = models.ForeignKey('versions.Version') user = models.ForeignKey('users.UserProfile') reply_to = models.ForeignKey('self', null=True, unique=True, db_column='reply_to') rating = models.PositiveSmallIntegerField(null=True) title = TranslatedField() body = TranslatedField() editorreview = models.BooleanField(default=False) flag = models.BooleanField(default=False) sandbox = models.BooleanField(default=False) class Meta: db_table = 'reviews' def fetch_translations(self, ids, lang): if not ids: return [] rv = {} ts = Translation.objects.filter(id__in=ids) # If a translation exists for the current language, use it. Otherwise, # make do with whatever is available. (Reviewers only write reviews in # their language). for id, translations in itertools.groupby(ts, lambda t: t.id): locales = dict((t.locale, t) for t in translations) if lang in locales: rv[id] = locales[lang] else: rv[id] = locales.itervalues().next() return rv.values() Update reviews model for new added field in 5.5import itertools from django.db import models import amo from translations.fields import TranslatedField from translations.models import Translation class Review(amo.ModelBase): version = models.ForeignKey('versions.Version') user = models.ForeignKey('users.UserProfile') reply_to = models.ForeignKey('self', null=True, unique=True, db_column='reply_to') rating = models.PositiveSmallIntegerField(null=True) title = TranslatedField() body = TranslatedField() ip_address = models.CharField(max_length=255, default='0.0.0.0') editorreview = models.BooleanField(default=False) flag = models.BooleanField(default=False) sandbox = models.BooleanField(default=False) class Meta: db_table = 'reviews' def fetch_translations(self, ids, lang): if not ids: return [] rv = {} ts = Translation.objects.filter(id__in=ids) # If a translation exists for the current language, use it. Otherwise, # make do with whatever is available. (Reviewers only write reviews in # their language). for id, translations in itertools.groupby(ts, lambda t: t.id): locales = dict((t.locale, t) for t in translations) if lang in locales: rv[id] = locales[lang] else: rv[id] = locales.itervalues().next() return rv.values()
<commit_before>import itertools from django.db import models import amo from translations.fields import TranslatedField from translations.models import Translation class Review(amo.ModelBase): version = models.ForeignKey('versions.Version') user = models.ForeignKey('users.UserProfile') reply_to = models.ForeignKey('self', null=True, unique=True, db_column='reply_to') rating = models.PositiveSmallIntegerField(null=True) title = TranslatedField() body = TranslatedField() editorreview = models.BooleanField(default=False) flag = models.BooleanField(default=False) sandbox = models.BooleanField(default=False) class Meta: db_table = 'reviews' def fetch_translations(self, ids, lang): if not ids: return [] rv = {} ts = Translation.objects.filter(id__in=ids) # If a translation exists for the current language, use it. Otherwise, # make do with whatever is available. (Reviewers only write reviews in # their language). for id, translations in itertools.groupby(ts, lambda t: t.id): locales = dict((t.locale, t) for t in translations) if lang in locales: rv[id] = locales[lang] else: rv[id] = locales.itervalues().next() return rv.values() <commit_msg>Update reviews model for new added field in 5.5<commit_after>import itertools from django.db import models import amo from translations.fields import TranslatedField from translations.models import Translation class Review(amo.ModelBase): version = models.ForeignKey('versions.Version') user = models.ForeignKey('users.UserProfile') reply_to = models.ForeignKey('self', null=True, unique=True, db_column='reply_to') rating = models.PositiveSmallIntegerField(null=True) title = TranslatedField() body = TranslatedField() ip_address = models.CharField(max_length=255, default='0.0.0.0') editorreview = models.BooleanField(default=False) flag = models.BooleanField(default=False) sandbox = models.BooleanField(default=False) class Meta: db_table = 'reviews' def fetch_translations(self, ids, lang): if not ids: return [] rv = {} ts = Translation.objects.filter(id__in=ids) # If a translation exists for the current language, use it. Otherwise, # make do with whatever is available. (Reviewers only write reviews in # their language). for id, translations in itertools.groupby(ts, lambda t: t.id): locales = dict((t.locale, t) for t in translations) if lang in locales: rv[id] = locales[lang] else: rv[id] = locales.itervalues().next() return rv.values()
b30be4ee2a9e7c656e78fd34c9b59a1653bed1a2
argonauts/testutils.py
argonauts/testutils.py
import json import functools from django.conf import settings from django.test import Client, TestCase __all__ = ['JsonTestClient', 'JsonTestMixin', 'JsonTestCase'] class JsonTestClient(Client): def _json_request(self, method, url, data=None, *args, **kwargs): method_func = getattr(super(JsonTestClient, self), method) if method == 'get': encode = lambda x: x else: encode = json.dumps if data is not None: resp = method_func(url, encode(data), content_type='application/json', *args, **kwargs) else: resp = method_func(url, content_type='application/json', *args, **kwargs) if resp['Content-Type'].startswith('application/json') and resp.content: charset = resp.charset or settings.DEFAULT_CHARSET resp.json = json.loads(resp.content.decode(charset)) return resp def __getattribute__(self, attr): if attr in ('get', 'post', 'put', 'delete', 'trace', 'head', 'patch', 'options'): return functools.partial(self._json_request, attr) else: return super(JsonTestClient, self).__getattribute__(attr) class JsonTestMixin(object): client_class = JsonTestClient class JsonTestCase(JsonTestMixin, TestCase): pass
import json import functools from django.conf import settings from django.test import Client, TestCase __all__ = ['JsonTestClient', 'JsonTestMixin', 'JsonTestCase'] class JsonTestClient(Client): def _json_request(self, method, url, data=None, *args, **kwargs): method_func = getattr(super(JsonTestClient, self), method) if method == 'get': encode = lambda x: x else: encode = json.dumps if data is not None: resp = method_func(url, encode(data), content_type='application/json', *args, **kwargs) else: resp = method_func(url, content_type='application/json', *args, **kwargs) if resp['Content-Type'].startswith('application/json') and resp.content: charset = resp.charset if hasattr(resp, 'charset') else settings.DEFAULT_CHARSET resp.json = json.loads(resp.content.decode(charset)) return resp def __getattribute__(self, attr): if attr in ('get', 'post', 'put', 'delete', 'trace', 'head', 'patch', 'options'): return functools.partial(self._json_request, attr) else: return super(JsonTestClient, self).__getattribute__(attr) class JsonTestMixin(object): client_class = JsonTestClient class JsonTestCase(JsonTestMixin, TestCase): pass
Test requests don't have a charset attribute
Test requests don't have a charset attribute
Python
bsd-2-clause
fusionbox/django-argonauts
import json import functools from django.conf import settings from django.test import Client, TestCase __all__ = ['JsonTestClient', 'JsonTestMixin', 'JsonTestCase'] class JsonTestClient(Client): def _json_request(self, method, url, data=None, *args, **kwargs): method_func = getattr(super(JsonTestClient, self), method) if method == 'get': encode = lambda x: x else: encode = json.dumps if data is not None: resp = method_func(url, encode(data), content_type='application/json', *args, **kwargs) else: resp = method_func(url, content_type='application/json', *args, **kwargs) if resp['Content-Type'].startswith('application/json') and resp.content: charset = resp.charset or settings.DEFAULT_CHARSET resp.json = json.loads(resp.content.decode(charset)) return resp def __getattribute__(self, attr): if attr in ('get', 'post', 'put', 'delete', 'trace', 'head', 'patch', 'options'): return functools.partial(self._json_request, attr) else: return super(JsonTestClient, self).__getattribute__(attr) class JsonTestMixin(object): client_class = JsonTestClient class JsonTestCase(JsonTestMixin, TestCase): pass Test requests don't have a charset attribute
import json import functools from django.conf import settings from django.test import Client, TestCase __all__ = ['JsonTestClient', 'JsonTestMixin', 'JsonTestCase'] class JsonTestClient(Client): def _json_request(self, method, url, data=None, *args, **kwargs): method_func = getattr(super(JsonTestClient, self), method) if method == 'get': encode = lambda x: x else: encode = json.dumps if data is not None: resp = method_func(url, encode(data), content_type='application/json', *args, **kwargs) else: resp = method_func(url, content_type='application/json', *args, **kwargs) if resp['Content-Type'].startswith('application/json') and resp.content: charset = resp.charset if hasattr(resp, 'charset') else settings.DEFAULT_CHARSET resp.json = json.loads(resp.content.decode(charset)) return resp def __getattribute__(self, attr): if attr in ('get', 'post', 'put', 'delete', 'trace', 'head', 'patch', 'options'): return functools.partial(self._json_request, attr) else: return super(JsonTestClient, self).__getattribute__(attr) class JsonTestMixin(object): client_class = JsonTestClient class JsonTestCase(JsonTestMixin, TestCase): pass
<commit_before>import json import functools from django.conf import settings from django.test import Client, TestCase __all__ = ['JsonTestClient', 'JsonTestMixin', 'JsonTestCase'] class JsonTestClient(Client): def _json_request(self, method, url, data=None, *args, **kwargs): method_func = getattr(super(JsonTestClient, self), method) if method == 'get': encode = lambda x: x else: encode = json.dumps if data is not None: resp = method_func(url, encode(data), content_type='application/json', *args, **kwargs) else: resp = method_func(url, content_type='application/json', *args, **kwargs) if resp['Content-Type'].startswith('application/json') and resp.content: charset = resp.charset or settings.DEFAULT_CHARSET resp.json = json.loads(resp.content.decode(charset)) return resp def __getattribute__(self, attr): if attr in ('get', 'post', 'put', 'delete', 'trace', 'head', 'patch', 'options'): return functools.partial(self._json_request, attr) else: return super(JsonTestClient, self).__getattribute__(attr) class JsonTestMixin(object): client_class = JsonTestClient class JsonTestCase(JsonTestMixin, TestCase): pass <commit_msg>Test requests don't have a charset attribute<commit_after>
import json import functools from django.conf import settings from django.test import Client, TestCase __all__ = ['JsonTestClient', 'JsonTestMixin', 'JsonTestCase'] class JsonTestClient(Client): def _json_request(self, method, url, data=None, *args, **kwargs): method_func = getattr(super(JsonTestClient, self), method) if method == 'get': encode = lambda x: x else: encode = json.dumps if data is not None: resp = method_func(url, encode(data), content_type='application/json', *args, **kwargs) else: resp = method_func(url, content_type='application/json', *args, **kwargs) if resp['Content-Type'].startswith('application/json') and resp.content: charset = resp.charset if hasattr(resp, 'charset') else settings.DEFAULT_CHARSET resp.json = json.loads(resp.content.decode(charset)) return resp def __getattribute__(self, attr): if attr in ('get', 'post', 'put', 'delete', 'trace', 'head', 'patch', 'options'): return functools.partial(self._json_request, attr) else: return super(JsonTestClient, self).__getattribute__(attr) class JsonTestMixin(object): client_class = JsonTestClient class JsonTestCase(JsonTestMixin, TestCase): pass
import json import functools from django.conf import settings from django.test import Client, TestCase __all__ = ['JsonTestClient', 'JsonTestMixin', 'JsonTestCase'] class JsonTestClient(Client): def _json_request(self, method, url, data=None, *args, **kwargs): method_func = getattr(super(JsonTestClient, self), method) if method == 'get': encode = lambda x: x else: encode = json.dumps if data is not None: resp = method_func(url, encode(data), content_type='application/json', *args, **kwargs) else: resp = method_func(url, content_type='application/json', *args, **kwargs) if resp['Content-Type'].startswith('application/json') and resp.content: charset = resp.charset or settings.DEFAULT_CHARSET resp.json = json.loads(resp.content.decode(charset)) return resp def __getattribute__(self, attr): if attr in ('get', 'post', 'put', 'delete', 'trace', 'head', 'patch', 'options'): return functools.partial(self._json_request, attr) else: return super(JsonTestClient, self).__getattribute__(attr) class JsonTestMixin(object): client_class = JsonTestClient class JsonTestCase(JsonTestMixin, TestCase): pass Test requests don't have a charset attributeimport json import functools from django.conf import settings from django.test import Client, TestCase __all__ = ['JsonTestClient', 'JsonTestMixin', 'JsonTestCase'] class JsonTestClient(Client): def _json_request(self, method, url, data=None, *args, **kwargs): method_func = getattr(super(JsonTestClient, self), method) if method == 'get': encode = lambda x: x else: encode = json.dumps if data is not None: resp = method_func(url, encode(data), content_type='application/json', *args, **kwargs) else: resp = method_func(url, content_type='application/json', *args, **kwargs) if resp['Content-Type'].startswith('application/json') and resp.content: charset = resp.charset if hasattr(resp, 'charset') else settings.DEFAULT_CHARSET resp.json = json.loads(resp.content.decode(charset)) return resp def __getattribute__(self, attr): if attr in ('get', 'post', 'put', 'delete', 'trace', 'head', 'patch', 'options'): return functools.partial(self._json_request, attr) else: return super(JsonTestClient, self).__getattribute__(attr) class JsonTestMixin(object): client_class = JsonTestClient class JsonTestCase(JsonTestMixin, TestCase): pass
<commit_before>import json import functools from django.conf import settings from django.test import Client, TestCase __all__ = ['JsonTestClient', 'JsonTestMixin', 'JsonTestCase'] class JsonTestClient(Client): def _json_request(self, method, url, data=None, *args, **kwargs): method_func = getattr(super(JsonTestClient, self), method) if method == 'get': encode = lambda x: x else: encode = json.dumps if data is not None: resp = method_func(url, encode(data), content_type='application/json', *args, **kwargs) else: resp = method_func(url, content_type='application/json', *args, **kwargs) if resp['Content-Type'].startswith('application/json') and resp.content: charset = resp.charset or settings.DEFAULT_CHARSET resp.json = json.loads(resp.content.decode(charset)) return resp def __getattribute__(self, attr): if attr in ('get', 'post', 'put', 'delete', 'trace', 'head', 'patch', 'options'): return functools.partial(self._json_request, attr) else: return super(JsonTestClient, self).__getattribute__(attr) class JsonTestMixin(object): client_class = JsonTestClient class JsonTestCase(JsonTestMixin, TestCase): pass <commit_msg>Test requests don't have a charset attribute<commit_after>import json import functools from django.conf import settings from django.test import Client, TestCase __all__ = ['JsonTestClient', 'JsonTestMixin', 'JsonTestCase'] class JsonTestClient(Client): def _json_request(self, method, url, data=None, *args, **kwargs): method_func = getattr(super(JsonTestClient, self), method) if method == 'get': encode = lambda x: x else: encode = json.dumps if data is not None: resp = method_func(url, encode(data), content_type='application/json', *args, **kwargs) else: resp = method_func(url, content_type='application/json', *args, **kwargs) if resp['Content-Type'].startswith('application/json') and resp.content: charset = resp.charset if hasattr(resp, 'charset') else settings.DEFAULT_CHARSET resp.json = json.loads(resp.content.decode(charset)) return resp def __getattribute__(self, attr): if attr in ('get', 'post', 'put', 'delete', 'trace', 'head', 'patch', 'options'): return functools.partial(self._json_request, attr) else: return super(JsonTestClient, self).__getattribute__(attr) class JsonTestMixin(object): client_class = JsonTestClient class JsonTestCase(JsonTestMixin, TestCase): pass
d3ee9e437d8fb0b35a5eb2df4ad0c2ba5127f39b
chainer/functions/activation/selu.py
chainer/functions/activation/selu.py
from chainer.functions.activation.elu import elu def selu(x, alpha=1.6732632423543772848170429916717, scale=1.0507009873554804934193349852946): """Scaled Exponential Linear Unit function. For parameters :math:`\\alpha` and :math:`\\lambda`, it is expressed as .. math:: f(x) = \\lambda \\left \\{ \\begin{array}{ll} x & {\\rm if}~ x \\ge 0 \\\\ \\alpha (\\exp(x) - 1) & {\\rm if}~ x < 0, \\end{array} \\right. See: https://arxiv.org/abs/1706.02515 Args: x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \ :class:`cupy.ndarray`): Input variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. alpha (float): Parameter :math:`\\alpha`. scale (float): Parameter :math:`\\lambda`. Returns: ~chainer.Variable: Output variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. """ return scale * elu(x, alpha=alpha)
from chainer.functions.activation import elu def selu(x, alpha=1.6732632423543772848170429916717, scale=1.0507009873554804934193349852946): """Scaled Exponential Linear Unit function. For parameters :math:`\\alpha` and :math:`\\lambda`, it is expressed as .. math:: f(x) = \\lambda \\left \\{ \\begin{array}{ll} x & {\\rm if}~ x \\ge 0 \\\\ \\alpha (\\exp(x) - 1) & {\\rm if}~ x < 0, \\end{array} \\right. See: https://arxiv.org/abs/1706.02515 Args: x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \ :class:`cupy.ndarray`): Input variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. alpha (float): Parameter :math:`\\alpha`. scale (float): Parameter :math:`\\lambda`. Returns: ~chainer.Variable: Output variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. """ return scale * elu.elu(x, alpha=alpha)
Stop directly importing non-module symbol
Stop directly importing non-module symbol
Python
mit
hvy/chainer,niboshi/chainer,pfnet/chainer,kashif/chainer,ktnyt/chainer,jnishi/chainer,chainer/chainer,ronekko/chainer,wkentaro/chainer,hvy/chainer,wkentaro/chainer,chainer/chainer,wkentaro/chainer,rezoo/chainer,tkerola/chainer,okuta/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,jnishi/chainer,niboshi/chainer,niboshi/chainer,hvy/chainer,okuta/chainer,chainer/chainer,jnishi/chainer,keisuke-umezawa/chainer,jnishi/chainer,okuta/chainer,chainer/chainer,niboshi/chainer,hvy/chainer,wkentaro/chainer,aonotas/chainer,ktnyt/chainer,ktnyt/chainer,anaruse/chainer,okuta/chainer,ktnyt/chainer,keisuke-umezawa/chainer
from chainer.functions.activation.elu import elu def selu(x, alpha=1.6732632423543772848170429916717, scale=1.0507009873554804934193349852946): """Scaled Exponential Linear Unit function. For parameters :math:`\\alpha` and :math:`\\lambda`, it is expressed as .. math:: f(x) = \\lambda \\left \\{ \\begin{array}{ll} x & {\\rm if}~ x \\ge 0 \\\\ \\alpha (\\exp(x) - 1) & {\\rm if}~ x < 0, \\end{array} \\right. See: https://arxiv.org/abs/1706.02515 Args: x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \ :class:`cupy.ndarray`): Input variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. alpha (float): Parameter :math:`\\alpha`. scale (float): Parameter :math:`\\lambda`. Returns: ~chainer.Variable: Output variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. """ return scale * elu(x, alpha=alpha) Stop directly importing non-module symbol
from chainer.functions.activation import elu def selu(x, alpha=1.6732632423543772848170429916717, scale=1.0507009873554804934193349852946): """Scaled Exponential Linear Unit function. For parameters :math:`\\alpha` and :math:`\\lambda`, it is expressed as .. math:: f(x) = \\lambda \\left \\{ \\begin{array}{ll} x & {\\rm if}~ x \\ge 0 \\\\ \\alpha (\\exp(x) - 1) & {\\rm if}~ x < 0, \\end{array} \\right. See: https://arxiv.org/abs/1706.02515 Args: x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \ :class:`cupy.ndarray`): Input variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. alpha (float): Parameter :math:`\\alpha`. scale (float): Parameter :math:`\\lambda`. Returns: ~chainer.Variable: Output variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. """ return scale * elu.elu(x, alpha=alpha)
<commit_before>from chainer.functions.activation.elu import elu def selu(x, alpha=1.6732632423543772848170429916717, scale=1.0507009873554804934193349852946): """Scaled Exponential Linear Unit function. For parameters :math:`\\alpha` and :math:`\\lambda`, it is expressed as .. math:: f(x) = \\lambda \\left \\{ \\begin{array}{ll} x & {\\rm if}~ x \\ge 0 \\\\ \\alpha (\\exp(x) - 1) & {\\rm if}~ x < 0, \\end{array} \\right. See: https://arxiv.org/abs/1706.02515 Args: x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \ :class:`cupy.ndarray`): Input variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. alpha (float): Parameter :math:`\\alpha`. scale (float): Parameter :math:`\\lambda`. Returns: ~chainer.Variable: Output variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. """ return scale * elu(x, alpha=alpha) <commit_msg>Stop directly importing non-module symbol<commit_after>
from chainer.functions.activation import elu def selu(x, alpha=1.6732632423543772848170429916717, scale=1.0507009873554804934193349852946): """Scaled Exponential Linear Unit function. For parameters :math:`\\alpha` and :math:`\\lambda`, it is expressed as .. math:: f(x) = \\lambda \\left \\{ \\begin{array}{ll} x & {\\rm if}~ x \\ge 0 \\\\ \\alpha (\\exp(x) - 1) & {\\rm if}~ x < 0, \\end{array} \\right. See: https://arxiv.org/abs/1706.02515 Args: x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \ :class:`cupy.ndarray`): Input variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. alpha (float): Parameter :math:`\\alpha`. scale (float): Parameter :math:`\\lambda`. Returns: ~chainer.Variable: Output variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. """ return scale * elu.elu(x, alpha=alpha)
from chainer.functions.activation.elu import elu def selu(x, alpha=1.6732632423543772848170429916717, scale=1.0507009873554804934193349852946): """Scaled Exponential Linear Unit function. For parameters :math:`\\alpha` and :math:`\\lambda`, it is expressed as .. math:: f(x) = \\lambda \\left \\{ \\begin{array}{ll} x & {\\rm if}~ x \\ge 0 \\\\ \\alpha (\\exp(x) - 1) & {\\rm if}~ x < 0, \\end{array} \\right. See: https://arxiv.org/abs/1706.02515 Args: x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \ :class:`cupy.ndarray`): Input variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. alpha (float): Parameter :math:`\\alpha`. scale (float): Parameter :math:`\\lambda`. Returns: ~chainer.Variable: Output variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. """ return scale * elu(x, alpha=alpha) Stop directly importing non-module symbolfrom chainer.functions.activation import elu def selu(x, alpha=1.6732632423543772848170429916717, scale=1.0507009873554804934193349852946): """Scaled Exponential Linear Unit function. For parameters :math:`\\alpha` and :math:`\\lambda`, it is expressed as .. math:: f(x) = \\lambda \\left \\{ \\begin{array}{ll} x & {\\rm if}~ x \\ge 0 \\\\ \\alpha (\\exp(x) - 1) & {\\rm if}~ x < 0, \\end{array} \\right. See: https://arxiv.org/abs/1706.02515 Args: x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \ :class:`cupy.ndarray`): Input variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. alpha (float): Parameter :math:`\\alpha`. scale (float): Parameter :math:`\\lambda`. Returns: ~chainer.Variable: Output variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. """ return scale * elu.elu(x, alpha=alpha)
<commit_before>from chainer.functions.activation.elu import elu def selu(x, alpha=1.6732632423543772848170429916717, scale=1.0507009873554804934193349852946): """Scaled Exponential Linear Unit function. For parameters :math:`\\alpha` and :math:`\\lambda`, it is expressed as .. math:: f(x) = \\lambda \\left \\{ \\begin{array}{ll} x & {\\rm if}~ x \\ge 0 \\\\ \\alpha (\\exp(x) - 1) & {\\rm if}~ x < 0, \\end{array} \\right. See: https://arxiv.org/abs/1706.02515 Args: x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \ :class:`cupy.ndarray`): Input variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. alpha (float): Parameter :math:`\\alpha`. scale (float): Parameter :math:`\\lambda`. Returns: ~chainer.Variable: Output variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. """ return scale * elu(x, alpha=alpha) <commit_msg>Stop directly importing non-module symbol<commit_after>from chainer.functions.activation import elu def selu(x, alpha=1.6732632423543772848170429916717, scale=1.0507009873554804934193349852946): """Scaled Exponential Linear Unit function. For parameters :math:`\\alpha` and :math:`\\lambda`, it is expressed as .. math:: f(x) = \\lambda \\left \\{ \\begin{array}{ll} x & {\\rm if}~ x \\ge 0 \\\\ \\alpha (\\exp(x) - 1) & {\\rm if}~ x < 0, \\end{array} \\right. See: https://arxiv.org/abs/1706.02515 Args: x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \ :class:`cupy.ndarray`): Input variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. alpha (float): Parameter :math:`\\alpha`. scale (float): Parameter :math:`\\lambda`. Returns: ~chainer.Variable: Output variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. """ return scale * elu.elu(x, alpha=alpha)
347681637c7c9d28ba1c787bb77da1296a02d13f
ckanext/archiver/default_settings.py
ckanext/archiver/default_settings.py
# path to ckan config file CKAN_CONFIG = '/home/okfn/pyenv/src/ckan/ckan.ini' # directory to save downloaded files to ARCHIVE_DIR = '/tmp/archive' # Use this user name when requesting data from ckan ARCHIVE_USER = u'okfn_maintenance' # Max content-length of archived files, larger files will be ignored MAX_CONTENT_LENGTH = 500000
# URL to the CKAN instance CKAN_URL = 'http://127.0.0.1:5000' # API key for the CKAN user that the archiver will authenticate as. # This user must be a system administrator API_KEY = '' # directory to save downloaded files to ARCHIVE_DIR = '/tmp/archive' # Max content-length of archived files, larger files will be ignored MAX_CONTENT_LENGTH = 500000
Change settings to use API key and CKAN URL
Change settings to use API key and CKAN URL
Python
mit
ckan/ckanext-archiver,ckan/ckanext-archiver,DanePubliczneGovPl/ckanext-archiver,ckan/ckanext-archiver,datagovuk/ckanext-archiver,datagovuk/ckanext-archiver,datagovuk/ckanext-archiver,DanePubliczneGovPl/ckanext-archiver,DanePubliczneGovPl/ckanext-archiver
# path to ckan config file CKAN_CONFIG = '/home/okfn/pyenv/src/ckan/ckan.ini' # directory to save downloaded files to ARCHIVE_DIR = '/tmp/archive' # Use this user name when requesting data from ckan ARCHIVE_USER = u'okfn_maintenance' # Max content-length of archived files, larger files will be ignored MAX_CONTENT_LENGTH = 500000 Change settings to use API key and CKAN URL
# URL to the CKAN instance CKAN_URL = 'http://127.0.0.1:5000' # API key for the CKAN user that the archiver will authenticate as. # This user must be a system administrator API_KEY = '' # directory to save downloaded files to ARCHIVE_DIR = '/tmp/archive' # Max content-length of archived files, larger files will be ignored MAX_CONTENT_LENGTH = 500000
<commit_before># path to ckan config file CKAN_CONFIG = '/home/okfn/pyenv/src/ckan/ckan.ini' # directory to save downloaded files to ARCHIVE_DIR = '/tmp/archive' # Use this user name when requesting data from ckan ARCHIVE_USER = u'okfn_maintenance' # Max content-length of archived files, larger files will be ignored MAX_CONTENT_LENGTH = 500000 <commit_msg>Change settings to use API key and CKAN URL<commit_after>
# URL to the CKAN instance CKAN_URL = 'http://127.0.0.1:5000' # API key for the CKAN user that the archiver will authenticate as. # This user must be a system administrator API_KEY = '' # directory to save downloaded files to ARCHIVE_DIR = '/tmp/archive' # Max content-length of archived files, larger files will be ignored MAX_CONTENT_LENGTH = 500000
# path to ckan config file CKAN_CONFIG = '/home/okfn/pyenv/src/ckan/ckan.ini' # directory to save downloaded files to ARCHIVE_DIR = '/tmp/archive' # Use this user name when requesting data from ckan ARCHIVE_USER = u'okfn_maintenance' # Max content-length of archived files, larger files will be ignored MAX_CONTENT_LENGTH = 500000 Change settings to use API key and CKAN URL# URL to the CKAN instance CKAN_URL = 'http://127.0.0.1:5000' # API key for the CKAN user that the archiver will authenticate as. # This user must be a system administrator API_KEY = '' # directory to save downloaded files to ARCHIVE_DIR = '/tmp/archive' # Max content-length of archived files, larger files will be ignored MAX_CONTENT_LENGTH = 500000
<commit_before># path to ckan config file CKAN_CONFIG = '/home/okfn/pyenv/src/ckan/ckan.ini' # directory to save downloaded files to ARCHIVE_DIR = '/tmp/archive' # Use this user name when requesting data from ckan ARCHIVE_USER = u'okfn_maintenance' # Max content-length of archived files, larger files will be ignored MAX_CONTENT_LENGTH = 500000 <commit_msg>Change settings to use API key and CKAN URL<commit_after># URL to the CKAN instance CKAN_URL = 'http://127.0.0.1:5000' # API key for the CKAN user that the archiver will authenticate as. # This user must be a system administrator API_KEY = '' # directory to save downloaded files to ARCHIVE_DIR = '/tmp/archive' # Max content-length of archived files, larger files will be ignored MAX_CONTENT_LENGTH = 500000
8da134823a56567e09a09aefc44837a837644912
ddcz/urls.py
ddcz/urls.py
from django.urls import path from . import views app_name='ddcz' urlpatterns = [ path('', views.index, name='news'), path('rubriky/<creative_page_slug>/', views.common_articles, name='common-article-list'), path('rubriky/<creative_page_slug>/<int:article_id>-<article_slug>/', views.common_article_detail, name='common-article-detail'), path('seznamka/', views.dating, name='dating'), path('nastaveni/zmena-skinu/', views.change_skin, name='change-skin'), ]
from django.urls import path from django.views.generic.base import RedirectView from . import views app_name='ddcz' urlpatterns = [ path('', RedirectView.as_view(url='aktuality/', permanent=True)), path('aktuality/', views.index, name='news'), path('rubriky/<creative_page_slug>/', views.common_articles, name='common-article-list'), path('rubriky/<creative_page_slug>/<int:article_id>-<article_slug>/', views.common_article_detail, name='common-article-detail'), path('seznamka/', views.dating, name='dating'), path('nastaveni/zmena-skinu/', views.change_skin, name='change-skin'), ]
Put news on non-root path for clarity
Put news on non-root path for clarity
Python
mit
dracidoupe/graveyard,dracidoupe/graveyard,dracidoupe/graveyard,dracidoupe/graveyard
from django.urls import path from . import views app_name='ddcz' urlpatterns = [ path('', views.index, name='news'), path('rubriky/<creative_page_slug>/', views.common_articles, name='common-article-list'), path('rubriky/<creative_page_slug>/<int:article_id>-<article_slug>/', views.common_article_detail, name='common-article-detail'), path('seznamka/', views.dating, name='dating'), path('nastaveni/zmena-skinu/', views.change_skin, name='change-skin'), ] Put news on non-root path for clarity
from django.urls import path from django.views.generic.base import RedirectView from . import views app_name='ddcz' urlpatterns = [ path('', RedirectView.as_view(url='aktuality/', permanent=True)), path('aktuality/', views.index, name='news'), path('rubriky/<creative_page_slug>/', views.common_articles, name='common-article-list'), path('rubriky/<creative_page_slug>/<int:article_id>-<article_slug>/', views.common_article_detail, name='common-article-detail'), path('seznamka/', views.dating, name='dating'), path('nastaveni/zmena-skinu/', views.change_skin, name='change-skin'), ]
<commit_before>from django.urls import path from . import views app_name='ddcz' urlpatterns = [ path('', views.index, name='news'), path('rubriky/<creative_page_slug>/', views.common_articles, name='common-article-list'), path('rubriky/<creative_page_slug>/<int:article_id>-<article_slug>/', views.common_article_detail, name='common-article-detail'), path('seznamka/', views.dating, name='dating'), path('nastaveni/zmena-skinu/', views.change_skin, name='change-skin'), ] <commit_msg>Put news on non-root path for clarity<commit_after>
from django.urls import path from django.views.generic.base import RedirectView from . import views app_name='ddcz' urlpatterns = [ path('', RedirectView.as_view(url='aktuality/', permanent=True)), path('aktuality/', views.index, name='news'), path('rubriky/<creative_page_slug>/', views.common_articles, name='common-article-list'), path('rubriky/<creative_page_slug>/<int:article_id>-<article_slug>/', views.common_article_detail, name='common-article-detail'), path('seznamka/', views.dating, name='dating'), path('nastaveni/zmena-skinu/', views.change_skin, name='change-skin'), ]
from django.urls import path from . import views app_name='ddcz' urlpatterns = [ path('', views.index, name='news'), path('rubriky/<creative_page_slug>/', views.common_articles, name='common-article-list'), path('rubriky/<creative_page_slug>/<int:article_id>-<article_slug>/', views.common_article_detail, name='common-article-detail'), path('seznamka/', views.dating, name='dating'), path('nastaveni/zmena-skinu/', views.change_skin, name='change-skin'), ] Put news on non-root path for clarityfrom django.urls import path from django.views.generic.base import RedirectView from . import views app_name='ddcz' urlpatterns = [ path('', RedirectView.as_view(url='aktuality/', permanent=True)), path('aktuality/', views.index, name='news'), path('rubriky/<creative_page_slug>/', views.common_articles, name='common-article-list'), path('rubriky/<creative_page_slug>/<int:article_id>-<article_slug>/', views.common_article_detail, name='common-article-detail'), path('seznamka/', views.dating, name='dating'), path('nastaveni/zmena-skinu/', views.change_skin, name='change-skin'), ]
<commit_before>from django.urls import path from . import views app_name='ddcz' urlpatterns = [ path('', views.index, name='news'), path('rubriky/<creative_page_slug>/', views.common_articles, name='common-article-list'), path('rubriky/<creative_page_slug>/<int:article_id>-<article_slug>/', views.common_article_detail, name='common-article-detail'), path('seznamka/', views.dating, name='dating'), path('nastaveni/zmena-skinu/', views.change_skin, name='change-skin'), ] <commit_msg>Put news on non-root path for clarity<commit_after>from django.urls import path from django.views.generic.base import RedirectView from . import views app_name='ddcz' urlpatterns = [ path('', RedirectView.as_view(url='aktuality/', permanent=True)), path('aktuality/', views.index, name='news'), path('rubriky/<creative_page_slug>/', views.common_articles, name='common-article-list'), path('rubriky/<creative_page_slug>/<int:article_id>-<article_slug>/', views.common_article_detail, name='common-article-detail'), path('seznamka/', views.dating, name='dating'), path('nastaveni/zmena-skinu/', views.change_skin, name='change-skin'), ]
a103968558963c032db7294ed15560429861550d
django_filepicker/widgets.py
django_filepicker/widgets.py
from django.conf import settings from django.forms import widgets #JS_URL is the url to the filepicker.io javascript library JS_VERSION = 1 JS_URL = "//api.filepicker.io/v%d/filepicker.js" % (JS_VERSION) if hasattr(settings, 'FILEPICKER_INPUT_TYPE'): INPUT_TYPE = settings.FILEPICKER_INPUT_TYPE else: INPUT_TYPE = 'filepicker-dragdrop' class FPFileWidget(widgets.Input): input_type = INPUT_TYPE needs_multipart_form = False def value_from_datadict_old(self, data, files, name): #If we are using the middleware, then the data will already be #in FILES, if not it will be in POST if name not in data: return super(FPFileWidget, self).value_from_datadict( data, files, name) return data class Media: js = (JS_URL,)
from django.conf import settings from django.forms import widgets #JS_URL is the url to the filepicker.io javascript library JS_VERSION = getattr(settings, "FILEPICKER_JS_VERSION", 0) JS_URL = "//api.filepicker.io/v%d/filepicker.js" % (JS_VERSION) INPUT_TYPE = getattr(settings, "FILEPICKER_INPUT_TYPE", "filepicker-dragdrop") class FPFileWidget(widgets.Input): input_type = INPUT_TYPE needs_multipart_form = False def value_from_datadict_old(self, data, files, name): #If we are using the middleware, then the data will already be #in FILES, if not it will be in POST if name not in data: return super(FPFileWidget, self).value_from_datadict( data, files, name) return data class Media: js = (JS_URL,)
Allow Filepicker JS version to be configured
Allow Filepicker JS version to be configured Filepicker JS version can now be configured using FILEPICKER_JS_VERSION. Version 0 is default. Changed the logic of INPUT_TYPE to use getattr instead of hasattr and an if statement.
Python
mit
filepicker/filepicker-django,filepicker/filepicker-django,FundedByMe/filepicker-django,FundedByMe/filepicker-django
from django.conf import settings from django.forms import widgets #JS_URL is the url to the filepicker.io javascript library JS_VERSION = 1 JS_URL = "//api.filepicker.io/v%d/filepicker.js" % (JS_VERSION) if hasattr(settings, 'FILEPICKER_INPUT_TYPE'): INPUT_TYPE = settings.FILEPICKER_INPUT_TYPE else: INPUT_TYPE = 'filepicker-dragdrop' class FPFileWidget(widgets.Input): input_type = INPUT_TYPE needs_multipart_form = False def value_from_datadict_old(self, data, files, name): #If we are using the middleware, then the data will already be #in FILES, if not it will be in POST if name not in data: return super(FPFileWidget, self).value_from_datadict( data, files, name) return data class Media: js = (JS_URL,) Allow Filepicker JS version to be configured Filepicker JS version can now be configured using FILEPICKER_JS_VERSION. Version 0 is default. Changed the logic of INPUT_TYPE to use getattr instead of hasattr and an if statement.
from django.conf import settings from django.forms import widgets #JS_URL is the url to the filepicker.io javascript library JS_VERSION = getattr(settings, "FILEPICKER_JS_VERSION", 0) JS_URL = "//api.filepicker.io/v%d/filepicker.js" % (JS_VERSION) INPUT_TYPE = getattr(settings, "FILEPICKER_INPUT_TYPE", "filepicker-dragdrop") class FPFileWidget(widgets.Input): input_type = INPUT_TYPE needs_multipart_form = False def value_from_datadict_old(self, data, files, name): #If we are using the middleware, then the data will already be #in FILES, if not it will be in POST if name not in data: return super(FPFileWidget, self).value_from_datadict( data, files, name) return data class Media: js = (JS_URL,)
<commit_before>from django.conf import settings from django.forms import widgets #JS_URL is the url to the filepicker.io javascript library JS_VERSION = 1 JS_URL = "//api.filepicker.io/v%d/filepicker.js" % (JS_VERSION) if hasattr(settings, 'FILEPICKER_INPUT_TYPE'): INPUT_TYPE = settings.FILEPICKER_INPUT_TYPE else: INPUT_TYPE = 'filepicker-dragdrop' class FPFileWidget(widgets.Input): input_type = INPUT_TYPE needs_multipart_form = False def value_from_datadict_old(self, data, files, name): #If we are using the middleware, then the data will already be #in FILES, if not it will be in POST if name not in data: return super(FPFileWidget, self).value_from_datadict( data, files, name) return data class Media: js = (JS_URL,) <commit_msg>Allow Filepicker JS version to be configured Filepicker JS version can now be configured using FILEPICKER_JS_VERSION. Version 0 is default. Changed the logic of INPUT_TYPE to use getattr instead of hasattr and an if statement.<commit_after>
from django.conf import settings from django.forms import widgets #JS_URL is the url to the filepicker.io javascript library JS_VERSION = getattr(settings, "FILEPICKER_JS_VERSION", 0) JS_URL = "//api.filepicker.io/v%d/filepicker.js" % (JS_VERSION) INPUT_TYPE = getattr(settings, "FILEPICKER_INPUT_TYPE", "filepicker-dragdrop") class FPFileWidget(widgets.Input): input_type = INPUT_TYPE needs_multipart_form = False def value_from_datadict_old(self, data, files, name): #If we are using the middleware, then the data will already be #in FILES, if not it will be in POST if name not in data: return super(FPFileWidget, self).value_from_datadict( data, files, name) return data class Media: js = (JS_URL,)
from django.conf import settings from django.forms import widgets #JS_URL is the url to the filepicker.io javascript library JS_VERSION = 1 JS_URL = "//api.filepicker.io/v%d/filepicker.js" % (JS_VERSION) if hasattr(settings, 'FILEPICKER_INPUT_TYPE'): INPUT_TYPE = settings.FILEPICKER_INPUT_TYPE else: INPUT_TYPE = 'filepicker-dragdrop' class FPFileWidget(widgets.Input): input_type = INPUT_TYPE needs_multipart_form = False def value_from_datadict_old(self, data, files, name): #If we are using the middleware, then the data will already be #in FILES, if not it will be in POST if name not in data: return super(FPFileWidget, self).value_from_datadict( data, files, name) return data class Media: js = (JS_URL,) Allow Filepicker JS version to be configured Filepicker JS version can now be configured using FILEPICKER_JS_VERSION. Version 0 is default. Changed the logic of INPUT_TYPE to use getattr instead of hasattr and an if statement.from django.conf import settings from django.forms import widgets #JS_URL is the url to the filepicker.io javascript library JS_VERSION = getattr(settings, "FILEPICKER_JS_VERSION", 0) JS_URL = "//api.filepicker.io/v%d/filepicker.js" % (JS_VERSION) INPUT_TYPE = getattr(settings, "FILEPICKER_INPUT_TYPE", "filepicker-dragdrop") class FPFileWidget(widgets.Input): input_type = INPUT_TYPE needs_multipart_form = False def value_from_datadict_old(self, data, files, name): #If we are using the middleware, then the data will already be #in FILES, if not it will be in POST if name not in data: return super(FPFileWidget, self).value_from_datadict( data, files, name) return data class Media: js = (JS_URL,)
<commit_before>from django.conf import settings from django.forms import widgets #JS_URL is the url to the filepicker.io javascript library JS_VERSION = 1 JS_URL = "//api.filepicker.io/v%d/filepicker.js" % (JS_VERSION) if hasattr(settings, 'FILEPICKER_INPUT_TYPE'): INPUT_TYPE = settings.FILEPICKER_INPUT_TYPE else: INPUT_TYPE = 'filepicker-dragdrop' class FPFileWidget(widgets.Input): input_type = INPUT_TYPE needs_multipart_form = False def value_from_datadict_old(self, data, files, name): #If we are using the middleware, then the data will already be #in FILES, if not it will be in POST if name not in data: return super(FPFileWidget, self).value_from_datadict( data, files, name) return data class Media: js = (JS_URL,) <commit_msg>Allow Filepicker JS version to be configured Filepicker JS version can now be configured using FILEPICKER_JS_VERSION. Version 0 is default. Changed the logic of INPUT_TYPE to use getattr instead of hasattr and an if statement.<commit_after>from django.conf import settings from django.forms import widgets #JS_URL is the url to the filepicker.io javascript library JS_VERSION = getattr(settings, "FILEPICKER_JS_VERSION", 0) JS_URL = "//api.filepicker.io/v%d/filepicker.js" % (JS_VERSION) INPUT_TYPE = getattr(settings, "FILEPICKER_INPUT_TYPE", "filepicker-dragdrop") class FPFileWidget(widgets.Input): input_type = INPUT_TYPE needs_multipart_form = False def value_from_datadict_old(self, data, files, name): #If we are using the middleware, then the data will already be #in FILES, if not it will be in POST if name not in data: return super(FPFileWidget, self).value_from_datadict( data, files, name) return data class Media: js = (JS_URL,)
7a3a1ffc6c153e4ea867988d12725f92d133ffc4
js2py/internals/seval.py
js2py/internals/seval.py
import pyjsparser from space import Space import fill_space from byte_trans import ByteCodeGenerator from code import Code from simplex import MakeError import sys sys.setrecursionlimit(100000) pyjsparser.parser.ENABLE_JS2PY_ERRORS = lambda msg: MakeError(u'SyntaxError', unicode(msg)) def eval_js_vm(js): a = ByteCodeGenerator(Code()) s = Space() a.exe.space = s s.exe = a.exe d = pyjsparser.parse(js) a.emit(d) fill_space.fill_space(s, a) # print a.exe.tape a.exe.compile() return a.exe.run(a.exe.space.GlobalObj)
import pyjsparser from space import Space import fill_space from byte_trans import ByteCodeGenerator from code import Code from simplex import MakeError import sys sys.setrecursionlimit(100000) pyjsparser.parser.ENABLE_JS2PY_ERRORS = lambda msg: MakeError(u'SyntaxError', unicode(msg)) def get_js_bytecode(js): a = ByteCodeGenerator(Code()) d = pyjsparser.parse(js) a.emit(d) return a.exe.tape def eval_js_vm(js): a = ByteCodeGenerator(Code()) s = Space() a.exe.space = s s.exe = a.exe d = pyjsparser.parse(js) a.emit(d) fill_space.fill_space(s, a) # print a.exe.tape a.exe.compile() return a.exe.run(a.exe.space.GlobalObj)
Add a function returning js bytecode.
Add a function returning js bytecode.
Python
mit
PiotrDabkowski/Js2Py,PiotrDabkowski/Js2Py,PiotrDabkowski/Js2Py
import pyjsparser from space import Space import fill_space from byte_trans import ByteCodeGenerator from code import Code from simplex import MakeError import sys sys.setrecursionlimit(100000) pyjsparser.parser.ENABLE_JS2PY_ERRORS = lambda msg: MakeError(u'SyntaxError', unicode(msg)) def eval_js_vm(js): a = ByteCodeGenerator(Code()) s = Space() a.exe.space = s s.exe = a.exe d = pyjsparser.parse(js) a.emit(d) fill_space.fill_space(s, a) # print a.exe.tape a.exe.compile() return a.exe.run(a.exe.space.GlobalObj) Add a function returning js bytecode.
import pyjsparser from space import Space import fill_space from byte_trans import ByteCodeGenerator from code import Code from simplex import MakeError import sys sys.setrecursionlimit(100000) pyjsparser.parser.ENABLE_JS2PY_ERRORS = lambda msg: MakeError(u'SyntaxError', unicode(msg)) def get_js_bytecode(js): a = ByteCodeGenerator(Code()) d = pyjsparser.parse(js) a.emit(d) return a.exe.tape def eval_js_vm(js): a = ByteCodeGenerator(Code()) s = Space() a.exe.space = s s.exe = a.exe d = pyjsparser.parse(js) a.emit(d) fill_space.fill_space(s, a) # print a.exe.tape a.exe.compile() return a.exe.run(a.exe.space.GlobalObj)
<commit_before>import pyjsparser from space import Space import fill_space from byte_trans import ByteCodeGenerator from code import Code from simplex import MakeError import sys sys.setrecursionlimit(100000) pyjsparser.parser.ENABLE_JS2PY_ERRORS = lambda msg: MakeError(u'SyntaxError', unicode(msg)) def eval_js_vm(js): a = ByteCodeGenerator(Code()) s = Space() a.exe.space = s s.exe = a.exe d = pyjsparser.parse(js) a.emit(d) fill_space.fill_space(s, a) # print a.exe.tape a.exe.compile() return a.exe.run(a.exe.space.GlobalObj) <commit_msg>Add a function returning js bytecode.<commit_after>
import pyjsparser from space import Space import fill_space from byte_trans import ByteCodeGenerator from code import Code from simplex import MakeError import sys sys.setrecursionlimit(100000) pyjsparser.parser.ENABLE_JS2PY_ERRORS = lambda msg: MakeError(u'SyntaxError', unicode(msg)) def get_js_bytecode(js): a = ByteCodeGenerator(Code()) d = pyjsparser.parse(js) a.emit(d) return a.exe.tape def eval_js_vm(js): a = ByteCodeGenerator(Code()) s = Space() a.exe.space = s s.exe = a.exe d = pyjsparser.parse(js) a.emit(d) fill_space.fill_space(s, a) # print a.exe.tape a.exe.compile() return a.exe.run(a.exe.space.GlobalObj)
import pyjsparser from space import Space import fill_space from byte_trans import ByteCodeGenerator from code import Code from simplex import MakeError import sys sys.setrecursionlimit(100000) pyjsparser.parser.ENABLE_JS2PY_ERRORS = lambda msg: MakeError(u'SyntaxError', unicode(msg)) def eval_js_vm(js): a = ByteCodeGenerator(Code()) s = Space() a.exe.space = s s.exe = a.exe d = pyjsparser.parse(js) a.emit(d) fill_space.fill_space(s, a) # print a.exe.tape a.exe.compile() return a.exe.run(a.exe.space.GlobalObj) Add a function returning js bytecode.import pyjsparser from space import Space import fill_space from byte_trans import ByteCodeGenerator from code import Code from simplex import MakeError import sys sys.setrecursionlimit(100000) pyjsparser.parser.ENABLE_JS2PY_ERRORS = lambda msg: MakeError(u'SyntaxError', unicode(msg)) def get_js_bytecode(js): a = ByteCodeGenerator(Code()) d = pyjsparser.parse(js) a.emit(d) return a.exe.tape def eval_js_vm(js): a = ByteCodeGenerator(Code()) s = Space() a.exe.space = s s.exe = a.exe d = pyjsparser.parse(js) a.emit(d) fill_space.fill_space(s, a) # print a.exe.tape a.exe.compile() return a.exe.run(a.exe.space.GlobalObj)
<commit_before>import pyjsparser from space import Space import fill_space from byte_trans import ByteCodeGenerator from code import Code from simplex import MakeError import sys sys.setrecursionlimit(100000) pyjsparser.parser.ENABLE_JS2PY_ERRORS = lambda msg: MakeError(u'SyntaxError', unicode(msg)) def eval_js_vm(js): a = ByteCodeGenerator(Code()) s = Space() a.exe.space = s s.exe = a.exe d = pyjsparser.parse(js) a.emit(d) fill_space.fill_space(s, a) # print a.exe.tape a.exe.compile() return a.exe.run(a.exe.space.GlobalObj) <commit_msg>Add a function returning js bytecode.<commit_after>import pyjsparser from space import Space import fill_space from byte_trans import ByteCodeGenerator from code import Code from simplex import MakeError import sys sys.setrecursionlimit(100000) pyjsparser.parser.ENABLE_JS2PY_ERRORS = lambda msg: MakeError(u'SyntaxError', unicode(msg)) def get_js_bytecode(js): a = ByteCodeGenerator(Code()) d = pyjsparser.parse(js) a.emit(d) return a.exe.tape def eval_js_vm(js): a = ByteCodeGenerator(Code()) s = Space() a.exe.space = s s.exe = a.exe d = pyjsparser.parse(js) a.emit(d) fill_space.fill_space(s, a) # print a.exe.tape a.exe.compile() return a.exe.run(a.exe.space.GlobalObj)
2ceb4f7195220d52ce92156da9332b50369fb746
bluesnap/exceptions.py
bluesnap/exceptions.py
class APIError(Exception): pass class ImproperlyConfigured(Exception): pass class ValidationError(Exception): pass
class APIError(Exception): def __init__(self, messages): self.messages = messages def __str__(self): import json return json.dumps(self.messages, indent=2) class ImproperlyConfigured(Exception): pass class ValidationError(Exception): pass
Return formatted messages in APIError
Return formatted messages in APIError
Python
mit
justyoyo/bluesnap-python,kowito/bluesnap-python,justyoyo/bluesnap-python,kowito/bluesnap-python
class APIError(Exception): pass class ImproperlyConfigured(Exception): pass class ValidationError(Exception): pass Return formatted messages in APIError
class APIError(Exception): def __init__(self, messages): self.messages = messages def __str__(self): import json return json.dumps(self.messages, indent=2) class ImproperlyConfigured(Exception): pass class ValidationError(Exception): pass
<commit_before>class APIError(Exception): pass class ImproperlyConfigured(Exception): pass class ValidationError(Exception): pass <commit_msg>Return formatted messages in APIError<commit_after>
class APIError(Exception): def __init__(self, messages): self.messages = messages def __str__(self): import json return json.dumps(self.messages, indent=2) class ImproperlyConfigured(Exception): pass class ValidationError(Exception): pass
class APIError(Exception): pass class ImproperlyConfigured(Exception): pass class ValidationError(Exception): pass Return formatted messages in APIErrorclass APIError(Exception): def __init__(self, messages): self.messages = messages def __str__(self): import json return json.dumps(self.messages, indent=2) class ImproperlyConfigured(Exception): pass class ValidationError(Exception): pass
<commit_before>class APIError(Exception): pass class ImproperlyConfigured(Exception): pass class ValidationError(Exception): pass <commit_msg>Return formatted messages in APIError<commit_after>class APIError(Exception): def __init__(self, messages): self.messages = messages def __str__(self): import json return json.dumps(self.messages, indent=2) class ImproperlyConfigured(Exception): pass class ValidationError(Exception): pass
0b122d1d4223844c1e53ce68b00a0cdb1e360573
docs/conf.py
docs/conf.py
import sys from os.path import dirname, abspath sys.path.insert(0, dirname(dirname(abspath(__file__)))) from django.conf import settings settings.configure() project = 'django-slack' version = '' release = '' copyright = '2014, 2015 Chris Lamb' extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx'] html_title = "%s documentation" % project html_static_path = [] master_doc = 'index' exclude_trees = ['_build'] templates_path = ['_templates'] latex_documents = [ ('index', '%s.tex' % project, html_title, 'manual', True), ] intersphinx_mapping = {'http://docs.python.org/': None}
import sys from os.path import dirname, abspath sys.path.insert(0, dirname(dirname(abspath(__file__)))) from django.conf import settings settings.configure() project = 'django-slack' version = '' release = '' copyright = '2014, 2015 Chris Lamb' author = 'lamby' extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx'] html_title = "%s documentation" % project html_static_path = [] master_doc = 'index' exclude_trees = ['_build'] templates_path = ['_templates'] latex_documents = [ ('index', '%s.tex' % project, html_title, author, 'manual', True), ] intersphinx_mapping = {'http://docs.python.org/': None}
Add author to latex_documents to fix sphinx build
Add author to latex_documents to fix sphinx build
Python
bsd-3-clause
lamby/django-slack
import sys from os.path import dirname, abspath sys.path.insert(0, dirname(dirname(abspath(__file__)))) from django.conf import settings settings.configure() project = 'django-slack' version = '' release = '' copyright = '2014, 2015 Chris Lamb' extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx'] html_title = "%s documentation" % project html_static_path = [] master_doc = 'index' exclude_trees = ['_build'] templates_path = ['_templates'] latex_documents = [ ('index', '%s.tex' % project, html_title, 'manual', True), ] intersphinx_mapping = {'http://docs.python.org/': None} Add author to latex_documents to fix sphinx build
import sys from os.path import dirname, abspath sys.path.insert(0, dirname(dirname(abspath(__file__)))) from django.conf import settings settings.configure() project = 'django-slack' version = '' release = '' copyright = '2014, 2015 Chris Lamb' author = 'lamby' extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx'] html_title = "%s documentation" % project html_static_path = [] master_doc = 'index' exclude_trees = ['_build'] templates_path = ['_templates'] latex_documents = [ ('index', '%s.tex' % project, html_title, author, 'manual', True), ] intersphinx_mapping = {'http://docs.python.org/': None}
<commit_before>import sys from os.path import dirname, abspath sys.path.insert(0, dirname(dirname(abspath(__file__)))) from django.conf import settings settings.configure() project = 'django-slack' version = '' release = '' copyright = '2014, 2015 Chris Lamb' extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx'] html_title = "%s documentation" % project html_static_path = [] master_doc = 'index' exclude_trees = ['_build'] templates_path = ['_templates'] latex_documents = [ ('index', '%s.tex' % project, html_title, 'manual', True), ] intersphinx_mapping = {'http://docs.python.org/': None} <commit_msg>Add author to latex_documents to fix sphinx build<commit_after>
import sys from os.path import dirname, abspath sys.path.insert(0, dirname(dirname(abspath(__file__)))) from django.conf import settings settings.configure() project = 'django-slack' version = '' release = '' copyright = '2014, 2015 Chris Lamb' author = 'lamby' extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx'] html_title = "%s documentation" % project html_static_path = [] master_doc = 'index' exclude_trees = ['_build'] templates_path = ['_templates'] latex_documents = [ ('index', '%s.tex' % project, html_title, author, 'manual', True), ] intersphinx_mapping = {'http://docs.python.org/': None}
import sys from os.path import dirname, abspath sys.path.insert(0, dirname(dirname(abspath(__file__)))) from django.conf import settings settings.configure() project = 'django-slack' version = '' release = '' copyright = '2014, 2015 Chris Lamb' extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx'] html_title = "%s documentation" % project html_static_path = [] master_doc = 'index' exclude_trees = ['_build'] templates_path = ['_templates'] latex_documents = [ ('index', '%s.tex' % project, html_title, 'manual', True), ] intersphinx_mapping = {'http://docs.python.org/': None} Add author to latex_documents to fix sphinx buildimport sys from os.path import dirname, abspath sys.path.insert(0, dirname(dirname(abspath(__file__)))) from django.conf import settings settings.configure() project = 'django-slack' version = '' release = '' copyright = '2014, 2015 Chris Lamb' author = 'lamby' extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx'] html_title = "%s documentation" % project html_static_path = [] master_doc = 'index' exclude_trees = ['_build'] templates_path = ['_templates'] latex_documents = [ ('index', '%s.tex' % project, html_title, author, 'manual', True), ] intersphinx_mapping = {'http://docs.python.org/': None}
<commit_before>import sys from os.path import dirname, abspath sys.path.insert(0, dirname(dirname(abspath(__file__)))) from django.conf import settings settings.configure() project = 'django-slack' version = '' release = '' copyright = '2014, 2015 Chris Lamb' extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx'] html_title = "%s documentation" % project html_static_path = [] master_doc = 'index' exclude_trees = ['_build'] templates_path = ['_templates'] latex_documents = [ ('index', '%s.tex' % project, html_title, 'manual', True), ] intersphinx_mapping = {'http://docs.python.org/': None} <commit_msg>Add author to latex_documents to fix sphinx build<commit_after>import sys from os.path import dirname, abspath sys.path.insert(0, dirname(dirname(abspath(__file__)))) from django.conf import settings settings.configure() project = 'django-slack' version = '' release = '' copyright = '2014, 2015 Chris Lamb' author = 'lamby' extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx'] html_title = "%s documentation" % project html_static_path = [] master_doc = 'index' exclude_trees = ['_build'] templates_path = ['_templates'] latex_documents = [ ('index', '%s.tex' % project, html_title, author, 'manual', True), ] intersphinx_mapping = {'http://docs.python.org/': None}