def __init__(self, color, previous, player, final, give_pie=False): super().__init__() self.logger = logging.getLogger("Question") logging.basicConfig( format='%(asctime)s - %(name)s: %(levelname)s - %(message)s', level=logging.INFO) self.final = final self.color = color self.previous = previous self.player = player self.handler = DatabaseHandler() if color == 'black': self.color = random.choice(['green', 'white', 'red', 'blue']) self.question = self.handler.select_color_question(self.color) self.answers = [] self.answers.append(self.question['correct']) self.answers += self.question['incorrect'] random.shuffle(self.answers) self.font = pygame.font.SysFont("Arial", 14) self.selected_answer = "" self.width, self.height = pygame.display.get_surface().get_size() self.delay = 0 self.give_pie = give_pie self.logger.info("Asking {0} a {1} question".format( self.player.name, self.color))
def test_routes_dataframe_closest_stops_returns_closest_stop(self): handler = DatabaseHandler('unit_test_db.sqlite3') handler.initialize_db() handler.add_address(MapLocation(latitude=1, longitude=1, id=1)) handler.add_stop(MapLocation(latitude=2, longitude=2, id=2)) handler.add_stop(MapLocation(latitude=3, longitude=3, id=3)) handler.add_route(address=1, stop=2, distance=100, time=100) handler.add_route(address=1, stop=3, distance=50, time=50) df = handler.routes_dataframe_closest_stops() self.assertEqual(1, df.shape[0], "should be 1 output row") self.assertEqual(1, df.ix[0, 'address_latitude'], 'address should have latitude of 1') self.assertEqual(1, df.ix[0, 'address_longitude'], 'address should have longitude of 1') self.assertEqual( 3, df.ix[0, 'stop_latitude'], 'the stop with latitude of 3 should have been ' 'returned since it had the smallest distance') self.assertEqual( 3, df.ix[0, 'stop_longitude'], 'the stop with longitude of 3 should have been ' 'returned since it had the smallest distance') self.assertEqual( 50, df.ix[0, 'distance'], "the route with the lowest distance should be" "returned in the output dataframe") self.assertEqual( 50, df.ix[0, 'time'], "the route the with lowest distance's time should be" "returned in the output dataframe")
def test_add_addresses_table_adds_table(self, mock_init_db): handler = DatabaseHandler('unit_test_db.sqlite3') handler._add_addresses_table() c = handler.conn.cursor() c.execute("SELECT NAME FROM sqlite_master WHERE " "TYPE='table' and NAME='addresses'") self.assertTrue(c.fetchone(), "addresses table not created")
def test_get_address_without_route_returns_with_correct_id(self): handler = DatabaseHandler('unit_test_db.sqlite3') handler.add_address(MapLocation(latitude=2, longitude=2, id=222)) address_generator = handler.get_address_generator() self.assertEqual(MapLocation(latitude=2, longitude=2, id=222), address_generator.next(), "MapLocation should return correct id")
def test_get_all_stops_returns_list_of_MapLocations(self, mock_init_db): handler = DatabaseHandler('unit_test_db.sqlite3') handler._add_stops_table() handler.add_stop(MapLocation(latitude=5, longitude=6)) handler.add_stop(MapLocation(latitude=3, longitude=-5)) stops = handler.get_all_stops() self.assertEqual((5, 6), (stops[0].latitude, stops[0].longitude)) self.assertEqual((3, -5), (stops[1].latitude, stops[1].longitude))
def test_get_address_without_route_returns_address_when_routes_empty(self): handler = DatabaseHandler('unit_test_db.sqlite3') handler.add_address( location=MapLocation(latitude=5, longitude=6, id=1)) address_generator = handler.get_address_generator() self.assertEqual(MapLocation(latitude=5, longitude=6, id=1), address_generator.next(), "Only MapLocation in addresses was not returned")
def test_add_stop_uses_MapLocation_id_if_nonzero(self, mock_init_db): handler = DatabaseHandler('unit_test_db.sqlite3') handler._add_stops_table() stop_location = MapLocation(latitude=0.48, longitude=179, id=888) handler.add_stop(stop_location) c = handler.conn.cursor() c.execute("SELECT * FROM stops") self.assertEqual(888, c.fetchone()[0])
def test_add_route_adds_route(self): handler = DatabaseHandler('unit_test_db.sqlite3') handler.add_address(location=MapLocation(latitude=5, longitude=5)) handler.add_stop(location=MapLocation(latitude=2, longitude=2)) handler.add_route(address=1, stop=1, distance=10, time=20) c = handler.conn.cursor() c.execute("SELECT * FROM routes") self.assertEqual((1, 1, 1, 10, 20), c.fetchone())
def test_add_address_uses_MapLocation_id_if_nonzero(self, mock_init_db): handler = DatabaseHandler('unit_test_db.sqlite3') handler._add_addresses_table() address_location = MapLocation(latitude=0.33, longitude=4, id=100) handler.add_address(address_location) c = handler.conn.cursor() c.execute("SELECT * FROM addresses") self.assertEqual(100, c.fetchone()[0])
def test_add_address_adds_to_address_table(self, mock_init_db): handler = DatabaseHandler('unit_test_db.sqlite3') handler._add_addresses_table() handler.add_address(location=MapLocation(latitude=0.56, longitude=9.5)) c = handler.conn.cursor() c.execute("SELECT latitude, longitude FROM addresses") row = c.fetchone() self.assertEqual((0.56, 9.5), row)
def test_construct_db_calls_add_stop_table(self): handler = DatabaseHandler('unit_test_db.sqlite3') mock_add_addresses = Mock() handler._add_addresses_table = mock_add_addresses mock_add_stops = Mock() handler._add_stops_table = mock_add_stops handler.initialize_db() self.assertTrue(mock_add_stops.called, "initialize_db did not call _add_stops_table")
def test_add_stop_adds_to_stops_table(self, mock_init_db): handler = DatabaseHandler('unit_test_db.sqlite3') handler._add_stops_table() map_location = MapLocation(latitude=-0.55, longitude=80) handler.add_stop(location=map_location) c = handler.conn.cursor() c.execute("SELECT latitude, longitude FROM stops") row = c.fetchone() self.assertEqual((-.55, 80), row)
def init_game(self): """ Initialize the game """ self.logger.info("Initializing Database") self.database = DatabaseHandler() self.questionHandler = QuestionHandler() self.dice = Dice(6) self.logger.info("Polishing Dice") self.logger.info("Starting Game - Welcome to trivial purfuit")
def test_get_address_without_route_generator_new_address_second_time(self): handler = DatabaseHandler('unit_test_db.sqlite3') handler.add_address(location=MapLocation(latitude=1, longitude=1)) handler.add_address(location=MapLocation(latitude=2, longitude=2)) address_generator = handler.get_address_generator() self.assertEqual(MapLocation(latitude=1, longitude=1, id=1), address_generator.next(), "first returned MapLocation was not correct") self.assertEqual(MapLocation(latitude=2, longitude=2, id=2), address_generator.next(), "second returned MapLocation was not correct")
def test_handler_add_stops_from_file_inserts_one_record( self, mock_init_db): handler = DatabaseHandler('unit_test_db.sqlite3') with open('test_file.csv', 'w') as f: f.write('latitude,longitude\n') f.write('15.35,-1.5\n') handler.add_stops_from_file('test_file.csv') c = handler.conn.cursor() c.execute("SELECT latitude, longitude FROM stops") row = c.fetchone() self.assertEqual((15.35, -1.5), row)
def test_select_color_question(self, random): with patch('builtins.open', mock_open(read_data="a,b,\"c, d, e\",blue")) as mock_file: handler = DatabaseHandler() self.assertEqual(handler.select_color_question('red'), "something") self.assertEqual(handler.select_color_question('blue'), "something") self.assertEqual(handler.select_color_question('green'), "something") self.assertEqual(handler.select_color_question('white'), "something")
def __init__(self): print("STARTING...") print("startup process, will be notified when startup is successful") print( "startup will open connection to mongodb, if not successful, server will crash" ) print("\n") logging.debug("starting mother, setting name, address, family to '' ") logging.debug("initializing database handler") self.databasehandler = DatabaseHandler() logging.debug("initializing self.devices to empty list") self.devices = []
def test_output_routes_calls_correct_function_when_closest_stop_true(self): handler = DatabaseHandler(full=False) handler.routes_dataframe = Mock() handler.routes_dataframe_closest_stops = Mock() handler.output_routes(file_path="test_file.csv", closest_stops_only=True) handler.routes_dataframe_closest_stops.assert_called_once_with() self.assertEqual(0, handler.routes_dataframe.call_count, "routes_dataframe should not be called")
def create_index(self): self.word_docs = {} self.inverted_index = {} db = DatabaseHandler() posts = db.get_posts() total_posts = len(posts) for doc_id in posts: self.pos_tagger(posts[doc_id].text, doc_id) self.compute_inverted_index(total_posts)
def test_get_address_without_route_returns_address_without_route(self): handler = DatabaseHandler('unit_test_db.sqlite3') handler.add_address(location=MapLocation(latitude=1, longitude=2)) handler.add_address(location=MapLocation(latitude=3, longitude=4)) handler.add_stop(location=MapLocation(latitude=0, longitude=0)) c = handler.conn.cursor() c.execute("INSERT INTO routes (address_id, stop_id, distance, time)" "VALUES (1, 1, 1, 1)") c.close() address_generator = handler.get_address_generator() self.assertEqual(MapLocation(latitude=3, longitude=4, id=2), address_generator.next(), "the MapLocation without route was not returned")
def handle_socket(conn): try: data = recv_msg(conn) if (data != None): data = data.decode('utf-8') print("[LOG] Receive Data") niceJson = json.loads(data) Database = DatabaseHandler(DATABASE_IP, DATABASE_PORT, "smartSystem") Database.insertBulkDocument("sensor", niceJson) except (socket.error): conn.close() print("[Warn] Connection Closed by Peer") except: print("[Warn] Unexpected error:", sys.exc_info()) conn.close()
def test_routes_dataframe_closest_stops_returns_for_many_addresses(self): handler = DatabaseHandler('unit_test_db.sqlite3') handler.initialize_db() handler.add_address(MapLocation(latitude=1, longitude=1, id=1)) handler.add_address(MapLocation(latitude=11, longitude=10, id=11)) handler.add_stop(MapLocation(latitude=2, longitude=2, id=2)) handler.add_stop(MapLocation(latitude=12, longitude=12, id=12)) handler.add_route(address=1, stop=2, distance=1, time=1) handler.add_route(address=1, stop=12, distance=11, time=11) handler.add_route(address=11, stop=2, distance=9, time=9) handler.add_route(address=11, stop=12, distance=1, time=1) df = handler.routes_dataframe_closest_stops() self.assertEqual( 2, df.shape[0], "should be 2 output rows since " "there are 2 addresses with routes") self.assertEqual( 1, df.ix[0, 'distance'], "distance for the first row should be 1 " "since that is the shortest route distance")
def main(self, MAX_POSTS=-1): # Load and fit data set print "Fitting data set" tfs = self.fit_dataset() # Take MAX_POSTS posts to classify from database posts = DatabaseHandler().get_posts(MAX_POSTS).values() for post in posts: # Creating vector for new document vec = self.vectorize_text(post.text) # Calculate cosine similarity sim = cosine_similarity(tfs, vec).flatten() # Find top matching category best_match_doc = sim.argmax() print "\nUrl : %s matches best:" % post.url print "Category %s with %.5f sim" % ( self.get_filename(best_match_doc), sim[best_match_doc])
def test_routes_dataframe_has_correct_values(self): handler = DatabaseHandler('unit_test_db.sqlite3') handler.initialize_db() handler.add_address(MapLocation(latitude=11, longitude=50, id=11)) handler.add_stop(MapLocation(latitude=-10, longitude=3, id=800)) handler.add_route(address=11, stop=800, distance=10000, time=50000) df = handler.routes_dataframe() self.assertEqual(1, df.shape[0], "only one row should be output") self.assertEqual(11, df.ix[0, 'address_latitude'], 'incorrect address latitude output') self.assertEqual(50, df.ix[0, 'address_longitude'], 'incorrect address longitude output') self.assertEqual(-10, df.ix[0, 'stop_latitude'], 'incorrect stop latitude output') self.assertEqual(3, df.ix[0, 'stop_longitude'], 'incorrect stop longitude output') self.assertEqual(10000, df.ix[0, 'distance'], 'incorrect distance output') self.assertEqual(50000, df.ix[0, 'time'], 'incorrect time output')
def main(): os.chdir(os.path.dirname(os.path.realpath(__file__))) config_file = parse_args() conf = load_config(config_file) init_logging(conf['DEFAULT']['LogPath']) dh = DatabaseHandler( host=conf['DATABASE']['Host'], user=conf['DATABASE']['User'], password=conf['DATABASE']['Password'], db_name=conf['DATABASE']['DB'] ) np = dh.readNewsProvider() crawler.get_articles_from_news_providers(np, dh) dh.close()
def test_routes_dataframe_only_grabs_routes_no_dangling_locations(self): handler = DatabaseHandler('unit_test_db.sqlite3') handler.initialize_db() handler.add_address(MapLocation(latitude=1, longitude=1, id=1)) handler.add_address(MapLocation(latitude=2, longitude=2, id=2)) handler.add_address(MapLocation(latitude=3, longitude=3, id=3)) handler.add_stop(MapLocation(latitude=11, longitude=11, id=11)) handler.add_stop(MapLocation(latitude=12, longitude=12, id=12)) handler.add_stop(MapLocation(latitude=13, longitude=13, id=13)) handler.add_route(address=1, stop=11, distance=100, time=1000) handler.add_route(address=3, stop=13, distance=100, time=1000) df = handler.routes_dataframe() self.assertEqual(2, df.shape[0], "should be 2 output rows") self.assertEqual(1, df.ix[0, 'address_latitude'], 'incorrect address latitude output') self.assertEqual(3, df.ix[1, 'address_latitude'], 'incorrect address latitude output') self.assertEqual(11, df.ix[0, 'stop_latitude'], 'incorrect stop latitude output') self.assertEqual(13, df.ix[1, 'stop_latitude'], 'incorrect stop latitude output')
def __init__(self, circuit_params=None, general_params=None, database_path=None, settings=None): if settings is None: self.settings = Settings(defaults.SETTINGS) if not os.path.isdir(self.settings.general.scratch_dir): os.mkdir(self.settings.general.scratch_dir) self.circuit_params = circuit_params self.general_params = general_params self.task_sets = [] self.db_handler = DatabaseHandler(self.settings.databases, database_path) self.circuit_submitter = CircuitSubmitter(self.settings.general, self.general_params) self.circuit_validator = CircuitValidator() self.circuit_critic = CircuitCritic(self.circuit_params) self.circuit_designer = CircuitDesigner(self.settings.general, self.circuit_params)
def test_output_routes_outputs_correctly_for_one_route(self): handler = DatabaseHandler('unit_test_db.sqlite3') handler.initialize_db() handler.add_address(MapLocation(latitude=3, longitude=4, id=1)) handler.add_stop(MapLocation(latitude=9, longitude=10, id=1)) handler.add_route(address=1, stop=1, distance=50, time=100) handler.output_routes(file_path='test_file.csv') self.assertTrue(os.path.exists('test_file.csv'), 'test_file.csv file not found') output = pd.read_csv('test_file.csv') self.assertNotEqual(0, output.shape[0], "no output rows in output .csv") self.assertEqual(3, output.ix[0, 'address_latitude'], 'incorrect address latitude output') self.assertEqual(4, output.ix[0, 'address_longitude'], 'incorrect address longitude output') self.assertEqual(9, output.ix[0, 'stop_latitude'], 'incorrect stop latitude output') self.assertEqual(10, output.ix[0, 'stop_longitude'], 'incorrect stop longitude output') self.assertEqual(50, output.ix[0, 'distance'], 'incorrect distance output') self.assertEqual(100, output.ix[0, 'time'], 'incorrect time output')
def test_populate_database_from_file_error(self, mock_reader): with patch('builtins.open', mock_open(read_data="a,b,\"c, d, e\",blue")) as mock_file: handler = DatabaseHandler() handler.populate_database_from_file("somefile")
from flask import render_template, flash, redirect, send_from_directory, request, url_for from app.flask_app import * from app.forms import * from static.static_vars import * from functions import * from DatabaseHandler import DatabaseHandler user = '******' # TODO remove placeholder db_handler = DatabaseHandler() @app.route('/') @app.route('/index') @app.route('/home') def index(): user = '******' # TODO Maybe add login later? products_data = db_handler.products_info_and_prices() return render_template("index.html", title="Home", user=user, products=products_data, stores=stores_analyzed) @app.route('/favicon.ico') def favicon(): return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon')