示例#1
0
 def test_table_exists(self):
     # users table已存在
     exists = db.table_exists(constants.table_name_users)
     self.assertEqual(exists, 3)
     # cards table已存在
     exists = db.table_exists(constants.table_name_cards)
     self.assertEqual(exists, 3)
示例#2
0
def setup_db():
    """Establishes a connection to our database and creates our url table if it
    does not yet exist. Returns the connection to the database file."""
    conn = db.setup_sql(db.MYLOCATION)
    if conn == None:  #Could not establish connection, so quit
        sys.exit()
    if not db.table_exists(db.MYTABLE, conn):  #create table if not yet created
        db.create_table(db.MYTABLE, conn)
    return conn
示例#3
0
文件: shrtn.py 项目: dholzgang/shrtn
def setup_db():
    """Establishes a connection to our database and creates our url table if it
    does not yet exist. Returns the connection to the database file."""
    conn = db.setup_sql(db.MYLOCATION)
    if conn == None: #Could not establish connection, so quit
        sys.exit()
    if not db.table_exists(db.MYTABLE, conn): #create table if not yet created
        db.create_table(db.MYTABLE, conn)
    return conn
示例#4
0
def test_table_exists_false(tmpdir):
    temp = tmpdir.mkdir("tmp")
    database.DBNAME = os.path.join(temp, 'task.db')
    name = database.table_name()

    test_db = sqlite3.connect(database.DBNAME)
    test_db.close()

    assert not database.table_exists(name)
示例#5
0
def test_table_exists_true(tmpdir):
    temp = tmpdir.mkdir("tmp")
    database.DBNAME = os.path.join(temp, 'task.db')
    name = "DAY_01_01_2000"
    add_table_cmd = ("""CREATE TABLE """ + name + """ (id INTEGER PRIMARY KEY,
                     task_name text, task_time, int)""")

    test_db = sqlite3.connect(database.DBNAME)
    with test_db:
        cursor = test_db.cursor()
        cursor.execute(add_table_cmd)
    test_db.close()

    assert database.table_exists(name)
示例#6
0
    def test_create(self):
        """Tests the create argument, which should create a new table."""

        args_set = [self.parser.parse_args(args) for args in read_args()
                if 'create' in args]
        for args in args_set:
            args.func(args)

            # Check that the table was created
            nose.tools.assert_true(
                    database.table_exists(TEST_PB, TEST_DB))

            # Check that only one table was created
            nose.tools.assert_true(
                    len(database.list_tables(TEST_DB)) == 1)

            # Check that no records were added
            nose.tools.assert_true(
                    len(database.read_table(TEST_PB, TEST_DB)) == 0)

            # Delete and recreate TEST_DB
            # There's probably a better way to do this
            self.tearDown()
            self.setUp()
示例#7
0
def main():
    config = config_from_xml_file(CONFIG_FILE)

    mysql_config = copy.deepcopy(config['mysql_config'])
    del mysql_config[
        'database']  # databases can't be checked or created if a database is specified
    database_connection = create_database_connection(mysql_config)
    database_cursor = create_database_cursor(database_connection)

    if database_exists(config, database_cursor):
        print("'{}' database already exists.".format(config['database_name']))
    else:
        create_database(config, database_cursor)
    print()

    database_cursor.stop_cursor()
    database_connection.disconnect()

    database_connection = create_database_connection(config['mysql_config'])
    database_cursor = create_database_cursor(database_connection)

    for table in config['tables'].keys():
        if table_exists(table, database_cursor):
            print("'{}' table already exists.".format(table))
        else:
            create_mysql_table(config, table, database_connection,
                               database_cursor)
            print("'{}' table has been created.".format(table))
            print("Populating '{}' table with data......".format(table))
            load_data_into_mysql_table(config, table, database_connection,
                                       database_cursor)
            print("Population of '{}' table has been completed".format(table))
            print()

    database_cursor.stop_cursor()
    database_connection.disconnect()
示例#8
0
from shortner import *
import database as db


if __name__ == "__main__":
    conn = setup_db() #setup connection to database
    assert db.table_exists(db.MYTABLE, conn) == True #check that table is ready
    
    #unit tests for shrtn functions
    good_short = "http://goo.gl/XPgc5"
    bad_short = "http://goo.gl/8cT/qrq"
    assert is_valid_short(good_short) == True
    assert is_valid_short(bad_short) == False
    
    standard = "http://example.com/"
    assert standardize_url("example.com") == standard
    assert standardize_url("http://example.com") == standard
    assert standardize_url("www.example.com/") != standard #do not adjust www
    
    assert standardize_url(good_short) is None #do not shorten our own URLs
    assert standardize_url("ftp://aserver/afile") is None #only http(s) allowed
    
    id = 78950039
    code = convert_to_code(id)
    a = resolve_to_id(code)
    assert a == id
    print "%d -> %s -> %d" % (id, code, a)
    
    id = -1 #should resolve to 0 so should not equal resolved id
    code = convert_to_code(id)
    assert resolve_to_id(code) != id
示例#9
0
def add_detector_to_database(name, params):
    if database.table_exists(name):  # Just in case!
        database.delete_table(name)
示例#10
0
def handle_mssg(mssg):

    # Unexpected bit: 
    # When the bot sends a message, this function is called. If the sender is 
    # itself, quit, to avoid an infinite loop.
    if mssg['sender_email'] == client.email:
        return

    print 'Message received!'

    content = mssg['content'].strip()

    first = content.split()[0]
    strip_len = len(first)

    while first.endswith(':'):
        strip_len += 1
        first = first[:-1]

    content = mssg['content'][strip_len:]
    content = content.lstrip()

    # First, assume the message is a "ssh" request.
    shh = first
    if shh.lower() == 'shh' or shh.lower() == 'ssh': # Allow for the ssh pun...because it's fun
        anon_shh(stream)
        return

    # Next, assume first is the recipient of an anonymous message
    recipient_email = first
    if recipient_email in emails:
        sender_email = mssg['sender_email']

        # Generate code, send it to person
        code = gen_new_relay_code()

        if not database.database_exists(filename):
            print 'Database %s doesn\'t yet exist. Creating it now...'%(filename)
            database.create_database(filename)
        if not database.table_exists(table, filename):
            # TODO: Put this block of code into the database module as the create_table function
            # The current problem is that I need a way of passing a tuple of strings, and
            # I'm not sure how to securely do this...
            # database.create_table(cols, table, database) where cols = (col1, col2)
            with sqlite3.connect(filename) as con:
                c = con.cursor()
                c.execute("CREATE TABLE %s (code TEXT, email TEXT)"%(table))

        database.add_record((code, sender_email), table, filename)

        end_content = '\n\nThis sender\'s key is %s. To reply, send a message in the following format:\n' %(code)
        end_content += '%s: <your_message>' %(code)
        content += end_content
        send_anon_pm(recipient_email, content)
        send_anon_pm(sender_email, 'Anon message sent to %s' %(recipient_email))
        return

    # Next, assume first is the code of a relax message
    code = first
    email_match = None
    if database.database_exists(filename):
        email_match = search_for_code(code)
    if email_match:
        sender_email = mssg['sender_email']
        content = 'Response from %s:\n'%(sender_email) + content
        end_content = '\nTo reply anonymously, send a message in the following format:\n'
        end_content += '"%s: <your_message>" (without the quotes)' %(sender_email)
        content += end_content
        send_anon_pm(email_match, content)
        send_anon_pm(sender_email, 'Your reply was sent to %s.' %(code))
        return

    # All assumptions exhausted, reply with help message.
    sender_email = mssg['sender_email']
    send_anon_pm(sender_email, get_help_response())
示例#11
0
文件: pv.py 项目: cosuroca/pv-model
def get_hourly_pv_pot(input_data, potential, use_case,
    schema=None, table_name=None, column_name=None,
    filename=None, directory=None, save=None,
    save_to_table=None, save_to_column='pv_pot',
    share_pot_used=1):
    '''
    Returns the hourly PV potential in MWh/h.
    Depending on which potential is wanted, either the total potential of the
    chosen district, the scaled potential (scaled to a maximum capacity of 1 MW)
    or the district's potential (installed capacity plus additional potential)
    is returned.
    Depending on the chosen use case the hourly potential is either retrieved
    from a file or database or calculated.
    '''
    # Returns the total hourly potential of the chosen area
    if potential == 'total':
        pv_area, hourly_pv_potential = total_power_output(input_data)

    # Returns the hourly potential of the chosen area scaled to the capacity of
    # 1 MW
    elif potential == 'scaled' or potential == 'district':
        # retrieve hourly pv potential from the database
        if use_case == 'db':
            if db.table_exists(table_name):
                hourly_pv_potential = db.retrieve_from_db_table(
                    schema, table_name, column_name)
                hourly_pv_potential = np.reshape(
                    hourly_pv_potential, (-1, ))
                # scale
                hourly_pv_potential = \
                    hourly_pv_potential / max(hourly_pv_potential)
            else:
                print (('Table to retrieve the hourly pv potential from ' +
                'does not exist.'))
        # retrieve hourly pv potential from file
        elif use_case == 'file':
            hourly_pv_potential = \
                db.read_profiles_from_file(filename, directory)[column_name]
            hourly_pv_potential = np.reshape(hourly_pv_potential, (-1, ))
            # scale
            hourly_pv_potential = \
                hourly_pv_potential / max(hourly_pv_potential)
        elif use_case == 'calc':
            hourly_pv_potential = scaled_power_output(input_data)
        else:
            print (('Hourly pv potential cannot be returned because of ' +
            'invalid use case. The use case chosen was: %s' % use_case))
        pv_area = None

    # Error message
    else:
        print (('Hourly pv potential cannot be returned because of ' +
        'invalid "potential" input. The "potential" chosen was: %s'
        % potential))

    # Returns the hourly potential of the chosen district in Wittenberg
    if potential == 'district':
        hourly_pv_potential = ee_potential_district.pv_potential(
            input_data, hourly_pv_potential, share_pot_used)

    # save results to db
    if save:
        if db.table_exists(save_to_table):
            db.save_results_to_db(
                schema, save_to_table, save_to_column, hourly_pv_potential)
        else:
            # create output table and id column
            db.create_db_table(schema, save_to_table,
                save_to_column + ' real')
            stringi = '(1)'
            for i in range(2, 8761):
                stringi = stringi + ',(' + str(i) + ')'
            db.insert_data_into_db_table(schema, save_to_table, 'id', stringi)
            db.save_results_to_db(
                schema, save_to_table, save_to_column, hourly_pv_potential)

    return hourly_pv_potential, pv_area
from shortner import *
import database as db


if __name__ == "__main__":
    conn = setup_db()  # setup connection to database
    assert db.table_exists(db.MYTABLE, conn) == True  # check that table is ready

    # unit tests for shrtn functions
    good_short = "http://goo.gl/XPgc5"
    bad_short = "http://goo.gl/8cT/qrq"
    assert is_valid_short(good_short) == True
    assert is_valid_short(bad_short) == False

    standard = "http://example.com/"
    assert standardize_url("example.com") == standard
    assert standardize_url("http://example.com") == standard
    assert standardize_url("www.example.com/") != standard  # do not adjust www

    assert standardize_url(good_short) is None  # do not shorten our own URLs
    assert standardize_url("ftp://aserver/afile") is None  # only http(s) allowed

    id = 78950039
    code = convert_to_code(id)
    a = resolve_to_id(code)
    assert a == id
    print "%d -> %s -> %d" % (id, code, a)

    id = -1  # should resolve to 0 so should not equal resolved id
    code = convert_to_code(id)
    assert resolve_to_id(code) != id